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:com.connexta.arbitro.TestUtil.java

/**
 * This creates the expected XACML response from a file
 *
 * @param rootDirectory   root directory of the  response files
 * @param versionDirectory   version directory of the  response files
 * @param responseId  response file name
 * @return ResponseCtx or null if any error
 *///from  ww w  . j a v  a 2s  . c  om
public static ResponseCtx createResponse(String rootDirectory, String versionDirectory, String responseId) {

    File file = new File(".");
    try {
        String filePath = file.getCanonicalPath() + File.separator + TestConstants.RESOURCE_PATH
                + File.separator + rootDirectory + File.separator + versionDirectory + File.separator
                + TestConstants.RESPONSE_DIRECTORY + File.separator + responseId;

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setIgnoringComments(true);
        factory.setNamespaceAware(true);
        factory.setValidating(false);
        DocumentBuilder db = factory.newDocumentBuilder();
        Document doc = db.parse(new FileInputStream(filePath));
        return ResponseCtx.getInstance(doc.getDocumentElement());
    } catch (Exception e) {
        log.error("Error while reading expected response from file ", e);
        //ignore any exception and return null
    }

    return null;
}

From source file:de.mpg.escidoc.services.syndication.Utils.java

public static DocumentBuilder createDocumentBuilder() throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(false);
    dbf.setIgnoringComments(true);/*  w w  w.j av a 2s .  c  o m*/
    return dbf.newDocumentBuilder();
}

From source file:com.connexta.arbitro.ctx.InputParser.java

/**
 * Tries to Parse the given output as a Context document.
 * /* w w w .j  a v a  2s  .  c  om*/
 * @param input the stream to parse
 * @param rootTag either "Request" or "Response"
 * 
 * @return the root node of the request/response
 * 
 * @throws ParsingException if a problem occurred parsing the document
 */
public static Node parseInput(InputStream input, String rootTag) throws ParsingException {
    NodeList nodes = null;

    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setIgnoringComments(true);

        DocumentBuilder builder = null;

        // as of 1.2, we always are namespace aware
        factory.setNamespaceAware(true);

        if (ipReference == null) {
            // we're not validating
            factory.setValidating(false);

            builder = factory.newDocumentBuilder();
        } else {
            // we are validating
            factory.setValidating(true);

            factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
            factory.setAttribute(JAXP_SCHEMA_SOURCE, ipReference.schemaFile);

            builder = factory.newDocumentBuilder();
            builder.setErrorHandler(ipReference);
        }

        Document doc = builder.parse(input);
        nodes = doc.getElementsByTagName(rootTag);
    } catch (Exception e) {
        throw new ParsingException("Error tring to parse " + rootTag + "Type", e);
    }

    if (nodes.getLength() != 1)
        throw new ParsingException("Only one " + rootTag + "Type allowed " + "at the root of a Context doc");

    return nodes.item(0);
}

From source file:com.microsoft.tfs.util.xml.JAXPUtils.java

