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.pentaho.di.job.entries.dtdvalidator.DTDValidator.java

public boolean validate() {

    boolean retval = false;

    FileObject xmlfile = null;//from w  ww. ja  va2s  .c  o  m
    FileObject DTDfile = null;

    ByteArrayInputStream ba = null;
    try {
        if (xmlfilename != null && ((getDTDFilename() != null && !isInternDTD()) || (isInternDTD()))) {
            xmlfile = KettleVFS.getFileObject(getXMLFilename());

            if (xmlfile.exists()) {

                URL xmlFile = new File(KettleVFS.getFilename(xmlfile)).toURI().toURL();
                StringBuffer xmlStringbuffer = new StringBuffer("");

                BufferedReader xmlBufferedReader = null;
                InputStreamReader is = null;
                try {
                    // open XML File
                    is = new InputStreamReader(xmlFile.openStream());
                    xmlBufferedReader = new BufferedReader(is);

                    char[] buffertXML = new char[1024];
                    int LenXML = -1;
                    while ((LenXML = xmlBufferedReader.read(buffertXML)) != -1) {
                        xmlStringbuffer.append(buffertXML, 0, LenXML);
                    }
                } finally {
                    if (is != null) {
                        is.close();
                    }
                    if (xmlBufferedReader != null) {
                        xmlBufferedReader.close();
                    }
                }

                // Prepare parsing ...
                DocumentBuilderFactory DocBuilderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder DocBuilder = DocBuilderFactory.newDocumentBuilder();

                // Let's try to get XML document encoding

                DocBuilderFactory.setValidating(false);
                ba = new ByteArrayInputStream(xmlStringbuffer.toString().getBytes("UTF-8"));
                Document xmlDocDTD = DocBuilder.parse(ba);
                if (ba != null) {
                    ba.close();
                }

                String encoding = null;
                if (xmlDocDTD.getXmlEncoding() == null) {
                    encoding = "UTF-8";
                } else {
                    encoding = xmlDocDTD.getXmlEncoding();
                }

                int xmlStartDTD = xmlStringbuffer.indexOf("<!DOCTYPE");

                if (isInternDTD()) {
                    // DTD find in the XML document
                    if (xmlStartDTD != -1) {
                        log.logBasic(BaseMessages.getString(PKG, "JobEntryDTDValidator.ERRORDTDFound.Label",
                                getXMLFilename()));
                    } else {
                        setErrorMessage(BaseMessages.getString(PKG,
                                "JobEntryDTDValidator.ERRORDTDNotFound.Label", getXMLFilename()));
                    }

                } else {
                    // DTD in external document
                    // If we find an intern declaration, we remove it
                    DTDfile = KettleVFS.getFileObject(getDTDFilename());

                    if (DTDfile.exists()) {
                        if (xmlStartDTD != -1) {
                            int EndDTD = xmlStringbuffer.indexOf(">", xmlStartDTD);
                            // String DocTypeDTD = xmlStringbuffer.substring(xmlStartDTD, EndDTD + 1);
                            xmlStringbuffer.replace(xmlStartDTD, EndDTD + 1, "");
                        }

                        String xmlRootnodeDTD = xmlDocDTD.getDocumentElement().getNodeName();

                        String RefDTD = "<?xml version='" + xmlDocDTD.getXmlVersion() + "' encoding='"
                                + encoding + "'?>\n<!DOCTYPE " + xmlRootnodeDTD + " SYSTEM '"
                                + KettleVFS.getFilename(DTDfile) + "'>\n";

                        int xmloffsetDTD = xmlStringbuffer.indexOf("<" + xmlRootnodeDTD);
                        xmlStringbuffer.replace(0, xmloffsetDTD, RefDTD);
                    } else {
                        log.logError(
                                BaseMessages.getString(PKG,
                                        "JobEntryDTDValidator.ERRORDTDFileNotExists.Subject"),
                                BaseMessages.getString(PKG, "JobEntryDTDValidator.ERRORDTDFileNotExists.Msg",
                                        getDTDFilename()));
                    }
                }

                if (!(isInternDTD() && xmlStartDTD == -1 || (!isInternDTD() && !DTDfile.exists()))) {

                    // Let's parse now ...
                    MyErrorHandler error = new MyErrorHandler();
                    DocBuilderFactory.setValidating(true);
                    DocBuilder = DocBuilderFactory.newDocumentBuilder();
                    DocBuilder.setErrorHandler(error);

                    ba = new ByteArrayInputStream(xmlStringbuffer.toString().getBytes(encoding));
                    xmlDocDTD = DocBuilder.parse(ba);

                    if (error.errorMessage == null) {
                        log.logBasic(BaseMessages.getString(PKG, "JobEntryDTDValidator.DTDValidatorOK.Subject"),
                                BaseMessages.getString(PKG, "JobEntryDTDValidator.DTDValidatorOK.Label",
                                        getXMLFilename()));

                        // Everything is OK
                        retval = true;
                    } else {
                        // Invalid DTD
                        setNrErrors(error.nrErrors);
                        setErrorMessage(BaseMessages.getString(PKG, "JobEntryDTDValidator.DTDValidatorKO",
                                getXMLFilename(), error.nrErrors, error.errorMessage));
                    }
                }

            } else {
                if (!xmlfile.exists()) {
                    setErrorMessage(BaseMessages.getString(PKG, "JobEntryDTDValidator.FileDoesNotExist.Label",
                            getXMLFilename()));
                }
            }
        } else {
            setErrorMessage(BaseMessages.getString(PKG, "JobEntryDTDValidator.AllFilesNotNull.Label"));
        }
    } catch (Exception e) {
        setErrorMessage(BaseMessages.getString(PKG, "JobEntryDTDValidator.ErrorDTDValidator.Label",
                getXMLFilename(), getDTDFilename(), e.getMessage()));
    } finally {
        try {
            if (xmlfile != null) {
                xmlfile.close();
            }
            if (DTDfile != null) {
                DTDfile.close();
            }
            if (ba != null) {
                ba.close();
            }
        } catch (IOException e) {
            // Ignore close errors
        }
    }
    return retval;
}

