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.bibsonomy.importer.bookmark.service.DeliciousImporter.java

/**
 * Method opens a connection and parses the retrieved InputStream with a JAXP parser.
 * @return The from the parse call returned Document Object
 * @throws IOException/*from  w ww .j a v a2 s .c  o m*/
 */
private Document getDocument() throws IOException {

    final URLConnection connection = apiURL.openConnection();
    connection.setRequestProperty(HEADER_USER_AGENT, userAgent);
    connection.setRequestProperty(HEADER_AUTHORIZATION, encodeForAuthorization());
    final InputStream inputStream = connection.getInputStream();

    // Get a JAXP parser factory object
    final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    // Tell the factory what kind of parser we want 
    dbf.setValidating(false);
    // Use the factory to get a JAXP parser object

    final DocumentBuilder parser;
    try {
        parser = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new IOException(e);
    }

    // Tell the parser how to handle errors.  Note that in the JAXP API,
    // DOM parsers rely on the SAX API for error handling
    parser.setErrorHandler(new ErrorHandler() {
        public void warning(SAXParseException e) {
            log.warn(e);
        }

        public void error(SAXParseException e) {
            log.error(e);
        }

        public void fatalError(SAXParseException e) throws SAXException {
            log.fatal(e);
            throw e; // re-throw the error
        }
    });

    // Finally, use the JAXP parser to parse the file.  
    // This call returns a Document object. 

    final Document document;
    try {
        document = parser.parse(inputStream);
    } catch (SAXException e) {
        throw new IOException(e);
    }

    inputStream.close();

    return document;

}

From source file:org.bibsonomy.importer.bookmark.service.DeliciousV2Importer.java

/**
 * Method opens a connection and parses the retrieved InputStream with a JAXP parser.
 * @return The from the parse call returned Document Object
 * @throws IOException/*from ww  w .  j  a  v a  2  s.c  o m*/
 */
private static Document getDocument(final InputStream inputStream) throws IOException {
    /*
     * TODO: this is copied code
     */
    // Get a JAXP parser factory object
    final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    // Tell the factory what kind of parser we want 
    dbf.setValidating(false);
    // Use the factory to get a JAXP parser object

    final DocumentBuilder parser;
    try {
        parser = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new IOException(e);
    }

    // Tell the parser how to handle errors.  Note that in the JAXP API,
    // DOM parsers rely on the SAX API for error handling
    parser.setErrorHandler(new ErrorHandler() {
        public void warning(SAXParseException e) {
            log.warn(e);
        }

        public void error(SAXParseException e) {
            log.error(e);
        }

        public void fatalError(SAXParseException e) throws SAXException {
            log.fatal(e);
            throw e; // re-throw the error
        }
    });

    // Finally, use the JAXP parser to parse the file.  
    // This call returns a Document object. 

    final Document document;
    try {
        document = parser.parse(inputStream);
    } catch (SAXException e) {
        throw new IOException(e);
    }

    inputStream.close();

    return document;

}

From source file:org.broadleafcommerce.common.extensibility.jpa.MergeJPAPersistenceResource.java

private void compileMappingFiles(List<String> mappingFiles, byte[] sourceArray)
        throws IOException, ParserConfigurationException, SAXException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);/*w  ww.jav a  2s.c o m*/
    DocumentBuilder parser = dbf.newDocumentBuilder();
    parser.setErrorHandler(handler);

    Document dom = parser.parse(new ByteArrayInputStream(sourceArray));

    NodeList nodes = dom.getElementsByTagName("/persistence/persistence-unit/mapping-file");
    if (nodes != null && nodes.getLength() > 0) {
        int length = nodes.getLength();
        for (int j = 0; j < length; j++) {
            Node node = nodes.item(j);
            mappingFiles.add(node.getNodeValue());
        }
    }
}

From source file:org.compass.core.config.builder.AbstractXmlConfigurationBuilder.java

protected DocumentBuilder createDocumentBuilder(DocumentBuilderFactory factory)
        throws ParserConfigurationException {
    DocumentBuilder docBuilder = factory.newDocumentBuilder();
    docBuilder.setErrorHandler(doGetErrorHandler());
    docBuilder.setEntityResolver(doGetEntityResolver());
    return docBuilder;
}

