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:net.sourceforge.eclipsetrader.ats.Repository.java

public void save() {
    try {//from w w  w  .j a  v  a2 s .  com
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        builder.setErrorHandler(errorHandler);
        Document document = builder.getDOMImplementation().createDocument(null, "data", null);

        Element root = document.getDocumentElement();
        root.setAttribute("nextId", String.valueOf(nextId));

        for (Iterator iter = systems.iterator(); iter.hasNext();) {
            TradingSystem system = (TradingSystem) iter.next();

            Element element = document.createElement("system");
            element.setAttribute("id", String.valueOf(system.getId()));

            Element node = document.createElement("name");
            node.appendChild(document.createTextNode(system.getName()));
            element.appendChild(node);

            if (system.getAccount().getId() != null) {
                node = document.createElement("account");
                node.appendChild(document.createTextNode(String.valueOf(system.getAccount().getId())));
                element.appendChild(node);
            }

            node = document.createElement("tradingProvider");
            node.appendChild(document.createTextNode(system.getTradingProviderId()));
            element.appendChild(node);

            if (system.getMoneyManager() != null) {
                node = document.createElement("moneyManager");
                saveComponent(system.getMoneyManager(), document, node);
                element.appendChild(node);
            }

            for (Iterator paramIter = system.getParams().keySet().iterator(); paramIter.hasNext();) {
                String key = (String) paramIter.next();
                node = document.createElement("param");
                node.setAttribute("key", key);
                node.setAttribute("value", (String) system.getParams().get(key));
                element.appendChild(node);
            }

            for (Iterator iter2 = system.getStrategies().iterator(); iter2.hasNext();)
                saveStrategy((Strategy) iter2.next(), document, element);

            root.appendChild(element);
        }

        saveDocument(document, "", "systems.xml");

    } catch (Exception e) {
        log.error(e.toString(), e);
    }
}

From source file:com.interface21.beans.factory.xml.XmlBeanFactory.java

/**
 * Load definitions from the given input stream and close it.
 * @param is InputStream containing XML/*from  www.j a  v  a 2  s  . co  m*/
 */
public void loadBeanDefinitions(InputStream is) throws BeansException {
    if (is == null)
        throw new BeanDefinitionStoreException("InputStream cannot be null: expected an XML file", null);

    try {
        logger.info("Loading XmlBeanFactory from InputStream [" + is + "]");
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        logger.debug("Using JAXP implementation [" + factory + "]");
        factory.setValidating(true);
        DocumentBuilder db = factory.newDocumentBuilder();
        db.setErrorHandler(new BeansErrorHandler());
        db.setEntityResolver(this.entityResolver != null ? this.entityResolver : new BeansDtdResolver());
        Document doc = db.parse(is);
        loadBeanDefinitions(doc);
    } catch (ParserConfigurationException ex) {
        throw new BeanDefinitionStoreException("ParserConfiguration exception parsing XML", ex);
    } catch (SAXException ex) {
        throw new BeanDefinitionStoreException("XML document is invalid", ex);
    } catch (IOException ex) {
        throw new BeanDefinitionStoreException("IOException parsing XML document", ex);
    } finally {
        try {
            if (is != null)
                is.close();
        } catch (IOException ex) {
            throw new FatalBeanException("IOException closing stream for XML document", ex);
        }
    }
}

From source file:hd3gtv.as5kpc.protocol.ProtocolHandler.java

/**
 * @return maybe null/*from  w  w w . j a v  a  2 s .c om*/
 */
