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.eclipse.lyo.testsuite.server.util.OSLCUtils.java

public static Document createXMLDocFromResponseBody(String respBody)
        throws ParserConfigurationException, IOException, SAXException {
    //Create XML Doc out of response
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);/*from   ww w. j  av  a 2  s . c  o  m*/
    dbf.setValidating(false);
    // Don't load external DTD
    dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(respBody));
    return db.parse(is);
}

From source file:hydrograph.ui.common.util.XMLUtil.java

/**
 * //w w  w .j  a  v a2  s. co m
 * Convert XML string to {@link Document}
 * 
 * @param xmlString
 * @return {@link Document}
 */
public static Document convertStringToDocument(String xmlString) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    try {
        factory.setFeature(Constants.DISALLOW_DOCTYPE_DECLARATION, true);
        builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new InputSource(new StringReader(xmlString)));

        return doc;
    } catch (ParserConfigurationException | SAXException | IOException e) {
        logger.debug("Unable to convert string to Document", e);
    }
    return null;
}

From source file:com.google.enterprise.adaptor.experimental.Sim.java

/** Find all record urls in Adaptor created XML metadata-and-url feed file. */
static Set<URL> extractUrls(String xml) throws SAXException, ParserConfigurationException, BadFeed {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    /* to avoid blowing up on doctype line:
     * http://stackoverflow.com/questions/155101/make-documentbuilder-parse-ignore-dtd-references */
    dbf.setValidating(false);/*from   ww w. jav a  2s .c  om*/
    dbf.setFeature("http://xml.org/sax/features/namespaces", false);
    dbf.setFeature("http://xml.org/sax/features/validation", false);
    dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputStream xmlStream = new ByteArrayInputStream(xml.getBytes(UTF8));
    Document doc;
    try {
        doc = db.parse(xmlStream);
    } catch (IOException ie) {
        throw new BadFeed(ie.getMessage());
    }
    doc.getDocumentElement().normalize();
    NodeList nodes = doc.getElementsByTagName("record");
    Set<URL> tmpUrls = new HashSet<URL>();
    for (int i = 0; i < nodes.getLength(); i++) {
        Element element = (Element) nodes.item(i);
        String url = element.getAttribute("url");
        if (null == url || url.trim().isEmpty()) {
            throw new BadFeed("record without url attribute");
        } else {
            try {
                tmpUrls.add(new URL(url));
            } catch (MalformedURLException male) {
                throw new BadFeed("record with bad url attribute: " + url);
            }
        }
        log.info("accepting url: " + url);
    }
    return tmpUrls;
}

From source file:com.puppycrawl.tools.checkstyle.AllChecksTest.java

/**
 * Gets a set of names of checkstyle's checks which are referenced in checkstyle_checks.xml.
 * @param configFilePath file path of checkstyle_checks.xml.
 * @return names of checkstyle's checks which are referenced in checkstyle_checks.xml.
 * @throws ParserConfigurationException if a DocumentBuilder cannot be created which satisfies the configuration requested.
 * @throws IOException if any IO errors occur.
 * @throws SAXException if any parse errors occur.
 *//* w ww.j ava  2  s . c  o  m*/
private static Set<String> getCheckStyleChecksReferencedInConfig(String configFilePath)
        throws ParserConfigurationException, IOException, SAXException {

    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    // Validations of XML file make parsing too slow, that is why we disable all validations.
    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 document = builder.parse(new File(configFilePath));

    // optional, but recommended
    // FYI: http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
    document.getDocumentElement().normalize();

    final NodeList nodeList = document.getElementsByTagName("module");

    Set<String> checksReferencedInCheckstyleChecksXML = new HashSet<>();
    for (int i = 0; i < nodeList.getLength(); i++) {
        final Node currentNode = nodeList.item(i);
        if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
            final Element module = (Element) currentNode;
            final String checkName = module.getAttribute("name");
            if (!"Checker".equals(checkName) && !"TreeWalker".equals(checkName)
                    && !"SuppressionFilter".equals(checkName)) {
                checksReferencedInCheckstyleChecksXML.add(checkName);
            }
        }
    }
    return checksReferencedInCheckstyleChecksXML;
}

From source file:com.puppycrawl.tools.checkstyle.AllChecksTest.java

/**
 * Gets names of checkstyle's modules which are documented in xdocs.
 * @param xdocsDirectoryPath xdocs directory path.
 * @return a set of checkstyle's modules which have xdoc documentation.
 * @throws ParserConfigurationException if a DocumentBuilder cannot be created which satisfies the configuration requested.
 * @throws IOException if any IO errors occur.
 * @throws SAXException if any parse errors occur.
 *//*from  www  . j  a v a  2 s  . co m*/
