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:ambit.data.qmrf.QMRFObject.java

protected Document buildDocument() throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    factory.setNamespaceAware(true);/*w  ww. java  2 s  . c o m*/
    factory.setValidating(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    builder.setErrorHandler(new SimpleErrorHandler(builder.getClass().getName()));
    Document doc = builder.newDocument();
    Element e = toXML(doc);
    doc.appendChild(e);
    return doc;
}

From source file:ambit.data.qmrf.QMRFObject.java

public Document readDocument(InputSource source, boolean validating, EntityResolver resolver) throws Exception {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    /*//from  www.j  a  va 2  s  .  c o  m
    factory.setNamespaceAware(true);      
    factory.setValidating(validating);
    */
    DocumentBuilder builder = factory.newDocumentBuilder();

    builder.setErrorHandler(new SimpleErrorHandler(getClass().getName()));

    // Install the entity resolver
    if (resolver != null)
        builder.setEntityResolver(resolver);

    return builder.parse(source);

}

From source file:ambit2.data.qmrf.QMRFObject.java

/**
  * Converts FO DOM Document into PDF (uses Apache FOP).
  * @param foDom  Document FO namespace xmlns:fo="http://www.w3.org/1999/XSL/Format"
  * @param pdf/*from w w w  .j av a 2  s . c o m*/
        
 protected void convertDOM2PDF(Document foDom, OutputStream pdf) {
try {
           
            
    // configure fopFactory as desired
    FopFactory fopFactory = FopFactory.newInstance();
            
        
    String foNS = "http://www.w3.org/1999/XSL/Format";           
    FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
    // configure foUserAgent as desired
         
    // Setup output
            
    BufferedOutputStream  out = new java.io.BufferedOutputStream(pdf);
         
    try {
        // Construct fop with desired output format and output stream
        Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);
                
        // Setup Identity Transformer
        TransformerFactory xfactory = TransformerFactory.newInstance();
        Transformer transformer = xfactory.newTransformer(); // identity transformer
                
        // Setup input for XSLT transformation
        Source src = new DOMSource(foDom);
                
        // Resulting SAX events (the generated FO) must be piped through to FOP
        Result res = new SAXResult(fop.getDefaultHandler());
                
        // Start XSLT transformation and FOP processing
        transformer.transform(src, res);
    } finally {
        out.close();
    }
            
} catch (Exception e) {
    e.printStackTrace(System.err);
    System.exit(-1);
}
        
 }
 */
/*
 * Needs Xerces Parser - to verify if can work with other SAX parsers
public void readSchema(InputStream in) throws Exception {
    SAXParser parser = new SAXParser();
    DeclHandler handler = new CustomDeclHandler(this);
    parser.setProperty("http://xml.org/sax/properties/declaration-handler",
    handler);
    String filename = "ambit/data/qmrf/qmrf.dtd";
    //InputStream stream = this.getClass().getClassLoader().getResourceAsStream(filename);
    InputStream stream = new FileInputStream("qmrf_empty.xml");
    parser.parse(new InputSource(stream));
    stream.close();
        
}
*/
public Document readDocument(InputSource source, boolean validating, EntityResolver resolver) throws Exception {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    /*
    factory.setNamespaceAware(true);      
    factory.setValidating(validating);
    */
    DocumentBuilder builder = factory.newDocumentBuilder();

    builder.setErrorHandler(new SimpleErrorHandler(getClass().getName()));

    // Install the entity resolver
    if (resolver != null)
        builder.setEntityResolver(resolver);

    return builder.parse(source);

}

From source file:com.hp.hpl.inkml.InkMLDOMParser.java

