类javax.xml.transform.TransformerFactory源码实例Demo

下面列出了怎么用javax.xml.transform.TransformerFactory的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: carbon-commons   文件: Util.java
/**
 * Transform based on parameters
 *
 * @param xmlIn    XML
 * @param xslIn    XSL
 * @param result   Result
 * @param paramMap Parameter map
 * @throws javax.xml.transform.TransformerException
 *          will be thrown
 */
public static void transform(Source xmlIn, Source xslIn, Result result, Map paramMap)
        throws TransformerException {
    try {
        TransformerFactory transformerFactory = new TransformerFactoryImpl();
        Transformer transformer = transformerFactory.newTransformer(xslIn);
        if (paramMap != null) {
            Set set = paramMap.keySet();
            for (Object aSet : set) {
                if (aSet != null) {
                    String key = (String) aSet;
                    String value = (String) paramMap.get(key);
                    transformer.setParameter(key, value);
                }
            }
        }
        transformer.transform(xmlIn, result);
    } catch (TransformerException e) {
        log.error(e.getMessage(), e);
        throw e;
    }
}
 
源代码2 项目: jpexs-decompiler   文件: XFLConverter.java
private static String prettyFormatXML(String input) {
    int indent = 5;
    try {
        Source xmlInput = new StreamSource(new StringReader(input));
        StringWriter stringWriter = new StringWriter();
        StreamResult xmlOutput = new StreamResult(stringWriter);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", indent);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.transform(xmlInput, xmlOutput);
        return xmlOutput.getWriter().toString();
    } catch (TransformerFactoryConfigurationError | IllegalArgumentException | TransformerException e) {
        logger.log(Level.SEVERE, "Pretty print error", e);
        return input;
    }
}
 
源代码3 项目: pra   文件: FXml.java
public static void sample()throws Exception {
  int no = 2;

  String root = "EnterRoot";
  DocumentBuilderFactory dbf =   DocumentBuilderFactory.newInstance();
  DocumentBuilder db =  dbf.newDocumentBuilder();
  Document d = db.newDocument();
  Element eRoot = d.createElement(root);
      d.appendChild(eRoot);
  for (int i = 1; i <= no; i++){

    String element = "EnterElement";
    String data = "Enter the data";
    
    Element e = d.createElement(element);
    e.appendChild(d.createTextNode(data));
    eRoot.appendChild(e);
  }
  TransformerFactory tf = TransformerFactory.newInstance();
   Transformer t = tf.newTransformer();
   DOMSource source = new DOMSource(d);
   StreamResult result =  new StreamResult(System.out);
   t.transform(source, result);

}
 
源代码4 项目: ats-framework   文件: XmlUtilities.java
/**
 * Pretty print XML Node
 * @param node
 * @return
 * @throws XmlUtilitiesException
 */
public String xmlNodeToString( Node node ) throws XmlUtilitiesException {

    StringWriter sw = new StringWriter();
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, "4");
        transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_LINE_SEPARATOR, "\n");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.transform(new DOMSource(node), new StreamResult(sw));
    } catch (TransformerException te) {
        throw new XmlUtilitiesException("Error transforming XML node to String", te);
    }
    return sw.toString().trim();
}
 
源代码5 项目: openjdk-jdk9   文件: Bug6467808.java
@Test
public void test() {
    try {
        SAXParserFactory fac = SAXParserFactory.newInstance();
        fac.setNamespaceAware(true);
        SAXParser saxParser = fac.newSAXParser();

        StreamSource src = new StreamSource(new StringReader(SIMPLE_TESTXML));
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        DOMResult result = new DOMResult();
        transformer.transform(src, result);
    } catch (Throwable ex) {
        // unexpected failure
        ex.printStackTrace();
        Assert.fail(ex.toString());
    }
}
 
源代码6 项目: XmlToJson   文件: JsonToXml.java
/**
 *
 * @param indent size of the indent (number of spaces)
 * @return the formatted XML
 */