/**
 * <p>/*from   w w w.j  a v a  2 s .com*/
 * Creates a new (or configures an existing) {@link DocumentBuilderFactory}
 * that will perform XML Schema validation when parsing. This method is
 * called before parsing to obtain a configured
 * {@link DocumentBuilderFactory} that produces {@link DocumentBuilder}s
 * that will be used for XML Schema for validation.
 * </p>
 *
 * <p>
 * The supplied <code>schemaSource</code> object must be one of the
 * following:
 * <ul>
 * <li>A {@link String} that points to the URI of the schema</li>
 *
 * <li>An {@link InputStream} with the schema contents (will not be closed
 * by this method)</li>
 *
 * <li>A SAX {@link InputSource} that indicates the schema</li>
 *
 * <li>A {@link File} that indicates the schema</li>
 *
 * <li>An array of objects, each one of which is one of the above</li>
 * </ul>
 * </p>
 *
 * @throws XMLException
 *         if the {@link DocumentBuilderFactory} can't be created or
 *         properly configured
 *
 * @param factory
 *        the {@link DocumentBuilderFactory} to configure, or
 *        <code>null</code> to create a {@link DocumentBuilderFactory} using
 *        the {@link #newDocumentBuilderFactory()} method
 * @param schemaSource
 *        the schema source as described above
 * @return a configured {@link DocumentBuilderFactory} (never
 *         <code>null</code>)
 */
public static DocumentBuilderFactory newDocumentBuilderFactoryForXSValidation(DocumentBuilderFactory factory,
        final Object schemaSource) {
    if (factory == null) {
        factory = newDocumentBuilderFactory();
    }

    factory.setNamespaceAware(true);
    factory.setValidating(true);

    try {
        factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
    } catch (final IllegalArgumentException e) {
        final String messageFormat = "The DocumentBuilderFactory [{0}] loaded from ClassLoader [{1}] does not support JAXP 1.2"; //$NON-NLS-1$
        final String message = MessageFormat.format(messageFormat, factory.getClass().getName(),
                factory.getClass().getClassLoader());
        throw new XMLException(message, e);
    }

    if (schemaSource != null) {
        factory.setAttribute(JAXP_SCHEMA_SOURCE, schemaSource);
    }

    return factory;
}

From source file:gpms.utils.PolicyTestUtil.java

/**
 * This creates the expected XACML response from a file
 *
 * @param rootDirectory/* ww  w. j a  v a  2 s.co  m*/
 *            root directory of the response files
 * @param versionDirectory
 *            version directory of the response files
 * @param responseId
 *            response file name
 * @return ResponseCtx or null if any error
 */
public static ResponseCtx createResponse(String rootDirectory, String versionDirectory, String responseId) {

    File file = new File(".");
    try {
        String filePath = file.getCanonicalPath() + File.separator + TestConstants.RESOURCE_PATH
                + File.separator + rootDirectory + File.separator + versionDirectory + File.separator
                + TestConstants.RESPONSE_DIRECTORY + File.separator + responseId;

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setIgnoringComments(true);
        factory.setNamespaceAware(true);
        factory.setValidating(false);
        DocumentBuilder db = factory.newDocumentBuilder();
        Document doc = db.parse(new FileInputStream(filePath));
        return ResponseCtx.getInstance(doc.getDocumentElement());
    } catch (Exception e) {
        log.error("Error while reading expected response from file ", e);
        // ignore any exception and return null
    }

    return null;
}

From source file:com.google.enterprise.adaptor.experimental.Sim.java

/** Find all record urls in Adaptor created XML metadata-and-url feed file. */
static Set<URL> extractUrls(String xml) throws SAXException, ParserConfigurationException, BadFeed {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    /* to avoid blowing up on doctype line:
     * http://stackoverflow.com/questions/155101/make-documentbuilder-parse-ignore-dtd-references */
    dbf.setValidating(false);
    dbf.setFeature("http://xml.org/sax/features/namespaces", false);
    dbf.setFeature("http://xml.org/sax/features/validation", false);
    dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputStream xmlStream = new ByteArrayInputStream(xml.getBytes(UTF8));
    Document doc;//from w  w  w.j a  va 2s.co m
    try {
        doc = db.parse(xmlStream);
    } catch (IOException ie) {
        throw new BadFeed(ie.getMessage());
    }
    doc.getDocumentElement().normalize();
    NodeList nodes = doc.getElementsByTagName("record");
    Set<URL> tmpUrls = new HashSet<URL>();
    for (int i = 0; i < nodes.getLength(); i++) {
        Element element = (Element) nodes.item(i);
        String url = element.getAttribute("url");
        if (null == url || url.trim().isEmpty()) {
            throw new BadFeed("record without url attribute");
        } else {
            try {
                tmpUrls.add(new URL(url));
            } catch (MalformedURLException male) {
                throw new BadFeed("record with bad url attribute: " + url);
            }
        }
        log.info("accepting url: " + url);
    }
    return tmpUrls;
}

From source file:com.puppycrawl.tools.checkstyle.AllChecksTest.java

/**
 * Gets a set of names of checkstyle's checks which are referenced in checkstyle_checks.xml.
 * @param configFilePath file path of checkstyle_checks.xml.
 * @return names of checkstyle's checks which are referenced in checkstyle_checks.xml.
 * @throws ParserConfigurationException if a DocumentBuilder cannot be created which satisfies the configuration requested.
 * @throws IOException if any IO errors occur.
 * @throws SAXException if any parse errors occur.
 *///ww  w  .j a  va  2s  .c  o  m
private static Set<String> getCheckStyleChecksReferencedInConfig(String configFilePath)
        throws ParserConfigurationException, IOException, SAXException {

    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    // Validations of XML file make parsing too slow, that is why we disable all validations.
    factory.setNamespaceAware(false);
    factory.setValidating(false);
    factory.setFeature("http://xml.org/sax/features/namespaces", false);
    factory.setFeature("http://xml.org/sax/features/validation", false);
    factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

    final DocumentBuilder builder = factory.newDocumentBuilder();
    final Document document = builder.parse(new File(configFilePath));

    // optional, but recommended
    // FYI: http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
    document.getDocumentElement().normalize();

    final NodeList nodeList = document.getElementsByTagName("module");

    Set<String> checksReferencedInCheckstyleChecksXML = new HashSet<>();
    for (int i = 0; i < nodeList.getLength(); i++) {
        final Node currentNode = nodeList.item(i);
        if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
            final Element module = (Element) currentNode;
            final String checkName = module.getAttribute("name");
            if (!"Checker".equals(checkName) && !"TreeWalker".equals(checkName)
                    && !"SuppressionFilter".equals(checkName)) {
                checksReferencedInCheckstyleChecksXML.add(checkName);
            }
        }
    }
    return checksReferencedInCheckstyleChecksXML;
}

