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.ganges.expressionengine.grammar.DefaultXMLGrammar.java

/**
 * Configures the grammar object with specified XML file
 *//*from  w  w w. j  av a  2 s .  c  om*/
private void configure() {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(true);

        DocumentBuilder builder = factory.newDocumentBuilder();

        LOGGER.debug("resourcePath[" + getClass().getClassLoader().getResource(""));
        Document document = builder.parse(getClass().getClassLoader().getResourceAsStream(FILE_PATH));
        Element root = document.getDocumentElement();

        // Extracting production rules
        NodeList nodeList = root.getChildNodes();
        int length = nodeList.getLength();

        for (int i = 0; i < length; i++) {
            Node childNode = nodeList.item(i);
            String nodeName = childNode.getNodeName();

            if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                if (PRODUCTION_RULES.equals(nodeName)) {
                    buildProductionRules((Element) childNode);
                } else if (BINARY_OPERATORS.equals(nodeName)) {
                    buildBinaryOperators((Element) childNode);
                    loadBinaryPrecedence((Element) childNode);
                } else if (UNARY_OPERATORS.equals(nodeName)) {
                    buildUnaryOperators((Element) childNode);
                    loadUnaryPrecedence((Element) childNode);
                } else if (FUNCTIONS.equals(nodeName)) {
                    buildFunctions((Element) childNode);
                    loadFunctionPrecedence((Element) childNode);
                } else if (DELIMITERS.equals(nodeName)) {
                    buildDelimiters((Element) childNode);
                } else if (BRACKETS.equals(nodeName)) {
                    loadBrackets((Element) childNode);
                } else if (IGNORE_BLANK.equals(nodeName)) {
                    ignoreBlank = TRUE.equals(((Element) childNode).getAttribute(NAME));
                }
            }
        }
    } catch (Exception ex) {
        throw new RuntimeException("Error while loading the configurations.", ex);
    }
}

From source file:org.geoserver.test.GeoServerAbstractTestSupport.java

/**
 * Parses a stream into a dom./*from   ww w .  j  a  v a 2  s .co m*/
 * @param input
 * @param skipDTD If true, will skip loading and validating against the associated DTD
 */
protected Document dom(InputStream input, boolean skipDTD)
        throws ParserConfigurationException, SAXException, IOException {
    if (skipDTD) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(false);

        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver(new EmptyResolver());
        Document dom = builder.parse(input);

        return dom;
    } else {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        return builder.parse(input);
    }
}

From source file:org.geoserver.test.GeoServerSystemTestSupport.java

protected Document dom(InputStream stream, boolean skipDTD, String encoding)
        throws ParserConfigurationException, SAXException, IOException {

    InputSource input = new InputSource(stream);
    if (encoding != null) {
        input.setEncoding(encoding);/*from ww w  .  ja  v  a  2 s.c om*/
    }

    if (skipDTD) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

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

        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver(new EmptyResolver());
        Document dom = builder.parse(input);

        return dom;
    } else {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        return builder.parse(input);
    }
}

From source file:org.geotools.data.wfs.internal.DescribeStoredQueriesResponse.java

public DescribeStoredQueriesResponse(WFSRequest originatingRequest, HTTPResponse response)
        throws IOException, ServiceException {
    super(originatingRequest, response);

    MODULE.finer("Parsing DescribeStoredQueries response");
    try {/*w  ww.j a va 2  s. co m*/
        final Document rawDocument;
        final byte[] rawResponse;
        {
            ByteArrayOutputStream buff = new ByteArrayOutputStream();
            InputStream inputStream = response.getResponseStream();
            try {
                IOUtils.copy(inputStream, buff);
            } finally {
                inputStream.close();
            }
            rawResponse = buff.toByteArray();
        }
        if (RESPONSES.isLoggable(Level.FINE)) {
            RESPONSES.fine("Full ListStoredQueries response: " + new String(rawResponse));
        }
        try {
            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
            builderFactory.setNamespaceAware(true);
            builderFactory.setValidating(false);
            DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
            rawDocument = documentBuilder.parse(new ByteArrayInputStream(rawResponse));
        } catch (Exception e) {
            throw new IOException("Error parsing capabilities document: " + e.getMessage(), e);
        }

        describeStoredQueriesResponse = parseStoredQueries(rawDocument, WFS_2_0_CONFIGURATION);

        if (null == describeStoredQueriesResponse) {
            throw new IllegalStateException("Unable to parse DescribeStoredQueriesResponse document");
        }

    } finally {
        response.dispose();
    }

}