public String toFormattedString(@IntRange(from = 0) int indent) {
    String input = toString();
    try {
        Source xmlInput = new StreamSource(new StringReader(input));
        StringWriter stringWriter = new StringWriter();
        StreamResult xmlOutput = new StreamResult(stringWriter);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "" + indent);
        transformer.transform(xmlInput, xmlOutput);
        return xmlOutput.getWriter().toString();
    } catch (Exception e) {
        throw new RuntimeException(e); // TODO: do my own
    }
}
 
源代码7 项目: mdw   文件: TransformActivity.java
private String transform(String xml, String xsl) {
    try {
        @SuppressWarnings("squid:S4435") // false positive
        TransformerFactory tFactory = TransformerFactory.newInstance();
        tFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

        Source xslSource = new StreamSource(new ByteArrayInputStream(xsl.getBytes()));
        Transformer transformer = tFactory.newTransformer(xslSource);

        Source xmlSource = new StreamSource(new ByteArrayInputStream(xml.getBytes()));
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        transformer.transform(xmlSource, new StreamResult(outputStream));

        return new String(outputStream.toByteArray());

    }
    catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
源代码8 项目: java-docs-samples   文件: StorageSample.java
/**
 * Prints out the contents of the given xml, in a more readable form.
 *
 * @param bucketName the name of the bucket you're listing.
 * @param content the raw XML string.
 */
private static void prettyPrintXml(final String bucketName, final String content) {
  // Instantiate transformer input.
  Source xmlInput = new StreamSource(new StringReader(content));
  StreamResult xmlOutput = new StreamResult(new StringWriter());

  // Configure transformer.
  try {
    Transformer transformer =
        TransformerFactory.newInstance().newTransformer(); // An identity transformer
    transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "testing.dtd");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    transformer.transform(xmlInput, xmlOutput);

    // Pretty print the output XML.
    System.out.println("\nBucket listing for " + bucketName + ":\n");
    System.out.println(xmlOutput.getWriter().toString());
  } catch (TransformerException e) {
    e.printStackTrace();
  }
}
 
源代码9 项目: nifi   文件: TransformXml.java
@Override
public ValidationResult validate(final String subject, final String input, final ValidationContext validationContext) {
    final Tuple<String, ValidationResult> lastResult = this.cachedResult;
    if (lastResult != null && lastResult.getKey().equals(input)) {
        return lastResult.getValue();
    } else {
        String error = null;
        final File stylesheet = new File(input);
        final TransformerFactory tFactory = new net.sf.saxon.TransformerFactoryImpl();
        final StreamSource styleSource = new StreamSource(stylesheet);

        try {
            tFactory.newTransformer(styleSource);
        } catch (final Exception e) {
            error = e.toString();
        }

        this.cachedResult = new Tuple<>(input, new ValidationResult.Builder()
                .input(input)
                .subject(subject)
                .valid(error == null)
                .explanation(error)
                .build());
        return this.cachedResult.getValue();
    }
}
 
源代码10 项目: openjdk-jdk9   文件: AuctionItemRepository.java
/**
 * Test if two non nested xi:include elements can include the same document
 * with an xi:include statement.
 *
 * @throws Exception If any errors occur.
 */
@Test(groups = {"readWriteLocalFiles"})
public void testXIncludeNestedPos() throws Exception {
    String resultFile = USER_DIR + "schedule.out";
    String goldFile = GOLDEN_DIR + "scheduleGold.xml";
    String xmlFile = XML_DIR + "schedule.xml";

    try (FileOutputStream fos = new FileOutputStream(resultFile)) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setXIncludeAware(true);
        dbf.setNamespaceAware(true);

        Document doc = dbf.newDocumentBuilder().parse(new File(xmlFile));
        doc.setXmlStandalone(true);
        TransformerFactory.newInstance().newTransformer()
                .transform(new DOMSource(doc), new StreamResult(fos));
    }
    assertTrue(compareDocumentWithGold(goldFile, resultFile));
}
 
源代码11 项目: Flink-CEPplus   文件: Configuration.java
/**
 * Write out the non-default properties in this configuration to the given
 * {@link Writer}.
 *
 * @param out the writer to write to.
 */
