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.terracotta.config.TCConfigurationParser.java

@SuppressWarnings("unchecked")
private static TcConfiguration parseStream(InputStream in, ErrorHandler eh, String source, ClassLoader loader)
        throws IOException, SAXException {
    Collection<Source> schemaSources = new ArrayList<>();

    for (ServiceConfigParser parser : loadConfigurationParserClasses(loader)) {
        schemaSources.add(parser.getXmlSchema());
        serviceParsers.put(parser.getNamespace(), parser);
    }//  ww w . java  2  s  .c  om
    schemaSources.add(new StreamSource(TERRACOTTA_XML_SCHEMA.openStream()));

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setIgnoringComments(true);
    factory.setIgnoringElementContentWhitespace(true);
    factory.setSchema(XSD_SCHEMA_FACTORY.newSchema(schemaSources.toArray(new Source[schemaSources.size()])));

    final DocumentBuilder domBuilder;
    try {
        domBuilder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new AssertionError(e);
    }
    domBuilder.setErrorHandler(eh);
    final Element config = domBuilder.parse(in).getDocumentElement();

    try {
        JAXBContext jc = JAXBContext.newInstance("org.terracotta.config",
                TCConfigurationParser.class.getClassLoader());
        Unmarshaller u = jc.createUnmarshaller();

        TcConfig tcConfig = u.unmarshal(config, TcConfig.class).getValue();
        if (tcConfig.getServers() == null) {
            Servers servers = new Servers();
            tcConfig.setServers(servers);
        }

        if (tcConfig.getServers().getServer().isEmpty()) {
            tcConfig.getServers().getServer().add(new Server());
        }
        DefaultSubstitutor.applyDefaults(tcConfig);
        applyPlatformDefaults(tcConfig, source);

        Map<String, Map<String, ServiceOverride>> serviceOverrides = new HashMap<>();
        for (Server server : tcConfig.getServers().getServer()) {
            if (server.getServiceOverrides() != null
                    && server.getServiceOverrides().getServiceOverride() != null) {
                for (ServiceOverride serviceOverride : server.getServiceOverrides().getServiceOverride()) {
                    String id = ((Service) serviceOverride.getOverrides()).getId();
                    if (serviceOverrides.get(id) == null) {
                        serviceOverrides.put(id, new HashMap<>());
                    }
                    serviceOverrides.get(id).put(server.getName(), serviceOverride);
                }
            }
        }

        Map<String, List<ServiceProviderConfiguration>> serviceConfigurations = new HashMap<>();
        if (tcConfig.getServices() != null && tcConfig.getServices().getService() != null) {
            //now parse the service configuration.
            for (Service service : tcConfig.getServices().getService()) {
                Element element = service.getAny();
                if (element != null) {
                    URI namespace = URI.create(element.getNamespaceURI());
                    ServiceConfigParser parser = serviceParsers.get(namespace);
                    if (parser == null) {
                        throw new TCConfigurationSetupException("Can't find parser for service " + namespace);
                    }
                    ServiceProviderConfiguration serviceProviderConfiguration = parser.parse(element, source);
                    for (Server server : tcConfig.getServers().getServer()) {
                        if (serviceConfigurations.get(server.getName()) == null) {
                            serviceConfigurations.put(server.getName(), new ArrayList<>());
                        }
                        if (serviceOverrides.get(service.getId()) != null
                                && serviceOverrides.get(service.getId()).containsKey(server.getName())) {
                            Element overrideElement = serviceOverrides.get(service.getId())
                                    .get(server.getName()).getAny();
                            if (overrideElement != null) {
                                serviceConfigurations.get(server.getName())
                                        .add(parser.parse(overrideElement, source));
                            }
                        } else {
                            serviceConfigurations.get(server.getName()).add(serviceProviderConfiguration);
                        }
                    }
                }
            }
        }

        return new TcConfiguration(tcConfig, source, serviceConfigurations);
    } catch (JAXBException e) {
        throw new TCConfigurationSetupException(e);
    }
}

From source file:org.tinygroup.jspengine.xmlparser.ParserUtils.java

