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:fll.scheduler.TournamentSchedule.java

/**
 * Validate the schedule XML document.//w  ww. ja v  a  2 s  .  c  o m
 * 
 * @throws SAXException on an error
 */
public static void validateXML(final org.w3c.dom.Document document) throws SAXException {
    try {
        final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

        final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        final Source schemaFile = new StreamSource(
                classLoader.getResourceAsStream("fll/resources/schedule.xsd"));
        final Schema schema = factory.newSchema(schemaFile);

        final Validator validator = schema.newValidator();
        validator.validate(new DOMSource(document));
    } catch (final IOException e) {
        throw new RuntimeException("Internal error, should never get IOException here", 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  www  . j  av  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:org.keycloak.testsuite.adapter.servlet.AbstractSAMLServletsAdapterTest.java

private void validateXMLWithSchema(String xml, String schemaFileName) throws SAXException, IOException {
    URL schemaFile = getClass().getResource(schemaFileName);

    Source xmlFile = new StreamSource(new ByteArrayInputStream(xml.getBytes()), xml);
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema(schemaFile);
    Validator validator = schema.newValidator();
    try {/*from w  w  w .  j a v  a 2s . c  o m*/
        validator.validate(xmlFile);
        System.out.println(xmlFile.getSystemId() + " is valid");
    } catch (SAXException e) {
        System.out.println(xmlFile.getSystemId() + " is NOT valid");
        System.out.println("Reason: " + e.getLocalizedMessage());
        Assert.fail();
    }
}

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   ww w  .  java  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
    }
}

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

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

    try {//from  w ww.j av a2s .  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);
    }
}

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 w ww  .j a  v a2s .c  om*/

        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:csiro.pidsvc.mappingstore.Manager.java

/**************************************************************************
 *  Generic processing methods./*  ww  w.  j av a2 s . c o  m*/
 */

protected void validateRequest(String inputData, String xmlSchemaResourcePath)
        throws IOException, ValidationException {
    try {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        schemaFactory.setResourceResolver(new LSResourceResolver() {
            @Override
            public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId,
                    String baseURI) {
                return new XsdSchemaResolver(type, namespaceURI, publicId, systemId, baseURI);
            }
        });

        Schema schema = schemaFactory
                .newSchema(new StreamSource(getClass().getResourceAsStream(xmlSchemaResourcePath)));
        Validator validator = schema.newValidator();
        _logger.trace("Validating XML Schema.");
        validator.validate(new StreamSource(new StringReader(inputData)));
    } catch (SAXException ex) {
        _logger.debug("Unknown format.", ex);
        throw new ValidationException("Unknown format.", ex);
    }
}

From source file:eu.eidas.auth.engine.EIDASSAMLEngine.java