public void writeXml(Writer out) throws IOException {
  Document doc = asXmlDocument();

  try {
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(out);
    TransformerFactory transFactory = TransformerFactory.newInstance();
    Transformer transformer = transFactory.newTransformer();

    // Important to not hold Configuration log while writing result, since
    // 'out' may be an HDFS stream which needs to lock this configuration
    // from another thread.
    transformer.transform(source, result);
  } catch (TransformerException te) {
    throw new IOException(te);
  }
}
 
源代码12 项目: ph-commons   文件: XMLTransformerFactory.java
/**
 * Create a new XSLT transformer for the passed resource.
 *
 * @param aTransformerFactory
 *        The transformer factory to be used. May not be <code>null</code>.
 * @param aSource
 *        The resource to be transformed. May not be <code>null</code>.
 * @return <code>null</code> if something goes wrong
 */
@Nullable
public static Transformer newTransformer (@Nonnull final TransformerFactory aTransformerFactory,
                                          @Nonnull final Source aSource)
{
  ValueEnforcer.notNull (aTransformerFactory, "TransformerFactory");
  ValueEnforcer.notNull (aSource, "Source");

  try
  {
    return aTransformerFactory.newTransformer (aSource);
  }
  catch (final TransformerConfigurationException ex)
  {
    LOGGER.error ("Failed to parse " + aSource, ex);
    return null;
  }
}
 
源代码13 项目: oodt   文件: SerializableMetadata.java
/**
 * Writes out this SerializableMetadata object in XML format to the
 * OutputStream provided
 * 
 * @param os
 *            The OutputStream this method writes to
 * @throws IOException
 *             for any Exception
 */
public void writeMetadataToXmlStream(OutputStream os) throws IOException {
    try {
        // Prepare the DOM document for writing
        Source source = new DOMSource(this.toXML());
        Result result = new StreamResult(os);

        // Write the DOM document to the file
        Transformer xformer = TransformerFactory.newInstance()
                .newTransformer();
        xformer.setOutputProperty(OutputKeys.ENCODING, this.xmlEncoding);
        xformer.setOutputProperty(OutputKeys.INDENT, "yes");
        xformer.transform(source, result);

    } catch (Exception e) {
        LOG.log(Level.SEVERE, e.getMessage());
        throw new IOException("Error generating metadata xml file!: "
                + e.getMessage());
    }
}
 
源代码14 项目: BuildmLearn-Toolkit-Android   文件: FileUtils.java
/**
 * @param destinationFolder Destination folder for saving the file
 * @param fileName          Destination file name
 * @param doc               Document object to be converted to xml formatted file
 * @return Returns true if successfully converted
 * @brief Converts a given Document object to xml format file
 */
public static boolean saveXmlFile(String destinationFolder, String fileName, Document doc) {

    File f = new File(destinationFolder);
    if (!f.isDirectory()) {
        f.mkdirs();
    }
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer;
    try {
        File newTemplateFile=new File(destinationFolder + fileName);
        if(newTemplateFile.exists())
            return false;
        transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(newTemplateFile);
        transformer.transform(source, result);

    } catch (TransformerException e) {
        e.printStackTrace();
    }
    return true;
}
 
源代码15 项目: lams   文件: LearningDesignRepositoryServlet.java
/**
 * the format should be something like this: [ ['My Workspace', null, ['Mary Morgan Folder', null, ['3 activity
 * sequence','1024'] ], ['Organisations', null, ['Developers Playpen', null, ['Lesson Sequence Folder', null,
 * ['',null] ] ], ['MATH111', null, ['Lesson Sequence Folder', null, ['',null] ] ] ] ] ]
 */
@Override
public String toString() {
    // return '[' + convert() + ']';

    Document document = getDocument();

    try {
	DOMSource domSource = new DOMSource(document);
	StringWriter writer = new StringWriter();
	StreamResult result = new StreamResult(writer);
	TransformerFactory tf = TransformerFactory.newInstance();
	Transformer transformer = tf.newTransformer();
	transformer.transform(domSource, result);
	return writer.toString();
    } catch (TransformerException ex) {
	ex.printStackTrace();
	return null;
    }
}
 
