Example usage for javax.xml.validation Schema newValidator

List of usage examples for javax.xml.validation Schema newValidator

Introduction

In this page you can find the example usage for javax.xml.validation Schema newValidator.

Prototype

public abstract Validator newValidator();

Source Link

Document

Creates a new Validator for this Schema .

Usage

From source file:eu.planets_project.pp.plato.evaluation.evaluators.ExperimentEvaluator.java

private String evaluateLogging(String logOutput) {
    if ((logOutput == null) || "".equals(logOutput)) {
        return "none";
    } else {/*from w w w .  j av a2 s.co m*/
        String result = "text";

        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        try {
            Schema schema = factory.newSchema();
            Validator validator = schema.newValidator();

            validator.validate(new StreamSource(new StringReader(logOutput)));

            // ok, the log is well-formed XML
            result = "XML";
        } catch (SAXException e) {
            // no xml - this is ok
        } catch (IOException e) {
            log.error("logoutput-evaluator is not properly configured: ", e);
        }

        return result;
    }
}

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);
    }//from   w  w w  .j a  v a2s .  c  o m
    validator.validate(new JAXBSource(CONTEXT, tfd));
}

From source file:io.aino.agents.core.config.InputStreamConfigBuilder.java

/**
 * Validates the config file against XSD schema.
 *
 * @param stream InputStream to config file.
 *//*from   www . j  a  v  a 2 s. co m*/
private void validateSchema(InputStream stream) {
    try {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        InputStream xsdStream = this.getClass().getClassLoader().getResourceAsStream(LOGGER_SCHEMA);
        Schema schema = factory.newSchema(new StreamSource(xsdStream));
        Validator validator = schema.newValidator();
        validator.validate(new StreamSource(stream));
    } catch (SAXException e) {
        throw new InvalidAgentConfigException("Failed to validate logger config.", e);
    } catch (IOException e) {
        throw new InvalidAgentConfigException("Failed to validate logger config.", e);
    }
}

From source file:eu.delving.test.TestMappingEngine.java

private Validator validator(SchemaVersion schemaVersion) {
    try {/*from w w  w.  jav  a 2  s .  c  om*/
        SchemaFactory factory = XMLToolFactory.schemaFactory(schemaVersion.getPrefix());
        factory.setResourceResolver(new CachedResourceResolver());
        String validationXsd = schemaRepo.getSchema(schemaVersion, SchemaType.VALIDATION_SCHEMA)
                .getSchemaText();
        if (validationXsd == null)
            throw new RuntimeException("Unable to find validation schema " + schemaVersion);
        Schema schema = factory.newSchema(new StreamSource(new StringReader(validationXsd)));
        return schema.newValidator();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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 {//ww w. java  2s  .  com
        // 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.sat.cfd.CFDv22.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]));
    }//from   w  ww.  ja va  2  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: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. java 2  s  . com
    validator.validate(new JAXBSource(context, document));
}

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 .  co  m*/
    validator.validate(new JAXBSource(context, document));
}

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 .  j a v  a  2 s  . c om
 * @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:ca.uhn.fhir.validation.SchemaBaseValidator.java

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

    try {/*from   www. ja v  a  2 s  .  c  o m*/
        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);
    }
}