private static Set<String> getModulesNamesWhichHaveXdoc(String xdocsDirectoryPath)
        throws ParserConfigurationException, IOException, SAXException {

    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    // Validations of XML file make parsing too slow, that is why we disable all validations.
    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 Set<Path> xdocsFilePaths = getXdocsFilePaths(xdocsDirectoryPath);
    final Set<String> modulesNamesWhichHaveXdoc = new HashSet<>();

    for (Path path : xdocsFilePaths) {
        final DocumentBuilder builder = factory.newDocumentBuilder();
        final Document document = builder.parse(path.toFile());

        // optional, but recommended
        // FYI: http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
        document.getDocumentElement().normalize();

        final NodeList nodeList = document.getElementsByTagName("section");

        for (int i = 0; i < nodeList.getLength(); i++) {
            final Node currentNode = nodeList.item(i);
            if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
                final Element module = (Element) currentNode;
                final String moduleName = module.getAttribute("name");
                if (!"Content".equals(moduleName) && !"Overview".equals(moduleName)) {
                    modulesNamesWhichHaveXdoc.add(moduleName);
                }
            }
        }
    }
    return modulesNamesWhichHaveXdoc;
}

From source file:io.cloudslang.content.xml.utils.XmlUtils.java

public static void setFeatures(DocumentBuilderFactory reader, String features)
        throws ParserConfigurationException {
    if (StringUtils.isNotBlank(features)) {
        Map featuresMap = parseFeatures(features);

        for (Object o : featuresMap.keySet()) {
            String key = (String) o;
            reader.setFeature(key, (Boolean) featuresMap.get(key));
        }/*  www. j a va 2s  . c o  m*/
    }

}

From source file:Main.java

/**
 * Configures a {@link DocumentBuilderFactory} to protect it against XML
 * External Entity attacks./*from ww  w  .j  ava2 s.  c  o  m*/
 * @param factory the factory
 * @see <a href=
 * "https://www.owasp.org/index.php/XML_External_Entity_%28XXE%29_Prevention_Cheat_Sheet#Java">
 * XXE Cheat Sheet</a>
 */
public static void applyXXEProtection(DocumentBuilderFactory factory) {
    Map<String, Boolean> features = new HashMap<String, Boolean>();
    features.put("http://apache.org/xml/features/disallow-doctype-decl", true);
    features.put("http://xml.org/sax/features/external-general-entities", false);
    features.put("http://xml.org/sax/features/external-parameter-entities", false);
    features.put("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

    for (Map.Entry<String, Boolean> entry : features.entrySet()) {
        String feature = entry.getKey();
        Boolean value = entry.getValue();
        try {
            factory.setFeature(feature, value);
        } catch (ParserConfigurationException e) {
            //feature is not supported by the local XML engine, skip it
        }
    }

    factory.setXIncludeAware(false);
    factory.setExpandEntityReferences(false);
}

From source file:com.netsteadfast.greenstep.base.action.BaseSupportAction.java

private static Map<String, String> loadStrutsConstants(InputStream is) throws Exception {
    if (loadStrutsSettingConstatns != null) {
        return loadStrutsSettingConstatns;
    }/*  www  . j  a v a 2s  .c o m*/
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setFeature("http://xml.org/sax/features/validation", false);
    dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
    dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    dbf.setValidating(false);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(is);
    NodeList nodes = doc.getElementsByTagName("constant");
    loadStrutsSettingConstatns = new HashMap<String, String>();
    for (int i = 0; nodes != null && i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        Element nodeElement = (Element) node;
        loadStrutsSettingConstatns.put(nodeElement.getAttribute("name"), nodeElement.getAttribute("value"));
    }
    return loadStrutsSettingConstatns;
}

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

/**
 * Constructs a DocumentBuilder object for XML documents
 *
 * @return DocumentBuilder object with the proper initializations
 *//*from ww  w.j a  v a 2s  .co m*/
public static DocumentBuilder generateDocumentBuilder() {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setIgnoringElementContentWhitespace(true);
        dbf.setIgnoringComments(true);
        dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
        dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        return dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        logger.error("ParserConfigurationException when attempting to generate a document builder.");
    }
    return null;
}

From source file:com.github.anba.es6draft.util.Resources.java

/**
 * Reads the xml-structure from {@link Reader} and returns the corresponding {@link Document}.
 *//*from ww  w  . j  av  a 2s.c  om*/
public static Document xml(Reader xml) throws IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    // turn off any validation or namespace features
    factory.setNamespaceAware(false);
    factory.setValidating(false);
    List<String> features = Arrays.asList("http://xml.org/sax/features/namespaces",
            "http://xml.org/sax/features/validation",
            "http://apache.org/xml/features/nonvalidating/load-dtd-grammar",
            "http://apache.org/xml/features/nonvalidating/load-external-dtd");
    for (String feature : features) {
        try {
            factory.setFeature(feature, false);
        } catch (ParserConfigurationException e) {
            // ignore invalid feature names
        }
    }

    try {
        return factory.newDocumentBuilder().parse(new InputSource(xml));
    } catch (ParserConfigurationException | SAXException e) {
        throw new IOException(e);
    }
}