public void CreateTaggedOutput()
{
try{	

	TransformerFactory transformerFactory = TransformerFactory.newInstance();
	Transformer transformer = transformerFactory.newTransformer();
	DOMSource source = new DOMSource(XMLDocumentTagged);

	StreamResult result =  new StreamResult(new File(filename));
	transformer.transform(source, result);
}
catch(Exception ex)
{
	ex.printStackTrace();
}
}
 
源代码17 项目: openjdk-jdk9   文件: AuctionItemRepository.java
/**
 * Test the simple case of including a document using xi:include within a
 * xi:fallback using a DocumentBuilder.
 *
 * @throws Exception If any errors occur.
 */
@Test(groups = {"readWriteLocalFiles"})
public void testXIncludeFallbackDOMPos() throws Exception {
    String resultFile = USER_DIR + "doc_fallbackDOM.out";
    String goldFile = GOLDEN_DIR + "doc_fallbackGold.xml";
    String xmlFile = XML_DIR + "doc_fallback.xml";
    try (FileOutputStream fos = new FileOutputStream(resultFile)) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setXIncludeAware(true);
        dbf.setNamespaceAware(true);

        Document doc = dbf.newDocumentBuilder().parse(new File(xmlFile));
        doc.setXmlStandalone(true);
        TransformerFactory.newInstance().newTransformer()
                .transform(new DOMSource(doc), new StreamResult(fos));
    }
    assertTrue(compareDocumentWithGold(goldFile, resultFile));
}
 
源代码18 项目: incubator-ratis   文件: RaftProperties.java
/**
 * Write out the non-default properties in this configuration to the given
 * {@link Writer}.
 *
 * @param out the writer to write to.
 */
public void writeXml(Writer out) throws IOException {
  Document doc = asXmlDocument();

  try {
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(out);
    TransformerFactory transFactory = TransformerFactory.newInstance();
    Transformer transformer = transFactory.newTransformer();

    // Important to not hold Configuration log while writing result, since
    // 'out' may be an HDFS stream which needs to lock this configuration
    // from another thread.
    transformer.transform(source, result);
  } catch (TransformerException te) {
    throw new IOException(te);
  }
}
 
源代码19 项目: hadoop   文件: Configuration.java
/** 
 * Write out the non-default properties in this configuration to the given
 * {@link Writer}.
 * 
 * @param out the writer to write to.
 */
public void writeXml(Writer out) throws IOException {
  Document doc = asXmlDocument();

  try {
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(out);
    TransformerFactory transFactory = TransformerFactory.newInstance();
    Transformer transformer = transFactory.newTransformer();

    // Important to not hold Configuration log while writing result, since
    // 'out' may be an HDFS stream which needs to lock this configuration
    // from another thread.
    transformer.transform(source, result);
  } catch (TransformerException te) {
    throw new IOException(te);
  }
}
 
源代码20 项目: alipay-sdk   文件: XmlUtils.java
/**
 * Converts the Node/Element instance to XML payload.
 *
 * @param node the node/element instance to convert
 * @return the XML payload representing the node/element
 * @throws ApiException problem converting XML to string
 */
public static String childNodeToString(Node node) throws AlipayApiException {
    String payload = null;

    try {
        Transformer tf = TransformerFactory.newInstance().newTransformer();

        Properties props = tf.getOutputProperties();
        props.setProperty(OutputKeys.OMIT_XML_DECLARATION, LOGIC_YES);
        tf.setOutputProperties(props);

        StringWriter writer = new StringWriter();
        tf.transform(new DOMSource(node), new StreamResult(writer));
        payload = writer.toString();
        payload = payload.replaceAll(REG_INVALID_CHARS, " ");
    } catch (TransformerException e) {
        throw new AlipayApiException("XML_TRANSFORM_ERROR", e);
    }

    return payload;
}
 
