Java Code Examples for javax.xml.parsers.DocumentBuilderFactory#setExpandEntityReferences()

The following examples show how to use javax.xml.parsers.DocumentBuilderFactory#setExpandEntityReferences() . 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: DavServlet.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * Return JAXP document builder instance.
 */
protected DocumentBuilder getDocumentBuilder() throws ServletException
{
	DocumentBuilder documentBuilder = null;
	DocumentBuilderFactory documentBuilderFactory = null;
	try
	{
		documentBuilderFactory =
			DocumentBuilderFactory.newInstance();
		documentBuilderFactory.setNamespaceAware(true);
		documentBuilderFactory.setExpandEntityReferences(false);
		documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false); 
		documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); 

		documentBuilder =
			documentBuilderFactory.newDocumentBuilder();
	}
	catch (ParserConfigurationException e)
	{
		throw new ServletException("Sakaidavservlet.jaxpfailed");
	}
	return documentBuilder;
}
 
Example 2
Source File: EntitlementUtil.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * * This method provides a secured document builder which will secure XXE attacks.
 *
 * @param setIgnoreComments whether to set setIgnoringComments in DocumentBuilderFactory.
 * @return DocumentBuilder
 * @throws ParserConfigurationException
 */
private static DocumentBuilder getSecuredDocumentBuilder(boolean setIgnoreComments) throws
        ParserConfigurationException {

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setIgnoringComments(setIgnoreComments);
    documentBuilderFactory.setNamespaceAware(true);
    documentBuilderFactory.setExpandEntityReferences(false);
    documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    documentBuilderFactory.setFeature(EXTERNAL_GENERAL_ENTITIES_URI, false);
    SecurityManager securityManager = new SecurityManager();
    securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT);
    documentBuilderFactory.setAttribute(SECURITY_MANAGER_PROPERTY, securityManager);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    documentBuilder.setEntityResolver(new CarbonEntityResolver());
    return documentBuilder;

}
 
Example 3
Source File: TaskUtils.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
public static Document convertToDocument(File file) throws TaskException {
    DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
    fac.setNamespaceAware(true);
    fac.setXIncludeAware(false);
    fac.setExpandEntityReferences(false);
    try {
        fac.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE, false);
        fac.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE, false);
        fac.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE, false);
        SecurityManager securityManager = new SecurityManager();
        securityManager.setEntityExpansionLimit(0);
        fac.setAttribute(Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY, securityManager);
        return fac.newDocumentBuilder().parse(file);
    } catch (Exception e) {
        throw new TaskException("Error in creating an XML document from file: "
                + e.getMessage(), Code.CONFIG_ERROR, e);
    }
}
 
Example 4
Source File: Wxs.java    From nutzwx with Apache License 2.0 6 votes vote down vote up
public static DocumentBuilder xmls()
        throws ParserConfigurationException, SAXException, IOException {
    // 修复XXE form
    // https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=23_5
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    String FEATURE = null;
    FEATURE = "http://apache.org/xml/features/disallow-doctype-decl";
    factory.setFeature(FEATURE, true);
    FEATURE = "http://xml.org/sax/features/external-general-entities";
    factory.setFeature(FEATURE, false);
    FEATURE = "http://xml.org/sax/features/external-parameter-entities";
    factory.setFeature(FEATURE, false);
    FEATURE = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
    factory.setFeature(FEATURE, false);
    factory.setXIncludeAware(false);
    factory.setExpandEntityReferences(false);
    return factory.newDocumentBuilder();
}
 
Example 5
Source File: Bug6794483Test.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public Document parseXmlFile(String fileName) throws Exception {
    System.out.println("Parsing XML file... " + fileName);
    DocumentBuilder docBuilder = null;
    Document doc = null;
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setCoalescing(true);
    docBuilderFactory.setXIncludeAware(true);
    System.out.println("Include: " + docBuilderFactory.isXIncludeAware());
    docBuilderFactory.setNamespaceAware(true);
    docBuilderFactory.setExpandEntityReferences(true);

    docBuilder = docBuilderFactory.newDocumentBuilder();

    File sourceFile = new File(fileName);
    doc = docBuilder.parse(sourceFile);

    System.out.println("XML file parsed");
    return doc;

}
 
Example 6
Source File: InMemoryPersistenceManager.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * * This method provides a secured document builder which will secure XXE attacks.
 *
 * @return DocumentBuilder
 * @throws ParserConfigurationException
 */
