Java Code Examples for javax.xml.transform.TransformerFactory#setFeature()

The following examples show how to use javax.xml.transform.TransformerFactory#setFeature() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DocumentationHelper.java    From teamengine with Apache License 2.0 6 votes vote down vote up
/**
 * Generate pseudocode documentation for CTL test scripts. Apply the
 * stylesheet to documentate the sources of tests.
 * 
 * @param sourcecodePath
 *            main file of test source
 * @param suiteName
 *            name of the suite to be documented (TBD)
 * @param htmlFileOutput
 *            path of generated file
 * @throws Exception
 */
public void generateDocumentation(String sourcecodePath, String suiteName,
        FileOutputStream htmlFileOutput) throws Exception {
    TransformerFactory tFactory = TransformerFactory.newInstance();
    // Fortify Mod: prevent external entity injection
    tFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    // Fortify Mod: prevent external entity injection
    factory.setExpandEntityReferences(false);
    factory.setNamespaceAware(true);
    factory.setXIncludeAware(true);
    DocumentBuilder parser = factory.newDocumentBuilder();
    Document document = parser.parse(sourcecodePath);
    Transformer transformer = tFactory.newTransformer(new StreamSource(
            xsltSystemId));
    transformer.transform(new DOMSource(document), new StreamResult(
            htmlFileOutput));

}
 
Example 2
Source File: Dom4jTransformer.java    From tutorials with MIT License 6 votes vote down vote up
public String modifyAttribute(String attribute, String oldValue, String newValue) throws TransformerException {
    // 2- Locate the node(s) with xpath, we can use index and iterator too.
    String expr = String.format("//*[contains(@%s, '%s')]", attribute, oldValue);
    XPath xpath = DocumentHelper.createXPath(expr);
    List<Node> nodes = xpath.selectNodes(input);
    // 3- Make the change on the selected nodes
    for (int i = 0; i < nodes.size(); i++) {
        Element element = (Element) nodes.get(i);
        element.addAttribute(attribute, newValue);
    }
    // 4- Save the result to a new XML doc
    TransformerFactory factory = TransformerFactory.newInstance();
    factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    Transformer xformer = factory.newTransformer();
    xformer.setOutputProperty(OutputKeys.INDENT, "yes");
    Writer output = new StringWriter();
    xformer.transform(new DocumentSource(input), new StreamResult(output));
    return output.toString();
}
 
Example 3
Source File: DomUtils.java    From teamengine with Apache License 2.0 6 votes vote down vote up
/**
 * Convert text node to element.
 * @param xmlString
 * @return Return the document object.
 * @throws Exception
 */
public static Document convertToElementNode(String xmlString) throws Exception {
       DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
       dbf.setNamespaceAware(true);
	   // Fortify Mod: Disable entity expansion to foil External Entity Injections
	   dbf.setExpandEntityReferences(false);
       Document doc = dbf.newDocumentBuilder().newDocument();
       if (xmlString != null) {
       	    // Fortify Mod: disable external entity injection
          TransformerFactory tf = TransformerFactory.newInstance();
          tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
          Transformer t = tf.newTransformer();
		    // End Fortify Mod
          t.transform(new StreamSource(new StringReader(xmlString)), new DOMResult(doc));
       }
       return doc;
   }
 
Example 4
Source File: ConfigFileCreator.java    From teamengine with Apache License 2.0 6 votes vote down vote up
public void saveConfigFile(Document docMain, String mainconfig) {
	try {
		TransformerFactory transformerFactory = TransformerFactory
				.newInstance();
                   // Fortify Mod: prevent external entity injection
               transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
		Transformer transformer = transformerFactory.newTransformer();
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		DOMSource source = new DOMSource(docMain);

		StreamResult result = new StreamResult(new FileOutputStream(
				mainconfig));
		LOGR.info("SUCCESSFULLY created config.xml at " + mainconfig);
		transformer.transform(source, result);
                       // Fortify Mod: Close the OutputStream associated with the StreamResult
                       result.getOutputStream().close();
	} catch (Exception e) {
		LOGR.warning("The main config file was not created at "
				+ mainconfig);
		e.printStackTrace();
	}
}
 
Example 5
Source File: Bug7143711Test.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test(enabled=false) //skipped due to bug JDK-8080097
public void testTransform_DOM_withSM() {
    System.out.println("Transform using DOM Source;  Security Manager is set:");
    setSystemProperty(DOM_FACTORY_ID, "MyDOMFactoryImpl");

    try {
        TransformerFactory factory = TransformerFactory.newInstance("com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl",
                TransformerFactory.class.getClassLoader());
        factory.setFeature(ORACLE_FEATURE_SERVICE_MECHANISM, true);
        if ((boolean) factory.getFeature(ORACLE_FEATURE_SERVICE_MECHANISM)) {
            Assert.fail("should not override in secure mode");
        }

    } catch (Exception e) {
        Assert.fail(e.getMessage());
    } finally {
        clearSystemProperty(DOM_FACTORY_ID);
    }
}
 