public static String validateSchema(String samlRequestXML) throws EIDASSAMLEngineException {
    Document document;//from   w  w  w. java2s  .  com
    javax.xml.validation.Schema schema = null;
    javax.xml.validation.Validator validator;

    try {
        BasicParserPool ppMgr = getNewBasicSecuredParserPool();
        ppMgr.setNamespaceAware(true);
        InputStream inputStream = new ByteArrayInputStream(samlRequestXML.getBytes("UTF-8"));
        document = ppMgr.parse(inputStream);
        Element samlElemnt = document.getDocumentElement();

        schema = SAMLSchemaBuilder.getSAML11Schema();

        validator = schema.newValidator();
        DOMSource domSrc = new DOMSource(samlElemnt);
        validator.validate(domSrc);
    } catch (XMLParserException e) {
        LOG.info(SAML_EXCHANGE, "BUSINESS EXCEPTION : Validate schema exception", e.getMessage());
        LOG.debug(SAML_EXCHANGE, "BUSINESS EXCEPTION : Validate schema exception", e);
        if (e.getCause().toString().contains("DOCTYPE is disallowed")) {
            throw new EIDASSAMLEngineException(
                    EIDASUtil.getConfig(EIDASErrors.DOC_TYPE_NOT_ALLOWED.errorCode()),
                    EIDASErrors.DOC_TYPE_NOT_ALLOWED.errorCode(),
                    "SAML request contains a DOCTYPE which is not allowed for security reason");
        } else {
            throw new EIDASSAMLEngineException(
                    EIDASUtil.getConfig(EIDASErrors.MESSAGE_VALIDATION_ERROR.errorCode()),
                    EIDASErrors.MESSAGE_VALIDATION_ERROR.errorMessage(), e);
        }
    } catch (SAXException e) {
        LOG.info(SAML_EXCHANGE, "BUSINESS EXCEPTION : Validate schema exception", e.getMessage());
        LOG.debug(SAML_EXCHANGE, "BUSINESS EXCEPTION : Validate schema exception", e);
        throw new EIDASSAMLEngineException(
                EIDASUtil.getConfig(EIDASErrors.MESSAGE_VALIDATION_ERROR.errorCode()),
                EIDASErrors.MESSAGE_VALIDATION_ERROR.errorMessage(), e);
    } catch (IOException e) {
        LOG.info(SAML_EXCHANGE, "BUSINESS EXCEPTION : Validate schema exception", e.getMessage());
        LOG.debug(SAML_EXCHANGE, "BUSINESS EXCEPTION : Validate schema exception", e);
        throw new EIDASSAMLEngineException(
                EIDASUtil.getConfig(EIDASErrors.MESSAGE_VALIDATION_ERROR.errorCode()),
                EIDASErrors.MESSAGE_VALIDATION_ERROR.errorMessage(), e);
    }
    return samlRequestXML;
}

From source file:eu.artist.postmigration.eubt.executiontrace.abstractor.SOAPTraceAbstractor.java

/**
 * Validates soap trace (i.e., list of soap responses) against schema and
 * stores the result// w w  w .  j  a v  a 2  s.  com
 * 
 * @param soapResponseTrace trace that contains soap responses
 * @return map of soap responses and their respective validation result
 * @throws EUBTException in case the schema location could not be found
 */
private LinkedMap<SOAPResponse, String> validateSoapTrace(final SOAPTrace soapResponseTrace)
        throws EUBTException {
    final LinkedMap<SOAPResponse, String> validationResults = new LinkedMap<SOAPResponse, String>();

    final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Validator validator;
    try {
        final Schema schema = schemaFactory.newSchema(new URL(schemaLocation));
        validator = schema.newValidator();
    } catch (SAXException | IOException e) {
        throw new EUBTException("Failed to create Schema from Schema location " + schemaLocation
                + ". Detailed Exception: " + e.getMessage());
    }
    // for each soap response
    for (final Response response : soapResponseTrace.getResponses()) {
        String validationResult = VALIDATION_INVALID;
        final SOAPResponse soapResponse = (SOAPResponse) response;
        final SOAPEnvelope soapEnvelope = (SOAPEnvelope) soapResponse.getData();
        final OMElement bodyContent = soapEnvelope.getBody().getFirstElement();

        // create some invalid content
        //         SOAP12Factory factory = new SOAP12Factory();
        //         OMElement invalidElement = factory.createOMElement(new QName("blah"));
        //         OMNamespace invalidNamespace = factory.createOMNamespace("http://notMyNamespace.com", "invNS");
        //         OMAttribute invalidAttribute = factory.createOMAttribute("someAttribute", invalidNamespace, "attributeValue");
        //         bodyContent.addChild(invalidElement);
        //         bodyContent.addAttribute(invalidAttribute);

        // validate soap body content -> will cause an exception if not valid
        try {
            validator.validate(bodyContent.getSAXSource(true));
            // validation succeeded
            validationResult = VALIDATION_VALID;
            Debug.debug(this, "Successfully validated SOAP body content " + bodyContent);
        } catch (final IOException e) {
            throw new EUBTException("Failed to validate SOAP body content " + bodyContent
                    + ". Detailed Exception: " + e.getMessage());
        } catch (final SAXException e) {
            // validation failed
            Debug.debug(this, "Failed to validate soap SOAP content " + bodyContent + ". Detailed Exception: "
                    + e.getMessage());
        }
        // finished validating, store result
        validationResults.put(soapResponse, validationResult);
        validator.reset();
    } // for each soap response

    return validationResults;
}