private DocumentBuilder getSecuredDocumentBuilder() throws ParserConfigurationException {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    documentBuilderFactory.setExpandEntityReferences(false);
    documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    documentBuilderFactory.setFeature(EXTERNAL_GENERAL_ENTITIES_URI, false);
    SecurityManager securityManager = new SecurityManager();
    securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT);
    documentBuilderFactory.setAttribute(SECURITY_MANAGER_PROPERTY, securityManager);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    documentBuilder.setEntityResolver(new CarbonEntityResolver());
    return documentBuilder;
}
 
Example 7
Source File: XmlHelper.java    From openmeetings with Apache License 2.0 5 votes vote down vote up
public static DocumentBuilder createBuilder() throws ParserConfigurationException {
	DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
	dbFactory.setFeature(NO_DOCTYPE, true);
	dbFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
	dbFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
	dbFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
	dbFactory.setXIncludeAware(false);
	dbFactory.setExpandEntityReferences(false);
	return dbFactory.newDocumentBuilder();
}
 
Example 8
Source File: DocumentBuilderSafeProperty.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void unsafeManualConfig1() throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    //dbf.setFeature("http://xml.org/sax/features/external-general-entities",true);
    dbf.setFeature("http://xml.org/sax/features/external-parameter-entities",true);
    dbf.setXIncludeAware(false);
    dbf.setExpandEntityReferences(false);
    DocumentBuilder db = dbf.newDocumentBuilder();

    Document doc = db.parse(getInputFile());
    print(doc);
}
 
Example 9
Source File: Profile.java    From geoportal-server-harvester with Apache License 2.0 5 votes vote down vote up
@Override
public String generateCSWGetRecordsRequest(ICriteria criteria) {
  String internalRequestXml = createInternalXmlRequest(criteria);
  try (
          ByteArrayInputStream internalRequestInputStream = new ByteArrayInputStream(internalRequestXml.getBytes("UTF-8"));
          InputStream reqXsltInputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(Constants.CONFIG_FOLDER_PATH + "/" + getGetRecordsReqXslt())) {
    
    // create internal request DOM
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
    builderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
    builderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    builderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    builderFactory.setXIncludeAware(false);
    builderFactory.setExpandEntityReferences(false);
    builderFactory.setNamespaceAware(true);
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Document internalRequestDOM = builder.parse(new InputSource(internalRequestInputStream));

    // create transformer
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Templates template = transformerFactory.newTemplates(new StreamSource(reqXsltInputStream));
    Transformer transformer = template.newTransformer();
    
    // perform transformation
    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(internalRequestDOM), new StreamResult(writer));
    
    return writer.toString();
  } catch (Exception ex) {
    LOG.warn("Error creating CSW get records request.", ex);
    return "";
  }
}
 