From source file:org.drools.guvnor.server.jaxrs.CategoryResourceIntegrationTest.java

public Map<String, Category> fromXMLToCategoriesMap(String xml) {
    try {//from   w ww .  j av  a  2  s.  com
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);

        final List<String> errors = new ArrayList<String>();
        DocumentBuilder builder = factory.newDocumentBuilder();

        builder.setErrorHandler(new ErrorHandler() {

            public void warning(SAXParseException exception) throws SAXException {
                java.util.logging.Logger.getLogger(Translator.class.getName()).log(Level.WARNING,
                        "Warning parsing categories from Guvnor", exception);
            }

            public void error(SAXParseException exception) throws SAXException {
                java.util.logging.Logger.getLogger(Translator.class.getName()).log(Level.SEVERE,
                        "Error parsing categories from Guvnor", exception);
                errors.add(exception.getMessage());
            }

            public void fatalError(SAXParseException exception) throws SAXException {
                java.util.logging.Logger.getLogger(Translator.class.getName()).log(Level.SEVERE,
                        "Error parsing categories from Guvnor", exception);
                errors.add(exception.getMessage());
            }
        });

        org.w3c.dom.Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes()));

        if (!errors.isEmpty()) {
            throw new IllegalStateException(
                    "Error parsing categories from guvnor. Check the log for errors' details.");
        }

        Map<String, Category> categories = new HashMap<String, Category>();

        //convert all catergories and add them to the list
        NodeList categoriesList = doc.getElementsByTagName("category");
        for (int i = 0; i < categoriesList.getLength(); i++) {
            Element element = (Element) categoriesList.item(i);
            Category category = new Category();

            NodeList pathNodes = element.getElementsByTagName("path");
            if (pathNodes.getLength() != 1) {
                throw new IllegalStateException(
                        "Malformed category. Expected 1 <path> tag, but found " + pathNodes.getLength());
            }
            Node pathNode = pathNodes.item(0);
            category.setPath(pathNode.getTextContent());

            NodeList refLinkNodes = element.getElementsByTagName("refLink");
            if (refLinkNodes.getLength() != 1) {
                throw new IllegalStateException(
                        "Malformed category. Expected 1 <refLink> tag, but found " + refLinkNodes.getLength());
            }
            Node refLinkNode = refLinkNodes.item(0);
            try {
                category.setRefLink(new URI(refLinkNode.getTextContent()));
            } catch (URISyntaxException e) {
                throw new RuntimeException("Error parsing categories xml", e);
            }

            categories.put(category.getPath(), category);
        }

        return categories;
    } catch (SAXException ex) {
        throw new RuntimeException("Error parsing categories xml", ex);
    } catch (IOException ex) {
        throw new RuntimeException("Error parsing categories xml", ex);
    } catch (ParserConfigurationException ex) {
        throw new RuntimeException("Error parsing categories xml", ex);
    }
}

From source file:org.easyrec.util.core.Web.java

/**
 * This procedure extracts the values/* w  w  w  .j  a  v a2  s. c om*/
 * of the <name>-Tags of a given Xml file into a list of Strings.
 * e.g.
 * <name>hanso</name>
 * <name>stritzi</name>
 * <p/>
 * --> {"hansi","stritzi"}
 *
 * @param apiURL  String
 * @param tagName String
 * @return a list of strings
 */
@SuppressWarnings({ "UnusedDeclaration" })
public static List<String> getInnerHTMLfromTags(String apiURL, String tagName) {

    List<String> innerHTMLList = new ArrayList<String>();

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db;
    try {
        db = dbf.newDocumentBuilder();
        db.setErrorHandler(new ErrorHandler() {
            public void warning(SAXParseException e) throws SAXException {
            }

            public void error(SAXParseException e) throws SAXException {
            }

            public void fatalError(SAXParseException e) throws SAXException {
            }
        });
        Document doc = db.parse(apiURL.replaceAll(" ", "%20"));

        NodeList tagNodes = doc.getElementsByTagName(tagName);

        for (int i = 0; i < tagNodes.getLength(); i++) {
            innerHTMLList.add(tagNodes.item(i).getTextContent());
        }
    } catch (ParserConfigurationException e1) {

        logger.warn("An error occurred!", e1);
    } catch (SAXException e) {
        logger.warn("An error occurred!", e);
    } catch (IOException e) {
        logger.warn("An error occurred!", e);
    }
    return innerHTMLList;
}

