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:com.qcadoo.maven.plugins.validator.ValidatorMojo.java

private void validateSchema(final String file) throws MojoFailureException {
    try {/*from w w  w .  java2s  .com*/
        getLog().info("Validating file: " + file);

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        factory.setNamespaceAware(true);

        try {
            URL url = new URL("http://www.qcadoo.com");
            url.openConnection();
            factory.setValidating(true);
        } catch (UnknownHostException e) {
            factory.setValidating(false);
        } catch (IOException e) {
            factory.setValidating(false);
        }

        factory.setValidating(false);
        factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                "http://www.w3.org/2001/XMLSchema");
        DocumentBuilder parser = factory.newDocumentBuilder();
        parser.setErrorHandler(new ValidationErrorHandler());
        parser.parse(new File(file));

    } catch (ParserConfigurationException e) {
        getLog().error(e.getMessage());
        throw (MojoFailureException) new MojoFailureException("We couldn't parse the file: " + file)
                .initCause(e);
    } catch (SAXException e) {
        getLog().error(e.getMessage());
        throw (MojoFailureException) new MojoFailureException("We couldn't parse the file: " + file)
                .initCause(e);
    } catch (IOException e) {
        getLog().error(e.getMessage());
        throw (MojoFailureException) new MojoFailureException("We couldn't parse the file: " + file)
                .initCause(e);
    }
}

From source file:de.hsos.ecs.richwps.wpsmonitor.communication.wpsclient.simple.SimpleWpsClient.java

private DocumentBuilder getDocumentBuilder() throws ParserConfigurationException {
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setNamespaceAware(true);

    DocumentBuilder newDocumentBuilder = docBuilderFactory.newDocumentBuilder();

    // Configure error handler
    newDocumentBuilder.setErrorHandler(new ErrorHandler() {
        @Override/*from w  ww .j ava2 s  .c o  m*/
        public void error(SAXParseException saxpe) throws SAXException {
            LOG.warn(saxpe);
        }

        @Override
        public void fatalError(SAXParseException saxpe) throws SAXException {
            LOG.warn(saxpe);
        }

        @Override
        public void warning(SAXParseException saxpe) throws SAXException {
            LOG.warn(saxpe);
        }
    });

    return newDocumentBuilder;
}