private ServerResponse send(Document document, ServerResponse response) throws IOException {
    byte[] message = null;
    try {
        DOMSource domSource = new DOMSource(document);
        StringWriter stringwriter = new StringWriter();
        StreamResult streamresult = new StreamResult(stringwriter);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();

        transformer.setOutputProperty(OutputKeys.INDENT, "no");
        transformer.transform(domSource, streamresult);
        message = stringwriter.toString().getBytes("UTF-8");
    } catch (UnsupportedEncodingException uee) {
        throw new IOException("Encoding XML is not supported", uee);
    } catch (TransformerException tc) {
        throw new IOException("Converting error between XML and String", tc);
    }

    if (log.isTraceEnabled()) {
        log.trace("Raw send >> " + new String(message, "UTF-8"));
    }

    /**
     * Send XML request
     */
    os.write(message);
    os.flush();

    /**
     * Wait and recevied XML response
     */
    int bytesRead;
    byte[] bytes = new byte[4092];
    try {
        while (socket.isConnected()) {
            try {
                while ((bytesRead = is.read(bytes)) != -1) {
                    try {
                        if (log.isTraceEnabled()) {
                            log.trace("Raw receive << " + new String(bytes, 0, bytesRead, "UTF-8"));
                        }
                        /**
                         * Decode XML response
                         */
                        ByteArrayInputStream bais = new ByteArrayInputStream(bytes, 0, bytesRead);
                        DocumentBuilderFactory xmlDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
                        DocumentBuilder xmlDocumentBuilder = xmlDocumentBuilderFactory.newDocumentBuilder();
                        xmlDocumentBuilder.setErrorHandler(null);
                        document = xmlDocumentBuilder.parse(bais);
                        Element root_element = document.getDocumentElement();

                        /**
                         * Check if result is valid/positive.
                         */
                        Element rply = (Element) root_element.getElementsByTagName("Reply").item(0);
                        String status = rply.getAttribute("Status").toLowerCase();
                        if (status.equals("ok") == false) {
                            String _message = "(no message)";
                            if (rply.hasAttribute("Msg")) {
                                _message = rply.getAttribute("Msg");
                            }

                            String error_type = "";
                            if (rply.hasAttribute("ErrNum")) {
                                int err = Integer.parseInt(rply.getAttribute("ErrNum"));
                                switch (err) {
                                case 1:
                                    error_type = "Command Error";
                                    break;
                                case 2:
                                    error_type = "System Error";
                                    break;
                                case 3:
                                    error_type = "XML format error";
                                    break;
                                case 4:
                                    error_type = "System BUSY";
                                    break;
                                default:
                                    break;
                                }
                            }

                            if (status.equals("warning")) {
                                log.warn(_message + ": " + error_type);
                            }
                            if (status.equals("error")) {
                                if (response instanceof ServerResponseClipdata
                                        && _message.toLowerCase().endsWith("does not exist")) {
                                    ((ServerResponseClipdata) response).not_found = true;
                                    return response;
                                } else {
                                    throw new IOException(
                                            "Server return: \"" + _message + ": " + error_type + "\"");
                                }
                            }
                        }

                        if (response != null) {
                            response.injectServerResponse(root_element);
                        }

                        return response;
                    } catch (ParserConfigurationException pce) {
                        log.error("DOM parser error", pce);
                    } catch (SAXException se) {
                        log.error("XML Struct error", se);
                    } catch (Exception e) {
                        log.error("Invalid response", e);
                    }
                }
            } catch (SocketTimeoutException soe) {
                Thread.sleep(100);
            }
        }
    } catch (InterruptedException e) {
    } catch (IOException e) {
        if (e.getMessage().equalsIgnoreCase("Socket closed")) {
            log.debug("Socket is closed, quit parser");
        } else {
            throw e;
        }
    }
    return null;
}

From source file:ar.com.tadp.xml.rinzo.core.resources.validation.XMLStringValidator.java

private void saxDTDValidate(String fileName, String fileContent,
        DocumentStructureDeclaration structureDeclaration) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);/*from  ww w  .  j  a v  a  2s .c om*/
    factory.setValidating(true);
    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        URI resolverURI = FileUtils.resolveURI(fileName, structureDeclaration.getSystemId());
        if (resolverURI != null) {
            this.resolver.setBaseURL(fileName);
            this.resolver.setSystemId(structureDeclaration.getSystemId());
            builder.setEntityResolver(this.resolver);
        }
        builder.setErrorHandler(this.errorHandler);
        builder.parse(new InputSource(new StringReader(fileContent)));
    } catch (Exception e) {
        //Do nothing because the errorHandler informs the error
    }
}

From source file:com.apdplat.platform.spring.APDPlatPersistenceUnitReader.java

/**
 * Validate the given stream and return a valid DOM document for parsing.
 *///w w w.j  a va  2s .co m
protected Document buildDocument(ErrorHandler handler, InputStream stream)
        throws ParserConfigurationException, SAXException, IOException {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder parser = dbf.newDocumentBuilder();
    parser.setErrorHandler(handler);
    return parser.parse(stream);
}

From source file:jp.ikedam.jenkins.plugins.viewcopy_builder.ViewcopyBuilder.java

/**
 * Returns the configuration XML document of a view
 * /*from  w ww  .j  av a2s . c o  m*/
 * @param view
 * @param logger
 * @return
 * @throws IOException 
 * @throws SAXException 
 * @throws ParserConfigurationException 
 */
