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.apache.solr.handler.dataimport.DataImporter.java

public DIHConfiguration loadDataConfig(InputSource configFile) {

    DIHConfiguration dihcfg = null;//from  ww  w . java  2s. c  o  m
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        // only enable xinclude, if a a SolrCore and SystemId is present (makes no sense otherwise)
        if (core != null && configFile.getSystemId() != null) {
            try {
                dbf.setXIncludeAware(true);
                dbf.setNamespaceAware(true);
            } catch (UnsupportedOperationException e) {
                LOG.warn("XML parser doesn't support XInclude option");
            }
        }

        DocumentBuilder builder = dbf.newDocumentBuilder();
        if (core != null)
            builder.setEntityResolver(new SystemIdResolver(core.getResourceLoader()));
        builder.setErrorHandler(XMLLOG);
        Document document;
        try {
            document = builder.parse(configFile);
        } finally {
            // some XML parsers are broken and don't close the byte stream (but they should according to spec)
            IOUtils.closeQuietly(configFile.getByteStream());
        }

        dihcfg = readFromXml(document);
        LOG.info("Data Configuration loaded successfully");
    } catch (Exception e) {
        throw new DataImportHandlerException(SEVERE, "Data Config problem: " + e.getMessage(), e);
    }
    for (Entity e : dihcfg.getEntities()) {
        if (e.getAllAttributes().containsKey(SqlEntityProcessor.DELTA_QUERY)) {
            isDeltaImportSupported = true;
            break;
        }
    }
    return dihcfg;
}

From source file:org.apache.woden.internal.DOMWSDLReader.java

/**
 * Create a JAXP DocumentBuilder will use for parsing XML documents. 
 * @param factory the JAXP DocumentBuilderFactory that the DocumentBuilder
 * should be created with/*ww  w  . j av  a  2s  .  c o m*/
 * @param entityResolver the SAX EntityResolver to use
 * @param errorHandler the SAX ErrorHandler to use
 * @return the JAXP DocumentBuilder
 * @throws ParserConfigurationException if thrown by JAXP methods
 */
protected DocumentBuilder createDocumentBuilder(DocumentBuilderFactory factory, EntityResolver entityResolver,
        ErrorHandler errorHandler) throws ParserConfigurationException {

    DocumentBuilder docBuilder = factory.newDocumentBuilder();
    if (entityResolver != null) {
        docBuilder.setEntityResolver(entityResolver);
    }
    if (errorHandler != null) {
        docBuilder.setErrorHandler(errorHandler);
    }
    return docBuilder;
}

From source file:org.apache.xml.security.samples.signature.VerifyMerlinsExamplesFifteen.java

/**
 * Method verify/*from  w  ww.j a v a 2 s.  co  m*/
 *
 * @param dbf
 * @param filename
 * @throws Exception
 */
public static void verifyHMAC(DocumentBuilderFactory dbf, String filename) throws Exception {

    File f = new File(filename);

    System.out.println("Try to verify " + f.toURL().toString());

    javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();

    if (VerifyMerlinsExamplesSixteen.schemaValidate) {
        db.setErrorHandler(new org.apache.xml.security.utils.IgnoreAllErrorHandler());
        db.setEntityResolver(new org.xml.sax.EntityResolver() {

            public org.xml.sax.InputSource resolveEntity(String publicId, String systemId)
                    throws org.xml.sax.SAXException {

                if (systemId.endsWith("xmldsig-core-schema.xsd")) {
                    try {
                        return new org.xml.sax.InputSource(new FileInputStream(signatureSchemaFile));
                    } catch (FileNotFoundException ex) {
                        throw new org.xml.sax.SAXException(ex);
                    }
                } else {
                    return null;
                }
            }
        });
    }

    org.w3c.dom.Document doc = db.parse(new java.io.FileInputStream(f));

    Element nscontext = SampleUtils.createDSctx(doc, "ds", Constants.SignatureSpecNS);
    Element sigElement = (Element) XPathAPI.selectSingleNode(doc, "//ds:Signature[1]", nscontext);
    XMLSignature signature = new XMLSignature(sigElement, f.toURL().toString());

    // signature.addResourceResolver(new OfflineResolver());

    byte keybytes[] = "secret".getBytes("ASCII");
    javax.crypto.SecretKey sk = signature.createSecretKey(keybytes);

    System.out.println("The XML signature in file " + f.toURL().toString() + " is "
            + (signature.checkSignatureValue(sk) ? "valid (good)" : "invalid !!!!! (bad)"));
}