From source file:org.pentaho.reporting.engine.classic.extensions.datasources.mondrian.MondrianUtil.java

private static String parseXmlDocument(final InputStream stream)
        throws ResourceCreationException, ParserConfigurationException {
    final DocumentBuilderFactory dbf = XMLParserFactoryProducer.createSecureDocBuilderFactory();
    dbf.setNamespaceAware(true);// w  w w  .j av a 2s  . c o  m
    dbf.setValidating(false);

    try {
        final DocumentBuilder db = dbf.newDocumentBuilder();
        db.setEntityResolver(ParserEntityResolver.getDefaultResolver());
        db.setErrorHandler(new LoggingErrorHandler());
        final InputSource input = new InputSource(stream);
        final Document document = db.parse(input);
        final Element documentElement = document.getDocumentElement();
        if ("Schema".equals(documentElement.getTagName())) { // NON-NLS
            return documentElement.getAttribute("name");
        }
        return null;
    } catch (ParserConfigurationException e) {
        throw new ResourceCreationException("Unable to initialize the XML-Parser", e);
    } catch (SAXException e) {
        throw new ResourceCreationException("Unable to parse the document.", e);
    } catch (IOException e) {
        throw new ResourceCreationException("Unable to parse the document.", e);
    }
}

From source file:org.pentaho.reporting.libraries.xmlns.parser.DomTreeResourceFactory.java

/**
 * Creates a resource by interpreting the data given in the resource-data object. If additional datastreams need to be
 * parsed, the provided resource manager should be used.
 *
 * @param manager the resource manager used for all resource loading.
 * @param data    the resource-data from where the binary data is read.
 * @param context the resource context used to resolve relative resource paths.
 * @return the parsed result, never null.
 * @throws org.pentaho.reporting.libraries.resourceloader.ResourceCreationException if the resource could not be
 *                                                                                  parsed due to syntaxctial or
 *                                                                                  logical errors in the data.
 * @throws org.pentaho.reporting.libraries.resourceloader.ResourceLoadingException  if the resource could not be
 *                                                                                  accessed from the physical
 *                                                                                  storage.
 *//*from   w  w  w.j  a  v a  2  s.c  om*/
