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.nifi.controller.service.ControllerServiceLoader.java

public List<ControllerServiceNode> loadControllerServices(final ControllerServiceProvider provider)
        throws IOException {
    final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    InputStream fis = null;/*from  w w w.  j a  v a2  s.  c om*/
    BufferedInputStream bis = null;
    documentBuilderFactory.setNamespaceAware(true);

    final List<ControllerServiceNode> services = new ArrayList<>();

    try {
        final URL configurationResource = this.getClass().getResource("/ControllerServiceConfiguration.xsd");
        if (configurationResource == null) {
            throw new NullPointerException("Unable to load XML Schema for ControllerServiceConfiguration");
        }
        final Schema schema = schemaFactory.newSchema(configurationResource);
        documentBuilderFactory.setSchema(schema);
        final DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();

        builder.setErrorHandler(new org.xml.sax.ErrorHandler() {

            @Override
            public void fatalError(final SAXParseException err) throws SAXException {
                logger.error("Config file line " + err.getLineNumber() + ", col " + err.getColumnNumber()
                        + ", uri " + err.getSystemId() + " :message: " + err.getMessage());
                if (logger.isDebugEnabled()) {
                    logger.error("Error Stack Dump", err);
                }
                throw err;
            }

            @Override
            public void error(final SAXParseException err) throws SAXParseException {
                logger.error("Config file line " + err.getLineNumber() + ", col " + err.getColumnNumber()
                        + ", uri " + err.getSystemId() + " :message: " + err.getMessage());
                if (logger.isDebugEnabled()) {
                    logger.error("Error Stack Dump", err);
                }
                throw err;
            }

            @Override
            public void warning(final SAXParseException err) throws SAXParseException {
                logger.warn(" Config file line " + err.getLineNumber() + ", uri " + err.getSystemId()
                        + " : message : " + err.getMessage());
                if (logger.isDebugEnabled()) {
                    logger.warn("Warning stack dump", err);
                }
                throw err;
            }
        });

        //if controllerService.xml does not exist, create an empty file...
        fis = Files.newInputStream(this.serviceConfigXmlPath, StandardOpenOption.READ);
        bis = new BufferedInputStream(fis);
        if (Files.size(this.serviceConfigXmlPath) > 0) {
            final Document document = builder.parse(bis);
            final NodeList servicesNodes = document.getElementsByTagName("services");
            final Element servicesElement = (Element) servicesNodes.item(0);

            final List<Element> serviceNodes = DomUtils.getChildElementsByTagName(servicesElement, "service");
            for (final Element serviceElement : serviceNodes) {
                //get properties for the specific controller task - id, name, class,
                //and schedulingPeriod must be set
                final String serviceId = DomUtils.getChild(serviceElement, "identifier").getTextContent()
                        .trim();
                final String serviceClass = DomUtils.getChild(serviceElement, "class").getTextContent().trim();

                //set the class to be used for the configured controller task
                final ControllerServiceNode serviceNode = provider.createControllerService(serviceClass,
                        serviceId, false);

                //optional task-specific properties
                for (final Element optionalProperty : DomUtils.getChildElementsByTagName(serviceElement,
                        "property")) {
                    final String name = optionalProperty.getAttribute("name").trim();
                    final String value = optionalProperty.getTextContent().trim();
                    serviceNode.setProperty(name, value);
                }

                services.add(serviceNode);
                provider.enableControllerService(serviceNode);
            }
        }
    } catch (SAXException | ParserConfigurationException sxe) {
        throw new IOException(sxe);
    } finally {
        FileUtils.closeQuietly(fis);
        FileUtils.closeQuietly(bis);
    }

    return services;
}

From source file:org.apache.nifi.fingerprint.FingerprintFactoryTest.java

private DocumentBuilder getValidatingDocumentBuilder() {
    final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final Schema schema;
    try {//ww  w. ja  v a 2  s .  co m
        schema = schemaFactory.newSchema(FingerprintFactory.class.getResource(FLOW_CONFIG_XSD));
    } catch (final Exception e) {
        throw new RuntimeException("Failed to parse schema for file flow configuration.", e);
    }
    try {
        documentBuilderFactory.setSchema(schema);
        DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
        docBuilder.setErrorHandler(new ErrorHandler() {
            @Override
            public void warning(SAXParseException e) throws SAXException {
                throw e;
            }

            @Override
            public void error(SAXParseException e) throws SAXException {
                throw e;
            }

            @Override
            public void fatalError(SAXParseException e) throws SAXException {
                throw e;
            }
        });
        return docBuilder;
    } catch (final Exception e) {
        throw new RuntimeException("Failed to create document builder for flow configuration.", e);
    }
}

From source file:org.apache.nifi.minifi.FlowParser.java

/**
 * Generates a {@link Document} from the flow configuration file provided
 *///from   ww  w .java2s . c  o m