Example 6
Source File: TransformActivity.java    From mdw with Apache License 2.0 6 votes vote down vote up
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;
    }
}
 
Example 7
Source File: TransformXml.java    From nifi with Apache License 2.0 6 votes vote down vote up
private Templates newTemplates(final ProcessContext context, final String path) throws TransformerConfigurationException, LookupFailureException {
    final Boolean secureProcessing = context.getProperty(SECURE_PROCESSING).asBoolean();
    TransformerFactory factory = TransformerFactory.newInstance();
    final boolean isFilename = context.getProperty(XSLT_FILE_NAME).isSet();

    if (secureProcessing) {
        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        // don't be overly DTD-unfriendly forcing http://apache.org/xml/features/disallow-doctype-decl
        factory.setFeature("http://saxon.sf.net/feature/parserFeature?uri=http://xml.org/sax/features/external-parameter-entities", false);
        factory.setFeature("http://saxon.sf.net/feature/parserFeature?uri=http://xml.org/sax/features/external-general-entities", false);
    }

    if(isFilename) {
        return factory.newTemplates(new StreamSource(path));
    } else {
        final String coordinateKey = lookupService.get().getRequiredKeys().iterator().next();
        final Optional<String> attributeValue = lookupService.get().lookup(Collections.singletonMap(coordinateKey, path));
        if (attributeValue.isPresent() && StringUtils.isNotBlank(attributeValue.get())) {
            return factory.newTemplates(new StreamSource(new ByteArrayInputStream(attributeValue.get().getBytes(StandardCharsets.UTF_8))));
        } else {
            throw new TransformerConfigurationException("No XSLT definition is associated to " + path + " in the lookup controller service.");
        }
    }
}
 
Example 8
Source File: WsdlValidator.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Load XML data to a temporary file.
 *
 * @param document XML DOM
 * @return URL of the file
 * @throws IOException          on error writing to file
 * @throws TransformerException on transforming error
 */
private URL loadXMLToFile(Document document) throws TransformerException, IOException {
    DOMSource source = new DOMSource(document);
    File tempFile = File.createTempFile("temp", ".txt");
    tempFile.deleteOnExit();
    FileWriter writer = new FileWriter(tempFile);
    StreamResult result = new StreamResult(writer);
    TransformerFactory transformerFactory;
    try {
        transformerFactory = TransformerFactory
                .newInstance("com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl", null);
    } catch (NoSuchMethodError e) {
        log.info("TransformerFactory.newInstance(String, ClassLoader) method not found. " +
                "Using TransformerFactory.newInstance()");
        transformerFactory = TransformerFactory.newInstance();
    }
    transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(source, result);
    return tempFile.toURI().toURL();
}
 
Example 9
Source File: WadlGenerator.java    From cxf with Apache License 2.0 6 votes vote down vote up
private String transformLocally(Message m, UriInfo ui, Source source) throws Exception {
    InputStream is = ResourceUtils.getResourceStream(stylesheetReference, m.getExchange().getBus());
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformerFactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
    try {
        transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
        transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
    } catch (IllegalArgumentException ex) {
        // ignore
    }

    Transformer t = transformerFactory.newTemplates(new StreamSource(is)).newTransformer();
    t.setParameter("base.path", m.get("http.base.path"));
    StringWriter stringWriter = new StringWriter();
    t.transform(source, new StreamResult(stringWriter));
    return stringWriter.toString();
}
 
Example 10
Source File: SoapUtils.java    From teamengine with Apache License 2.0 6 votes vote down vote up
/**
   * A method to create a SOAP message and retrieve it as byte.
   * 
   * @param version
   *            the SOAP version to be used (1.1 or 1.2).
   * @param headerBlocks
   *            the list of Header Blocks to be included in the SOAP Header .
   * @param body
   *            the XML message to be included in the SOAP BODY element.
   * @param encoding
   *            the encoding to be used for the message creation.
   * 
   * @return The created SOAP message as byte.
   * 
   * @author Simone Gianfranceschi
   */
  public static byte[] getSoapMessageAsByte(String version,
          List headerBlocks, Element body, String encoding) throws Exception {
      Document message = createSoapMessage(version, headerBlocks, body);
      ByteArrayOutputStream baos = new ByteArrayOutputStream();

      TransformerFactory tf = TransformerFactory.newInstance();
        // Fortify Mod: prevent external entity injection
      tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
      Transformer t = tf.newTransformer();
// End Fortify Mod
      t.setOutputProperty(OutputKeys.ENCODING, encoding);
      t.transform(new DOMSource(message), new StreamResult(baos));

      // System.out.println("SOAP MESSAGE : " + baos.toString());

      return baos.toByteArray();
  }
 
