Example usage for javax.xml.parsers DocumentBuilderFactory setFeature

List of usage examples for javax.xml.parsers DocumentBuilderFactory setFeature

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilderFactory setFeature.

Prototype

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

Source Link

Document

Set a feature for this DocumentBuilderFactory and DocumentBuilder s created by this factory.

Usage

From source file:org.hippoecm.frontend.plugins.gallery.imageutil.ScaleImageOperation.java

private void disableValidation(final DocumentBuilderFactory factory) throws ParserConfigurationException {
    factory.setNamespaceAware(false);//from w  w  w  .  j  a  va2  s  .c  o m
    factory.setValidating(false);
    factory.setFeature("http://xml.org/sax/features/namespaces", false);
    factory.setFeature("http://xml.org/sax/features/validation", false);
    factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
    factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
}

From source file:org.hippoecm.frontend.plugins.gallery.imageutil.ScaleImageOperationTest.java

@Test
public void scaleSvgAddsViewboxWhenMissing()
        throws GalleryException, IOException, ParserConfigurationException, SAXException {
    InputStream data = getClass().getResourceAsStream("/test-SVG-without-viewbox.svg");
    ScaleImageOperation scaleOp = new ScaleImageOperation(200, 100, true, ImageUtils.ScalingStrategy.SPEED);
    scaleOp.execute(data, "image/svg+xml");

    InputStream scaledData = scaleOp.getScaledData();

    // read svg//from w w w .ja  va 2  s  .  c  o  m
    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(false);
    factory.setValidating(false);
    factory.setFeature("http://xml.org/sax/features/namespaces", false);
    factory.setFeature("http://xml.org/sax/features/validation", false);
    factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    final DocumentBuilder builder = factory.newDocumentBuilder();
    final Document svgDocument = builder.parse(scaledData);
    final Element svgElement = svgDocument.getDocumentElement();

    assertEquals("SVG without a 'viewBox' attribute should have gotten one set to the original image size",
            "0 0 178.0 145.0", svgElement.getAttribute("viewBox"));
}

From source file:org.icatproject.idav.methods.AbstractMethod.java

/**
 * Return JAXP document builder instance.
 *//*w w w. ja v a2 s . c  o m*/
protected DocumentBuilder getDocumentBuilder() throws ServletException {
    DocumentBuilder documentBuilder = null;
    DocumentBuilderFactory documentBuilderFactory = null;
    try {
        documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        // disable XML External Entities to prevent XML XXE attacks as described at:
        // https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet
        documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
        documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        documentBuilderFactory.setXIncludeAware(false);
        documentBuilderFactory.setExpandEntityReferences(false);
        //
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        String msg = "Failed to create an XML DocumentBuilder which satisfies the configuration requested: "
                + e.getMessage();
        LOG.error(msg);
        throw new ServletException(msg);
    }
    return documentBuilder;
}

From source file:org.jaggeryjs.modules.sso.common.util.Util.java

/**
 * Create DocumentBuilderFactory with the XXE prevention measurements
 *
 * @return DocumentBuilderFactory instance
 *//* w w  w  .  j  a v a  2  s  . c o  m*/
public static DocumentBuilderFactory getSecuredDocumentBuilder() {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setXIncludeAware(false);
    dbf.setExpandEntityReferences(false);
    try {
        dbf.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE, false);
        dbf.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE, false);
        dbf.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE, false);
    } catch (ParserConfigurationException e) {
        log.error("Failed to load XML Processor Feature " + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE + " or "
                + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE + " or " + Constants.LOAD_EXTERNAL_DTD_FEATURE);
    }

    SecurityManager securityManager = new SecurityManager();
    securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT);
    dbf.setAttribute(Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY, securityManager);

    return dbf;
}

From source file:org.jboss.dashboard.export.ImportManagerImpl.java

protected DocumentBuilder createDocumentBuilder() throws Exception {
    DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
    dFactory.setIgnoringComments(true);//from w  w  w  .j a  v a 2s .c  om

    // BZ-1211316: XXE/SSRF vulnerability
    dFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
    dFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    dFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);

    return dFactory.newDocumentBuilder();
}

From source file:org.jmingo.parser.xml.dom.DocumentBuilderFactoryCreator.java

/**
 * Creates DocumentBuilderFactory.//ww w . jav a 2  s  .  c o  m
 *
 * @param parserConfiguration {@link ParserConfiguration}
 * @return DocumentBuilderFactory a factory API that enables applications to obtain a
 *         parser that produces DOM object trees from XML documents
 * @throws ParserConfigurationException {@link ParserConfigurationException}
 */