From source file:org.apache.xml.security.samples.signature.VerifyMerlinsExamplesSixteen.java

/**
 * Method verify/*  ww w  . jav a  2s  .c  o m*/
 *
 * @param dbf
 * @param filename
 * @throws Exception
 */
public static void verify(DocumentBuilderFactory dbf, String filename) throws Exception {

    File f = new File(filename);

    System.out.println("Try to verify " + f.toURL().toString());

    javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();

    if (VerifyMerlinsExamplesSixteen.schemaValidate) {
        db.setErrorHandler(new org.apache.xml.security.utils.IgnoreAllErrorHandler());
        db.setEntityResolver(new org.xml.sax.EntityResolver() {

            public org.xml.sax.InputSource resolveEntity(String publicId, String systemId)
                    throws org.xml.sax.SAXException {

                if (systemId.endsWith("xmldsig-core-schema.xsd")) {
                    try {
                        return new org.xml.sax.InputSource(new FileInputStream(signatureSchemaFile));
                    } catch (FileNotFoundException ex) {
                        throw new org.xml.sax.SAXException(ex);
                    }
                } else {
                    return null;
                }
            }
        });
    }

    org.w3c.dom.Document doc = db.parse(new java.io.FileInputStream(f));

    Element nscontext = SampleUtils.createDSctx(doc, "ds", Constants.SignatureSpecNS);
    Element sigElement = (Element) XPathAPI.selectSingleNode(doc, "//ds:Signature[1]", nscontext);
    XMLSignature signature = new XMLSignature(sigElement, f.toURL().toString());

    signature.getSignedInfo()
            .addResourceResolver(new org.apache.xml.security.samples.utils.resolver.OfflineResolver());

    signature.setFollowNestedManifests(false);

    // signature.addResourceResolver(new OfflineResolver());

    // XMLUtils.outputDOMc14nWithComments(signature.getElement(), System.out);
    KeyInfo ki = signature.getKeyInfo();

    if (ki != null) {
        /*
        if (ki.containsX509Data()) {
           System.out.println("Could find a X509Data element in the KeyInfo");
        }
        */

        X509Certificate cert = signature.getKeyInfo().getX509Certificate();

        if (cert != null) {
            /*
            System.out.println(
               "I try to verify the signature using the X509 Certificate: "
               + cert);
            */
            System.out.println("The XML signature in file " + f.toURL().toString() + " is "
                    + (signature.checkSignatureValue(cert) ? "valid (good)" : "invalid !!!!! (bad)"));
        } else {
            // System.out.println("Did not find a Certificate");

            PublicKey pk = signature.getKeyInfo().getPublicKey();

            if (pk != null) {
                // System.out.println("I try to verify the signature using the public key: " + pk);
                System.out.println("The XML signature in file " + f.toURL().toString() + " is "
                        + (signature.checkSignatureValue(pk) ? "valid (good)" : "invalid !!!!! (bad)"));
            } else {
                System.out.println("Did not find a public key, so I can't check the signature");
            }
        }
    } else {
        System.out.println("Did not find a KeyInfo");
    }

    /*
    SignedInfo s = signature.getSignedInfo();
    for (int i=0; i<s.getSignedContentLength(); i++) {
       System.out.println("################ Signed Resource " + i + " ################");
       FileOutputStream f2 = new FileOutputStream(filename + "." + i + ".input");
       byte[] data = s.getSignedContentItem(i);
       f2.write(data);
       f2.close();
            
       System.out.println(new String(data));
       System.out.println();
    }
    */
}

From source file:org.apache.xml.security.samples.signature.VerifyMerlinsExamplesTwentyThree.java

/**
 * Method verify/*ww  w  . j  ava  2 s  . c  om*/
 *
 * @param dbf
 * @param filename
 * @throws Exception
 */
