Example usage for javax.xml.parsers DocumentBuilder setEntityResolver

List of usage examples for javax.xml.parsers DocumentBuilder setEntityResolver

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilder setEntityResolver.

Prototype


public abstract void setEntityResolver(EntityResolver er);

Source Link

Document

Specify the EntityResolver to be used to resolve entities present in the XML document to be parsed.

Usage

From source file:org.wso2.carbon.utils.CarbonUtils.java

/**
 *
 * @param xmlConfiguration InputStream that carries xml configuration
 * @return returns a InputStream that has evaluated system variables in input
 * @throws CarbonException//from w  ww .j  a v a 2s .  com
 */
public static InputStream replaceSystemVariablesInXml(InputStream xmlConfiguration) throws CarbonException {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder;
    Document doc;
    try {
        documentBuilderFactory.setNamespaceAware(true);
        documentBuilderFactory.setExpandEntityReferences(false);
        documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        SecurityManager securityManager = new SecurityManager();
        securityManager.setEntityExpansionLimit(CarbonConstants.ENTITY_EXPANSION_LIMIT_0);
        documentBuilderFactory.setAttribute(CarbonConstants.SECURITY_MANAGER_PROPERTY, securityManager);
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        documentBuilder.setEntityResolver(new CarbonEntityResolver());
        doc = documentBuilder.parse(xmlConfiguration);
    } catch (Exception e) {
        throw new CarbonException("Error in building Document", e);
    }
    NodeList nodeList = null;
    if (doc != null) {
        nodeList = doc.getElementsByTagName("*");
    }
    if (nodeList != null) {
        for (int i = 0; i < nodeList.getLength(); i++) {
            resolveLeafNodeValue(nodeList.item(i));
        }
    }
    return toInputStream(doc);
}

From source file:org.wso2.identity.iml.dsl.mediators.SAMLRequestProcessor.java

private AuthnRequest SAMLRequestParser(String samlRequest) throws ParserConfigurationException, SAXException,
        ConfigurationException, IOException, UnmarshallingException {

    IMLUtils.doBootstrap();/*w w w .  ja v  a  2s.  co  m*/
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    documentBuilderFactory.setExpandEntityReferences(false);
    documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

    org.apache.xerces.util.SecurityManager securityManager = new SecurityManager();
    securityManager.setEntityExpansionLimit(0);

    documentBuilderFactory.setAttribute(SECURITY_MANAGER_PROPERTY, securityManager);
    DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
    docBuilder.setEntityResolver((publicId, systemId) -> {
        throw new SAXException(
                "SAML request contains invalid elements. Possible XML External Entity " + "(XXE) attack.");
    });

    try (InputStream inputStream = new ByteArrayInputStream(
            samlRequest.trim().getBytes(StandardCharsets.UTF_8))) {

        Document document = docBuilder.parse(inputStream);
        Element element = document.getDocumentElement();

        UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);

        AuthnRequest authnRequest = (AuthnRequest) unmarshaller.unmarshall(element);
        return authnRequest;
    }

}

From source file:org.xwiki.wysiwyg.internal.plugin.alfresco.server.DefaultAlfrescoTokenManager.java

/**
 * Parses the given XML input stream.// ww w. j  a  va 2 s .c  o  m
 *
 * @param xml the XML stream to be parsed
 * @return the DOM document corresponding to the XML input stream
 */
private Document parseXML(InputStream xml) {
    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        documentBuilder.setEntityResolver(entityResolver);
        return documentBuilder.parse(xml);
    } catch (Exception e) {
        throw new RuntimeException("Failed to parse XML response.", e);
    }
}

From source file:org.zanata.rest.service.TMXStreamingOutputTest.java