private Document getViewConfigXmlDocument(View view, final PrintStream logger)
        throws IOException, SAXException, ParserConfigurationException {
    XStream2 xStream2 = new XStream2(new DomDriver("UTF-8"));
    xStream2.omitField(View.class, "owner");
    xStream2.omitField(View.class, "name"); // this field causes disaster when overwriting.

    PipedOutputStream sout = new PipedOutputStream();
    PipedInputStream sin = new PipedInputStream(sout);

    xStream2.toXML(view, sout);
    sout.close();

    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    builder.setErrorHandler(new ErrorHandler() {
        @Override
        public void warning(SAXParseException exception) throws SAXException {
            exception.printStackTrace(logger);
        }

        @Override
        public void error(SAXParseException exception) throws SAXException {
            exception.printStackTrace(logger);
        }

        @Override
        public void fatalError(SAXParseException exception) throws SAXException {
            exception.printStackTrace(logger);
        }
    });
    return builder.parse(sin);
}

From source file:module.signature.util.XAdESValidator.java

/**
 * @author joantune/*from  www .  j a  v  a2  s .  com*/
 * 
 *         Makes sure that the document which was signed is equal to the one
 *         that was sent. It also checks to see if the signers are the
 *         correct persons or not NOTE: It does note validate the validity
 *         of the signature itself, only that what was sent was the same
 *         that was receveived.
 * 
 *         To validate, see:
 * 
 * @see XAdESValidator#validateXMLSignature(byte[])
 * @param receivedContent
 *            the received signature
 * @param originalContent
 *            the byte array of what was sent to the signer
 * @param usersPermitted
 *            Users that are permitted to be on the signature
 * @param usersExcluded
 *            Users which must not be on the list of signers, or null/empty
 *            list if none is excluded
 * @param allUsersPermittedShouldBeThere
 *            if true, all of the users of <i>usersPermitted</i> must be on
 *            the list of signers
 * @throws SignatureDataException
 *             if any error has been observed, thus the validation fails
 */
public static void validateSentAndReceivedContent(String receivedContent, byte[] originalContent,
        Set<User> usersPermitted, Set<User> usersExcluded, boolean allUsersPermittedShouldBeThere)
        throws SignatureDataException {
    //let's validate the content. That is, what we received against what we sent and make sure it hasn't changed

    if (schemaXSD == null) {
        loadXAdESSchemas();
    }
    //we know that we are receiving a XaDES-T signature
    boolean validSignature = false;
    try {

        //let's extract the signatureContent and compare it against what we sent

        //let's decode and interpret the XML file

        //making the objects to interpret the XML document
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder parser = dbf.newDocumentBuilder();

        ErrorHandler eh = new ErrorHandler() {

            @Override
            public void warning(SAXParseException exception) throws SAXException {
                throw new UnsupportedOperationException("Not supported yet.", exception);
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                throw new UnsupportedOperationException("Not supported yet.", exception);
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                throw new UnsupportedOperationException("Not supported yet.", exception);
            }
        };

        //let's decode the document

        byte[] signatureDecoded = Base64.decode(receivedContent);
        ByteArrayInputStream bais = new ByteArrayInputStream(signatureDecoded);

        // let's parse the document
        parser.setErrorHandler(eh);
        Document document = parser.parse(bais);

        NodeList fileContentNodeList = document.getElementsByTagName("FileContent");

        //Even if we have more than one signature, we should only have one file content!! if not, let's throw an exception here
        if (fileContentNodeList.getLength() > 1) {
            throw new SignatureDataException("too.many.file.content.nodes.malformed.signature.document", true,
                    null);
        }
        if (fileContentNodeList.getLength() < 1) {
            throw new SignatureDataException("no.file.content.nodes.in.received.signature", true, null);
        }

        Node fileContentNode = fileContentNodeList.item(0).getFirstChild();

        //now finally, we can compare the content of this node with the one that we generated
        //debug lines:

        byte[] receivedDecodedByteContent = Base64.decode(fileContentNode.getNodeValue());

        //ok, so let's parse this again to strings and then we can better compare them and maybe know exactly why they are different

        String originalEncodedContent = Base64.encodeBytes(originalContent);

        String originalDecodedContent = new String(Base64.decode(originalEncodedContent),
                Charset.forName("UTF-8"));
        String receivedDecodedContent = new String(receivedDecodedByteContent, Charset.forName("UTF-8"));
        //now let's
        //make sure the signature is from the right person
        //TODO uncomment the following line:
        //       validateSigner(document, usersPermitted, usersExcluded, allUsersPermittedShouldBeThere);

        if (!StringUtils.equals(StringUtils.trimToEmpty(originalDecodedContent),
                StringUtils.trimToEmpty(receivedDecodedContent))) {
            //       }
            throw new SignatureDataException("signature.content.sent.and.received.are.different");
        } else {
            validSignature = true;
        }

        //TODO FENIX-196 assert if one should be notified of these errors
    } catch (IOException e1) {
        //       e1.printStackTrace();
        throw new SignatureDataException("error.decoding.base64.sig", e1);
    } catch (SAXException e) {
        //       e.printStackTrace();
        throw new SignatureDataException("error.parsing.received.signature.file", e);
    } catch (ParserConfigurationException e) {
        //       e.printStackTrace();
        throw new SignatureDataException("error.parsing.received.signature.file.parser.configuration", e);
    }

    if (!validSignature) {
        throw new SignatureDataException("invalid.signature.content");
    }

}