public static DocumentBuilderFactory createDocumentBuilderFactory(ParserConfiguration parserConfiguration)
        throws ParserConfigurationException {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setValidating(parserConfiguration.isValidate());
    documentBuilderFactory.setNamespaceAware(parserConfiguration.isNamespaceAware());
    documentBuilderFactory.setFeature(ParserConstants.DYNAMIC_VALIDATION, true);
    List<Source> sourceList = createSchemaSources(parserConfiguration.getXsdSchemaPaths());
    if (CollectionUtils.isNotEmpty(sourceList)) {
        documentBuilderFactory.setSchema(createSchema(sourceList));
    }
    return documentBuilderFactory;
}

From source file:org.josso.tooling.gshell.install.installer.VFSInstaller.java

protected Document readContentAsDom(FileObject file, boolean nameSpaceAware) throws Exception {
    InputStream is = null;//  w  w w .j  a v a 2s .c o m

    try {
        is = file.getContent().getInputStream();

        DocumentBuilderFactory parserFactory = DocumentBuilderFactory.newInstance();
        parserFactory.setValidating(false);
        parserFactory.setNamespaceAware(nameSpaceAware);
        parserFactory.setIgnoringElementContentWhitespace(false);
        parserFactory.setIgnoringComments(false);

        DocumentBuilder builder = parserFactory.newDocumentBuilder();

        boolean dtdNotFound = false;
        Document doc = null;
        try {
            doc = builder.parse(is);
        } catch (FileNotFoundException e) {
            dtdNotFound = true;
        }

        // if dtd doesn't exist parse the document again without trying to load dtd
        if (dtdNotFound) {
            is = file.getContent().getInputStream();
            // disable dtd loading
            parserFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
            builder = parserFactory.newDocumentBuilder();
            doc = builder.parse(is);
        }

        DocumentType docType = doc.getDoctype();

        if (log.isDebugEnabled() && docType != null) {
            log.debug("docType.getPublicId()=" + docType.getPublicId());
            log.debug("docType.getSystemId()=" + docType.getSystemId());
        }

        return doc;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw e;
    } finally {
        if (is != null)
            try {
                is.close();
            } catch (IOException e) {
                /**/}
    }

}

From source file:org.kitodo.production.editor.XMLEditor.java

/**
 * Constructor./*from www .  ja  va  2s  .  co m*/
 */
public XMLEditor() {
    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        logger.error("ERROR: unable to instantiate document builder: " + e.getMessage());
    }
}

From source file:org.kitodo.production.plugin.importer.massimport.PicaMassImport.java

/**
 * Get OPAC address.//from   w w w  .ja va2  s.c o m
 *
 * @return the address of the opac catalogue
 */
private String getOpacAddress() throws ImportPluginException {

    String address;

    try (FileInputStream istream = new FileInputStream(KitodoConfigFile.OPAC_CONFIGURATION.getFile())) {

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

        DocumentBuilder builder = factory.newDocumentBuilder();

        Document xmlDocument = builder.parse(istream);

        XPath xPath = XPathFactory.newInstance().newXPath();

        Node node = (Node) xPath
                .compile("/opacCatalogues/catalogue[@title='" + this.getOpacCatalogue() + "']/config")
                .evaluate(xmlDocument, XPathConstants.NODE);

        address = node.getAttributes().getNamedItem("address").getNodeValue();

    } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) {
        logger.error(e.getMessage(), e);
        throw new ImportPluginException(e);
    }
    return address;
}

From source file:org.kitodo.production.services.data.ImportService.java

private Document transformXmlByXslt(String xmlString, File stylesheetFile) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {//from   ww  w .j  av  a 2  s . c  o m
        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    } catch (ParserConfigurationException e) {
        throw new IllegalArgumentException(e.getMessage(), e);
    }
    factory.setNamespaceAware(true);
    try {
        SAXBuilder saxBuilder = new SAXBuilder();
        DOMOutputter outputter = new DOMOutputter();
        StreamSource transformSource = new StreamSource(stylesheetFile);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        File outputFile = File.createTempFile("transformed", "xml");
        try (FileOutputStream outputStream = new FileOutputStream(outputFile)) {
            Transformer xsltTransformer = transformerFactory.newTransformer(transformSource);
            TransformerHandler handler = ((SAXTransformerFactory) SAXTransformerFactory.newInstance())
                    .newTransformerHandler();
            handler.setResult(new StreamResult(outputStream));
            Result saxResult = new SAXResult(handler);
            SAXSource saxSource = new SAXSource(new InputSource(new StringReader(xmlString)));
            xsltTransformer.transform(saxSource, saxResult);
        }
        return outputter.output(saxBuilder.build(outputFile));
    } catch (JDOMException | IOException | TransformerException e) {
        throw new ConfigException("Error in transforming the response in intern format : ", e);
    }
}