Example 11
Source File: CatalogSupportBase.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns an instance of TransformerFactory with either a custom URIResolver
 * or Catalog.
 *
 * @param setUseCatalog a flag indicates whether USE_CATALOG shall be set
 * through the factory
 * @param useCatalog the value of USE_CATALOG
 * @param catalog a catalog
 * @param resolver a custom resolver
 * @return an instance of TransformerFactory
 * @throws Exception
 */
TransformerFactory getTransformerFactory(boolean setUseCatalog, boolean useCatalog,
        String catalog, URIResolver resolver)
        throws Exception {

    TransformerFactory factory = TransformerFactory.newInstance();
    if (setUseCatalog) {
        factory.setFeature(XMLConstants.USE_CATALOG, useCatalog);
    }
    if (catalog != null) {
        factory.setAttribute(CatalogFeatures.Feature.FILES.getPropertyName(), catalog);
    }

    // use resolver or catalog if resolver = null
    if (resolver != null) {
        factory.setURIResolver(resolver);
    }

    return factory;
}
 
Example 12
Source File: DocViewFormat.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
/** internally formats the given file and computes their checksum
 * 
 * @param file the file
 * @param original checksum of the original file
 * @param formatted checksum of the formatted file
 * @return the formatted bytes
 * @throws IOException if an error occurs */
private byte[] format(File file, Checksum original, Checksum formatted) throws IOException {
    try (InputStream in = new CheckedInputStream(new BufferedInputStream(new FileInputStream(file)), original)) {
        @SuppressWarnings("resource")
        ByteArrayOutputStream buffer = formattingBuffer != null ? formattingBuffer.get() : null;
        if (buffer == null) {
            buffer = new ByteArrayOutputStream();
            formattingBuffer = new WeakReference<>(buffer);
        } else {
            buffer.reset();
        }

        try (OutputStream out = new CheckedOutputStream(buffer, formatted);
             FormattingXmlStreamWriter writer = FormattingXmlStreamWriter.create(out, format)) {
            // cannot use XMlStreamReader due to comment handling:
            // https://stackoverflow.com/questions/15792007/why-does-xmlstreamreader-staxsource-strip-comments-from-xml
            TransformerFactory tf = TransformerFactory.newInstance();
            tf.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
            SAXSource saxSource = new SAXSource(new InputSource(in));
            SAXParserFactory sf = SAXParserFactory.newInstance();
            sf.setNamespaceAware(true);
            sf.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
            sf.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
            saxSource.setXMLReader(new NormalizingSaxFilter(sf.newSAXParser().getXMLReader()));
            Transformer t = tf.newTransformer();
            StAXResult result = new StAXResult(writer);
            t.transform(saxSource, result);
        }
        return buffer.toByteArray();
    } catch (TransformerException | XMLStreamException | FactoryConfigurationError | ParserConfigurationException | SAXException ex) {
        throw new IOException(ex);
    }
}
 
Example 13
Source File: UrlRewriteRulesDescriptorAdapter.java    From knox with Apache License 2.0 5 votes vote down vote up
private static InputStream nodeToInputStream(Node node) throws Exception {
  try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    transformerFactory.newTransformer().transform(new DOMSource(node), new StreamResult(outputStream));
    return new ByteArrayInputStream(outputStream.toByteArray());
  }
}
 
Example 14
Source File: XmlUtil.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public static TransformerFactory newTransformerFactory(boolean secureXmlProcessingEnabled) {
    TransformerFactory factory = TransformerFactory.newInstance();
    try {
        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, isXMLSecurityDisabled(secureXmlProcessingEnabled));
    } catch (TransformerConfigurationException e) {
        LOGGER.log(Level.WARNING, "Factory [{0}] doesn't support secure xml processing!", new Object[]{factory.getClass().getName()});
    }
    return factory;
}
 
Example 15
Source File: IdentityUtil.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Create TransformerFactory with the XXE and XEE prevention measurements.
 *
 * @return TransformerFactory instance
 */