From source file:com.icesoft.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
 * @throws JasperException if an input/output error occurs
 * @throws JasperException if a parsing error occurs
 *///from  w  w w  .j  a va  2s . com
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) {
        if (log.isErrorEnabled()) {
            log.error("XML parsing failed for " + uri + "SAXException: " + sx.getMessage());
        }
        throw new JasperException(
                Localizer.getMessage("jsp.error.parse.xml", uri) + "SAXException: " + sx.getMessage(), 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:com.runwaysdk.request.ClientRequestManager.java

/**
 * Constructs a new ConnectionManager object by reading in an xml file detailing connections to servers and then populating a HashMap of Connection objects.
 *///from   ww w .j av  a 2 s  . c o m
private ClientRequestManager() {
    // initialize the connections and proxies.
    connections = new HashMap<String, ConnectionLabel>();

    URL connectionsXmlFile;
    try {
        connectionsXmlFile = ConfigurationManager.getResource(ConfigGroup.CLIENT, "connections.xml");
    } catch (RunwayConfigurationException e) {
        log.warn("connections.xml configuration file not found.", e);
        return;
    }

    InputStream connectionsSchemaFile;
    try {
        connectionsSchemaFile = ConfigurationManager.getResource(ConfigGroup.XSD, "connectionsSchema.xsd")
                .openStream();
    } catch (IOException e) {
        throw new RunwayConfigurationException(e);
    }

    Document document = null;
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    factory.setAttribute(XMLConstants.JAXP_SCHEMA_LANGUAGE, XMLConstants.W3C_XML_SCHEMA);
    factory.setAttribute(XMLConstants.JAXP_SCHEMA_SOURCE, connectionsSchemaFile);

    DocumentBuilder builder;
    try {
        builder = factory.newDocumentBuilder();
        builder.setErrorHandler(new XMLConnectionsErrorHandler());
        document = builder.parse(connectionsXmlFile.openStream());
    } catch (ParserConfigurationException e) {
        throw new ClientRequestException(e);
    } catch (SAXException e) {
        throw new ClientRequestException(e);
    } catch (IOException e) {
        throw new ClientRequestException(e);
    }
    parseDocument(document);
}

From source file:com.mingo.parser.xml.dom.QuerySetParser.java

/**
 * {@inheritDoc}/*  w w  w  .  j a v a  2 s.c  o  m*/
 */
@Override
public QuerySet parse(InputStream xml) throws ParserException {
    LOGGER.debug("QuerySetParser:: START PARSING");
    QuerySet querySet;
    try {
        DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
        builder.setErrorHandler(parseErrorHandler);
        Document document = builder.parse(new InputSource(xml));
        Element root = document.getDocumentElement();
        querySet = new QuerySet();
        parseConfigTag(root, querySet);
        parseQueryFragments(root, querySet);
        parseQueries(root, querySet);
    } catch (Exception e) {
        throw new ParserException(e);
    }
    return querySet;
}

From source file:com.amalto.core.util.Util.java

public static Document parse(String xmlString) throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory factory;
    factory = getDocumentBuilderFactory();
    DocumentBuilder builder = factory.newDocumentBuilder();
    SAXErrorHandler seh = new SAXErrorHandler();
    builder.setErrorHandler(seh);
    Document d = builder.parse(new InputSource(new StringReader(xmlString)));
    // check if document parsed correctly against the schema
    String errors = seh.getErrors();
    if (errors.length() != 0) {
        String err = "Document did not parse against schema: \n" + errors + "\n"
                + xmlString.substring(0, Math.min(100, xmlString.length()));
        throw new SAXException(err);
    }//from  w  ww.  j  a v a2s.c o  m
    return d;
}

From source file:com.servoy.extension.install.LibActivationHandler.java

protected void replaceReferencesInJNLP(File jnlp, File libFileToBeRemoved,
        FullLibDependencyDeclaration toActivate) {
    try {//  ww w . j  a  va2s.  c  om
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setErrorHandler(new XMLErrorHandler(jnlp.getName()));

        Document doc = db.parse(jnlp);
        Element root = doc.getDocumentElement();
        root.normalize();

        NodeList list;
        if ("jnlp".equals(root.getNodeName())) //$NON-NLS-1$
        {
            list = root.getElementsByTagName("resources"); //$NON-NLS-1$
            if (list != null && list.getLength() == 1 && list.item(0).getNodeType() == Node.ELEMENT_NODE) {
                File appServerDir = new File(installDir, APP_SERVER_DIR);
                Element resourcesNode = (Element) list.item(0);
                boolean replaced1 = findAndReplaceReferences(resourcesNode, "jar", appServerDir, //$NON-NLS-1$
                        libFileToBeRemoved, toActivate);
                boolean replaced2 = findAndReplaceReferences(resourcesNode, "nativelib", appServerDir, //$NON-NLS-1$
                        libFileToBeRemoved, toActivate);

                if (replaced1 || replaced2) {
                    // save back the jnlp file
                    try {
                        writeBackXML(doc, jnlp, doc.getXmlEncoding());
                    } catch (Exception e) {
                        messages.addError("Cannot write back jnlp file (when deactivating lib): " + jnlp); //$NON-NLS-1$ 
                        Debug.error(e);
                    }
                }
            }
        }
    } catch (ParserConfigurationException e) {
        String msg = "Cannot parse jnlp '" + jnlp.getName() + "'."; //$NON-NLS-1$ //$NON-NLS-2$
        Debug.log(msg, e);
    } catch (SAXException e) {
        String msg = "Cannot parse jnlp '" + jnlp.getName() + "'."; //$NON-NLS-1$ //$NON-NLS-2$
        Debug.log(msg, e);
    } catch (IOException e) {
        String msg = "Cannot parse jnlp '" + jnlp.getName() + "'."; //$NON-NLS-1$ //$NON-NLS-2$
        Debug.log(msg, e);
    } catch (FactoryConfigurationError e) {
        String msg = "Cannot parse jnlp '" + jnlp.getName() + "'. Please report this problem to Servoy."; //$NON-NLS-1$ //$NON-NLS-2$
        Debug.error(msg, e);
    }
}

From source file:de.fzi.ALERT.actor.MessageObserver.ComplexEventObserver.JMSMessageParser.java

public Message XMLFileParse(String msgString) {

    Message message = new Message();

    try {// w ww. jav  a  2 s.c o  m

        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        builder.setErrorHandler(new MyErrorHandler());

        InputStream in = new ByteArrayInputStream(msgString.getBytes("UTF-8"));
        org.w3c.dom.Document doc = builder.parse(in);

        XPath xpath = XPathFactory.newInstance().newXPath();
        // XPath Query for showing all nodes value
        javax.xml.xpath.XPathExpression expr = xpath.compile("//patternID/text()");

        Object result = expr.evaluate(doc, XPathConstants.NODESET);

        NodeList nodes = (NodeList) result;
        Pattern pattern = new Pattern();
        if (nodes.getLength() > 0) {
            pattern = patternDAO.findById(nodes.item(0).getNodeValue());
        }
        if (pattern != null) {

            message.setPatternId(pattern);
            for (int i = 0; i < nodes.getLength(); i++) {
                System.out.println(nodes.item(i).getNodeValue());
            }

            javax.xml.xpath.XPathExpression expr1 = xpath.compile("//alertcomplex/*/text()");

            Object result1 = expr1.evaluate(doc, XPathConstants.NODESET);
            NodeList nodes1 = (NodeList) result1;
            String content = "";
            if (nodes.getLength() > 0) {
                for (int i = 0; i < nodes1.getLength(); i++) {
                    System.out.println("modes " + nodes1.item(i).getParentNode().getNodeName());
                    System.out.println(nodes1.item(i).getNodeValue());
                    content += nodes1.item(i).getNodeValue();
                }
            }
            message.setSubject("complex event");
            message.setSummary("default summary");
            message.setContent(content);
            message.setMsgDate(new Date());
            message.setMsgID(1);
        } else {
            message.setContent("ERROR!");
        }
    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        message.setContent("ERROR!");
        System.out.println(e.getMessage());
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        message.setContent("ERROR!");
        System.out.println(e.getMessage());
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        message.setContent("ERROR!");
        System.out.println(e.getMessage());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        message.setContent("ERROR!");
        System.out.println(e.getMessage());
    } catch (XPathExpressionException e) {
        // TODO Auto-generated catch block
        message.setContent("ERROR!");
        System.out.println(e.getMessage());
    }

    return message;

}

From source file:net.sourceforge.eclipsetrader.ats.Repository.java

public void load() {
    File file = new File(Platform.getLocation().toFile(), "systems.xml"); //$NON-NLS-1$
    if (file.exists() == true) {
        log.info("Loading trading systems");
        try {/*from ww w  .j a va 2s  .  c  o  m*/
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            builder.setErrorHandler(errorHandler);
            Document document = builder.parse(file);

            Node firstNode = document.getFirstChild();
            nextId = new Integer(firstNode.getAttributes().getNamedItem("nextId").getNodeValue()); //$NON-NLS-1$

            NodeList childNodes = firstNode.getChildNodes();
            for (int i = 0; i < childNodes.getLength(); i++) {
                Node item = childNodes.item(i);
                String nodeName = item.getNodeName();
                if (nodeName.equalsIgnoreCase("system")) //$NON-NLS-1$
                {
                    TradingSystem system = loadTradingSystem(item.getChildNodes());
                    if (system != null)
                        systems.add(system);
                }
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
    }
}

From source file:com.verisign.epp.codec.verificationcode.EPPEncodedSignedCodeValue.java

/**
 * Creates an <code>EPPEncodedSignedCodeValue</code> that is initialized by
 * decoding the input <code>byte[]</code>.
 * /*from   w  w  w  . jav  a  2s. co  m*/
 * @param aEncodedSignedCodeArray
 *            <code>byte[]</code> to decode the attribute values
 * @throws EPPDecodeException
 *             Error decoding the input <code>byte[]</code>.
 */
public EPPEncodedSignedCodeValue(byte[] aEncodedSignedCodeArray) throws EPPDecodeException {
    cat.debug("EPPSignedCode(byte[]): enter");

    byte[] signedCodeXML = null;
    Element elm;
    ByteArrayInputStream is = null;
    try {
        is = new ByteArrayInputStream(aEncodedSignedCodeArray);
        DocumentBuilder parser = new EPPSchemaCachingParser();
        // Disable the validation
        parser.setErrorHandler(null);
        Document doc = parser.parse(is);
        elm = doc.getDocumentElement();
        String base64SignedCode = EPPUtil.getTextContent(elm);
        signedCodeXML = Base64.decodeBase64(base64SignedCode);
    } catch (Exception ex) {
        throw new EPPDecodeException("Error decoding signed code array: " + ex);
    } finally {
        if (is != null) {
            try {
                is.close();
                is = null;
            } catch (IOException e) {
            }
        }
    }

    super.decode(signedCodeXML);

    cat.debug("EPPSignedCode.decode(byte[]): exit");
}