From source file:org.geotools.data.wfs.internal.ListStoredQueriesResponse.java

public ListStoredQueriesResponse(WFSRequest originatingRequest, HTTPResponse response)
        throws IOException, ServiceException {
    super(originatingRequest, response);
    MODULE.finer("Parsing ListStoredQueries response");
    try {//from ww  w.j a  v a  2s  . com
        final Document rawDocument;
        final byte[] rawResponse;
        {
            ByteArrayOutputStream buff = new ByteArrayOutputStream();
            InputStream inputStream = response.getResponseStream();
            try {
                IOUtils.copy(inputStream, buff);
            } finally {
                inputStream.close();
            }
            rawResponse = buff.toByteArray();
        }
        if (RESPONSES.isLoggable(Level.FINE)) {
            RESPONSES.fine("Full ListStoredQueries response: " + new String(rawResponse));
        }
        try {
            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
            builderFactory.setNamespaceAware(true);
            builderFactory.setValidating(false);
            DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
            rawDocument = documentBuilder.parse(new ByteArrayInputStream(rawResponse));
        } catch (Exception e) {
            throw new IOException("Error parsing capabilities document: " + e.getMessage(), e);
        }

        listStoredQueriesResponse = parseStoredQueries(rawDocument, WFS_2_0_CONFIGURATION);

        if (null == listStoredQueriesResponse) {
            throw new IllegalStateException("Unable to parse ListStoredQueries document");
        }

    } finally {
        response.dispose();
    }
}

From source file:org.gluu.oxtrust.ldap.service.Shibboleth2ConfService.java

/**
 * @param stream/*ww w .j av  a 2  s.  co  m*/
 * @throws IOException
 * @throws SAXException
 * @throws ParserConfigurationException
 */
public synchronized GluuErrorHandler validateMetadata(InputStream stream)
        throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory newFactory = DocumentBuilderFactory.newInstance();
    newFactory.setCoalescing(false);
    newFactory.setExpandEntityReferences(true);
    newFactory.setIgnoringComments(false);

    newFactory.setIgnoringElementContentWhitespace(false);
    newFactory.setNamespaceAware(true);
    newFactory.setValidating(false);
    DocumentBuilder xmlParser = newFactory.newDocumentBuilder();
    Document xmlDoc = xmlParser.parse(stream);
    String schemaDir = System.getProperty("catalina.home") + File.separator + "conf" + File.separator
            + "shibboleth2" + File.separator + "idp" + File.separator + "schema" + File.separator;
    Schema schema = SchemaBuilder.buildSchema(SchemaLanguage.XML, schemaDir);
    Validator validator = schema.newValidator();
    GluuErrorHandler handler = new GluuErrorHandler();
    validator.setErrorHandler(handler);
    validator.validate(new DOMSource(xmlDoc));

    return handler;

}

From source file:org.hippoecm.frontend.editor.layout.LayoutProvider.java

public LayoutProvider(IModel<ClassLoader> loaderModel) {
    this.classLoaderModel = loaderModel;

    layouts = new TreeMap<String, LayoutEntry>();
    final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);/*from  w  w w .  j  av a 2  s.co m*/
    dbf.setValidating(false);

    final ClassLoader loader = classLoaderModel.getObject();
    if (loader == null) {
        log.error("No class-loader could be obtained from the user session, skip reading layout extensions.");
        return;
    }

    try {
        for (Enumeration<URL> iter = loader.getResources("hippoecm-layouts.xml"); iter.hasMoreElements();) {
            URL configurationURL = iter.nextElement();
            InputStream stream = configurationURL.openStream();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document document = db.parse(stream);

            Element element = document.getDocumentElement();
            if (!"layouts".equals(element.getNodeName())) {
                throw new RuntimeException("unable to parse layout: no layout node found");
            }

            NodeList nodes = element.getElementsByTagName("layout");
            for (int i = 0; i < nodes.getLength(); i++) {
                Element padElement = (Element) nodes.item(i);

                NodeList plugins = padElement.getElementsByTagName("plugin");
                if (plugins.getLength() != 1) {
                    throw new RuntimeException(
                            "Invalid layout, 0 or more than 1 plugin child nodes found at " + configurationURL);
                }

                Element pluginElement = (Element) plugins.item(0);
                Node childNode = pluginElement.getFirstChild();
                String plugin = childNode.getNodeValue();
                addLayoutEntry(plugin, null);

                NodeList variants = padElement.getElementsByTagName("variant");
                for (int j = 0; j < variants.getLength(); j++) {
                    Element variantElement = (Element) variants.item(j);
                    Node variantNode = variantElement.getFirstChild();
                    String variant = variantNode.getNodeValue();
                    addLayoutEntry(plugin, variant);
                }
            }
        }
    } catch (IOException e) {
        throw new RuntimeException("Error while reading layouts extension", e);
    } catch (ParserConfigurationException ex) {
        throw new RuntimeException("Parser configuration error:", ex);
    } catch (SAXException ex) {
        throw new RuntimeException("SAX error:", ex);
    }
}

