Example usage for javax.xml.parsers DocumentBuilderFactory setValidating

List of usage examples for javax.xml.parsers DocumentBuilderFactory setValidating

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilderFactory setValidating.

Prototype


public void setValidating(boolean validating) 

Source Link

Document

Specifies that the parser produced by this code will validate documents as they are parsed.

Usage

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

/**
 * Method main/*from  ww  w. ja va2  s  .co  m*/
 *
 * @param unused
 */
public static void main(String unused[]) {

    if (schemaValidate) {
        System.out.println("We do schema-validation");
    } else {
        System.out.println("We do not schema-validation");
    }

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

    if (VerifyMerlinsExamplesSixteen.schemaValidate) {
        dbf.setAttribute("http://apache.org/xml/features/validation/schema", Boolean.TRUE);
        dbf.setAttribute("http://apache.org/xml/features/dom/defer-node-expansion", Boolean.TRUE);
        dbf.setValidating(true);
        dbf.setAttribute("http://xml.org/sax/features/validation", Boolean.TRUE);
        dbf.setAttribute("http://apache.org/xml/properties/schema/external-schemaLocation",
                Constants.SignatureSpecNS + " " + VerifyMerlinsExamplesSixteen.signatureSchemaFile);
    }

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

    //J-
    String filenames[] = { // "16signature.xml"
            // "merlinsSixteenRecreated.xml"
            "data/ie/baltimore/merlin-examples/merlin-xmldsig-sixteen/signature.xml" };
    //J+
    int start = 0;
    int end = filenames.length;

    for (int i = start; i < end; i++) {
        String signatureFileName = filenames[i];

        try {
            verify(dbf, signatureFileName);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

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

/**
 * Method main/*from  w w  w  . j  a  v  a2s  . c  o  m*/
 *
 * @param unused
 */
public static void main(String unused[]) {

    if (schemaValidate) {
        System.out.println("We do schema-validation");
    } else {
        System.out.println("We do not schema-validation");
    }

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

    if (VerifyMerlinsExamplesTwentyThree.schemaValidate) {
        dbf.setAttribute("http://apache.org/xml/features/validation/schema", Boolean.TRUE);
        dbf.setAttribute("http://apache.org/xml/features/dom/defer-node-expansion", Boolean.TRUE);
        dbf.setValidating(true);
        dbf.setAttribute("http://xml.org/sax/features/validation", Boolean.TRUE);
        dbf.setAttribute("http://apache.org/xml/properties/schema/external-schemaLocation",
                Constants.SignatureSpecNS + " " + VerifyMerlinsExamplesTwentyThree.signatureSchemaFile);
    }

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

    //J-
    String merlinsDir = "data/ie/baltimore/merlin-examples/merlin-xmldsig-twenty-three/";
    String filenames[] = { // "23signature.xml"
            // "merlinsTwentyThreeRecreated.xml"
            merlinsDir + "signature.xml", merlinsDir + "signature-enveloped-dsa.xml",
            merlinsDir + "signature-enveloping-b64-dsa.xml", merlinsDir + "signature-enveloping-dsa.xml",
            merlinsDir + "signature-enveloping-hmac-sha1.xml", merlinsDir + "signature-enveloping-rsa.xml",
            merlinsDir + "signature-external-b64-dsa.xml", merlinsDir + "signature-external-dsa.xml" };
    //J+
    int start = 0;
    int end = filenames.length;

    for (int i = start; i < end; i++) {
        String signatureFileName = filenames[i];

        try {
            verify(dbf, signatureFileName);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

From source file:org.apache.xml.security.signature.XMLSignatureInput.java

void convertToNodes()
        throws CanonicalizationException, ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
    dfactory.setValidating(false);
    dfactory.setNamespaceAware(true);/*from w  w w.  j  a va2s. com*/
    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  w  w.j av  a2 s .c  om
    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  a  va 2s.c  o m
 *
 * @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//  w w  w  .j a  v a  2 s . c o  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.external.org.apache.xalan.XPathAPI.AttributeAncestorOrSelfTest.java

/**
 * Process input args and execute the XPath.
 *
 * @param xmlString/*  w w w  .  j a v a  2 s. c o  m*/
 * @param ctxNodeStr
 * @param evalStr
 *
 * @throws Exception
 */
static private boolean isAncestorOf(String xmlString, String ctxNodeStr, String evalStr) throws Exception {

    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();

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

    DocumentBuilder db = dfactory.newDocumentBuilder();
    Document document = db.parse(new ByteArrayInputStream(_nodeSetInput1.getBytes()));
    Element nscontext = document.createElementNS(null, "nscontext");

    nscontext.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", "http://www.w3.org/2000/09/xmldsig#");

    Node ctxNode = XPathAPI.selectSingleNode(document, ctxNodeStr, nscontext);
    XObject include = XPathAPI.eval(ctxNode, evalStr, nscontext);

    return include.bool();
}

From source file:org.bibsonomy.importer.bookmark.service.DeliciousImporter.java

/**
 * Method opens a connection and parses the retrieved InputStream with a JAXP parser.
 * @return The from the parse call returned Document Object
 * @throws IOException//from   w  ww.  j  a v a2s  .  c o m
 */
private Document getDocument() throws IOException {

    final URLConnection connection = apiURL.openConnection();
    connection.setRequestProperty(HEADER_USER_AGENT, userAgent);
    connection.setRequestProperty(HEADER_AUTHORIZATION, encodeForAuthorization());
    final InputStream inputStream = connection.getInputStream();

    // Get a JAXP parser factory object
    final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    // Tell the factory what kind of parser we want 
    dbf.setValidating(false);
    // Use the factory to get a JAXP parser object

    final DocumentBuilder parser;
    try {
        parser = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new IOException(e);
    }

    // Tell the parser how to handle errors.  Note that in the JAXP API,
    // DOM parsers rely on the SAX API for error handling
    parser.setErrorHandler(new ErrorHandler() {
        public void warning(SAXParseException e) {
            log.warn(e);
        }

        public void error(SAXParseException e) {
            log.error(e);
        }

        public void fatalError(SAXParseException e) throws SAXException {
            log.fatal(e);
            throw e; // re-throw the error
        }
    });

    // Finally, use the JAXP parser to parse the file.  
    // This call returns a Document object. 

    final Document document;
    try {
        document = parser.parse(inputStream);
    } catch (SAXException e) {
        throw new IOException(e);
    }

    inputStream.close();

    return document;

}

From source file:org.bibsonomy.importer.bookmark.service.DeliciousV2Importer.java

/**
 * Method opens a connection and parses the retrieved InputStream with a JAXP parser.
 * @return The from the parse call returned Document Object
 * @throws IOException/*ww w  .  j  a v a2s. c  om*/
 */
private static Document getDocument(final InputStream inputStream) throws IOException {
    /*
     * TODO: this is copied code
     */
    // Get a JAXP parser factory object
    final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    // Tell the factory what kind of parser we want 
    dbf.setValidating(false);
    // Use the factory to get a JAXP parser object

    final DocumentBuilder parser;
    try {
        parser = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new IOException(e);
    }

    // Tell the parser how to handle errors.  Note that in the JAXP API,
    // DOM parsers rely on the SAX API for error handling
    parser.setErrorHandler(new ErrorHandler() {
        public void warning(SAXParseException e) {
            log.warn(e);
        }

        public void error(SAXParseException e) {
            log.error(e);
        }

        public void fatalError(SAXParseException e) throws SAXException {
            log.fatal(e);
            throw e; // re-throw the error
        }
    });

    // Finally, use the JAXP parser to parse the file.  
    // This call returns a Document object. 

    final Document document;
    try {
        document = parser.parse(inputStream);
    } catch (SAXException e) {
        throw new IOException(e);
    }

    inputStream.close();

    return document;

}

From source file:org.chiba.tools.schemabuilder.AbstractSchemaFormBuilder.java

/**
 * Creates a new instance of AbstractSchemaFormBuilder
 *///from www .j av a 2s.c  o m
public AbstractSchemaFormBuilder(String rootTagName) {
    this._rootTagName = rootTagName;
    typeTree = new TreeMap();
    properties = new Properties();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    try {
        factory.setNamespaceAware(true);
        factory.setValidating(false);
        documentBuilder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException x) {
        x.printStackTrace();
    }

    //default wrapper: HTML
    //_wrapper = new BaseWrapperElementsBuilder();
    _wrapper = new XHTMLWrapperElementsBuilder();
    reset();
}