Example usage for javax.xml.validation Validator validate

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

Introduction

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

Prototype

public void validate(Source source) throws SAXException, IOException 

Source Link

Document

Validates the specified input.

Usage

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

public void validate(ErrorHandler handler) throws Exception {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = sf.newSchema(getClass().getResource(XSD));
    Validator validator = schema.newValidator();
    if (handler != null) {
        validator.setErrorHandler(handler);
    }/*from   w  w  w  .ja  v a 2s  .c  om*/
    validator.validate(new JAXBSource(CONTEXT, document));
}

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

public void validar(ErrorHandler handler) throws Exception {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = sf.newSchema(getClass().getResource(XSD));
    Validator validator = schema.newValidator();
    if (handler != null) {
        validator.setErrorHandler(handler);
    }//www  . j a va2 s  .c o  m
    validator.validate(new JAXBSource(CONTEXT, tfd));
}

From source file:de.drv.dsrv.spoc.web.webservice.jax.ExtraSchemaValidationHandler.java

private void validateExtraRequest(final Node transportNode, final ServletContext servletContext)
        throws Exception {

    // Validator-Objekt mit eXTra-Schema als Basis erstellen
    final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final Schema schema = factory.newSchema(servletContext.getResource(SCHEMA_PATH));
    final Validator validator = schema.newValidator();

    try {//from   ww w. j  ava 2  s .c om
        // Validiere Transport-Element gegen eXTra-Schema
        validator.validate(new DOMSource(transportNode));
    } catch (final SAXException e) {
        // Falls MTOM-Attachement, dann den Fehler bzgl. cid-Referenz
        // ignorieren
        if (!(e.getMessage().contains("cid:") && e.getMessage().contains("'base64Binary'"))) {
            LOG.warn("Fehler bei der XML-Validierung: " + e.getMessage());
            throw new InvalidExtraRequestException(e.getMessage());
        }
    }
}

From source file:mx.bigdata.cfdi.TFDv1.java

public void validate(ErrorHandler handler) throws Exception {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = sf.newSchema(getClass().getResource(XSD));
    Validator validator = schema.newValidator();
    if (handler != null) {
        validator.setErrorHandler(handler);
    }/*w  w  w.j a v a2 s  . c  om*/
    validator.validate(new JAXBSource(CONTEXT, tfd));
}

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

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 ava  2s .c  o m
    Schema schema = sf.newSchema(schemas);
    Validator validator = schema.newValidator();
    if (handler != null) {
        validator.setErrorHandler(handler);
    }
    validator.validate(new JAXBSource(CONTEXT, tfd));
}

From source file:com.jkoolcloud.tnt4j.streams.configure.sax.StreamsConfigSAXParser.java

/**
 * Validates configuration XML against XML defined XSD schema.
 *
 * @param config//from  ww  w.j av a2s . c o m
 *            {@link InputStream} to get configuration data from
 * @return map of found validation errors
 * @throws SAXException
 *             if there was an error parsing the configuration
 * @throws IOException
 *             if there is an error reading the configuration data
 */
public static Map<OpLevel, List<SAXParseException>> validate(InputStream config)
        throws SAXException, IOException {
    final Map<OpLevel, List<SAXParseException>> validationErrors = new HashMap<>();
    try {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema();
        Validator validator = schema.newValidator();
        validator.setErrorHandler(new ErrorHandler() {
            @Override
            public void warning(SAXParseException exception) throws SAXException {
                handleValidationError(OpLevel.WARNING, exception);
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                handleValidationError(OpLevel.ERROR, exception);
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                handleValidationError(OpLevel.FATAL, exception);
            }

            private void handleValidationError(OpLevel level, SAXParseException exception) {
                List<SAXParseException> lErrorsList = validationErrors.get(level);
                if (lErrorsList == null) {
                    lErrorsList = new ArrayList<>();
                    validationErrors.put(level, lErrorsList);
                }

                lErrorsList.add(exception);
            }
        });
        validator.validate(new StreamSource(config));
    } finally {
        if (config.markSupported()) {
            config.reset();
        }
    }

    return validationErrors;
}

From source file:at.tfr.securefs.module.validation.SchemaValidationModule.java