Example 10
Source File: EntitiesTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
private Set<String> getMappedResources() {
    try {
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        docBuilderFactory.setValidating(false);
        docBuilderFactory.setNamespaceAware(false);
        docBuilderFactory.setExpandEntityReferences(false);
        docBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        docBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document document = docBuilder.parse(this.getClass().getClassLoader().getResourceAsStream(AppEngineConfiguration.DEFAULT_MYBATIS_MAPPING_FILE));
        Set<String> resources = new HashSet<>();
        NodeList nodeList = document.getElementsByTagName("mapper");
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            String resource = node.getAttributes().getNamedItem("resource").getTextContent();
            if (resource.startsWith("org/flowable/app") && !resource.contains("common.xml")) {
                resource = resource.replaceAll("org/flowable/app/db/mapping/entity/", "");
                resource = resource.replaceAll(".xml", "");
                resources.add(resource);
            }
        }
        
        resources.remove("TableData"); // not an entity
        
        assertThat(resources.size()).isPositive();
        return resources;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 11
Source File: MegaMekXmlUtil.java    From megamek with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a DocumentBuilder safe from XML external entities
 * attacks, and XML entity expansion attacks.
 * @return A DocumentBuilder safe to use to read untrusted XML.
 */
public static DocumentBuilder newSafeDocumentBuilder() throws ParserConfigurationException {
	DocumentBuilderFactory dbf = DOCUMENT_BUILDER_FACTORY;
	if (null == dbf) {
		// At worst we may do this twice if multiple threads
		// hit this method. It is Ok to have more than one
		// instance of the builder factory, as long as it is
		// XXE safe.
		dbf = DocumentBuilderFactory.newInstance();

		//
		// Adapted from: https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet#JAXP_DocumentBuilderFactory.2C_SAXParserFactory_and_DOM4J
		//
		// "...The JAXP DocumentBuilderFactory setFeature method allows a
		// developer to control which implementation-specific XML processor
		// features are enabled or disabled. The features can either be set
		// on the factory or the underlying XMLReader setFeature method. 
		// Each XML processor implementation has its own features that 
		// govern how DTDs and external entities are processed."
		//
		// "[disable] these as well, per Timothy Morgan's 2014 paper: 'XML 
		// Schema, DTD, and Entity Attacks'"
		dbf.setXIncludeAware(false);
		dbf.setExpandEntityReferences(false);

		// "This is the PRIMARY defense. If DTDs (doctypes) are disallowed,
		// almost all XML entity attacks are prevented"
		String FEATURE = "http://apache.org/xml/features/disallow-doctype-decl";
		dbf.setFeature(FEATURE, true);

		DOCUMENT_BUILDER_FACTORY = dbf;
	}

	return dbf.newDocumentBuilder();
}
 
Example 12
Source File: DocumentBuilderFactoryTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Test the setExpandEntityReferences.
 * @throws Exception If any errors occur.
 */
@Test
public void testCheckDocumentBuilderFactory08() throws Exception {
    try (FileInputStream fis = new FileInputStream(new File(
            XML_DIR, "DocumentBuilderFactory02.xml"))) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setExpandEntityReferences(false);
        DocumentBuilder docBuilder = dbf.newDocumentBuilder();
        Document doc = docBuilder.parse(fis);
        Element e = (Element) doc.getElementsByTagName("title").item(0);
        NodeList nl = e.getChildNodes();
        assertNull(nl.item(0).getNodeValue());
    }
}
 
Example 13
Source File: PaymentFactory.java    From MicroCommunity with Apache License 2.0 5 votes vote down vote up
/**
     * Map转换为 Xml
     *
     * @return Xml
     * @throws Exception
     */
    public static String mapToXml(SortedMap<String, String> map) throws Exception {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
//防止XXE攻击
        documentBuilderFactory.setXIncludeAware(false);
        documentBuilderFactory.setExpandEntityReferences(false);
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        org.w3c.dom.Document document = documentBuilder.newDocument();
        org.w3c.dom.Element root = document.createElement("xml");
        document.appendChild(root);
        for (String key : map.keySet()) {
            String value = map.get(key);
            if (value == null) {
                value = "";
            }
            value = value.trim();
            org.w3c.dom.Element filed = document.createElement(key);
            filed.appendChild(document.createTextNode(value));
            root.appendChild(filed);
        }
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        DOMSource source = new DOMSource(document);
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        transformer.transform(source, result);
        String output = writer.getBuffer().toString();
        try {
            writer.close();
        } catch (Exception ex) {
        }
        return output;
    }
 