public static TransformerFactory getSecuredTransformerFactory() {

    TransformerFactory trfactory = TransformerFactory.newInstance();
    try {
        trfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    } catch (TransformerConfigurationException e) {
        log.error("Failed to load XML Processor Feature " + XMLConstants.FEATURE_SECURE_PROCESSING +
                " for secure-processing.");
    }
    trfactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
    trfactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
    return trfactory;
}
 
Example 16
Source File: DomHelper.java    From mdw with Apache License 2.0 5 votes vote down vote up
public static InputStream toInputStream(Node domNode) throws TransformerException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    DOMSource xmlSource = new DOMSource(domNode);
    Result outputTarget = new StreamResult(outputStream);
    @SuppressWarnings("squid:S4435") // false positive
    TransformerFactory tFactory = TransformerFactory.newInstance();
    tFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    Transformer transformer = tFactory.newTransformer();
    transformer.transform(xmlSource, outputTarget);
    return new ByteArrayInputStream(outputStream.toByteArray());
}
 
Example 17
Source File: XmlBeanWrapper.java    From mdw with Apache License 2.0 5 votes vote down vote up
public String transform(String xslt) throws TransformerException {
    @SuppressWarnings("squid:S4435") // false positive
    TransformerFactory tFactory = TransformerFactory.newInstance();
    tFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

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

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

    return new String(outputStream.toByteArray());
}
 
Example 18
Source File: DomUtils.java    From teamengine with Apache License 2.0 5 votes vote down vote up
/** HELPER METHOD TO PRINT A DOM TO STDOUT */
static public void displayNode(Node node) {
    try {
        TransformerFactory TF = TransformerFactory.newInstance();
          // Fortify Mod: disable external entity injection
        TF.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        Transformer identity = TF.newTransformer();
 // End Fortify Mod
        identity.transform(new DOMSource(node),
                new StreamResult(System.out));
    } catch (Exception ex) {
        System.out.println("ERROR: " + ex.getMessage());
    }
}
 
Example 19
Source File: XMLParserFactoryProducer.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
public static TransformerFactory createSecureTransformerFactory() throws TransformerConfigurationException {
  TransformerFactory factory = TransformerFactory.newInstance();
  //using explicit string here because Sonar is still reporting a violation when using FEATURE_SECURE_PROCESSING
  factory.setFeature( "http://javax.xml.XMLConstants/feature/secure-processing", true );
  return factory;
}
 
Example 20
Source File: XMLValidatingParser.java    From teamengine with Apache License 2.0 4 votes vote down vote up
/**
 * Validates an XML resource against a list of DTD schemas or as indicated by a
 * DOCTYPE declaration. Validation errors are reported to the given handler. If
 * no DTD references are provided the external schema reference in the DOCTYPE
 * declaration is used (Note: an internal subset is ignored).
 * 
 * @param doc
 *            The input Document.
 * @param dtdList
 *            A list of DTD schema references. May be empty but not null.
 * @param errHandler
 *            An ErrorHandler that collects validation errors.
 * @throws Exception
 *             If any errors occur while attempting to validate the document.
 */
private void validateAgainstDTDList(Document doc, ArrayList<Object> dtdList,
		ErrorHandler errHandler) throws Exception {
	jlogger.finer("Validating XML resource from " + doc.getDocumentURI());
	DocumentBuilder db = dtdValidatingDBF.newDocumentBuilder();
	db.setErrorHandler(errHandler);
             // Fortify Mod: prevent external entity injection
         // includes try block to capture exceptions to setFeature.
	TransformerFactory tf = TransformerFactory.newInstance();
	try {
     	        tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
	    } catch (Exception e) {
	        jlogger.warning("Failed to secure Transformer");
	    }
	// End Fortify Mod
     Transformer copier = tf.newTransformer();
          ByteArrayOutputStream content = new ByteArrayOutputStream();
	Result copy = new StreamResult(content);
	if (dtdList.isEmpty()) {
		DocumentType doctype = doc.getDoctype();
		if (null == doctype) {
			return;
		}
		URI systemId = URI.create(doctype.getSystemId());
		if (!systemId.isAbsolute() && null != doc.getBaseURI()) {
			systemId = URI.create(doc.getBaseURI()).resolve(systemId);
		}
		copier.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,
				systemId.toString());
		copier.transform(new DOMSource(doc), copy);
		db.parse(new ByteArrayInputStream(content.toByteArray()));
	} else {
		for (Object dtdRef : dtdList) {
			content.reset();
			copier.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,
					dtdRef.toString());
			copier.transform(new DOMSource(doc), copy);
			db.parse(new ByteArrayInputStream(content.toByteArray()));
		}
	}
}