public Document parse(final File flowConfigurationFile) {
    if (flowConfigurationFile == null) {
        logger.debug("Flow Configuration file was null");
        return null;
    }

    // if the flow doesn't exist or is 0 bytes, then return null
    final Path flowPath = flowConfigurationFile.toPath();
    try {
        if (!Files.exists(flowPath) || Files.size(flowPath) == 0) {
            logger.warn("Flow Configuration does not exist or was empty");
            return null;
        }
    } catch (IOException e) {
        logger.error("An error occurred determining the size of the Flow Configuration file");
        return null;
    }

    // otherwise create the appropriate input streams to read the file
    try (final InputStream in = Files.newInputStream(flowPath, StandardOpenOption.READ);
            final InputStream gzipIn = new GZIPInputStream(in)) {

        final byte[] flowBytes = IOUtils.toByteArray(gzipIn);
        if (flowBytes == null || flowBytes.length == 0) {
            logger.warn("Could not extract root group id because Flow Configuration File was empty");
            return null;
        }

        final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setNamespaceAware(true);
        docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

        // parse the flow
        final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        docBuilder.setErrorHandler(new LoggingXmlParserErrorHandler("Flow Configuration", logger));
        final Document document = docBuilder.parse(new ByteArrayInputStream(flowBytes));
        return document;

    } catch (final SAXException | ParserConfigurationException | IOException ex) {
        logger.error("Unable to parse flow {} due to {}", new Object[] { flowPath.toAbsolutePath(), ex });
        return null;
    }
}

From source file:org.apache.ode.utils.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) {
                __log.error(e);//from  ww  w.  j a v  a  2s .  c om
                throw new RuntimeException(e);
            }
        }
        __builders.set(builder);
    }
    return builder;
}

From source file:org.apache.openjpa.lib.xml.XMLFactory.java

/**
 * Return a DocumentBuilder with the specified configuration.
 *//*  w  ww . j a va 2s . c o  m*/
public static DocumentBuilder getDOMParser(boolean validating, boolean namespaceAware) {
    DocumentBuilder db;
    try {
        db = _domFactories[factoryIndex(validating, namespaceAware)].newDocumentBuilder();
    } catch (ParserConfigurationException pce) {
        throw new NestableRuntimeException(pce);
    }

    if (validating)
        db.setErrorHandler(_validating);
    return db;
}

From source file:org.apache.sling.urlrewriter.internal.SlingUrlRewriteFilter.java

private Document createDocument(final String rules) {
    if (StringUtils.isBlank(rules)) {
        logger.warn("given rules are blank");
        return null;
    }//w  w w  .j a  v a 2s .  co  m

    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    factory.setNamespaceAware(true);
    factory.setIgnoringComments(true);
    factory.setIgnoringElementContentWhitespace(true);

    try {
        final String systemId = "";
        final ConfHandler confHandler = new ConfHandler(systemId);
        final DocumentBuilder documentBuilder = factory.newDocumentBuilder();
        documentBuilder.setErrorHandler(confHandler);
        documentBuilder.setEntityResolver(confHandler);

        final InputStream inputStream = new ByteArrayInputStream(rules.getBytes("UTF-8"));
        final Document document = documentBuilder.parse(inputStream); // , systemId);
        IOUtils.closeQuietly(inputStream);
        return document;
    } catch (Exception e) {
        logger.error("error creating document from rules property", e);
        return null;
    }
}

From source file:org.apache.solr.core.Config.java

/**
 * Builds a config://w  w w  .j  av a  2 s  .  c  o m
 * <p>
 * Note that the 'name' parameter is used to obtain a valid input stream if no valid one is provided through 'is'.
 * If no valid stream is provided, a valid SolrResourceLoader instance should be provided through 'loader' so
 * the resource can be opened (@see SolrResourceLoader#openResource); if no SolrResourceLoader instance is provided, a default one
 * will be created.
 * </p>
 * <p>
 * Consider passing a non-null 'name' parameter in all use-cases since it is used for logging & exception reporting.
 * </p>
 * @param loader the resource loader used to obtain an input stream if 'is' is null
 * @param name the resource name used if the input stream 'is' is null
 * @param is the resource as a SAX InputSource
 * @param prefix an optional prefix that will be preprended to all non-absolute xpath expressions
 * @throws javax.xml.parsers.ParserConfigurationException
 * @throws java.io.IOException
 * @throws org.xml.sax.SAXException
 */