/**
 * Parse the specified XML document, and return a <code>TreeNode</code>
 * that corresponds to the root node of the document tree.
 *
 * @param uri URI of the XML document being parsed
 * @param is Input source containing the deployment descriptor
 * @param validate true if the XML document needs to be validated against
 * its DTD or schema, false otherwise//w  w  w.  j a  v a2s .  c o m
 *
 * @exception JasperException if an I/O or parsing error has occurred
 */
public TreeNode parseXMLDocument(String uri, InputSource is, boolean validate) throws JasperException {

    Document document = null;

    // Perform an XML parse of this document, via JAXP

    // START 6412405
    ClassLoader currentLoader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    // END 6412405
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        /* See CR 6399139
        factory.setFeature(
        "http://apache.org/xml/features/validation/dynamic",
        true);
        */
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver(entityResolver);
        builder.setErrorHandler(errorHandler);
        document = builder.parse(is);
        document.setDocumentURI(uri);
        if (validate) {
            Schema schema = getSchema(document);
            if (schema != null) {
                // Validate TLD against specified schema
                schema.newValidator().validate(new DOMSource(document));
            }
            /* See CR 6399139
            else {
            log.warn(Localizer.getMessage(
                "jsp.warning.dtdValidationNotSupported"));
            }
            */
        }
    } catch (ParserConfigurationException ex) {
        throw new JasperException(Localizer.getMessage("jsp.error.parse.xml", uri), ex);
    } catch (SAXParseException ex) {
        throw new JasperException(Localizer.getMessage("jsp.error.parse.xml.line", uri,
                Integer.toString(ex.getLineNumber()), Integer.toString(ex.getColumnNumber())), ex);
    } catch (SAXException sx) {
        throw new JasperException(Localizer.getMessage("jsp.error.parse.xml", uri), sx);
    } catch (IOException io) {
        throw new JasperException(Localizer.getMessage("jsp.error.parse.xml", uri), io);
        // START 6412405
    } finally {
        Thread.currentThread().setContextClassLoader(currentLoader);
        // END 6412405
    }

    // Convert the resulting document to a graph of TreeNodes
    return (convert(null, document.getDocumentElement()));
}

From source file:org.unigram.docvalidator.ConfigurationLoader.java

protected static Document parseConfigurationString(InputStream input) {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    Document doc = null;//from   ww  w .  j  ava 2 s . c o m
    try {
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        dBuilder.setErrorHandler(new SAXErrorHandler());
        doc = dBuilder.parse(input);
    } catch (SAXException e) {
        LOG.error(e.getMessage());
    } catch (IOException e) {
        LOG.error(e.getMessage());
    } catch (ParserConfigurationException e) {
        LOG.error(e.getMessage());
    } catch (Throwable e) {
        LOG.error(e.getMessage());
    }
    return doc;
}

From source file:org.webical.plugin.xml.PluginManifestReader.java

/**
 * Validates the pluginManifest to the webicalPluginSchemaSource
 * @param pluginManifest the manifest to validate
 * @return the Domdocument build to validate
 * @throws ParserConfigurationException on error
 * @throws SAXException on error/*from   w w w .j a v a  2 s  .c om*/
 * @throws IOException on error
 */
private Document validatePluginManifest(File pluginManifest)
        throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(true);

    factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
    if (log.isDebugEnabled()) {
        log.debug("Xsd resource property: " + webicalPluginSchema);
        log.debug("Setting xsd to: " + webicalPluginSchema);
    }

    factory.setAttribute(JAXP_SCHEMA_SOURCE, webicalPluginSchema);

    DocumentBuilder documentBuilder = factory.newDocumentBuilder();
    documentBuilder.setErrorHandler(new PluginValidationErrorHandler(pluginManifest));

    return documentBuilder.parse(pluginManifest);
}

From source file:org.wso2.balana.ctx.InputParser.java

/**
 * Tries to Parse the given output as a Context document.
 * /*from   www  . j  a  v  a 2 s.  co  m*/
 * @param input the stream to parse
 * @param rootTage 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 = Utils.getSecuredDocumentBuilderFactory();
        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:org.wso2.carbon.bpel.common.DOMUtils.java