From source file:org.hippoecm.frontend.plugins.gallery.imageutil.ScaleImageOperation.java

private void disableValidation(final DocumentBuilderFactory factory) throws ParserConfigurationException {
    factory.setNamespaceAware(false);//from ww  w. j  a  v a  2 s  .c  o m
    factory.setValidating(false);
    factory.setFeature("http://xml.org/sax/features/namespaces", false);
    factory.setFeature("http://xml.org/sax/features/validation", false);
    factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    factory.setFeature("http://xml.org/sax/features/external-general-entities", 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);
}

From source file:org.hippoecm.frontend.plugins.gallery.imageutil.ScaleImageOperationTest.java

@Test
public void scaleSvgAddsViewboxWhenMissing()
        throws GalleryException, IOException, ParserConfigurationException, SAXException {
    InputStream data = getClass().getResourceAsStream("/test-SVG-without-viewbox.svg");
    ScaleImageOperation scaleOp = new ScaleImageOperation(200, 100, true, ImageUtils.ScalingStrategy.SPEED);
    scaleOp.execute(data, "image/svg+xml");

    InputStream scaledData = scaleOp.getScaledData();

    // read svg/*from w ww  .java 2 s  .  c om*/
    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    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 svgDocument = builder.parse(scaledData);
    final Element svgElement = svgDocument.getDocumentElement();

    assertEquals("SVG without a 'viewBox' attribute should have gotten one set to the original image size",
            "0 0 178.0 145.0", svgElement.getAttribute("viewBox"));
}

From source file:org.infoscoop.service.GadgetResourceService.java

private byte[] validateGadgetData(String type, String path, String name, byte[] data) {
    Document gadgetDoc;/*from www  . j  a  v  a 2 s  . com*/

    try {
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setValidating(false);
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        builder.setEntityResolver(NoOpEntityResolver.getInstance());
        gadgetDoc = builder.parse(new ByteArrayInputStream(data));

        Element moduleNode = gadgetDoc.getDocumentElement();
        NodeList contentNodes = moduleNode.getElementsByTagName("Content");
        //The preparations for Locale tag
        NodeList modulePrefsList = gadgetDoc.getElementsByTagName("ModulePrefs");

        if (!"Module".equals(moduleNode.getTagName()) || contentNodes == null || contentNodes.getLength() == 0
                || modulePrefsList == null || modulePrefsList.getLength() == 0) {
            throw new GadgetResourceException("It is an invalid gadget module. ",
                    "ams_gadgetResourceInvalidGadgetModule");
        }

        Element iconElm = (Element) XPathAPI.selectSingleNode(gadgetDoc, "/Module/ModulePrefs/Icon");
        if (iconElm != null) {
            String iconUrl = iconElm.getTextContent();
            for (int i = 0; i < modulePrefsList.getLength(); i++) {
                Element modulePrefs = (Element) modulePrefsList.item(i);
                if (modulePrefs.hasAttribute("resource_url")) {
                    iconUrl = modulePrefs.getAttribute("resource_url") + iconUrl;
                    break;
                }
            }
            gadgetIconDAO.insertUpdate(type, iconUrl);
        } else {
            gadgetIconDAO.insertUpdate(type, "");
        }

        return XmlUtil.dom2String(gadgetDoc).getBytes("UTF-8");
    } catch (GadgetResourceException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new GadgetResourceException("It is an invalid gadget module. ",
                "ams_gadgetResourceInvalidGadgetModule", ex);
    }
}