Example 14
Source File: XMLUtil.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
private static DocumentBuilderFactory getDocumentBuilderFactory() throws ParserConfigurationException {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setAttribute(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    documentBuilderFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
    documentBuilderFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
    for (String feature : DISABLED_FEATURES) {
        documentBuilderFactory.setFeature(feature, false);
    }
    documentBuilderFactory.setXIncludeAware(false);
    documentBuilderFactory.setExpandEntityReferences(false);
    return documentBuilderFactory;
}
 
Example 15
Source File: XMLHelper.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a new DocumentBuilderFactory, with sensible defaults
 */
public static DocumentBuilderFactory getDocumentBuilderFactory() {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setExpandEntityReferences(false);
    trySetSAXFeature(factory, XMLConstants.FEATURE_SECURE_PROCESSING, true);
    trySetSAXFeature(factory, "http://xml.org/sax/features/external-general-entities", false);
    trySetSAXFeature(factory, "http://xml.org/sax/features/external-parameter-entities", false);
    trySetSAXFeature(factory, "http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    trySetSAXFeature(factory, "http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    return factory;
}
 
Example 16
Source File: QueryNodeXML.java    From Extractor with MIT License 5 votes vote down vote up
private DocumentBuilder getsafeDB() throws ParserConfigurationException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    String FEATURE = null;
    // This is the PRIMARY defense. If DTDs (doctypes) are disallowed, almost all XML entity attacks are prevented
    // Xerces 2 only - http://xerces.apache.org/xerces2-j/features.html#disallow-doctype-decl
    FEATURE = "http://apache.org/xml/features/disallow-doctype-decl";
    dbf.setFeature(FEATURE, true);

    // If you can't completely disable DTDs, then at least do the following:
    // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-general-entities
    // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-general-entities
    // JDK7+ - http://xml.org/sax/features/external-general-entities    
    FEATURE = "http://xml.org/sax/features/external-general-entities";
    dbf.setFeature(FEATURE, false);

    // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-parameter-entities
    // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-parameter-entities
    // JDK7+ - http://xml.org/sax/features/external-parameter-entities    
    FEATURE = "http://xml.org/sax/features/external-parameter-entities";
    dbf.setFeature(FEATURE, false);

    // Disable external DTDs as well
    FEATURE = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
    dbf.setFeature(FEATURE, false);

    // and these as well, per Timothy Morgan's 2014 paper: "XML Schema, DTD, and Entity Attacks"
    dbf.setXIncludeAware(false);
    dbf.setExpandEntityReferences(false);

    return dbf.newDocumentBuilder();
}
 
Example 17
Source File: XMLTypeValidator.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
/**
 * Safely create a DocumentBuilderFactory following OWASP best practises
 * @return DocumentBuilderFactory instance
 */
private static DocumentBuilderFactory createDocumentBuilderFactoryInstance() throws ParserConfigurationException {

  final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  String FEATURE;

  // This is the PRIMARY defense. If DTDs (doctypes) are disallowed, almost all XML entity attacks are prevented
  // Xerces 2 only - http://xerces.apache.org/xerces2-j/features.html#disallow-doctype-decl
  FEATURE = "http://apache.org/xml/features/disallow-doctype-decl";
  dbf.setFeature(FEATURE, true);

  // If you can't completely disable DTDs, then at least do the following:
  // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-general-entities
  // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-general-entities
  // JDK7+ - http://xml.org/sax/features/external-general-entities
  FEATURE = "http://xml.org/sax/features/external-general-entities";
  dbf.setFeature(FEATURE, false);

  // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-parameter-entities
  // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-parameter-entities
  // JDK7+ - http://xml.org/sax/features/external-parameter-entities
  FEATURE = "http://xml.org/sax/features/external-parameter-entities";
  dbf.setFeature(FEATURE, false);

  // Disable external DTDs as well
  FEATURE = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
  dbf.setFeature(FEATURE, false);

  // and these as well, per Timothy Morgan's 2014 paper: "XML Schema, DTD, and Entity Attacks"
  dbf.setXIncludeAware(false);
  dbf.setExpandEntityReferences(false);

  // And, per Timothy Morgan: "If for some reason support for inline DOCTYPEs are a requirement, then
  // ensure the entity settings are disabled (as shown above) and beware that SSRF attacks
  // (http://cwe.mitre.org/data/definitions/918.html) and denial
  // of service attacks (such as billion laughs or decompression bombs via "jar:") are a risk."

  return dbf;
}
 
Example 18
Source File: XMLUtil.java    From jdmn with Apache License 2.0 4 votes vote down vote up
public static DocumentBuilderFactory makeDocumentBuilderFactory() throws ParserConfigurationException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); // Compliant
    dbf.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); // compliant
    String feature = null;
    try {
        // This is the PRIMARY defense. If DTDs (doctypes) are disallowed, almost all
        // XML entity attacks are prevented
        // Xerces 2 only - http://xerces.apache.org/xerces2-j/features.html#disallow-doctype-decl
        feature = "http://apache.org/xml/features/disallow-doctype-decl";
        dbf.setFeature(feature, true);

        // If you can't completely disable DTDs, then at least do the following:
        // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-general-entities
        // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-general-entities
        // JDK7+ - http://xml.org/sax/features/external-general-entities
        feature = "http://xml.org/sax/features/external-general-entities";
        dbf.setFeature(feature, false);

        // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-parameter-entities
        // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-parameter-entities
        // JDK7+ - http://xml.org/sax/features/external-parameter-entities
        feature = "http://xml.org/sax/features/external-parameter-entities";
        dbf.setFeature(feature, false);

        // Disable external DTDs as well
        feature = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
        dbf.setFeature(feature, false);

        // and these as well, per Timothy Morgan's 2014 paper: "XML Schema, DTD, and Entity Attacks"
        dbf.setXIncludeAware(false);
        dbf.setExpandEntityReferences(false);

        // And, per Timothy Morgan: "If for some reason support for inline DOCTYPEs are a requirement, then
        // ensure the entity settings are disabled (as shown above) and beware that SSRF attacks
        // (http://cwe.mitre.org/data/definitions/918.html) and denial
        // of service attacks (such as billion laughs or decompression bombs via "jar:") are a risk."
    } catch (ParserConfigurationException e) {
        // This should catch a failed setFeature feature
        LOGGER.info("ParserConfigurationException was thrown. The feature '" + feature
                + "' is probably not supported by your XML processor.");
    }

    return dbf;
}
 