源代码21 项目: weasis-dicom-tools   文件: FindSCU.java
private TransformerHandler getTransformerHandler() throws Exception {
    SAXTransformerFactory tf = saxtf;
    if (tf == null) {
        saxtf = tf = (SAXTransformerFactory) TransformerFactory.newInstance();
        tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    }
    if (xsltFile == null) {
        return tf.newTransformerHandler();
    }

    Templates tpls = xsltTpls;
    if (tpls == null) {
        xsltTpls = tpls = tf.newTemplates(new StreamSource(xsltFile));
    }

    return tf.newTransformerHandler(tpls);
}
 
源代码22 项目: Decision   文件: SolrOperationsService.java
public void createSolrSchema(List<ColumnNameTypeValue> columns, String confpath) throws ParserConfigurationException, URISyntaxException, IOException, SAXException, TransformerException {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setIgnoringComments(true);
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse(new File(ClassLoader.getSystemResource("./solr-config/schema.xml").toURI()));
    NodeList nodes = doc.getElementsByTagName("schema");
    for (ColumnNameTypeValue column: columns) {
        Element field = doc.createElement("field");
        field.setAttribute("name", column.getColumn());
        field.setAttribute("type", streamingToSolr(column.getType()));
        field.setAttribute("indexed", "true");
        field.setAttribute("stored", "true");
        nodes.item(0).appendChild(field);
    }
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult streamResult =  new StreamResult(new File(confpath+"/schema.xml"));
    transformer.transform(source, streamResult);
}
 
源代码23 项目: carbon-apimgt   文件: ConfiguratorTest.java
@Test
public void main() throws Exception {
    String carbonHome = System.getProperty(ConfigConstants.CARBON_HOME);
    setAPIMConfigurations();
    RegistryXmlConfigurator registryXmlConfigurator = new RegistryXmlConfigurator();
    TransformerIdentityImpl transformerIdentity = PowerMockito.mock(TransformerIdentityImpl.class);
    TransformerFactory transformerFactory = PowerMockito.mock(TransformerFactory.class);
    PowerMockito.mockStatic(TransformerFactory.class);
    PowerMockito.when(TransformerFactory.newInstance()).thenReturn(transformerFactory);
    PowerMockito.when(transformerFactory.newTransformer()).thenReturn(transformerIdentity);
    PowerMockito.doNothing().when(transformerIdentity).transform(any(DOMSource.class), any(StreamResult.class));
    registryXmlConfigurator.configure(carbonConfigDirPath, gatewayConfigs);
    Log4JConfigurator log4JConfigurator = new Log4JConfigurator();
    log4JConfigurator.configure(carbonConfigDirPath);
    Configurator.writeConfiguredLock(carbonHome);
    //Cleaning the log4j.properties file
    PrintWriter writer = new PrintWriter(carbonHome + File.separator + ConfigConstants.REPOSITORY_DIR + File.separator + ConfigConstants.CONF_DIR + File.separator + "log4j.properties");
    writer.print("\n");
    writer.close();
}
 
源代码24 项目: jsons2xsd   文件: XmlUtil.java
public static String asXmlString(Node node)
{
    final Source source = new DOMSource(node);
    final StringWriter stringWriter = new StringWriter();
    final Result result = new StreamResult(stringWriter);
    final TransformerFactory factory = TransformerFactory.newInstance();

    try
    {
        final Transformer transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.transform(source, result);
        return stringWriter.getBuffer().toString();
    }
    catch (TransformerException exc)
    {
        throw new UncheckedIOException(exc.getMessage(), new IOException(exc));
    }
}
 
源代码25 项目: gemfirexd-oss   文件: Misc.java
public static String serializeXMLAsString(Element el, String xsltFileName) {
  try {
    TransformerFactory tFactory = TransformerFactory.newInstance();
    StringWriter sw = new StringWriter();
    DOMSource source = new DOMSource(el);

    ClassLoader cl = InternalDistributedSystem.class.getClassLoader();
    // fix for bug 33274 - null classloader in Sybase app server
    if (cl == null) {
      cl = ClassLoader.getSystemClassLoader();
    }
    InputStream is = cl
        .getResourceAsStream("com/pivotal/gemfirexd/internal/impl/tools/planexporter/resources/"
            + xsltFileName);

    Transformer transformer = tFactory
        .newTransformer(new javax.xml.transform.stream.StreamSource(is));
    StreamResult result = new StreamResult(sw);

    transformer.transform(source, result);
    return sw.toString();
  } catch (TransformerException te) {
    throw GemFireXDRuntimeException.newRuntimeException(
        "serializeXMLAsString: unexpected exception", te);
  }
}
 