public Resource create(final ResourceManager manager, final ResourceData data, final ResourceKey context)
        throws ResourceCreationException, ResourceLoadingException {
    final DocumentBuilderFactory dbf;
    try {
        dbf = XMLParserFactoryProducer.createSecureDocBuilderFactory();
        dbf.setNamespaceAware(true);
        dbf.setValidating(false);
        final DocumentBuilder db = dbf.newDocumentBuilder();
        db.setEntityResolver(ParserEntityResolver.getDefaultResolver());
        db.setErrorHandler(new LoggingErrorHandler());
        final ResourceDataInputSource input = new ResourceDataInputSource(data, manager);
        return new DomResource(data.getKey(), db.parse(input), data.getVersion(manager));
    } catch (ParserConfigurationException e) {
        throw new ResourceCreationException("Unable to initialize the XML-Parser", e);
    } catch (SAXException e) {
        throw new ResourceCreationException("Unable to parse the document: " + data.getKey(), e);
    } catch (IOException e) {
        throw new ResourceLoadingException("Unable to read the stream from document: " + data.getKey(), e);
    }
}

From source file:org.plasma.sdo.helper.PlasmaXMLHelper.java

private void validateDOM(InputStream inputStream, String locationURI, XMLOptions options) throws IOException {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);//from  w  ww .j a  v a  2 s . c  om
    factory.setValidating(true);
    try {
        factory.setAttribute(XMLConstants.JAXP_SCHEMA_LANGUAGE, SchemaConstants.XMLSCHEMA_NAMESPACE_URI);
        factory.setValidating(true);
        //factory.setNamespaceAware(true);
        //factory.setFeature("http://apache.org/xml/features/validation/schema",true);
        //factory.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
    } catch (IllegalArgumentException e) {
        log.warn("parser does not support JAXP 1.2");
    } /*catch (ParserConfigurationException e) {
       throw new PlasmaDataObjectException(e);
      }*/

    if (locationURI != null) {
        factory.setAttribute(XMLConstants.JAXP_NO_NAMESPACE_SCHEMA_SOURCE, locationURI);
    }

    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        if (options.getErrorHandler() == null)
            builder.setErrorHandler(new DefaultErrorHandler(options));
        else
            builder.setErrorHandler(options.getErrorHandler());
        if (log.isDebugEnabled())
            log.debug("validating...");
        builder.parse(inputStream);

    } catch (ParserConfigurationException e) {
        throw new PlasmaDataObjectException(e);
    } catch (SAXException e) {
        throw new PlasmaDataObjectException(e);
    }

}

From source file:org.rimudb.configuration.AbstractXmlLoader.java

private Document loadXML(InputStream is) throws Exception {
    // Load document
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);//  w ww .  j  a  v a  2  s. c  o  m

    factory.setIgnoringElementContentWhitespace(true);
    factory.setIgnoringComments(true);
    factory.setValidating(false); // Don't use DTD validation

    DocumentBuilder docBuilder = factory.newDocumentBuilder();

    ErrorHandler eh = new StrictErrorHandler();
    docBuilder.setErrorHandler(eh);

    InputSource inputSource = new InputSource(is);
    inputSource.setPublicId(RimuDBNamespace.URI);
    inputSource.setSystemId(RimuDBNamespace.URI);

    Document document = docBuilder.parse(is);
    is.close();

    // Determine the XML schema version from the XML document without validating
    Element root = document.getDocumentElement();
    setDocumentSchema(lookupSchemaVersion(root));

    // Validate the XML document and determine the XML Schema version
    if (isValidateXML()) {
        if (getDocumentSchema() != null) {
            // Validate the document against the schema found in the document 
            SAXParseException saxParseException = validate(document, getDocumentSchema());
            if (saxParseException != null) {
                throw saxParseException;
            }
        } else {
            setDocumentSchema(lookupSchemaByValidation(document));
        }
    }

    return document;
}

From source file:org.settings4j.config.DOMConfigurator.java

private void doConfigure(final ParseAction action) throws FactoryConfigurationError {
    DocumentBuilderFactory dbf = null;
    try {/*from   w  w w  .ja va  2  s  . c om*/
        LOG.debug("System property is: {}", System.getProperty(DOCUMENT_BUILDER_FACTORY_KEY));
        dbf = DocumentBuilderFactory.newInstance();
        LOG.debug("Standard DocumentBuilderFactory search succeded.");
        LOG.debug("DocumentBuilderFactory is: {}", dbf.getClass().getName());
    } catch (final FactoryConfigurationError fce) {
        final Exception e = fce.getException();
        LOG.debug("Could not instantiate a DocumentBuilderFactory.", e);
        throw fce;
    }

    try {
        dbf.setValidating(true);

        final DocumentBuilder docBuilder = dbf.newDocumentBuilder();

        docBuilder.setErrorHandler(new SAXErrorHandler());
        docBuilder.setEntityResolver(new Settings4jEntityResolver());

        final Document doc = action.parse(docBuilder);
        parse(doc.getDocumentElement());
    } catch (final Exception e) {
        // I know this is miserable...
        LOG.error("Could not parse {}.", action.toString(), e);
    }
}