/**
 * Method to parse the InkML file identified by the inkmlFilename given in the parameter and creates data objects. It performs validation with schema. It
 * must have "ink" as root element with InkML name space specified with xmlns="http://www.w3.org/2003/InkML". The schema location may be specified. If it is
 * not specified or if relative path of the InkML.xsd file is specified, then the InkML.xsd file path must be added to * CLASSPATH for the parser to locate
 * it. An example of a typical header is, <ink xmlns="http://www.w3.org/2003/InkML" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 * xsi:schemaLocation="http://www.w3.org/2003/InkML C:\project\schema\inkml.xsd">
 * /*from www  .  ja va2 s . c o m*/
 * @param inkmlFileName
 * @throws InkMLException
 */
public void parseInkMLFile(final InputStream inputStream) throws InkMLException {

    // Get the DOM document object by parsing the InkML input file
    try {
        final InputSource input = new InputSource(inputStream);

        // get the DOM document object of the input InkML XML file.
        final DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        dbFactory.setIgnoringComments(true);
        dbFactory.setNamespaceAware(true);
        dbFactory.setIgnoringElementContentWhitespace(true);
        dbFactory.setValidating(false);
        if (this.isSchemaValidationEnabled()) {
            InkMLDOMParser.LOG.info("Validation using schema is enabled.");
            dbFactory.setSchema(this.schemaFactory
                    .newSchema(new StreamSource(this.getClass().getResourceAsStream("/schema/inkml.xsd"))));
        } else {
            InkMLDOMParser.LOG.info("Validation using schema is disabled.");
        }
        final DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        dBuilder.setErrorHandler(this);
        this.inkmlDOMDocument = dBuilder.parse(input);
        InkMLDOMParser.LOG.info("\nInput InkML XML file parsing is completed.\n");
        this.inkMLProcessor.beginInkSession();
        this.bindData(this.inkMLProcessor.getInk());
    } catch (final ParserConfigurationException e) {
        throw new InkMLException("Error in parsing Input InkML XML file.\n Message: " + e.getMessage(), e);
    } catch (final SAXException e) {
        throw new InkMLException("Error in parsing Input InkML XML file.\n Message: " + e.getMessage(), e);
    } catch (final IOException e) {
        throw new InkMLException("I/O error while parsing Input InkML XML file.\n Message: " + e.getMessage(),
                e);
    }
}

From source file:it.cnr.icar.eric.server.profile.ws.wsdl.cataloger.WSDLCatalogerEngine.java

private Document parseXML(InputSource source) throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setNamespaceAware(true);
    builderFactory.setValidating(false);
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    builder.setErrorHandler(new ErrorHandler() {
        public void error(SAXParseException e) throws SAXParseException {
            throw e;
        }// ww  w  .j a v  a  2s .  c o  m

        public void fatalError(SAXParseException e) throws SAXParseException {
            throw e;
        }

        public void warning(SAXParseException err) throws SAXParseException {
            // do nothing
        }
    });

    return builder.parse(source);
}

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

/**
 * @author joao.antunes@tagus.ist.utl.pt adapted it from {@link #validateXMLSignature(String)}
 * @param streamWithSignature//from  ww  w. j a v a 2s.  co m
 *            the {@link InputStream} that has the signature content
 * @return true if it's valid, false otherwise
 */