From source file:org.easyrec.utils.Web.java

/**
 * This procedure extracts the values//from  w  w  w  .j  av a 2  s  .  c  om
 * of the <name>-Tags of a given Xml file into a list of Strings.
 * e.g.
 * <name>hanso</name>
 * <name>stritzi</name>
 * <p/>
 * --> {"hansi","stritzi"}
 *
 * @param apiURL  String
 * @param tagName String
 * @return a list of strings
 */
@SuppressWarnings({ "UnusedDeclaration" })
public static List<String> getInnerHTMLfromTags(String apiURL, String tagName) {

    List<String> innerHTMLList = new ArrayList<String>();

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db;
    try {
        db = dbf.newDocumentBuilder();
        db.setErrorHandler(new ErrorHandler() {
            public void warning(SAXParseException e) throws SAXException {
            }

            public void error(SAXParseException e) throws SAXException {
            }

            public void fatalError(SAXParseException e) throws SAXException {
            }
        });
        Document doc = db.parse(apiURL.replaceAll(" ", "%20"));

        NodeList tagNodes = doc.getElementsByTagName(tagName);

        for (int i = 0; i < tagNodes.getLength(); i++) {
            innerHTMLList.add(tagNodes.item(i).getTextContent());
        }
    } catch (ParserConfigurationException e1) {
        e1.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return innerHTMLList;
}

From source file:org.fcrepo.server.security.PolicyParser.java

/**
 * Parses the given policy and optionally schema validates it.
 *
 * @param policyStream//w w w .  j  a v  a2 s  .  c om
 *          the serialized XACML policy
 * @param validate
 *          whether to schema validate
 * @return the parsed policy.
 * @throws ValidationException
 *           if the given xml is not a valid policy. This will occur if it
 *           is not well-formed XML, its root element is not named
 *           <code>Policy</code> or <code>PolicySet</code>, it triggers
 *           a parse exception in the Sun libraries when constructing an
 *           <code>AbstractPolicy</code> from the DOM, or (if validation
 *           is true) it is not schema-valid.
 */
public AbstractPolicy parse(InputStream policyStream, boolean schemaValidate) throws ValidationException {

    // Parse; die if not well-formed
    Document doc = null;
    DocumentBuilder domParser = null;
    try {
        domParser = XmlTransformUtility.borrowDocumentBuilder();
        domParser.setErrorHandler(THROW_ALL);
        doc = domParser.parse(policyStream);
    } catch (Exception e) {
        throw new ValidationException("Policy invalid; malformed XML", e);
    } finally {
        if (domParser != null) {
            XmlTransformUtility.returnDocumentBuilder(domParser);
        }
    }

    if (schemaValidate) {
        // XSD-validate; die if not schema-valid
        Validator validator = null;
        try {
            validator = m_validators.borrowObject();
            validator.validate(new DOMSource(doc));
        } catch (Exception e) {
            throw new ValidationException("Policy invalid; schema" + " validation failed", e);
        } finally {
            if (validator != null)
                try {
                    m_validators.returnObject(validator);
                } catch (Exception e) {
                    logger.warn(e.getMessage(), e);
                }
        }
    }

    // Construct AbstractPolicy from doc; die if root isn't "Policy[Set]"
    Element root = doc.getDocumentElement();
    String rootName = root.getTagName();
    try {
        if (rootName.equals("Policy")) {
            return Policy.getInstance(root);
        } else if (rootName.equals("PolicySet")) {
            return PolicySet.getInstance(root);
        } else {
            throw new ValidationException(
                    "Policy invalid; root element is " + rootName + ", but should be " + "Policy or PolicySet");
        }
    } catch (ParsingException e) {
        throw new ValidationException("Policy invalid; failed parsing by " + "Sun XACML implementation", e);
    }
}

From source file:org.forgerock.maven.plugins.LinkTester.java

@Override()
public void execute() throws MojoExecutionException, MojoFailureException {
    if (outputFile != null) {
        if (!outputFile.isAbsolute()) {
            outputFile = new File(project.getBasedir(), outputFile.getPath());
        }/* ww  w . j  a va 2 s.c o m*/
        if (outputFile.exists()) {
            debug("Deleting existing outputFile: " + outputFile);
            outputFile.delete();
        }
        try {
            outputFile.createNewFile();
            fileWriter = new FileWriter(outputFile);
        } catch (IOException ioe) {
            error("Error while creating output file", ioe);
        }
    }
    initializeSkipUrlPatterns();

    //Initialize XML parsers and XPath expressions
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setExpandEntityReferences(false);
    dbf.setXIncludeAware(xIncludeAware);

    if (validating) {
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        try {
            Schema schema = sf.newSchema(new URL(DOCBOOK_XSD));
            dbf.setSchema(schema);
        } catch (MalformedURLException murle) {
            error("Invalid URL provided as schema source", murle);
        } catch (SAXException saxe) {
            error("Parsing error occurred while constructing schema for validation", saxe);
        }
    }
    DocumentBuilder db;
    try {
        db = dbf.newDocumentBuilder();
        db.setErrorHandler(new LoggingErrorHandler(this));
    } catch (ParserConfigurationException pce) {
        throw new MojoExecutionException("Unable to create new DocumentBuilder", pce);
    }

    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();
    xpath.setNamespaceContext(new XmlNamespaceContext());
    XPathExpression expr;
    try {
        expr = xpath.compile("//@xml:id");
    } catch (XPathExpressionException xpee) {
        throw new MojoExecutionException("Unable to compile Xpath expression", xpee);
    }

    if (docSources != null) {
        for (DocSource docSource : docSources) {
            processDocSource(docSource, db, expr);
        }
    }

    try {
        if (!skipOlinks) {
            //we can only check olinks after going through all the documents, otherwise we would see false
            //positives, because of the not yet processed files
            for (Map.Entry<String, Collection<String>> entry : (Set<Map.Entry<String, Collection<String>>>) olinks
                    .entrySet()) {
                for (String val : entry.getValue()) {
                    checkOlink(entry.getKey(), val);
                }
            }
        }
        if (!failedUrls.isEmpty()) {
            error("The following files had invalid URLs:\n" + failedUrls.toString());
        }
        if (!timedOutUrls.isEmpty()) {
            warn("The following files had unavailable URLs (connection or read timed out):\n"
                    + timedOutUrls.toString());
        }
        if (failedUrls.isEmpty() && timedOutUrls.isEmpty() && !failure) {
            //there are no failed URLs and the parser didn't encounter any errors either
            info("DocBook links successfully tested, no errors reported.");
        }
    } finally {
        flushReport();
    }
    if (failOnError) {
        if (failure || !failedUrls.isEmpty()) {
            throw new MojoFailureException("One or more error occurred during plugin execution");
        }
    }
}

From source file:org.fosstrak.epcis.repository.capture.CaptureOperationsModule.java

/**
 * Parses the input into a DOM. If a schema is given, the input is also
 * validated against this schema. The schema may be null.
 *///  ww  w .j a  v  a2s  .c  o m
private Document parseInput(InputStream in, Schema schema)
        throws InternalBusinessException, SAXException, IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setIgnoringComments(true);
    factory.setIgnoringElementContentWhitespace(true);
    factory.setSchema(schema);
    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setErrorHandler(new ErrorHandler() {
            public void warning(SAXParseException e) throws SAXException {
                LOG.warn("warning while parsing XML input: " + e.getMessage());
            }

            public void fatalError(SAXParseException e) throws SAXException {
                LOG.error("non-recovarable error while parsing XML input: " + e.getMessage());
                throw e;
            }

            public void error(SAXParseException e) throws SAXException {
                LOG.error("error while parsing XML input: " + e.getMessage());
                throw e;
            }
        });
        Document document = builder.parse(in);
        LOG.debug("payload successfully parsed as XML document");
        if (LOG.isDebugEnabled()) {
            logDocument(document);
        }
        return document;
    } catch (ParserConfigurationException e) {
        throw new InternalBusinessException("unable to configure document builder to parse XML input", e);
    }
}