Example usage for javax.xml.transform TransformerFactory setFeature

List of usage examples for javax.xml.transform TransformerFactory setFeature

Introduction

In this page you can find the example usage for javax.xml.transform TransformerFactory setFeature.

Prototype

public abstract void setFeature(String name, boolean value) throws TransformerConfigurationException;

Source Link

Document

Set a feature for this TransformerFactory and Transformer s or Template s created by this factory.

Usage

From source file:Main.java

/**
 * potentially unsafe XML transformation.
 * @param source The XML input to transform.
 * @param out The Result of transforming the <code>source</code>.
 *//*from  w  w w  . j  a v  a2 s  .c  o m*/
private static void _transform(Source source, Result out) throws TransformerException {
    TransformerFactory factory = TransformerFactory.newInstance();
    factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

    // this allows us to use UTF-8 for storing data,
    // plus it checks any well-formedness issue in the submitted data.
    Transformer t = factory.newTransformer();
    t.transform(source, out);
}

From source file:Main.java

private static TransformerFactory newTransformerFactory() throws TransformerConfigurationException {
    TransformerFactory factory = TransformerFactory.newInstance();
    factory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);

    return factory;
}

From source file:Main.java

public static Transformer getTransformer(boolean standalone, boolean indent, int indentNumber,
        boolean omitXmlDeclaration) throws TransformerException {
    TransformerFactory f = TransformerFactory.newInstance();
    f.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
    if (indent) {
        f.setAttribute("indent-number", indentNumber);
    }// w  ww  . j a  va2s .  c  om

    Transformer t = f.newTransformer();
    if (standalone) {
        t.setOutputProperty(OutputKeys.STANDALONE, "yes");
    }
    if (indent) {
        t.setOutputProperty(OutputKeys.INDENT, "yes");
        t.setOutputProperty("{xml.apache.org/xslt}indent-amount", "" + indentNumber);
    }
    if (omitXmlDeclaration) {
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    }

    return t;
}

From source file:Main.java

/**
 * Writes  XML Document into an xml file.
 * // ww w. j  a v a2s .  c  o m
 * @param fileName  the target file with the full path
 * @param document   the source document
 * @return   boolean true if the file saved
 * @throws Exception
 */
public static boolean writeXmlFile(String fileName, Document document) throws Exception {

    // creating and writing to xml file  

    File file = new File(fileName);

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); // to prevent XML External Entities attack

    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    transformer.transform(new DOMSource(document), new StreamResult(file));

    return true;

}

From source file:Main.java

/**
 * Executes a transformation./*from w ww .  jav  a 2 s. co  m*/
 * <br>The output encoding is set to UTF-8
 * @param source the transformation source
 * @param result the transformation result
 * @param indent if true, the output indent key is set to "yes"
 * @throws TransformerException if an exception occurs
 */
public static void transform(javax.xml.transform.Source source, javax.xml.transform.Result result,
        boolean indent) throws TransformerException {
    TransformerFactory factory = TransformerFactory.newInstance();
    factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
    factory.setFeature("http://javax.xml.XMLConstants/feature/secure-processing", true);
    //factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl",true); 
    Transformer transformer = factory.newTransformer();
    transformer.setOutputProperty(OutputKeys.ENCODING, DEFAULT_ENCODING);
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    if (indent) {
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    }
    transformer.transform(source, result);
}

From source file:com.bcmcgroup.flare.client.ClientUtil.java

/**
 * Convert a Document into a String// www. j  a  v  a2s.c om
 *
 * @param document           the Document to be converted to String
 * @param omitXmlDeclaration set to true if you'd like to omit the XML declaration, false otherwise
 * @return the String converted from a Document
 *
 */
public static String convertDocumentToString(Document document, boolean omitXmlDeclaration) {
    try {
        StringWriter stringWriter = new StringWriter();
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        Transformer transformer = transformerFactory.newTransformer();
        if (omitXmlDeclaration) {
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        } else {
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        }
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.INDENT, "no");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
        return stringWriter.toString();
    } catch (TransformerException e) {
        logger.error("Transformer Exception when attempting to convert a document to a string. ");
    }
    return null;
}

From source file:eu.europa.esig.dss.DSSXMLUtils.java

public static TransformerFactory getSecureTransformerFactory() {
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    try {/*from www . j a va 2s.  c om*/
        transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    } catch (TransformerConfigurationException e) {
        throw new DSSException(e);
    }
    return transformerFactory;
}

From source file:com.adaptris.util.text.xml.XmlTransformerFactoryImpl.java

TransformerFactory configure(TransformerFactory tf) throws TransformerConfigurationException {
    for (KeyValuePair kp : getTransformerFactoryAttributes()) {
        tf.setAttribute(kp.getKey(), kp.getValue());
    }// w  w w  .j a va2s.  c o  m
    for (KeyValuePair kp : getTransformerFactoryFeatures()) {
        tf.setFeature(kp.getKey(), BooleanUtils.toBoolean(kp.getValue()));
    }
    tf.setErrorListener(new DefaultErrorListener(failOnRecoverableError()));
    return tf;
}

From source file:org.apache.nifi.processors.standard.TransformXml.java

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(/*from   w  w w. j a  v  a2 s  .c om*/
                "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.");
        }
    }
}

From source file:org.apache.syncope.core.logic.init.CamelRouteLoader.java

private void loadRoutes(final String domain, final DataSource dataSource, final Resource resource,
        final AnyTypeKind anyTypeKind) {

    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    boolean shouldLoadRoutes = jdbcTemplate.queryForList(
            String.format("SELECT * FROM %s WHERE ANYTYPEKIND = ?", CamelRoute.class.getSimpleName()),
            new Object[] { anyTypeKind.name() }).isEmpty();

    if (shouldLoadRoutes) {
        try {//from www.j a va2 s  . c  o  m
            TransformerFactory tf = null;
            DOMImplementationLS domImpl = null;
            NodeList routeNodes;
            if (IS_JBOSS) {
                tf = TransformerFactory.newInstance();
                tf.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                dbFactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document doc = dBuilder.parse(resource.getInputStream());

                routeNodes = doc.getDocumentElement().getElementsByTagName("route");
            } else {
                DOMImplementationRegistry reg = DOMImplementationRegistry.newInstance();
                domImpl = (DOMImplementationLS) reg.getDOMImplementation("LS");
                LSInput lsinput = domImpl.createLSInput();
                lsinput.setByteStream(resource.getInputStream());

                LSParser parser = domImpl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);

                routeNodes = parser.parse(lsinput).getDocumentElement().getElementsByTagName("route");
            }

            for (int s = 0; s < routeNodes.getLength(); s++) {
                Node routeElement = routeNodes.item(s);
                String routeContent = IS_JBOSS ? nodeToString(routeNodes.item(s), tf)
                        : nodeToString(routeNodes.item(s), domImpl);
                String routeId = ((Element) routeElement).getAttribute("id");

                jdbcTemplate.update(
                        String.format("INSERT INTO %s(ID, ANYTYPEKIND, CONTENT) VALUES (?, ?, ?)",
                                CamelRoute.class.getSimpleName()),
                        new Object[] { routeId, anyTypeKind.name(), routeContent });
                LOG.info("[{}] Route successfully loaded: {}", domain, routeId);
            }
        } catch (Exception e) {
            LOG.error("[{}] Route load failed", domain, e);
        }
    }
}