@Override
public ModuleResult apply(InputStream input, ModuleConfiguration moduleConfiguration)
        throws ModuleException, IOException {
    SchemaResolver errorHandler = null;//from   www . j  a  v a2 s .  c  o m
    moduleStatistics.getCalls().incrementAndGet();

    try {
        // parse an XML document into a DOM tree
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setValidating(true);
        dbf.setCoalescing(true);
        dbf.setCoalescing(true);

        if (schema == null) {
            loadSchema(moduleConfiguration);
        }

        DOMImplementationLS domImpl = (DOMImplementationLS) dbf.newDocumentBuilder().getDOMImplementation();
        errorHandler = new SchemaResolver(configuration.getSchemaPath(), domImpl);

        Validator validator = schema.newValidator();
        validator.setErrorHandler(errorHandler);
        validator.setResourceResolver(errorHandler);

        validator.validate(new StreamSource(input));

    } catch (SAXParseException e) {
        moduleStatistics.getFailures().incrementAndGet();
        String message = "error validating: " + getCurrent() + " err: " + e;
        log.debug(message, e);
        log.info(message);
        if (moduleConfiguration.isMandatory()) {
            throw new ModuleException(message, e);
        } else {
            return new ModuleResult(false, e);
        }
    } catch (Exception e) {
        moduleStatistics.getErrors().incrementAndGet();
        String message = "error validating: " + getCurrent() + " err: " + e;
        log.info(message, e);
        log.warn(message);
        if (moduleConfiguration.isMandatory()) {
            throw new IOException(message, e);
        } else {
            return new ModuleResult(false, e);
        }
    }

    if (errorHandler != null && errorHandler.getErrors().size() > 0) {

        moduleStatistics.getFailures().incrementAndGet();

        String message = "Validation errors for File: " + getCurrent() + " errors: " + errorHandler.getErrors();
        if (log.isDebugEnabled()) {
            log.debug(message);
            if (log.isTraceEnabled()) {
                log.trace("Validation warnings for File: " + getCurrent() + " errors: "
                        + errorHandler.getWarnings());
            }
        }
        if (moduleConfiguration.isMandatory()) {
            throw new ModuleException(message);
        } else {
            log.info("accepted errors - " + message);
        }
        return new ModuleResult(false, errorHandler.getErrors().get(0));
    }

    moduleStatistics.getSuccesses().incrementAndGet();
    return new ModuleResult(true);
}

From source file:com.predic8.membrane.core.interceptor.schemavalidation.AbstractXMLSchemaValidator.java

public Outcome validateMessage(Exchange exc, Message msg, String source) throws Exception {
    List<Exception> exceptions = new ArrayList<Exception>();
    String preliminaryError = getPreliminaryError(xopr, msg);
    if (preliminaryError == null) {
        List<Validator> vals = validators.take();
        try {// w  ww.  j a  v  a2  s  .  c o  m
            // the message must be valid for one schema embedded into WSDL
            for (Validator validator : vals) {
                SchemaValidatorErrorHandler handler = (SchemaValidatorErrorHandler) validator.getErrorHandler();
                try {
                    validator.validate(getMessageBody(xopr.reconstituteIfNecessary(msg)));
                    if (handler.noErrors()) {
                        valid.incrementAndGet();
                        return Outcome.CONTINUE;
                    }
                    exceptions.add(handler.getException());
                } finally {
                    handler.reset();
                }
            }
        } catch (Exception e) {
            exceptions.add(e);
        } finally {
            validators.put(vals);
        }
    } else {
        exceptions.add(new Exception(preliminaryError));
    }
    if (skipFaults && isFault(msg)) {
        valid.incrementAndGet();
        return Outcome.CONTINUE;
    }
    if (failureHandler == FailureHandler.VOID) {
        exc.setProperty("error", getErrorMsg(exceptions));
    } else if (failureHandler != null) {
        failureHandler.handleFailure(getErrorMsg(exceptions), exc);
        exc.setResponse(createErrorResponse("validation error"));
    } else {
        exc.setResponse(createErrorResponse(getErrorMsg(exceptions)));
        exc.getResponse().getHeader().add(Header.VALIDATION_ERROR_SOURCE, source);
    }
    invalid.incrementAndGet();
    return Outcome.ABORT;
}

From source file:mx.bigdata.sat.cfd.CFDv2.java

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

From source file:be.fedict.eid.dss.document.xml.XMLDSSDocumentService.java

public void checkIncomingDocument(byte[] document) throws Exception {

    LOG.debug("checking incoming document");
    ByteArrayInputStream documentInputStream = new ByteArrayInputStream(document);
    Document dom = this.documentBuilder.parse(documentInputStream);

    String namespace = dom.getDocumentElement().getNamespaceURI();
    if (null == namespace) {
        LOG.debug("no namespace defined");
        return;/*from  www. ja v  a2  s.com*/
    }

    byte[] xsd = this.context.getXmlSchema(namespace);
    if (null == xsd) {
        LOG.debug("no XML schema available for namespace: " + namespace);
        return;
    }

    LOG.debug("validating against XML schema: " + namespace);
    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    schemaFactory.setResourceResolver(new SignatureServiceLSResourceResolver(this.context));
    StreamSource schemaSource = new StreamSource(new ByteArrayInputStream(xsd));
    Schema schema = schemaFactory.newSchema(schemaSource);
    Validator validator = schema.newValidator();
    DOMSource domSource = new DOMSource(dom);
    validator.validate(domSource);
}