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:nl.imvertor.common.file.XmlFile.java

public boolean isWellFormed() {
    messages.removeAllElements();//from w w  w  .ja  v a2 s  .  c  o  m
    try {
        wfcode = WFCODE_OKAY;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setNamespaceAware(true);
        factory.setXIncludeAware(true);

        DocumentBuilder builder = factory.newDocumentBuilder();

        builder.setErrorHandler(this);
        builder.parse(new InputSource(this.getCanonicalPath()));

    } catch (Exception e) {
        wfcode = WFCODE_FATAL;
    }
    return wfcode < WFCODE_ERROR;
}

From source file:nl.imvertor.common.file.XmlFile.java

public boolean isValid() {
    messages.removeAllElements();/*w w w . ja  v  a2 s  .c o  m*/
    try {
        wfcode = WFCODE_OKAY;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(true);
        factory.setNamespaceAware(true);
        factory.setXIncludeAware(true);
        factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                "http://www.w3.org/2001/XMLSchema");

        DocumentBuilder builder = factory.newDocumentBuilder();

        builder.setErrorHandler(this);
        builder.parse(new InputSource(this.getCanonicalPath()));
    } catch (Exception e) {
        wfcode = WFCODE_FATAL;
    }
    return wfcode < WFCODE_ERROR;
}

From source file:org.apache.axis.utils.XMLUtils.java

/**
 * Releases a DocumentBuilder/*from   w w w  . ja v  a  2 s . co m*/
 * @param db
 */
public static void releaseDocumentBuilder(DocumentBuilder db) {
    try {
        db.setErrorHandler(null); // setting implementation default
    } catch (Throwable t) {
        log.debug("Failed to set ErrorHandler to null on DocumentBuilder", t);
    }
    try {
        db.setEntityResolver(null); // setting implementation default
    } catch (Throwable t) {
        log.debug("Failed to set EntityResolver to null on DocumentBuilder", t);
    }
}

From source file:org.apache.axis.utils.XMLUtils.java

/**
 * Get a new Document read from the input source
 * @return Document/*w  w w. j a  va2  s  .co  m*/
 * @throws ParserConfigurationException if construction problems occur
 * @throws SAXException if the document has xml sax problems
 * @throws IOException if i/o exceptions occur
 */
public static Document newDocument(InputSource inp)
        throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilder db = null;
    try {
        db = getDocumentBuilder();
        try {
            db.setEntityResolver(new DefaultEntityResolver());
        } catch (Throwable t) {
            log.debug("Failed to set EntityResolver on DocumentBuilder", t);
        }
        try {
            db.setErrorHandler(new XMLUtils.ParserErrorHandler());
        } catch (Throwable t) {
            log.debug("Failed to set ErrorHandler on DocumentBuilder", t);
        }
        Document doc = db.parse(inp);
        return doc;
    } finally {
        if (db != null) {
            releaseDocumentBuilder(db);
        }
    }
}

From source file:org.apache.beehive.netui.util.config.internal.catalog.CatalogParser.java

public CatalogConfig parse(final String resourcePath, final InputStream inputStream) {
    CatalogConfig catalogConfig = null;/*from  w ww  . j  av  a2  s .  c o  m*/
    InputStream xmlInputStream = null;
    InputStream xsdInputStream = null;
    try {
        xmlInputStream = inputStream;
        xsdInputStream = getClass().getClassLoader().getResourceAsStream(CONFIG_SCHEMA);

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setValidating(true);
        dbf.setNamespaceAware(true);
        dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
        dbf.setAttribute(JAXP_SCHEMA_SOURCE, xsdInputStream);

        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setErrorHandler(new ErrorHandler() {
            public void warning(SAXParseException exception) {
                LOG.info("Validation warning validating config file \"" + resourcePath
                        + "\" against XML Schema \"" + CONFIG_SCHEMA);
            }

            public void error(SAXParseException exception) {
                throw new RuntimeException("Validation errors occurred parsing the config file \""
                        + resourcePath + "\".  Cause: " + exception, exception);
            }

            public void fatalError(SAXParseException exception) {
                throw new RuntimeException("Validation errors occurred parsing the config file \""
                        + resourcePath + "\".  Cause: " + exception, exception);
            }
        });

        db.setEntityResolver(new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId) {
                if (systemId.endsWith("/catalog-config.xsd")) {
                    InputStream inputStream = getClass().getClassLoader().getResourceAsStream(CONFIG_SCHEMA);
                    return new InputSource(inputStream);
                } else
                    return null;
            }
        });

        Document document = db.parse(xmlInputStream);
        Element catalogElement = document.getDocumentElement();
        catalogConfig = parse(catalogElement);

    } catch (ParserConfigurationException e) {
        throw new RuntimeException("Error occurred parsing the config file \"" + resourcePath + "\"", e);
    } catch (IOException e) {
        throw new RuntimeException("Error occurred parsing the config file \"" + resourcePath + "\"", e);
    } catch (SAXException e) {
        throw new RuntimeException("Error occurred parsing the config file \"" + resourcePath + "\"", e);
    } finally {
        try {
            if (xsdInputStream != null)
                xsdInputStream.close();
        } catch (IOException e) {
        }
    }

    return catalogConfig;
}