From source file:com.puppycrawl.tools.checkstyle.AllChecksTest.java

/**
 * Gets names of checkstyle's modules which are documented in xdocs.
 * @param xdocsDirectoryPath xdocs directory path.
 * @return a set of checkstyle's modules which have xdoc documentation.
 * @throws ParserConfigurationException if a DocumentBuilder cannot be created which satisfies the configuration requested.
 * @throws IOException if any IO errors occur.
 * @throws SAXException if any parse errors occur.
 *//*w w w .j  a v a  2 s  .c o  m*/
private static Set<String> getModulesNamesWhichHaveXdoc(String xdocsDirectoryPath)
        throws ParserConfigurationException, IOException, SAXException {

    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    // Validations of XML file make parsing too slow, that is why we disable all validations.
    factory.setNamespaceAware(false);
    factory.setValidating(false);
    factory.setFeature("http://xml.org/sax/features/namespaces", false);
    factory.setFeature("http://xml.org/sax/features/validation", false);
    factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

    final Set<Path> xdocsFilePaths = getXdocsFilePaths(xdocsDirectoryPath);
    final Set<String> modulesNamesWhichHaveXdoc = new HashSet<>();

    for (Path path : xdocsFilePaths) {
        final DocumentBuilder builder = factory.newDocumentBuilder();
        final Document document = builder.parse(path.toFile());

        // optional, but recommended
        // FYI: http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
        document.getDocumentElement().normalize();

        final NodeList nodeList = document.getElementsByTagName("section");

        for (int i = 0; i < nodeList.getLength(); i++) {
            final Node currentNode = nodeList.item(i);
            if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
                final Element module = (Element) currentNode;
                final String moduleName = module.getAttribute("name");
                if (!"Content".equals(moduleName) && !"Overview".equals(moduleName)) {
                    modulesNamesWhichHaveXdoc.add(moduleName);
                }
            }
        }
    }
    return modulesNamesWhichHaveXdoc;
}

From source file:com.puppycrawl.tools.checkstyle.XDocsPagesTest.java

private static Document getRawXml(String fileName, String code, String unserializedSource)
        throws ParserConfigurationException {
    try {//from  w  w w .j  a v  a2s  .  c om
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setNamespaceAware(true);

        final DocumentBuilder builder = factory.newDocumentBuilder();

        return builder.parse(new InputSource(new StringReader(code)));
    } catch (IOException | SAXException e) {
        Assert.fail(fileName + " has invalid xml (" + e.getMessage() + "): " + unserializedSource);
    }

    return null;
}

From source file:net.sf.taverna.t2.activities.biomoby.ExecuteAsyncCgiService.java

/**
 *
 * @param url/*from   w  w w. j a v a  2  s .c  o  m*/
 * @param serviceName
 * @param xml
 * @return
 */
