Example usage for javax.xml.validation Validator setErrorHandler

List of usage examples for javax.xml.validation Validator setErrorHandler

Introduction

In this page you can find the example usage for javax.xml.validation Validator setErrorHandler.

Prototype

public abstract void setErrorHandler(ErrorHandler errorHandler);

Source Link

Document

Sets the ErrorHandler to receive errors encountered during the validate method invocation.

Usage

From source file:mx.bigdata.sat.cfdi.CFDv3.java

public void validar(ErrorHandler handler) throws Exception {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Source[] schemas = new Source[] { new StreamSource(getClass().getResourceAsStream(XSD)),
            new StreamSource(getClass().getResourceAsStream(XSD_TFD)) };
    Schema schema = sf.newSchema(schemas);
    Validator validator = schema.newValidator();
    if (handler != null) {
        validator.setErrorHandler(handler);
    }/*  w  w  w  .ja va 2 s  .c  o  m*/
    validator.validate(new JAXBSource(context, document));
}

From source file:ca.uhn.fhir.validation.SchemaBaseValidator.java

private void doValidate(IValidationContext<?> theContext, String schemaName) {
    Schema schema = loadSchema("dstu", schemaName);

    try {/*from ww  w  . ja  v  a  2 s. c  om*/
        Validator validator = schema.newValidator();
        MyErrorHandler handler = new MyErrorHandler(theContext);
        validator.setErrorHandler(handler);
        String encodedResource;
        if (theContext.getResourceAsStringEncoding() == EncodingEnum.XML) {
            encodedResource = theContext.getResourceAsString();
        } else {
            encodedResource = theContext.getFhirContext().newXmlParser()
                    .encodeResourceToString((IBaseResource) theContext.getResource());
        }

        try {
            /*
             * See https://github.com/jamesagnew/hapi-fhir/issues/339
             * https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing
             */
            validator.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
            validator.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
        } catch (SAXNotRecognizedException ex) {
            ourLog.warn("Jaxp 1.5 Support not found.", ex);
        }

        validator.validate(new StreamSource(new StringReader(encodedResource)));
    } catch (SAXParseException e) {
        SingleValidationMessage message = new SingleValidationMessage();
        message.setLocationLine(e.getLineNumber());
        message.setLocationCol(e.getColumnNumber());
        message.setMessage(e.getLocalizedMessage());
        message.setSeverity(ResultSeverityEnum.FATAL);
        theContext.addValidationMessage(message);
    } catch (SAXException e) {
        // Catch all
        throw new ConfigurationException("Could not load/parse schema file", e);
    } catch (IOException e) {
        // Catch all
        throw new ConfigurationException("Could not load/parse schema file", e);
    }
}

From source file:cl.vmetrix.operation.persistence.XmlValidator.java

/**
 * The method validatorXMLstg determinate if the String XML is correct. 
 * @return a boolean (true or false) to indicate if the XML is correct.
 * @param xml is the String XML to validate against XSD Schema
 * @throws SAXException/*from   ww w .  jav a  2 s  . co m*/
 * @throws IOException
 */

public boolean validateXMLstg(String xml) throws SAXException, IOException {
    String rpta = "";

    boolean validation = true;
    try {

        xml = new String(xml.getBytes("UTF-8"));

        //         System.out.println("---> XML in UTF-8: "+ xml);
        // convert String into InputStream
        InputStream is = new ByteArrayInputStream(xml.getBytes());

        Source xmlFile = new StreamSource(is);//new File("C:/XML/424437.xml"));

        // XSD schema
        String schemea = getFileSchema("operationSchema.xsd");

        InputStream sch = new ByteArrayInputStream(schemea.getBytes());

        Source schemaFile = new StreamSource(sch);//new File("main/resources/Operation.xsd"));

        // Preparing the schema
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(schemaFile);

        // Validator creation
        Validator validator = schema.newValidator();

        // DException handle of validator
        final List<SAXParseException> exceptions = new LinkedList<SAXParseException>();
        validator.setErrorHandler(new ErrorHandler() {
            @Override
            public void warning(SAXParseException exception) throws SAXException {
                exceptions.add(exception);
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                exceptions.add(exception);
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                exceptions.add(exception);
            }
        });

        // XML validation
        validator.validate(xmlFile);

        // Validation result. If there are errors, detailed the exact position in the XML  and the error
        if (exceptions.size() == 0) {
            rpta = "XML IS VALID";
        } else {
            validation = false;
            StringBuffer sb = new StringBuffer();
            sb.append("XML IS INVALID");
            sb.append("\n");
            sb.append("NUMBER OF ERRORS: " + exceptions.size());
            sb.append("\n");
            for (int i = 0; i < exceptions.size(); i++) {
                i = i + 1;
                sb.append("Error # " + i + ":");
                sb.append("\n");
                i = i - 1;
                sb.append("    - Line: " + ((SAXParseException) exceptions.get(i)).getLineNumber());
                sb.append("\n");
                sb.append("    - Column: " + ((SAXParseException) exceptions.get(i)).getColumnNumber());
                sb.append("\n");
                sb.append("    - Error message: " + ((Throwable) exceptions.get(i)).getLocalizedMessage());
                sb.append("\n");
                sb.append("------------------------------");
            }
            rpta = sb.toString();
            logger.debug(rpta);

        }
    } catch (SAXException e) {
        logger.error("SAXException in XML validator: ", e);
        logger.debug(rpta);
        throw new SAXException(e);
    } catch (IOException e) {
        logger.error("IOException in XML validator: ", e);
        logger.debug(rpta);
        throw new IOException(e);
    }

    return validation;
}