private Document writeToXmlWithValidation(StreamingOutput output) throws IOException, SAXException {
    StringBuilderWriter sbWriter = new StringBuilderWriter();
    WriterOutputStream writerOutputStream = new WriterOutputStream(sbWriter);
    output.write(writerOutputStream);/*from w w w  . ja  v a2 s.c  o m*/
    writerOutputStream.close();
    String xml = sbWriter.toString();
    assertValidTMX(xml);
    DocumentBuilder controlParser = XMLUnit.newControlParser();
    controlParser.setEntityResolver(new TmxDtdResolver());
    Document doc = XMLUnit.buildDocument(controlParser, new StringReader(xml));
    return doc;
}

From source file:org.zaproxy.zap.utils.ZapXmlConfiguration.java

@Override
protected DocumentBuilder createDocumentBuilder() throws ParserConfigurationException {
    DocumentBuilderFactory factory = XmlUtils.newXxeDisabledDocumentBuilderFactory();

    // Same behaviour as base method:
    if (isValidating()) {
        factory.setValidating(true);//ww  w .ja v  a  2  s  .  c  om
        if (isSchemaValidation()) {
            factory.setNamespaceAware(true);
            factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                    "http://www.w3.org/2001/XMLSchema");
        }
    }

    DocumentBuilder result = factory.newDocumentBuilder();
    result.setEntityResolver(getEntityResolver());

    if (isValidating()) {
        result.setErrorHandler(new DefaultHandler() {

            @Override
            public void error(SAXParseException ex) throws SAXException {
                throw ex;
            }
        });
    }
    return result;
}

From source file:pl.otros.logview.importer.UtilLoggingXmlLogImporter.java

@Override
public void initParsingContext(ParsingContext parsingContext) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(false);/*from w  w w  .  j a  v  a  2s.  c om*/

    try {
        DocumentBuilder docBuilder = dbf.newDocumentBuilder();
        docBuilder.setErrorHandler(new SAXErrorHandler());
        docBuilder.setEntityResolver(new UtilLoggingEntityResolver());
        parsingContext.getCustomConextProperties().put(DOC_BUILDER, docBuilder);
        parsingContext.getCustomConextProperties().put(PARTIAL_EVENT, "");
    } catch (ParserConfigurationException pce) {
        System.err.println("Unable to get document builder");
    }

}

From source file:ru.codeinside.gses.webui.utils.JarParseUtils.java

public static Document readXml(InputStream is) throws SAXException, IOException, ParserConfigurationException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setValidating(false);/*w w w  .j a v  a2 s  .  com*/
    dbf.setIgnoringComments(false);
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setNamespaceAware(true);
    // dbf.setCoalescing(true);
    // dbf.setExpandEntityReferences(true);

    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setEntityResolver(new NullResolver());

    // db.setErrorHandler( new MyErrorHandler());

    return db.parse(is);
}

From source file:simpleserver.config.DTDEntityResolver.java

private XMLConfiguration initConf(boolean validate) {
    XMLConfiguration conf = new XMLConfiguration();

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = null;
    try {/*w  w w.  ja  v  a 2s .  c  o m*/
        dbf.setValidating(validate);
        db = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
    }

    if (db != null) {
        db.setEntityResolver(new DTDEntityResolver(this));
        db.setErrorHandler(new DTDErrorHandler(this));

        conf.setDocumentBuilder(db);
    }

    conf.setExpressionEngine(new XPathExpressionEngine());
    conf.setDelimiterParsingDisabled(true);

    return conf;
}

From source file:test.unit.be.fedict.eid.applet.service.signer.AbstractXmlSignatureServiceTest.java

@Test
public void testLoadXMLFileWithDTD() throws Exception {
    InputStream documentInputStream = AbstractXmlSignatureServiceTest.class
            .getResourceAsStream("/bookstore.xml");

    InputSource inputSource = new InputSource(documentInputStream);
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    EntityResolver entityResolver = new MyEntityResolver();
    documentBuilder.setEntityResolver(entityResolver);
    Document document = documentBuilder.parse(inputSource);
    assertNotNull(document);//w  w w.j  av a2 s.c  om
}