public static void verify(DocumentBuilderFactory dbf, String filename) throws Exception {

    File f = new File(filename);

    System.out.println("Try to verify " + f.toURL().toString());

    javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();

    if (VerifyMerlinsExamplesTwentyThree.schemaValidate) {
        db.setErrorHandler(new org.apache.xml.security.utils.IgnoreAllErrorHandler());
        db.setEntityResolver(new org.xml.sax.EntityResolver() {

            public org.xml.sax.InputSource resolveEntity(String publicId, String systemId)
                    throws org.xml.sax.SAXException {

                if (systemId.endsWith("xmldsig-core-schema.xsd")) {
                    try {
                        return new org.xml.sax.InputSource(new FileInputStream(signatureSchemaFile));
                    } catch (FileNotFoundException ex) {
                        throw new org.xml.sax.SAXException(ex);
                    }
                } else {
                    return null;
                }
            }
        });
    }

    org.w3c.dom.Document doc = db.parse(new java.io.FileInputStream(f));

    Element nscontext = SampleUtils.createDSctx(doc, "ds", Constants.SignatureSpecNS);
    Element sigElement = (Element) XPathAPI.selectSingleNode(doc, "//ds:Signature[1]", nscontext);
    XMLSignature signature = new XMLSignature(sigElement, f.toURL().toString());

    signature.getSignedInfo()
            .addResourceResolver(new org.apache.xml.security.samples.utils.resolver.OfflineResolver());

    signature.setFollowNestedManifests(false);

    // signature.addResourceResolver(new OfflineResolver());

    // XMLUtils.outputDOMc14nWithComments(signature.getElement(), System.out);
    KeyInfo ki = signature.getKeyInfo();

    if (ki != null) {
        /*
        if (ki.containsX509Data()) {
           System.out.println("Could find a X509Data element in the KeyInfo");
        }
        */

        X509Certificate cert = signature.getKeyInfo().getX509Certificate();

        if (cert != null) {
            /*
            System.out.println(
               "I try to verify the signature using the X509 Certificate: "
               + cert);
            */
            System.out.println("The XML signature in file " + f.toURL().toString() + " is "
                    + (signature.checkSignatureValue(cert) ? "valid (good)" : "invalid !!!!! (bad)"));
        } else {
            // System.out.println("Did not find a Certificate");

            PublicKey pk = signature.getKeyInfo().getPublicKey();

            if (pk != null) {
                // System.out.println("I try to verify the signature using the public key: " + pk);
                System.out.println("The XML signature in file " + f.toURL().toString() + " is "
                        + (signature.checkSignatureValue(pk) ? "valid (good)" : "invalid !!!!! (bad)"));
            } else {
                System.out.println("Did not find a public key, so I can't check the signature");
            }
        }
    } else {
        System.out.println("Did not find a KeyInfo");
    }

    /*
    SignedInfo s = signature.getSignedInfo();
    for (int i=0; i<s.getSignedContentLength(); i++) {
       System.out.println("################ Signed Resource " + i + " ################");
       FileOutputStream f2 = new FileOutputStream(filename + "." + i + ".input");
       byte[] data = s.getSignedContentItem(i);
       f2.write(data);
       f2.close();
            
       System.out.println(new String(data));
       System.out.println();
    }
    */
}

From source file:org.apache.xml.security.test.c14n.implementations.Canonicalizer20010315Test.java

/**
 * 3.7 Document Subsets//  ww  w . j  a  va  2s  .co  m
 *
 * @throws CanonicalizationException
 * @throws FileNotFoundException
 * @throws IOException
 * @throws InvalidCanonicalizerException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @see <A HREF="http://www.w3.org/TR/2001/PR-xml-c14n-20010119#Example-DocSubsets">the example from the spec</A>
 * @throws TransformerException
 */
public static void test37byNodeList()
        throws IOException, FileNotFoundException, SAXException, ParserConfigurationException,
        CanonicalizationException, InvalidCanonicalizerException, TransformerException {

    //String descri = "3.7 Document Subsets. (uncommented), c14n by NodeList";
    String fileIn = prefix + "in/37_input.xml";
    String fileRef = prefix + "in/37_c14n.xml";
    //String c14nURI = Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS;
    //boolean validating = true;
    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();

    dfactory.setNamespaceAware(true);

    DocumentBuilder db = dfactory.newDocumentBuilder();
    org.xml.sax.EntityResolver resolver = new TestVectorResolver();

    db.setEntityResolver(resolver);

    Document doc = db.parse(resolver.resolveEntity(null, fileIn));
    //J-
    Element nscontext = TestUtils.createDSctx(doc, "ietf", "http://www.ietf.org");

    String xpath = "(//. | //@* | //namespace::*)" + "[ " + "self::ietf:e1 or "
            + "(parent::ietf:e1 and not(self::text() or self::e2)) or "
            + "count(id(\"E3\")|ancestor-or-self::node()) = count(ancestor-or-self::node()) " + "]";
    //J+
    CachedXPathAPI xpathAPI = new CachedXPathAPI();

    NodeList nodes = xpathAPI.selectNodeList(doc, xpath, nscontext);
    Canonicalizer c14n = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
    byte c14nBytes[] = c14n.canonicalizeXPathNodeSet(nodes);
    InputStream refStream = resolver.resolveEntity(null, fileRef).getByteStream();
    byte refBytes[] = JavaUtils.getBytesFromStream(refStream);
    assertEquals(new String(refBytes), new String(c14nBytes));
}