From source file:org.apache.felix.karaf.deployer.blueprint.BlueprintDeploymentListener.java

protected Document parse(File artifact) throws Exception {
    if (dbf == null) {
        dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);//ww  w.ja v a 2  s  . c o  m
    }
    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setErrorHandler(new ErrorHandler() {
        public void warning(SAXParseException exception) throws SAXException {
        }

        public void error(SAXParseException exception) throws SAXException {
        }

        public void fatalError(SAXParseException exception) throws SAXException {
            throw exception;
        }
    });
    return db.parse(artifact);
}

From source file:org.apache.jasper.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 stream containing the deployment descriptor
 *
 * @exception JasperException if an input/output error occurs
 * @exception JasperException if a parsing error occurs
 *///from w  w w  .j a v a2s  .c o m
public TreeNode parseXMLDocument(String uri, InputStream is) throws JasperException {

    Document document = null;

    // Perform an XML parse of this document, via JAXP
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(validating);
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver(entityResolver);
        builder.setErrorHandler(errorHandler);
        document = builder.parse(is);
    } 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);
    }

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

From source file:org.apache.jmeter.protocol.http.sampler.WebServiceSampler.java

/**
 * Open the file and create a Document.//  w  ww  .  j  a v a  2 s . c o  m
 *
 * @param file - input filename or empty if using data from tesplan
 * @return Document
 * @throws IOException
 * @throws SAXException
 */
private Document openDocument(String file) throws SAXException, IOException {
    /*
     * Consider using Apache commons pool to create a pool of document
     * builders or make sure XMLParserUtils creates builders efficiently.
     */
    DocumentBuilder XDB = XMLParserUtils.getXMLDocBuilder();
    XDB.setErrorHandler(null);//Suppress messages to stdout

    Document doc = null;
    // if either a file or path location is given,
    // get the file object.
    if (file.length() > 0) {// we have a file
        if (this.getReadResponse()) {
            TextFile tfile = new TextFile(file);
            fileContents = tfile.getText();
        }
        InputStream fileInputStream = null;
        try {
            fileInputStream = new BufferedInputStream(new FileInputStream(file));
            doc = XDB.parse(fileInputStream);
        } finally {
            JOrphanUtils.closeQuietly(fileInputStream);
        }
    } else {// must be a "here" document
        fileContents = getXmlData();
        if (fileContents != null && fileContents.length() > 0) {
            doc = XDB.parse(new InputSource(new StringReader(fileContents)));
        } else {
            log.warn("No post data provided!");
        }
    }
    return doc;
}

From source file:org.apache.myfaces.shared_impl.webapp.webxml.WebXmlParser.java

public WebXml parse() {
    _webXml = new WebXml();

    try {/*from  ww w  .ja  va  2s  . co  m*/
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setIgnoringElementContentWhitespace(true);
        dbf.setIgnoringComments(true);
        dbf.setNamespaceAware(true);
        dbf.setValidating(false);
        //            dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);

        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setEntityResolver(new _EntityResolver());
        db.setErrorHandler(new MyFacesErrorHandler(log));

        InputSource is = createContextInputSource(null, WEB_XML_PATH);

        if (is == null) {
            URL url = _context.getResource(WEB_XML_PATH);
            log.debug("No web-xml found at : " + (url == null ? " null " : url.toString()));
            return _webXml;
        }

        Document document = db.parse(is);

        Element webAppElem = document.getDocumentElement();
        if (webAppElem == null || !webAppElem.getNodeName().equals("web-app")) {
            throw new FacesException("No valid web-app root element found!");
        }

        readWebApp(webAppElem);

        return _webXml;
    } catch (Exception e) {
        log.fatal("Unable to parse web.xml", e);
        throw new FacesException(e);
    }
}

From source file:org.apache.nifi.cluster.manager.impl.WebClusterManager.java

private Document parse(final byte[] serialized) throws SAXException, ParserConfigurationException, IOException {
    final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setNamespaceAware(true);/*from ww  w .  j  a  va2  s.  c  om*/

    final DocumentBuilder builder = docFactory.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;
        }
    });

    // build the docuemnt
    final Document document = builder.parse(new ByteArrayInputStream(serialized));
    return document;
}