From source file:test.unit.be.fedict.eid.applet.service.signer.AbstractXmlSignatureServiceTest.java

@Test
public void testSignEnvelopingDocumentWithDTD() throws Exception {
    // setup/*from  w w w  .j a  va2s  . co  m*/
    InputStream documentInputStream = AbstractXmlSignatureServiceTest.class
            .getResourceAsStream("/bookstore.xml");

    InputSource inputSource = new InputSource(documentInputStream);
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    EntityResolver entityResolver = new MyEntityResolver();
    documentBuilder.setEntityResolver(entityResolver);
    Document document = documentBuilder.parse(inputSource);

    SignatureFacet signatureFacet = new EnvelopedSignatureFacet();
    XmlSignatureTestService testedInstance = new XmlSignatureTestService(signatureFacet);
    testedInstance.setEnvelopingDocument(document);
    testedInstance.setSignatureDescription("test-signature-description");

    // operate
    DigestInfo digestInfo = testedInstance.preSign(null, null);

    // verify
    assertNotNull(digestInfo);
    LOG.debug("digest info description: " + digestInfo.description);
    assertEquals("test-signature-description", digestInfo.description);
    assertNotNull(digestInfo.digestValue);
    LOG.debug("digest algo: " + digestInfo.digestAlgo);
    assertEquals("SHA-1", digestInfo.digestAlgo);

    TemporaryTestDataStorage temporaryDataStorage = (TemporaryTestDataStorage) testedInstance
            .getTemporaryDataStorage();
    assertNotNull(temporaryDataStorage);
    InputStream tempInputStream = temporaryDataStorage.getTempInputStream();
    assertNotNull(tempInputStream);
    Document tmpDocument = PkiTestUtils.loadDocument(tempInputStream);

    LOG.debug("tmp document: " + PkiTestUtils.toString(tmpDocument));
    Element nsElement = tmpDocument.createElement("ns");
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", Constants.SignatureSpecNS);
    Node digestValueNode = XPathAPI.selectSingleNode(tmpDocument, "//ds:DigestValue", nsElement);
    assertNotNull(digestValueNode);
    String digestValueTextContent = digestValueNode.getTextContent();
    LOG.debug("digest value text content: " + digestValueTextContent);
    assertFalse(digestValueTextContent.isEmpty());

    /*
     * Sign the received XML signature digest value.
     */
    KeyPair keyPair = PkiTestUtils.generateKeyPair();
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPrivate());
    byte[] digestInfoValue = ArrayUtils.addAll(PkiTestUtils.SHA1_DIGEST_INFO_PREFIX, digestInfo.digestValue);
    byte[] signatureValue = cipher.doFinal(digestInfoValue);

    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusYears(1);
    X509Certificate certificate = PkiTestUtils.generateCertificate(keyPair.getPublic(), "CN=Test", notBefore,
            notAfter, null, keyPair.getPrivate(), true, 0, null, null, new KeyUsage(KeyUsage.nonRepudiation));

    /*
     * Operate: postSign
     */
    testedInstance.postSign(signatureValue, Collections.singletonList(certificate));

    byte[] signedDocumentData = testedInstance.getSignedDocumentData();
    assertNotNull(signedDocumentData);
    Document signedDocument = PkiTestUtils.loadDocument(new ByteArrayInputStream(signedDocumentData));
    LOG.debug("signed document: " + PkiTestUtils.toString(signedDocument));

    NodeList signatureNodeList = signedDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    assertEquals(1, signatureNodeList.getLength());
    Node signatureNode = signatureNodeList.item(0);

    DOMValidateContext domValidateContext = new DOMValidateContext(
            KeySelector.singletonKeySelector(keyPair.getPublic()), signatureNode);
    XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance();
    XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
    boolean validity = xmlSignature.validate(domValidateContext);
    assertTrue(validity);
}