From source file:org.squale.squaleweb.applicationlayer.action.export.ppt.PPTData.java

/**
 * Create a document with mapping file//w  w  w  .  j av a2s  .c  om
 * 
 * @param mappingStream stream of mapping file
 * @throws PPTGeneratorException if error while parsing mapping file
 */
public void setMapping(InputStream mappingStream) throws PPTGeneratorException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    try {
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setEntityResolver(new XmlResolver(PUBLIC_ID, DTD_LOCATION));
        db.setErrorHandler(new ParsingHandler(LOGGER, errors));
        mapping = db.parse(mappingStream);
        if (errors.length() > 0) {
            handleException("export.audit_report.mapping.error", new String[] { errors.toString() });
        }
    } catch (ParserConfigurationException e) {
        handleException("export.audit_report.mapping.error", new String[] { e.getMessage() });
    } catch (SAXException e) {
        handleException("export.audit_report.mapping.error", new String[] { e.getMessage() });
    } catch (IOException e) {
        handleException("export.audit_report.mapping.error", new String[] { e.getMessage() });
    }
}

From source file:manchester.synbiochem.datacapture.SeekConnector.java

private DocumentBuilder parser() throws ParserConfigurationException {
    DocumentBuilder builder = dbf.newDocumentBuilder();
    builder.setErrorHandler(new DefaultHandler() {
        @Override//from   w ww.j ava2  s  .  co  m
        public void warning(SAXParseException exception) throws SAXException {
            log.warn(exception.getMessage());
        }

        @Override
        public void error(SAXParseException exception) throws SAXException {
            log.error(exception.getMessage(), exception);
        }
    });
    return builder;
}

From source file:nl.armatiek.xslweb.configuration.WebApp.java