public Config(SolrResourceLoader loader, String name, InputSource is, String prefix)
        throws ParserConfigurationException, IOException, SAXException {
    if (loader == null) {
        loader = new SolrResourceLoader(null);
    }
    this.loader = loader;
    this.name = name;
    this.prefix = (prefix != null && !prefix.endsWith("/")) ? prefix + '/' : prefix;
    try {
        javax.xml.parsers.DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        if (is == null) {
            is = new InputSource(loader.openConfig(name));
            is.setSystemId(SystemIdResolver.createSystemIdFromResourceName(name));
        }

        // only enable xinclude, if a SystemId is available
        if (is.getSystemId() != null) {
            try {
                dbf.setXIncludeAware(true);
                dbf.setNamespaceAware(true);
            } catch (UnsupportedOperationException e) {
                log.warn(name + " XML parser doesn't support XInclude option");
            }
        }

        final DocumentBuilder db = dbf.newDocumentBuilder();
        db.setEntityResolver(new SystemIdResolver(loader));
        db.setErrorHandler(xmllog);
        try {
            doc = db.parse(is);
        } finally {
            // some XML parsers are broken and don't close the byte stream (but they should according to spec)
            IOUtils.closeQuietly(is.getByteStream());
        }

        DOMUtil.substituteProperties(doc, loader.getCoreProperties());
    } catch (ParserConfigurationException e) {
        SolrException.log(log, "Exception during parsing file: " + name, e);
        throw e;
    } catch (SAXException e) {
        SolrException.log(log, "Exception during parsing file: " + name, e);
        throw e;
    } catch (SolrException e) {
        SolrException.log(log, "Error in " + name, e);
        throw e;
    }
}

From source file:org.apache.solr.handler.dataimport.DataImporter.java

public DIHConfiguration loadDataConfig(InputSource configFile) {

    DIHConfiguration dihcfg = null;//from   w w  w .  j av a  2s .  c o  m
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        // only enable xinclude, if a a SolrCore and SystemId is present (makes no sense otherwise)
        if (core != null && configFile.getSystemId() != null) {
            try {
                dbf.setXIncludeAware(true);
                dbf.setNamespaceAware(true);
            } catch (UnsupportedOperationException e) {
                LOG.warn("XML parser doesn't support XInclude option");
            }
        }

        DocumentBuilder builder = dbf.newDocumentBuilder();
        if (core != null)
            builder.setEntityResolver(new SystemIdResolver(core.getResourceLoader()));
        builder.setErrorHandler(XMLLOG);
        Document document;
        try {
            document = builder.parse(configFile);
        } finally {
            // some XML parsers are broken and don't close the byte stream (but they should according to spec)
            IOUtils.closeQuietly(configFile.getByteStream());
        }

        dihcfg = readFromXml(document);
        LOG.info("Data Configuration loaded successfully");
    } catch (Exception e) {
        throw new DataImportHandlerException(SEVERE, "Data Config problem: " + e.getMessage(), e);
    }
    for (Entity e : dihcfg.getEntities()) {
        if (e.getAllAttributes().containsKey(SqlEntityProcessor.DELTA_QUERY)) {
            isDeltaImportSupported = true;
            break;
        }
    }
    return dihcfg;
}

From source file:org.apache.tika.parser.pdf.PDFParser.java

private Document loadDOM(PDMetadata pdMetadata, Metadata metadata, ParseContext context) {
    if (pdMetadata == null) {
        return null;
    }//from  w ww  . j a v a 2 s .co m
    InputStream is = null;
    try {
        try {
            is = pdMetadata.exportXMPMetadata();
        } catch (IOException e) {
            EmbeddedDocumentUtil.recordEmbeddedStreamException(e, metadata);
            return null;
        }
        DocumentBuilder documentBuilder = context.getDocumentBuilder();
        documentBuilder.setErrorHandler((ErrorHandler) null);
        return documentBuilder.parse(is);
    } catch (IOException | SAXException | TikaException e) {
        EmbeddedDocumentUtil.recordException(e, metadata);
    } finally {
        IOUtils.closeQuietly(is);
    }
    return null;

}

From source file:org.apache.woden.internal.DOMWSDLReader.java

/**
 * Create a JAXP DocumentBuilder will use for parsing XML documents. 
 * @param factory the JAXP DocumentBuilderFactory that the DocumentBuilder
 * should be created with/*from  ww  w. j a  v  a  2  s  .  c  o  m*/
 * @param entityResolver the SAX EntityResolver to use
 * @param errorHandler the SAX ErrorHandler to use
 * @return the JAXP DocumentBuilder
 * @throws ParserConfigurationException if thrown by JAXP methods
 */
protected DocumentBuilder createDocumentBuilder(DocumentBuilderFactory factory, EntityResolver entityResolver,
        ErrorHandler errorHandler) throws ParserConfigurationException {

    DocumentBuilder docBuilder = factory.newDocumentBuilder();
    if (entityResolver != null) {
        docBuilder.setEntityResolver(entityResolver);
    }
    if (errorHandler != null) {
        docBuilder.setErrorHandler(errorHandler);
    }
    return docBuilder;
}