From source file:org.apereo.portal.utils.DocumentFactory.java

public static Document getDocumentFromStream(InputStream stream, EntityResolver er, String publicId)
        throws IOException, SAXException {
    DocumentBuilder builder = getThreadDocumentBuilder();
    builder.setEntityResolver(er);
    InputSource source = new InputSource(stream);
    source.setPublicId(publicId);//from w  ww .j  av a 2 s.  c om
    Document doc = builder.parse(source);
    return doc;
}

From source file:org.apereo.portal.utils.ResourceLoader.java

/**
 * Get the contents of a URL as an XML Document
 * @param requestingClass the java.lang.Class object of the class that is attempting to load the resource
 * @param resource a String describing the full or partial URL of the resource whose contents to load
 * @param validate boolean. True if the document builder factory should validate, false otherwise.
 * @return the actual contents of the resource as an XML Document
 * @throws ResourceMissingException// w  w w .  ja  v a  2s  . c o m
 * @throws java.io.IOException
 * @throws javax.xml.parsers.ParserConfigurationException
 * @throws org.xml.sax.SAXException
 */
public static Document getResourceAsDocument(Class<?> requestingClass, String resource, boolean validate)
        throws ResourceMissingException, IOException, ParserConfigurationException, SAXException {
    Document document = null;
    InputStream inputStream = null;

    try {

        DocumentBuilderFactory factoryToUse = null;

        if (validate) {
            factoryToUse = ResourceLoader.validatingDocumentBuilderFactory;
        } else {
            factoryToUse = ResourceLoader.nonValidatingDocumentBuilderFactory;
        }
        inputStream = getResourceAsStream(requestingClass, resource);
        DocumentBuilder db = factoryToUse.newDocumentBuilder();

        db.setEntityResolver(new DTDResolver());
        db.setErrorHandler(new SAXErrorHandler("ResourceLoader.getResourceAsDocument(" + resource + ")"));
        document = db.parse(inputStream);
    } finally {
        if (inputStream != null)
            inputStream.close();
    }
    return document;
}

From source file:org.codehaus.enunciate.modules.BasicAppModule.java

/**
 * Loads the node model for merging xml.
 *
 * @param inputStream The input stream of the xml.
 * @return The node model.// ww w.  j  a va2  s  . c  o m
 */
protected Document loadMergeXml(InputStream inputStream) throws EnunciateException {
    Document doc;
    try {
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setNamespaceAware(false); //no namespace for the merging...
        builderFactory.setValidating(false);
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        builder.setEntityResolver(new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
                //we don't want to validate or parse external dtds...
                return new InputSource(new StringReader(""));
            }
        });
        doc = builder.parse(inputStream);
    } catch (Exception e) {
        throw new EnunciateException("Error parsing web.xml file for merging", e);
    }
    return doc;
}

From source file:org.codehaus.enunciate.modules.docs.DocumentationDeploymentModule.java

private NodeModel loadNodeModel(File xml) throws EnunciateException {
    Document doc;//from   w ww .  j  ava 2 s  .c o m
    try {
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setNamespaceAware(false);
        builderFactory.setValidating(false);
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        builder.setEntityResolver(new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
                //we don't want to validate or parse external dtds...
                return new InputSource(new StringReader(""));
            }
        });
        doc = builder.parse(new FileInputStream(xml));
    } catch (Exception e) {
        throw new EnunciateException("Error parsing " + xml, e);
    }

    NodeModel.simplify(doc);
    return NodeModel.wrap(doc.getDocumentElement());
}