Example usage for javax.xml.parsers DocumentBuilder setErrorHandler

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

Introduction

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

Prototype


public abstract void setErrorHandler(ErrorHandler eh);

Source Link

Document

Specify the ErrorHandler to be used by the parser.

Usage

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

/**
 * Method main/*from   w w w  . ja v a  2s  .c  o m*/
 *
 * @param unused
 * @throws Exception
 */
public static void main(String unused[]) throws Exception {

    javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();

    dbf.setNamespaceAware(true);
    dbf.setAttribute("http://xml.org/sax/features/namespaces", Boolean.TRUE);

    try {
        File signatureFile = new File("collectableSignature.xml");
        String BaseURI = signatureFile.toURL().toString();

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

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

        db.setErrorHandler(new org.apache.xml.security.utils.IgnoreAllErrorHandler());

        org.w3c.dom.Document doc = db.parse(new java.io.FileInputStream(signatureFile));
        Element nscontext = SampleUtils.createDSctx(doc, "ds", Constants.SignatureSpecNS);
        NodeList signatureElems = XPathAPI.selectNodeList(doc, "//ds:Signature", nscontext);

        for (int i = 0; i < signatureElems.getLength(); i++) {
            Element sigElement = (Element) signatureElems.item(i);
            XMLSignature signature = new XMLSignature(sigElement, BaseURI);
            byte[] secretKey = "secretValue".getBytes();

            System.out.println("The XML signature number " + i + " in file " + BaseURI + " is "
                    + (signature.checkSignatureValue(
                            signature.createSecretKey(CreateCollectableSignature.passphrase.getBytes()))
                                    ? "valid (good)"
                                    : "invalid !!!!! (bad)"));

            SignedInfo s = signature.getSignedInfo();

            for (int j = 0; j < s.getSignedContentLength(); j++) {
                System.out.println("################ Signed Resource " + i + "/" + j + " ################");
                System.out.println(new String(s.getSignedContentItem(j)));
                System.out.println();
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

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

/**
 * Method verify/*  w  ww.jav  a2  s  . com*/
 *
 * @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. j  a  v  a  2 s .  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/*from   w  w  w .  j  a  v  a2  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.signature.XMLSignatureInput.java

void convertToNodes()
        throws CanonicalizationException, ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
    dfactory.setValidating(false);//w  w  w  .ja  va  2s . c  o  m
    dfactory.setNamespaceAware(true);
    DocumentBuilder db = dfactory.newDocumentBuilder();
    // select all nodes, also the comments.        
    try {
        db.setErrorHandler(new org.apache.xml.security.utils.IgnoreAllErrorHandler());

        Document doc = db.parse(this.getOctetStream());

        this._subNode = doc;
    } catch (SAXException ex) {

        // if a not-wellformed nodeset exists, put a container around it...
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        baos.write("<container>".getBytes());
        baos.write(this.getBytes());
        baos.write("</container>".getBytes());

        byte result[] = baos.toByteArray();
        Document document = db.parse(new ByteArrayInputStream(result));
        this._subNode = document.getDocumentElement().getFirstChild().getFirstChild();
    }
    this._inputOctetStreamProxy = null;
    this.bytes = null;
}

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

private boolean c14nAndCompare(String fileIn, String fileRef, String fileOut, String c14nURI,
        boolean validating, Object xpath)
        throws IOException, FileNotFoundException, SAXException, ParserConfigurationException,
        CanonicalizationException, InvalidCanonicalizerException, TransformerException {
    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();

    dfactory.setNamespaceAware(true);/*from  w ww  . j av a2  s.co m*/
    dfactory.setValidating(validating);

    DocumentBuilder documentBuilder = dfactory.newDocumentBuilder();

    // throw away all warnings and errors
    documentBuilder.setErrorHandler(new IgnoreAllErrorHandler());

    // org.xml.sax.EntityResolver resolver = new TestVectorResolver();
    // documentBuilder.setEntityResolver(resolver);
    // Document doc = documentBuilder.parse(resolver.resolveEntity(null, fileIn));

    Document doc = documentBuilder.parse(fileIn);

    Canonicalizer c14n = Canonicalizer.getInstance(c14nURI);
    byte c14nBytes[] = null;

    if (xpath == null) {
        c14nBytes = c14n.canonicalizeSubtree(doc);
    } else {
        CachedXPathAPI xpathAPI = new CachedXPathAPI();
        NodeList nl = null;

        if (xpath instanceof String) {
            nl = xpathAPI.selectNodeList(doc, (String) xpath);
        } else {
            Element xpathElement = (Element) xpath;
            String xpathStr = ((Text) xpathElement.getFirstChild()).getData();

            nl = xpathAPI.selectNodeList(doc, xpathStr, xpathElement);
        }

        c14nBytes = c14n.canonicalizeXPathNodeSet(nl);
    }

    // org.xml.sax.InputSource refIs = resolver.resolveEntity(null, fileRef);
    // byte refBytes[] = JavaUtils.getBytesFromStream(refIs.getByteStream());
    byte refBytes[] = JavaUtils.getBytesFromFile(fileRef);

    // if everything is OK, result is true; we do a binary compare, byte by byte
    boolean result = java.security.MessageDigest.isEqual(refBytes, c14nBytes);

    if (result == false) {
        File f = new File(fileOut);
        if (!f.exists()) {
            File parent = new File(f.getParent());
            parent.mkdirs();
            f.createNewFile();
        }
        FileOutputStream fos = new FileOutputStream(f);

        fos.write(c14nBytes);
        log.debug("Wrote errorneous result to file " + f.toURI().toURL().toString());
        assertEquals(new String(refBytes), new String(c14nBytes));
    }

    return result;
}

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

/**
 * Method doTestXMLAttributes/*w w  w .  j ava2 s  .  com*/
 *
 * @param input
 * @param definedOutput
 * @param writeResultsToFile
 *
 * @throws CanonicalizationException
 * @throws FileNotFoundException
 * @throws IOException
 * @throws InvalidCanonicalizerException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws TransformerException
 */
private static boolean doTestXMLAttributes(String input, String definedOutput)
        throws IOException, FileNotFoundException, SAXException, ParserConfigurationException,
        CanonicalizationException, InvalidCanonicalizerException, TransformerException {

    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();

    dfactory.setNamespaceAware(true);
    dfactory.setValidating(true);

    DocumentBuilder db = dfactory.newDocumentBuilder();

    db.setErrorHandler(new org.apache.xml.security.utils.IgnoreAllErrorHandler());

    Document doc = db.parse(new ByteArrayInputStream(input.getBytes()));
    Canonicalizer c14nizer = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
    CachedXPathAPI xpathAPI = new CachedXPathAPI();

    //XMLUtils.circumventBug2650(doc);

    NodeList nodes = xpathAPI.selectNodeList(doc,
            "(//*[local-name()='included'] | //@*[parent::node()[local-name()='included']])");
    byte result[] = c14nizer.canonicalizeXPathNodeSet(nodes);
    byte defined[] = definedOutput.getBytes();
    assertEquals(definedOutput, new String(result));
    return java.security.MessageDigest.isEqual(defined, result);
}

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

/**
 * Method c14nAndCompare//from w  ww . ja  v a 2 s  . co  m
 *
 * @param fileIn
 * @param fileRef
 * @param fileOut
 * @param c14nURI
 * @param validating
 * @param xpath
 *
 * @throws CanonicalizationException
 * @throws FileNotFoundException
 * @throws IOException
 * @throws InvalidCanonicalizerException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws TransformerException
 */
private static boolean c14nAndCompare(String fileIn, String fileRef, String fileOut, String c14nURI,
        boolean validating, Object xpath)
        throws IOException, FileNotFoundException, SAXException, ParserConfigurationException,
        CanonicalizationException, InvalidCanonicalizerException, TransformerException {

    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();

    dfactory.setNamespaceAware(true);
    dfactory.setValidating(validating);

    DocumentBuilder documentBuilder = dfactory.newDocumentBuilder();

    // throw away all warnings and errors
    documentBuilder.setErrorHandler(new IgnoreAllErrorHandler());

    // org.xml.sax.EntityResolver resolver = new TestVectorResolver();
    // documentBuilder.setEntityResolver(resolver);
    // Document doc = documentBuilder.parse(resolver.resolveEntity(null, fileIn));

    Document doc = documentBuilder.parse(fileIn);

    Canonicalizer c14n = Canonicalizer.getInstance(c14nURI);
    byte c14nBytes[] = null;

    if (xpath == null) {
        c14nBytes = c14n.canonicalizeSubtree(doc);
    } else {
        CachedXPathAPI xpathAPI = new CachedXPathAPI();
        NodeList nl = null;

        if (xpath instanceof String) {
            nl = xpathAPI.selectNodeList(doc, (String) xpath);
        } else {
            Element xpathElement = (Element) xpath;
            String xpathStr = ((Text) xpathElement.getFirstChild()).getData();

            nl = xpathAPI.selectNodeList(doc, xpathStr, xpathElement);
        }

        c14nBytes = c14n.canonicalizeXPathNodeSet(nl);
    }

    // org.xml.sax.InputSource refIs = resolver.resolveEntity(null, fileRef);
    // byte refBytes[] = JavaUtils.getBytesFromStream(refIs.getByteStream());
    byte refBytes[] = JavaUtils.getBytesFromFile(fileRef);

    // if everything is OK, result is true; we do a binary compare, byte by byte
    boolean result = java.security.MessageDigest.isEqual(refBytes, c14nBytes);

    if (result == false) {
        File f = new File(fileOut);
        if (!f.exists()) {
            File parent = new File(f.getParent());
            parent.mkdirs();
            f.createNewFile();
        }
        FileOutputStream fos = new FileOutputStream(f);

        fos.write(c14nBytes);
        log.debug("Wrote errornous result to file " + f.toURL().toString());
        assertEquals(new String(refBytes), new String(c14nBytes));
    }

    return result;
}

From source file:org.apache.xml.security.test.transforms.implementations.TransformBase64DecodeTest.java

/**
 * Method test3/*w w  w .j  a  va  2s.  com*/
 *
 * @throws Exception
 */
public static void test3() throws Exception {
    //J-
    String input = "" + "<Object xmlns:signature='http://www.w3.org/2000/09/xmldsig#'>\n"
            + "<signature:Base64>\n"
            + "VGhlIFVSSSBvZiB0aGU   gdHJhbn<RealText>Nmb  3JtIGlzIG<test/>h0dHA6</RealText>Ly93d3cudzMub3JnLzIwMDAvMDkveG1s\n"
            + "ZHNpZyNiYXNlNjQ=\n" + "</signature:Base64>\n" + "</Object>\n";
    //J+
    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();

    dfactory.setNamespaceAware(true);

    DocumentBuilder db = dfactory.newDocumentBuilder();

    db.setErrorHandler(new org.apache.xml.security.utils.IgnoreAllErrorHandler());

    Document doc = db.parse(new ByteArrayInputStream(input.getBytes()));
    //XMLUtils.circumventBug2650(doc);
    Element nscontext = TestUtils.createDSctx(doc, "ds", Constants.SignatureSpecNS);

    Node base64Node = XPathAPI.selectSingleNode(doc, "//ds:Base64", nscontext);
    XMLSignatureInput xmlinput = new XMLSignatureInput(base64Node);

    Document doc2 = TransformBase64DecodeTest.createDocument();
    Transforms t = new Transforms(doc2);
    doc2.appendChild(t.getElement());
    t.addTransform(Transforms.TRANSFORM_BASE64_DECODE);

    XMLSignatureInput out = t.performTransforms(xmlinput);
    String result = new String(out.getBytes());

    assertTrue("\"" + result + "\"",
            result.equals("The URI of the transform is http://www.w3.org/2000/09/xmldsig#base64"));
}

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  ww . j av a  2s.c  om*/
 * @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;
}