From source file:mx.bigdata.sat.cfdi.CFDv33.java

@Override
public void validar(ErrorHandler handler) throws Exception {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Source[] schemas = new Source[XSD.length];
    for (int i = 0; i < XSD.length; i++) {
        schemas[i] = new StreamSource(getClass().getResourceAsStream(XSD[i]));
    }//w  w w. j  a v a2  s.  co m
    Schema schema = sf.newSchema(schemas);
    Validator validator = schema.newValidator();
    if (handler != null) {
        validator.setErrorHandler(handler);
    }
    validator.validate(new JAXBSource(context, document));
}

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

public void validateXml(Schema schema, org.w3c.dom.Document doc) {
    try {/* ww w .j  a v a2 s. c  om*/
        // creating a Validator instance
        Validator validator = schema.newValidator();
        System.out.println();
        System.out.println("Validator Class: " + validator.getClass().getName());

        // setting my own error handler
        validator.setErrorHandler(new MyErrorHandler());

        // validating the document against the schema
        validator.validate(new DOMSource(doc));
        System.out.println();
        if (errorCount > 0) {
            System.out.println("Failed with errors: " + errorCount);
        } else {
            System.out.println("Passed.");
        }

    } catch (Exception e) {
        // catching all validation exceptions
        System.out.println();
        System.out.println(e.toString());
    }
}

From source file:edu.unc.lib.dl.ingest.sip.METSPackageSIPProcessor.java

private void xsdValidate(File metsFile2) throws IngestException {
    // TODO can reuse schema object, it is thread safe
    javax.xml.validation.SchemaFactory schemaFactory = javax.xml.validation.SchemaFactory
            .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    StreamSource xml = new StreamSource(getClass().getResourceAsStream(schemaPackage + "xml.xsd"));
    StreamSource xlink = new StreamSource(getClass().getResourceAsStream(schemaPackage + "xlink.xsd"));
    StreamSource mets = new StreamSource(getClass().getResourceAsStream(schemaPackage + "mets.xsd"));
    StreamSource premis = new StreamSource(getClass().getResourceAsStream(schemaPackage + "premis-v2-0.xsd"));
    StreamSource mods = new StreamSource(getClass().getResourceAsStream(schemaPackage + "mods-3-4.xsd"));
    StreamSource acl = new StreamSource(getClass().getResourceAsStream(schemaPackage + "acl.xsd"));
    Schema schema;//w w  w.  ja v  a2 s .c  o m
    try {
        Source[] sources = { xml, xlink, mets, premis, mods, acl };
        schema = schemaFactory.newSchema(sources);
    } catch (SAXException e) {
        throw new Error("Cannot locate METS schema in classpath.", e);
    }

    Validator metsValidator = schema.newValidator();
    METSParseException handler = new METSParseException("There was a problem parsing METS XML.");
    metsValidator.setErrorHandler(handler);
    // TODO get a Result document for reporting error
    try {
        metsValidator.validate(new StreamSource(metsFile2));
    } catch (SAXException e) {
        if (log.isDebugEnabled()) {
            log.debug(e.getMessage());
        }
        throw handler;
    } catch (IOException e) {
        throw new IngestException("The supplied METS file is not readable.", e);
    }
}

From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.util.QCliveXMLSchemaValidator.java