From source file:org.springframework.beans.factory.xml.DefaultDocumentLoader.java

/**
 * Create a JAXP DocumentBuilder that this bean definition reader
 * will use for parsing XML documents. Can be overridden in subclasses,
 * adding further initialization of the builder.
 * @param factory the JAXP DocumentBuilderFactory that the DocumentBuilder
 * should be created with//from  w w  w.j  a v a  2 s . co  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,
        @Nullable EntityResolver entityResolver, @Nullable ErrorHandler errorHandler)
        throws ParserConfigurationException {

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

From source file:org.springframework.webflow.engine.model.builder.xml.DefaultDocumentLoader.java

public Document loadDocument(Resource resource) throws IOException, ParserConfigurationException, SAXException {
    InputStream is = null;/*from ww w. j  ava  2 s .  c  o m*/
    try {
        is = resource.getInputStream();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(isValidating());
        factory.setNamespaceAware(true);
        try {
            factory.setAttribute(SCHEMA_LANGUAGE_ATTRIBUTE, XSD_SCHEMA_LANGUAGE);
        } catch (IllegalArgumentException ex) {
            throw new IllegalStateException("Unable to validate using XSD: Your JAXP provider [" + factory
                    + "] does not support XML Schema. "
                    + "Are you running on Java 1.4 or below with Apache Crimson? "
                    + "If so you must upgrade to Apache Xerces (or Java 5 or >) for full XSD support.");
        }
        DocumentBuilder docBuilder = factory.newDocumentBuilder();
        docBuilder.setErrorHandler(new SimpleSaxErrorHandler(logger));
        docBuilder.setEntityResolver(getEntityResolver());
        return docBuilder.parse(is);
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:org.springmodules.remoting.xmlrpc.dom.AbstractDomXmlRpcParser.java

/**
 * Creates a new XML document by parsing the given InputStream.
 * /* w  w w . j ava  2 s .c o  m*/
 * @param inputStream
 *          the InputStream to parse.
 * @return the created XML document.
 * @throws XmlRpcServerException
 *           if there are any internal errors.
 * @throws XmlRpcParsingException
 *           if there are any errors during the parsing.
 */
protected final Document loadXmlDocument(InputStream inputStream) {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        if (logger.isDebugEnabled()) {
            logger.debug("Using JAXP implementation [" + factory + "]");
        }
        factory.setValidating(validating);

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

        return docBuilder.parse(inputStream);

    } catch (ParserConfigurationException exception) {
        throw new XmlRpcInternalException("Parser configuration exception", exception);

    } catch (SAXParseException exception) {
        throw new XmlRpcNotWellFormedException(
                "Line " + exception.getLineNumber() + " in XML-RPC payload is invalid", exception);

    } catch (SAXException exception) {
        throw new XmlRpcNotWellFormedException("XML-RPC payload is invalid", exception);

    } catch (IOException exception) {
        throw new XmlRpcInternalException("IOException when parsing XML-RPC payload", exception);

    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException exception) {
                logger.warn("Could not close InputStream", exception);
            }
        }
    }
}

From source file:org.springmodules.remoting.xmlrpc.dom.AbstractDomXmlRpcWriter.java

/**
 * Creates an empty XML document.//  w w  w .  j a  va 2 s . c  o  m
 * 
 * @return the created XML document.
 */
protected final Document createEmptyXmlDocument() {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        if (logger.isDebugEnabled()) {
            logger.debug("Using JAXP implementation [" + factory + "]");
        }

        DocumentBuilder docBuilder = factory.newDocumentBuilder();
        docBuilder.setErrorHandler(errorHandler);

        return docBuilder.newDocument();

    } catch (ParserConfigurationException exception) {
        throw new XmlRpcWriterException("Parser configuration exception", exception);
    }
}