Example 19
Source File: Client.java    From geoportal-server-harvester with Apache License 2.0 4 votes vote down vote up
/**
 * Reads record from the stream
 *
 * @param contentStream content stream
 * @return list of records
 * @throws IOException if reading records fails
 * @throws TransformerConfigurationException if creating transformer fails
 * @throws TransformerException if creating transformer fails
 * @throws ParserConfigurationException if unable to create XML parser
 * @throws SAXException if unable to parse content
 * @throws XPathExpressionException if invalid XPath
 */
private List<IRecord> readRecords(InputStream contentStream) throws IOException, TransformerConfigurationException, TransformerException, ParserConfigurationException, SAXException, XPathExpressionException {
  ArrayList<IRecord> records = new ArrayList<>();

  // create transformer
  Templates template = TemplatesManager.getInstance().getTemplate(profile.getResponsexslt());
  Transformer transformer = template.newTransformer();

  // perform transformation
  StringWriter writer = new StringWriter();
  transformer.transform(new StreamSource(contentStream), new StreamResult(writer));
  
  LOG.trace(String.format("Received records:\n%s", writer.toString()));

  try (ByteArrayInputStream transformedContentStream = new ByteArrayInputStream(writer.toString().getBytes("UTF-8"))) {

    // create internal request DOM
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
    builderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
    builderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    builderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    builderFactory.setXIncludeAware(false);
    builderFactory.setExpandEntityReferences(false);
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Document resultDom = builder.parse(new InputSource(transformedContentStream));

    // create xpath
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();

    NodeList recordNodeList = (NodeList) xpath.evaluate("/Records/Record", resultDom, XPathConstants.NODESET);
    for (int i = 0; i < recordNodeList.getLength(); i++) {
      Node recordNode = recordNodeList.item(i);
      String id = (String) xpath.evaluate("ID", recordNode, XPathConstants.STRING);
      String strModifiedDate = (String) xpath.evaluate("ModifiedDate", recordNode, XPathConstants.STRING);
      Date modifedDate = parseIsoDate(strModifiedDate);
      IRecord record = new Record(id, modifedDate);
      records.add(record);
    }
  }

  return records;
}
 
Example 20
Source File: PolicyEditorService.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * Formats a given unformatted XML string
 *
 * @param xml
 * @return A CDATA wrapped, formatted XML String
 */
public String formatXML(String xml) {

    try {
        // create the factory
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setIgnoringComments(true);
        docFactory.setNamespaceAware(true);
        docFactory.setExpandEntityReferences(false);
        SecurityManager securityManager = new SecurityManager();
        securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT);
        docFactory.setAttribute(SECURITY_MANAGER_PROPERTY, securityManager);
        DocumentBuilder docBuilder;
        Document xmlDoc;

        // now use the factory to create the document builder
        docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        docFactory.setFeature(EXTERNAL_GENERAL_ENTITIES_URI, false);
        docBuilder = docFactory.newDocumentBuilder();
        docBuilder.setEntityResolver(new CarbonEntityResolver());
        xmlDoc = docBuilder.parse(new ByteArrayInputStream(xml.getBytes(Charsets.UTF_8)));


        OutputFormat format = new OutputFormat(xmlDoc);
        format.setLineWidth(0);
        format.setIndenting(true);
        format.setIndent(2);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        XMLSerializer serializer = new XMLSerializer(baos, format);
        serializer.serialize(xmlDoc);

        xml = baos.toString("UTF-8");

    } catch (ParserConfigurationException pce) {
        throw new IllegalArgumentException("Failed to parse the unformatted XML String. ", pce);
    } catch (Exception e) {
        log.error("Error occured while formtting the unformatted XML String. ", e);
    }

    return "<![CDATA[" + xml + "]]>";
}