public static String executeMobyCgiAsyncService(String url, String serviceName, String xml)
        throws MobyException {

    // First, let's get the queryIds
    org.w3c.dom.Document message = null;

    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setValidating(false);
        DocumentBuilder db = dbf.newDocumentBuilder();

        message = db.parse(new InputSource(new StringReader(xml)));
    } catch (Throwable t) {
        throw new MobyException("Error while parsing input query", t);
    }

    NodeList l_data = message.getElementsByTagNameNS(MobyPrefixResolver.MOBY_XML_NAMESPACE, MobyTags.MOBYDATA);
    if (l_data == null || l_data.getLength() == 0) {
        l_data = message.getElementsByTagNameNS(MobyPrefixResolver.MOBY_XML_NAMESPACE_INVALID,
                MobyTags.MOBYDATA);
    }

    // Freeing resources
    message = null;

    if (l_data == null || l_data.getLength() == 0) {
        throw new MobyException("Empty asynchronous MOBY query!");
    }

    int nnode = l_data.getLength();
    String[] queryIds = new String[nnode];
    String[] tmpQueryIds = new String[nnode];
    String[] results = new String[nnode];
    for (int inode = 0; inode < nnode; inode++) {
        String queryId = null;

        org.w3c.dom.Element mdata = (org.w3c.dom.Element) l_data.item(inode);

        queryId = mdata.getAttribute(MobyTags.QUERYID);
        if (queryId == null || queryId.length() == 0)
            queryId = mdata.getAttributeNS(MobyPrefixResolver.MOBY_XML_NAMESPACE, MobyTags.QUERYID);
        if (queryId == null || queryId.length() == 0)
            queryId = mdata.getAttributeNS(MobyPrefixResolver.MOBY_XML_NAMESPACE_INVALID, MobyTags.QUERYID);

        if (queryId == null || queryId.length() == 0) {
            throw new MobyException("Unable to extract queryId for outgoing MOBY message");
        }

        tmpQueryIds[inode] = queryIds[inode] = queryId;
        results[inode] = null;
    }

    // Freeing resources
    l_data = null;

    // Second, let's launch
    EndpointReference epr = launchCgiAsyncService(url, xml);

    // Third, waiting for the results
    try {
        // FIXME - add appropriate values here
        long pollingInterval = 1000L;
        double backoff = 1.0;

        // Max: one minute pollings
        long maxPollingInterval = 60000L;

        // Min: one second
        if (pollingInterval <= 0L)
            pollingInterval = 1000L;

        // Backoff: must be bigger than 1.0
        if (backoff <= 1.0)
            backoff = 1.5;

        do {
            try {
                Thread.sleep(pollingInterval);
            } catch (InterruptedException ie) {
                // DoNothing(R)
            }

            if (pollingInterval != maxPollingInterval) {
                pollingInterval = (long) ((double) pollingInterval * backoff);
                if (pollingInterval > maxPollingInterval) {
                    pollingInterval = maxPollingInterval;
                }
            }
        } while (pollAsyncCgiService(serviceName, url, epr, tmpQueryIds, results));
    } finally {

        // Call destroy on this service ....
        freeCgiAsyncResources(url, epr);

    }

    // Fourth, assembling back the results

    // Results array already contains mobyData
    Element[] mobydatas = new Element[results.length];
    for (int x = 0; x < results.length; x++) {
        // TODO remove the extra wrapping from our result
        try {
            Element inputElement = XMLUtilities.getDOMDocument(results[x]).getRootElement();
            if (inputElement.getName().indexOf("GetMultipleResourcePropertiesResponse") >= 0)
                if (inputElement.getChildren().size() > 0)
                    inputElement = (Element) inputElement.getChildren().get(0);
            if (inputElement.getName().indexOf("result_") >= 0)
                if (inputElement.getChildren().size() > 0)
                    inputElement = (Element) inputElement.getChildren().get(0);
            // replace results[x]
            mobydatas[x] = inputElement;
        } catch (MobyException e) {
            // TODO what should i do?
        }
    }
    Element e = null;
    try {
        e = XMLUtilities.createMultipleInvokations(mobydatas);
    } catch (Exception ex) {
        logger.error("There was a problem creating our XML message ...", ex);
    }
    // Fifth, returning results
    return e == null ? "" : new XMLOutputter(Format.getPrettyFormat()).outputString(e);
}