protected Boolean validateSchema(final List<Source> schemaSourceList, final Document document,
        final File xmlFile, final QcContext context) throws SAXException, IOException {

    final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    // instantiate the schema
    Schema schema = factory.newSchema(schemaSourceList.toArray(new Source[] {}));
    // now validate the file against the schema
    // note: supposedly there is a way to just let the XML document figure
    // out its own schema based on what is referred to, but
    // I could not get that to work, which is why I am looking for the
    // schema in the attribute

    final DOMSource source = new DOMSource(document);
    final Validator validator = schema.newValidator();

    // wow this looks dumb, but isValid has to be final to be accessed from
    // within an inner class
    // and this was IDEA's solution to the problem: make it an array and set
    // the first element of the array
    final boolean[] isValid = new boolean[] { true };

    // add error handler that will add validation errors and warnings
    // directly to the QcContext object
    validator.setErrorHandler(new ErrorHandler() {
        public void warning(final SAXParseException exception) {
            context.addWarning(new StringBuilder().append(xmlFile.getName()).append(": ")
                    .append(exception.getMessage()).toString());
        }//from  www.  j  a  v  a2 s  .  c o m

        public void error(final SAXParseException exception) {
            context.addError(MessageFormat.format(MessagePropertyType.XML_FILE_PROCESSING_ERROR,
                    xmlFile.getName(), new StringBuilder().append(xmlFile.getName()).append(": ")
                            .append(exception.getMessage()).toString()));
            isValid[0] = false;
        }

        public void fatalError(final SAXParseException exception) throws SAXException {
            context.getArchive().setDeployStatus(Archive.STATUS_INVALID);
            throw exception;
        }
    });
    validator.validate(source);
    return isValid[0];
}

From source file:fr.cls.atoll.motu.library.misc.xml.XMLUtils.java

/**
 * Validate xml.//from  w w  w .  jav  a  2 s  . c o m
 * 
 * @param inSchemas the in schemas
 * @param inXml the in xml
 * @param schemaLanguage the schema language
 * 
 * @return the xML error handler
 * 
 * @throws MotuException the motu exception
 */
public static XMLErrorHandler validateXML(InputStream[] inSchemas, InputStream inXml, String schemaLanguage)
        throws MotuException {
    // parse an XML document into a DOM tree
    Document document;
    // create a Validator instance, which can be used to validate an instance document
    Validator validator;
    XMLErrorHandler errorHandler = new XMLErrorHandler();

    try {

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true); // Must enable namespace processing!!!!!
        try {
            documentBuilderFactory.setXIncludeAware(true);
        } catch (Exception e) {
            // Do Nothing
        }
        // documentBuilderFactory.setExpandEntityReferences(true);

        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        // document = documentBuilder.parse(new File(xmlUrl.toURI()));
        documentBuilder.setErrorHandler(errorHandler);
        document = documentBuilder.parse(inXml);

        // create a SchemaFactory capable of understanding WXS schemas
        SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage);
        schemaFactory.setErrorHandler(errorHandler);

        // load a WXS schema, represented by a Schema instance

        Source[] schemaFiles = new Source[inSchemas.length];

        // InputStream inShema = null;
        int i = 0;
        for (InputStream inSchema : inSchemas) {
            schemaFiles[i] = new StreamSource(inSchema);
            i++;
        }

        Schema schema = schemaFactory.newSchema(schemaFiles);

        validator = schema.newValidator();
        validator.setErrorHandler(errorHandler);
        validator.validate(new DOMSource(document));

    } catch (Exception e) {
        throw new MotuException(e);
        // instance document is invalid!
    }

    return errorHandler;
}

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

private void saxSchemaValidate(String fileName, String fileContent,
        Collection<DocumentStructureDeclaration> schemaDefinitions) {
    try {/*from  www. ja  va  2 s .  c o m*/
        Validator validator;
        Map<Collection<DocumentStructureDeclaration>, Validator> schemaValidatorsCache = XMLEditorPlugin
                .getDefault().getSchemaValidatorsCache();

        validator = schemaValidatorsCache.get(schemaDefinitions);
        if (validator == null) {
            StreamSource[] sources = new StreamSource[schemaDefinitions.size()];
            int pos = 0;
            Map<String, String> fileLocations = DocumentCache.getInstance().getAllLocations(schemaDefinitions,
                    fileName);
            for (Map.Entry<String, String> fileLocation : fileLocations.entrySet()) {
                StreamSource streamSource = new StreamSource(fileLocation.getValue());
                streamSource.setPublicId(fileLocation.getKey());
                sources[pos++] = streamSource;
            }
            validator = this.createValidator(sources);
            schemaValidatorsCache.put(schemaDefinitions, validator);
        }

        validator.reset();
        validator.setErrorHandler(this.errorHandler);
        validator.validate(new StreamSource(new StringReader(fileContent)));
    } catch (SAXParseException saxE) {
        try {
            this.errorHandler.error(saxE);
        } catch (SAXException e) {
        }
    } catch (Exception exception) {
        //Do nothing because the errorHandler informs the error
    }
}