源代码26 项目: openjdk-jdk8u-backup   文件: XmlFactory.java
/**
 * Returns properly configured (e.g. security features) factory
 * - securityProcessing == is set based on security processing property, default is true
 */
public static TransformerFactory createTransformerFactory(boolean disableSecureProcessing) throws IllegalStateException {
    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, "TransformerFactory instance: {0}", factory);
        }
        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, !isXMLSecurityDisabled(disableSecureProcessing));
        return factory;
    } catch (TransformerConfigurationException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
        throw new IllegalStateException( ex);
    } catch (AbstractMethodError er) {
        LOGGER.log(Level.SEVERE, null, er);
        throw new IllegalStateException(Messages.INVALID_JAXP_IMPLEMENTATION.format(), er);
    }
}
 
源代码27 项目: studio   文件: AbstractXsltFileUpgradeOperation.java
protected void executeTemplate(String site, String path, OutputStream os) throws UpgradeException {
    if(contentRepository.contentExists(site, path)) {
        try(InputStream templateIs = template.getInputStream()) {
            // Saxon is used to support XSLT 2.0
            Transformer transformer =
                TransformerFactory.newInstance(SAXON_CLASS, null)
                    .newTransformer(new StreamSource(templateIs));
            logger.info("Applying XSLT template {0} to file {1} for site {2}", template, path, site);
            try(InputStream sourceIs = contentRepository.getContent(site, path)) {
                transformer.setParameter(PARAM_KEY_SITE, site);
                transformer.setParameter(PARAM_KEY_VERSION, nextVersion);
                transformer.setURIResolver(getURIResolver(site));
                transformer.transform(new StreamSource(sourceIs), new StreamResult(os));
            }
        } catch (Exception e) {
            throw new UpgradeException("Error processing file", e);
        }
    } else {
        logger.warn("Source file {0} does not exist in site {1}", path, site);
    }
}
 
源代码28 项目: sakai   文件: I18nXmlUtility.java
/**
 * Adds the specified element to the XML document and returns the document's contents as a String
 */
public static String addElementAndGetDocumentAsString(Document doc, Element el)
{
	doc.appendChild(el);

	try {
		TransformerFactory tranFactory = TransformerFactory.newInstance();
		Transformer aTransformer = tranFactory.newTransformer();
		Source src = new DOMSource(doc);
		StringWriter writer = new StringWriter();
		Result dest = new StreamResult(writer);
		aTransformer.transform(src, dest);
		String result = writer.getBuffer().toString();
		return result;
	}
	catch (Exception e) {
		throw new ContentReviewProviderException("Failed to transform the XML Document into a String");
	}
}
 
源代码29 项目: teamengine   文件: MonitorServlet.java
public void init() throws ServletException {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
            // Fortify Mod: prevent external entity injection
        dbf.setExpandEntityReferences(false);
        DB = dbf.newDocumentBuilder();
            // Fortify Mod: prevent external entity injection 
        TransformerFactory tf = TransformerFactory.newInstance();
        tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        identityTransformer = tf.newTransformer();
        // identityTransformer = TransformerFactory.newInstance().newTransformer();
        // End Fortify Mod

        servletName = this.getServletName();
    } catch (Exception e) {
        throw new ServletException(e);
    }
}
 
源代码30 项目: scava   文件: XML.java
public void saveToFile(File file) throws Exception{
    Source domSource = new DOMSource(doc);
    FileWriter writer = new FileWriter(file);
    Result result = new StreamResult(writer);
    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    xformer.transform(domSource, result);
    writer.flush();writer.close();
}