public boolean validateXMLSignature(InputStream streamWithSignature) {
    try {

        // get the  xsd schema

        Validator validator = schemaXSD.newValidator();

        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);
            }
        };

        // parse the document
        parser.setErrorHandler(eh);
        Document document = parser.parse(streamWithSignature);

        // XAdES extension
        NodeList nlObject = document.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Object");
        // XMLDSIG
        NodeList nlSignature = document.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#",
                "Signature");

        if (checkSchema) {
            if (nlObject.getLength() < 1) {
                return false;
            }
            if (nlSignature.getLength() < 1) {
                return false;
            }

            // parse the XML DOM tree againts the XSD schema
            validator.validate(new DOMSource(nlSignature.item(0)));
        }

        if (checkSignature) {
            // Validate Every Signature Element (including CounterSignatures)
            for (int i = 0; i < nlSignature.getLength(); i++) {

                Element signature = (Element) nlSignature.item(i);
                //          String baseURI = fileToValidate.toURL().toString();
                XMLSignature xmlSig = new XMLSignature(signature, null);

                KeyInfo ki = xmlSig.getKeyInfo();

                // If signature contains X509Data
                if (ki.containsX509Data()) {

                    NodeList nlSigningTime = signature.getElementsByTagNameNS(xadesNS, "SigningTime");
                    Date signingDate = null;

                    if (nlSigningTime.item(0) != null) {
                        StringBuilder xmlDate = new StringBuilder(nlSigningTime.item(0).getTextContent())
                                .deleteCharAt(22);
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
                        signingDate = simpleDateFormat.parse(xmlDate.toString());
                    }

                    //verificao OCSP
                    //TODO FENIX-189 joantune: na realidade acho que isto no verifica mesmo a revocao.. a no ser que a keystore indicada seja actualizada regularmente.
                    if (checkRevocation) {
                        //keystore certs cc, raiz estado

                        Security.setProperty("ocsp.enable", "true");
                        //System.setProperty("com.sun.security.enableCRLDP", "true");

                        CertificateFactory cf = CertificateFactory.getInstance("X.509");

                        CertPath certPath = cf
                                .generateCertPath(Collections.singletonList(ki.getX509Certificate()));
                        //             TrustAnchor trustA = new TrustAnchor(ki.getX509Certificate(), null);
                        //             Set trustAnchors = Collections.singleton(trustA);

                        PKIXParameters params = new PKIXParameters(cartaoCidadaoKeyStore);
                        params.setRevocationEnabled(true);

                        // validar o estado na data da assinatura
                        if (nlSigningTime.item(0) != null) {
                            params.setDate(signingDate);
                        }

                        try {
                            CertPathValidator cpValidator = CertPathValidator.getInstance("PKIX");
                            CertPathValidatorResult result = cpValidator.validate(certPath, params);
                            //TODO FENIX-196 probably one would want to send a notification here
                        } catch (CertPathValidatorException ex) {
                            return false;
                        } catch (InvalidAlgorithmParameterException ex) {
                            return false;
                        }
                    }

                    // verifica a validade do certificado no momento da assinatura
                    if (checkValidity) {

                        if (nlSigningTime.item(0) != null) { // continue if there is no SigningTime, if CounterSignature isn't XAdES
                            try {
                                ki.getX509Certificate().checkValidity(signingDate);
                            } catch (CertificateExpiredException ex) {
                                return false;
                            } catch (CertificateNotYetValidException ex) {
                                return false;
                            }
                        }
                    }

                    // validate against Certificate Public Key
                    boolean validSignature = xmlSig.checkSignatureValue(ki.getX509Certificate().getPublicKey());

                    if (!validSignature) {
                        return false;
                    }
                }

                // if signature includes KeyInfo KeyValue, also check against it
                if (ki.containsKeyValue()) {
                    boolean validSignature = xmlSig.checkSignatureValue(ki.getPublicKey());
                    if (!validSignature) {
                        return false;
                    }
                }

                //let's check the SignatureTimeStamp(s) joantune

                NodeList signatureTimeStamps = signature.getElementsByTagNameNS("*", "SignatureTimeStamp");
                Element signatureValue = null;
                if (signatureTimeStamps.getLength() > 0) {
                    signatureValue = (Element) signature.getElementsByTagNameNS("*", "SignatureValue").item(0);
                }
                for (int j = 0; j < signatureTimeStamps.getLength(); j++) {
                    logger.debug("Found a SignatureTimeStamp");
                    Element signatureTimeStamp = (Element) signatureTimeStamps.item(j);
                    //for now we are ignoring the XMLTimeStamp element, let's iterate through all of the EncapsulatedTimeStamp that we find
                    NodeList encapsulatedTimeStamps = signatureTimeStamp.getElementsByTagNameNS("*",
                            "EncapsulatedTimeStamp");
                    for (int k = 0; k < encapsulatedTimeStamps.getLength(); k++) {
                        logger.debug("Found an EncapsulatedTimeStamp");
                        Element encapsulatedTimeStamp = (Element) encapsulatedTimeStamps.item(k);
                        //let's check it
                        // note, we have the timestamptoken, not the whole response, that is, we don't have the status field

                        ASN1Sequence signedTimeStampToken = ASN1Sequence
                                .getInstance(Base64.decode(encapsulatedTimeStamp.getTextContent()));

                        CMSSignedData cmsSignedData = new CMSSignedData(
                                Base64.decode(encapsulatedTimeStamp.getTextContent()));

                        TimeStampToken timeStampToken = new TimeStampToken(cmsSignedData);

                        //let's construct the Request to make sure this is a valid response

                        //let's generate the digest
                        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
                        byte[] digest = sha1.digest(signatureValue.getTextContent().getBytes("UTF-8"));

                        //let's make sure the digests are the same
                        if (!Arrays.equals(digest,
                                timeStampToken.getTimeStampInfo().getMessageImprintDigest())) {
                            //TODO probably want to send an e-mail if this happens, as it's clearly a sign of tampering
                            //FENIX-196
                            logger.debug("Found a different digest in the timestamp!");
                            return false;
                        }

                        try {
                            //TODO for now we won't use the provided certificates that came with the TST
                            //            X509Store certificateStore = (X509Store) timeStampToken.getCertificates();
                            //            JcaDigestCalculatorProviderBuilder builder = new JcaDigestCalculatorProviderBuilder();
                            //            timeStampToken.validate(tsaCert, "BC");
                            //            timeStampToken.validate(new SignerInformationVerifier(new JcaContentVerifierProviderBuilder()
                            //               .build(tsaCert), builder.build()));
                            timeStampToken.validate(new SignerInformationVerifier(
                                    new JcaContentVerifierProviderBuilder().build(tsaCert),
                                    new BcDigestCalculatorProvider()));
                            //let's just verify that the timestamp was done in the past :) - let's give a tolerance of 5 mins :)
                            Date currentDatePlus5Minutes = new Date();
                            //let's make it go 5 minutes ahead
                            currentDatePlus5Minutes.setMinutes(currentDatePlus5Minutes.getMinutes() + 5);
                            if (!timeStampToken.getTimeStampInfo().getGenTime()
                                    .before(currentDatePlus5Minutes)) {
                                //FENIX-196 probably we want to log this!
                                //what the heck, timestamp is done in the future!! (clocks might be out of sync)
                                logger.warn("Found a timestamp in the future!");
                                return false;
                            }
                            logger.debug("Found a valid TimeStamp!");
                            //as we have no other timestamp elements in this signature, this means all is ok! :) 
                            //(point 5) of g.2.2.16.1.3 on the specs

                        } catch (TSPException exception) {
                            logger.debug("TimeStamp response did not validate", exception);
                            return false;
                        }

                    }
                }
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (SAXException ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (Exception ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }
    return true;
}

From source file:io.datalayer.conf.XmlConfigurationTest.java

/**
 * Creates a validating document builder.
 * //  ww w. ja  v  a2 s .co m
 * @return the document builder
 * @throws ParserConfigurationException
 *             if an error occurs
 */
private DocumentBuilder createValidatingDocBuilder() throws ParserConfigurationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    builder.setErrorHandler(new DefaultHandler() {
        @Override
        public void error(SAXParseException ex) throws SAXException {
            throw ex;
        }
    });
    return builder;
}

From source file:com.meidusa.amoeba.context.ProxyRuntimeContext.java

private ProxyServerConfig loadConfig(String configFileName) {
    DocumentBuilder db;

    try {//from   www.j a va  2  s .  co  m
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setValidating(true);
        dbf.setNamespaceAware(false);

        db = dbf.newDocumentBuilder();
        db.setEntityResolver(new EntityResolver() {

            public InputSource resolveEntity(String publicId, String systemId) {
                if (systemId.endsWith("amoeba.dtd")) {
                    InputStream in = ProxyRuntimeContext.class
                            .getResourceAsStream("/com/meidusa/amoeba/xml/amoeba.dtd");
                    if (in == null) {
                        LogLog.error("Could not find [amoeba.dtd]. Used ["
                                + ProxyRuntimeContext.class.getClassLoader() + "] class loader in the search.");
                        return null;
                    } else {
                        return new InputSource(in);
                    }
                } else {
                    return null;
                }
            }
        });

        db.setErrorHandler(new ErrorHandler() {

            public void warning(SAXParseException exception) {
            }

            public void error(SAXParseException exception) throws SAXException {
                logger.error(exception.getMessage() + " at (" + exception.getLineNumber() + ":"
                        + exception.getColumnNumber() + ")");
                throw exception;
            }

            public void fatalError(SAXParseException exception) throws SAXException {
                logger.fatal(exception.getMessage() + " at (" + exception.getLineNumber() + ":"
                        + exception.getColumnNumber() + ")");
                throw exception;
            }
        });
        return loadConfigurationFile(configFileName, db);
    } catch (Exception e) {
        logger.fatal("Could not load configuration file, failing", e);
        throw new ConfigurationException("Error loading configuration file " + configFileName, e);
    }
}

From source file:ch.entwine.weblounge.common.impl.site.SiteImpl.java

/**
 * Loads and registers the integration tests that are found in the bundle at
 * the given location.//from   w w w. j a va 2s  .c  o  m
 * 
 * @param dir
 *          the directory containing the test files
 */
private List<IntegrationTest> loadIntegrationTestDefinitions(String dir) {
    Enumeration<?> entries = bundleContext.getBundle().findEntries(dir, "*.xml", true);

    // Schema validator setup
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL schemaUrl = SiteImpl.class.getResource("/xsd/test.xsd");
    Schema testSchema = null;
    try {
        testSchema = schemaFactory.newSchema(schemaUrl);
    } catch (SAXException e) {
        logger.error("Error loading XML schema for test definitions: {}", e.getMessage());
        return Collections.emptyList();
    }

    // Module.xml document builder setup
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setSchema(testSchema);
    docBuilderFactory.setNamespaceAware(true);

    // The list of tests
    List<IntegrationTest> tests = new ArrayList<IntegrationTest>();

    while (entries != null && entries.hasMoreElements()) {
        URL entry = (URL) entries.nextElement();

        // Validate and read the module descriptor
        ValidationErrorHandler errorHandler = new ValidationErrorHandler(entry);
        DocumentBuilder docBuilder;

        try {
            docBuilder = docBuilderFactory.newDocumentBuilder();
            docBuilder.setErrorHandler(errorHandler);
            Document doc = docBuilder.parse(entry.openStream());
            if (errorHandler.hasErrors()) {
                logger.warn("Error parsing integration test {}: XML validation failed", entry);
                continue;
            }
            IntegrationTestGroup test = IntegrationTestParser.fromXml(doc.getFirstChild());
            test.setSite(this);
            test.setGroup(getName());
            tests.add(test);
        } catch (SAXException e) {
            throw new IllegalStateException(e);
        } catch (IOException e) {
            throw new IllegalStateException(e);
        } catch (ParserConfigurationException e) {
            throw new IllegalStateException(e);
        }
    }

    return tests;
}

From source file:net.sourceforge.eclipsetrader.core.internal.XMLRepository.java

private History loadHistory(Integer id) {
    History barData = new History(id);

    File file = new File(Platform.getLocation().toFile(), "history/" + String.valueOf(id) + ".xml"); //$NON-NLS-1$ //$NON-NLS-2$  $NON-NLS-2$
    if (file.exists() == true) {
        try {/*from  www  . j  ava  2  s . com*/
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            builder.setErrorHandler(errorHandler);
            Document document = builder.parse(file);
            barData.addAll(decodeBarData(document.getFirstChild().getChildNodes()));
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
    }

    barData.clearChanged();

    return barData;
}