private static DocumentBuilder getBuilder() {
    DocumentBuilder builder = builders.get();
    if (builder == null) {
        synchronized (documentBuilderFactory) {
            try {
                builder = documentBuilderFactory.newDocumentBuilder();
                builder.setErrorHandler(new LoggingErrorHandler());
            } catch (ParserConfigurationException e) {
                String errMsg = "Error occurred while building the document";
                log.error(errMsg, e);//w  w  w  .j a  v  a2  s  .c o m
                throw new RuntimeException(errMsg, e);
            }
        }
        builders.set(builder);
    }
    return builder;
}

From source file:org.wso2.carbon.humantask.core.utils.DOMUtils.java

private static DocumentBuilder getBuilder() {
    DocumentBuilder builder = builders.get();
    if (builder == null) {
        synchronized (documentBuilderFactory) {
            try {
                builder = documentBuilderFactory.newDocumentBuilder();
                builder.setErrorHandler(new SAXLoggingErrorHandler());

            } catch (ParserConfigurationException e) {
                log.error(e.getMessage(), e);
                throw new RuntimeException(e);
            }//from  w  w w .j a va  2 s .  com
        }
        builders.set(builder);
    }
    return builder;
}

From source file:org.yamj.core.tools.xml.DOMHelper.java

/**
 * Get a DOM document from the supplied file
 *
 * @param xmlFile// w w w .j  a  va2s . c  om
 * @return
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws SAXException
 */
public static Document getDocFromFile(File xmlFile)
        throws ParserConfigurationException, SAXException, IOException {
    URL url = xmlFile.toURI().toURL();
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();

    // Custom error handler
    db.setErrorHandler(new SaxErrorHandler());
    Document doc;
    try (InputStream in = url.openStream()) {
        doc = db.parse(in);
    } catch (SAXParseException ex) {
        if (FilenameUtils.isExtension(xmlFile.getName().toLowerCase(), "xml")) {
            throw new SAXParseException("Failed to process file as XML", null, ex);
        }
        // Try processing the file a different way
        doc = null;
    }

    if (doc == null) {
        // try wrapping the file in a root
        try (StringReader sr = new StringReader(wrapInXml(FileTools.readFileToString(xmlFile)))) {
            doc = db.parse(new InputSource(sr));
        }
    }

    if (doc != null) {
        doc.getDocumentElement().normalize();
    }
    return doc;
}

From source file:org.zaproxy.zap.utils.ZapXmlConfiguration.java

@Override
protected DocumentBuilder createDocumentBuilder() throws ParserConfigurationException {
    DocumentBuilderFactory factory = XmlUtils.newXxeDisabledDocumentBuilderFactory();

    // Same behaviour as base method:
    if (isValidating()) {
        factory.setValidating(true);/*from   w  w  w.  j  av a 2s  .  c  o m*/
        if (isSchemaValidation()) {
            factory.setNamespaceAware(true);
            factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                    "http://www.w3.org/2001/XMLSchema");
        }
    }

    DocumentBuilder result = factory.newDocumentBuilder();
    result.setEntityResolver(getEntityResolver());

    if (isValidating()) {
        result.setErrorHandler(new DefaultHandler() {

            @Override
            public void error(SAXParseException ex) throws SAXException {
                throw ex;
            }
        });
    }
    return result;
}

From source file:pl.otros.logview.importer.UtilLoggingXmlLogImporter.java

@Override
public void initParsingContext(ParsingContext parsingContext) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(false);/*from  ww  w .  j ava  2 s  .c  o m*/

    try {
        DocumentBuilder docBuilder = dbf.newDocumentBuilder();
        docBuilder.setErrorHandler(new SAXErrorHandler());
        docBuilder.setEntityResolver(new UtilLoggingEntityResolver());
        parsingContext.getCustomConextProperties().put(DOC_BUILDER, docBuilder);
        parsingContext.getCustomConextProperties().put(PARTIAL_EVENT, "");
    } catch (ParserConfigurationException pce) {
        System.err.println("Unable to get document builder");
    }

}