public WebApp(File webAppDefinition) throws Exception {
    logger.info(String.format("Loading webapp definition \"%s\" ...", webAppDefinition.getAbsolutePath()));

    Context context = Context.getInstance();
    this.definition = webAppDefinition;
    this.homeDir = webAppDefinition.getParentFile();
    this.name = this.homeDir.getName();

    this.configuration = new XSLWebConfiguration(this);
    this.processor = new Processor(this.configuration.getConfiguration());

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);/*from ww w  .  j a  va  2 s  . co m*/
    dbf.setSchema(context.getWebAppSchema());
    dbf.setXIncludeAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setErrorHandler(this);

    String defXml = IOUtils.toString(new XmlStreamReader(webAppDefinition));
    Properties vars = new Properties(System.getProperties());
    vars.setProperty("webapp-dir", webAppDefinition.getParentFile().getAbsolutePath().replace('\\', '/'));
    String resolvedDefXml = XSLWebUtils.resolveProperties(defXml, vars);
    // Document webAppDoc = db.parse(webAppDefinition);
    InputSource src = new InputSource(new StringReader(resolvedDefXml));
    src.setSystemId(webAppDefinition.getAbsolutePath());
    Document webAppDoc = db.parse(src);

    XPath xpath = new XPathFactoryImpl().newXPath();
    xpath.setNamespaceContext(XMLUtils.getNamespaceContext("webapp", Definitions.NAMESPACEURI_XSLWEB_WEBAPP));
    Node docElem = webAppDoc.getDocumentElement();
    this.title = (String) xpath.evaluate("webapp:title", docElem, XPathConstants.STRING);
    this.description = (String) xpath.evaluate("webapp:description", docElem, XPathConstants.STRING);
    String devModeValue = (String) xpath.evaluate("webapp:development-mode", docElem, XPathConstants.STRING);
    this.developmentMode = XMLUtils.getBooleanValue(devModeValue, false);
    String maxUploadSizeValue = (String) xpath.evaluate("webapp:max-upload-size", docElem,
            XPathConstants.STRING);
    this.maxUploadSize = XMLUtils.getIntegerValue(maxUploadSizeValue, 10);
    String waitForJobsAtCloseValue = (String) xpath.evaluate("webapp:wait-for-jobs-at-close", docElem,
            XPathConstants.STRING);
    this.waitForJobsAtClose = XMLUtils.getBooleanValue(waitForJobsAtCloseValue, true);

    NodeList resourceNodes = (NodeList) xpath.evaluate("webapp:resources/webapp:resource", docElem,
            XPathConstants.NODESET);
    for (int i = 0; i < resourceNodes.getLength(); i++) {
        resources.add(new Resource((Element) resourceNodes.item(i)));
    }
    NodeList paramNodes = (NodeList) xpath.evaluate("webapp:parameters/webapp:parameter", docElem,
            XPathConstants.NODESET);
    for (int i = 0; i < paramNodes.getLength(); i++) {
        parameters.add(new Parameter(processor, (Element) paramNodes.item(i)));
    }
    NodeList jobNodes = (NodeList) xpath.evaluate("webapp:jobs/webapp:job", docElem, XPathConstants.NODESET);
    if (jobNodes.getLength() > 0) {
        File quartzFile = new File(homeDir, Definitions.FILENAME_QUARTZ);
        quartzFile = (quartzFile.isFile()) ? quartzFile
                : new File(context.getHomeDir(), "config" + File.separatorChar + Definitions.FILENAME_QUARTZ);
        SchedulerFactory sf;
        if (quartzFile.isFile()) {
            logger.info(String.format("Initializing Quartz scheduler using properties file \"%s\" ...",
                    quartzFile.getAbsolutePath()));
            Properties props = XSLWebUtils.readProperties(quartzFile);
            props.setProperty(StdSchedulerFactory.PROP_SCHED_INSTANCE_NAME, name);
            sf = new StdSchedulerFactory(props);
        } else {
            logger.info("Initializing Quartz scheduler ...");
            sf = new StdSchedulerFactory();
        }
        scheduler = sf.getScheduler();
        for (int i = 0; i < jobNodes.getLength(); i++) {
            Element jobElem = (Element) jobNodes.item(i);
            String jobName = XMLUtils.getValueOfChildElementByLocalName(jobElem, "name");
            String jobUri = XMLUtils.getValueOfChildElementByLocalName(jobElem, "uri");
            String jobCron = XMLUtils.getValueOfChildElementByLocalName(jobElem, "cron");
            boolean concurrent = XMLUtils
                    .getBooleanValue(XMLUtils.getValueOfChildElementByLocalName(jobElem, "concurrent"), true);
            String jobId = "job_" + name + "_" + jobName;
            JobDetail job = newJob(concurrent ? XSLWebJob.class : NonConcurrentExecutionXSLWebJob.class)
                    .withIdentity(jobId, name).usingJobData("webapp-path", getPath())
                    .usingJobData("uri", jobUri).build();
            Trigger trigger = newTrigger().withIdentity("trigger_" + name + "_" + jobName, name)
                    .withSchedule(cronSchedule(jobCron)).forJob(jobId, name).build();
            logger.info(String.format("Scheduling job \"%s\" of webapp \"%s\" ...", jobName, name));
            scheduler.scheduleJob(job, trigger);
        }
    }

    NodeList dataSourceNodes = (NodeList) xpath.evaluate("webapp:datasources/webapp:datasource", docElem,
            XPathConstants.NODESET);
    for (int i = 0; i < dataSourceNodes.getLength(); i++) {
        DataSource dataSource = new DataSource((Element) dataSourceNodes.item(i));
        dataSources.put(dataSource.getName(), dataSource);
    }

    NodeList fopConfigNodes = (NodeList) xpath.evaluate("webapp:fop-configs/webapp:fop-config", docElem,
            XPathConstants.NODESET);
    for (int i = 0; i < fopConfigNodes.getLength(); i++) {
        Element fopConfig = (Element) fopConfigNodes.item(i);
        Element fopElement = XMLUtils.getFirstChildElement(fopConfig);
        fopConfigs.put(fopConfig.getAttribute("name"), XMLUtils.nodeToString(fopElement));
    }

    // initClassLoader();

    initFileAlterationObservers();
}