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:org.dataconservancy.dcs.access.server.TransformerServiceImpl.java

@Override
public SchemaType.Name validateXML(String inputXml, String schemaURI) {

    if (schemaURI == null)
        return null;
    for (SchemaType.Name schemaName : SchemaType.Name.values()) {
        if (Pattern.compile(Pattern.quote(schemaName.nameValue()), Pattern.CASE_INSENSITIVE).matcher(schemaURI)
                .find()) {/*from  w ww . jav a  2  s.co m*/
            DocumentBuilder parser;
            Document document;
            try {

                parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();

                document = parser.parse(new StringBufferInputStream(inputXml));

                SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

                Source schemaFile = new StreamSource(
                        new File(getServletContext().getContextPath() + "xml/" + schemaName.name() + ".xsd"));
                Schema schema = factory.newSchema(schemaFile);

                Validator validator = schema.newValidator();
                validator.validate(new DOMSource(document));
                return schemaName;
            } catch (Exception e) {
                e.printStackTrace();

            }

        }
    }
    return null;

}

From source file:org.dataconservancy.model.builder.DcsModelBuilderTest.java

private ErrorHandlerCollector isValid(TestCase tc, String xml) throws IOException, SAXException {
    assertNotNull(tc);/*  www. ja  v  a  2  s  . c o  m*/
    assertNotNull(xml);
    assertFalse(xml.trim().length() == 0);

    final TestResult result;

    final Schema s = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
            .newSchema(new StreamSource(dcpSchema.getInputStream()));

    final ErrorHandlerCollector errors = new ErrorHandlerCollector();

    final Validator v = s.newValidator();
    v.setErrorHandler(errors);
    try {
        v.validate(new StreamSource(IOUtils.toInputStream(xml)));
    } catch (SAXException e) {
        // ignore
    } catch (IOException e) {
        // ignore
    }

    return errors;
}

From source file:org.dataconservancy.ui.model.builder.xstream.XstreamBusinessObjectBuilder.java

/**
 * Constructs a builder that will perform validation when de-serializing XML streams if <code>isValidating</code>
 * is <code>true</code>.  The schema used for validation is the BOP 1.0 schema.
 * <p/>// w  w  w. ja  v  a2s.  c om
 * <strong><em>N.B.</em></strong>: currently this class will only validate incoming DC BOPs (it will <em>not</em>
 * validate entities).  At a later time this implementation may be updated to validate entities as well.
 *
 * @param isValidating flag indicating whether or not validation should be enabled
 * @throws IllegalStateException if the BOP schema cannot be resolved or parsed
 */
public XstreamBusinessObjectBuilder(XStream xStream, boolean isValidating) {
    x = xStream;
    validating = isValidating;

    if (validating) {
        try {
            // Create a namespace-aware parser that will parse XML into a DOM tree.
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            parser = dbf.newDocumentBuilder();

            // Create a SchemaFactory
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

            // Load the schema
            final URL businessObjectSchema = this.getClass().getResource(BOP_SCHEMA_RESOURCE);
            Source schemaFile = new StreamSource(businessObjectSchema.openStream());
            Schema schema = factory.newSchema(schemaFile);

            // Create a Validator instance, which can be used to validate an instance document
            validator = schema.newValidator();
        } catch (ParserConfigurationException e) {
            throw new IllegalStateException("Unable to initialize " + this.getClass().getName()
                    + ": error configuring parser: " + e.getMessage(), e);
        } catch (SAXException e) {
            throw new IllegalStateException(
                    "Unable to initialize " + this.getClass().getName() + ": error retrieving "
                            + " or parsing class path resource " + BOP_SCHEMA_RESOURCE + ": " + e.getMessage(),
                    e);
        } catch (IOException e) {
            throw new IllegalStateException(
                    "Unable to initialize " + this.getClass().getName() + ": IO error: " + e.getMessage(), e);
        }
    }
}

From source file:org.deegree.protocol.csw.client.getrecords.TestGetRecordsXMLEncoderTest.java

private void validateGetRecordsXml(ByteArrayOutputStream os) throws SAXException, IOException {
    InputStream getRecordsRequest = new ByteArrayInputStream(os.toByteArray());
    SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    Validator validator = null;//from w ww  .jav  a 2s.  c  o  m
    Source source = null;
    try {
        URL schemaLocation = new URL("http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd");
        Schema schema = factory.newSchema(schemaLocation);
        validator = schema.newValidator();
        source = new StreamSource(getRecordsRequest);
    } catch (Exception e) {
        Assume.assumeNoException(e);
        return;
    }
    validator.validate(source);
}

From source file:org.ebayopensource.turmeric.tools.errorlibrary.util.ErrorLibraryUtils.java

public static boolean validateAgainstSchema(String xmlLocation, String xsdLocation)
        throws PreProcessFailedException {
    boolean isValidate = false;

    Document document = null;/*from www  .j  a v  a2s .c o  m*/
    Schema schema = null;
    try {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true);
        DocumentBuilder parser = domFactory.newDocumentBuilder();
        document = parser.parse(new File(xmlLocation));

        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        URL schemaUrl = Thread.currentThread().getContextClassLoader().getResource(xsdLocation);
        if (schemaUrl == null) {
            throw new PreProcessFailedException("Unable to find schema resource: " + xsdLocation);
        }

        InputStream stream = null;
        try {
            stream = schemaUrl.openStream();
            Source schemaFile = new StreamSource(stream);
            schema = factory.newSchema(schemaFile);
        } finally {
            IOUtils.closeQuietly(stream);
        }

    } catch (ParserConfigurationException exception) {
        throw new PreProcessFailedException("XML parsing failed : " + exception.getMessage(), exception);

    } catch (SAXException exception) {
        throw new PreProcessFailedException("XML parsing failed : " + exception.getMessage(), exception);

    } catch (IOException exception) {
        throw new PreProcessFailedException(
                "XML parsing failed because of IOException : " + exception.getMessage(), exception);
    } catch (Exception exception) {
        throw new PreProcessFailedException("XML parsing failed : " + exception.getMessage(), exception);
    }

    Validator validator = schema.newValidator();

    try {
        validator.validate(new DOMSource(document));
        isValidate = true;
    } catch (SAXException exception) {
        throw new PreProcessFailedException("XML validation against XSD failed : " + exception.getMessage(),
                exception);
    } catch (IOException exception) {
        throw new PreProcessFailedException(
                "Schema validation failed because of IOException : " + exception.getMessage(), exception);
    }

    return isValidate;
}

From source file:org.eclipse.mdht.dita.ui.util.DitaUtil.java

public static void validate(IPath tmpFileInWorkspaceDir)
        throws IOException, ParserConfigurationException, SAXException, URISyntaxException {

    // TODO delete commented out code which was used for debugging (debug code needs to stay at least two releases after 2.5.9)
    // Get the XSD file
    Bundle bundle = Platform.getBundle("org.eclipse.mdht.dita.ui");
    // Path ditaSchemadirPath = new Path("DITA-OT/schema/technicalContent/xsd/topic.xsd");
    // URL ditaXSD = FileLocator.toFileURL(FileLocator.find(bundle, ditaSchemadirPath, null));
    Path ditaFolderPath = new Path("DITA-OT");
    URL ditaFolder = FileLocator.toFileURL(FileLocator.find(bundle, ditaFolderPath, null));
    // System.out.println(ditaFolder);

    // Create DBF and ignore DTD
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);/*from  w w  w.ja  va  2 s  .  c om*/
    dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    DocumentBuilder parser = dbf.newDocumentBuilder();
    Document document = parser.parse(tmpFileInWorkspaceDir.toFile());

    // create a SchemaFactory capable of understanding WXS schemas
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    // Use catalog
    // Path ditaCatalogPath = new Path("DITA-OT/schema/catalog.xml");
    // URL ditaCatalog = FileLocator.toFileURL(FileLocator.find(bundle, ditaCatalogPath, null));
    File ditaCatalogFile = new File(ditaFolder.getFile(), "schema/catalog.xml");
    // System.out.println(ditaCatalogFile);
    // System.out.println(ditaCatalogFile.exists());
    XMLCatalogResolver resolver = new XMLCatalogResolver(new String[] { ditaCatalogFile.getAbsolutePath() });
    schemaFactory.setResourceResolver(resolver);

    // load a WXS schema, represented by a Schema instance
    File ditaSchemaFile = new File(ditaFolder.getFile(), "schema/technicalContent/xsd/topic.xsd");

    // System.out.println(ditaSchemaFile);
    // System.out.println(ditaSchemaFile.exists());
    Source schemaFile = new StreamSource(ditaSchemaFile);
    Schema schema = schemaFactory.newSchema(schemaFile);
    Validator validator = schema.newValidator();

    DOMSource dom = new DOMSource(document);
    validator.validate(dom);
}

From source file:org.eurekastreams.server.action.validation.gallery.UrlXmlValidator.java

/**
 * Validates xml from given Url returning true if it passes validation, false otherwise.
 *
 * @param inActionContext/*w  w w .  j a v  a 2  s  . c om*/
 *            the action context
 * @throws ValidationException
 *             on error
 */
@Override
@SuppressWarnings("unchecked")
public void validate(final ServiceActionContext inActionContext) throws ValidationException {
    InputStream schemaStream = null;
    Map<String, Serializable> fields = (Map<String, Serializable>) inActionContext.getParams();
    String galleryItemUrl = (String) fields.get(URL_KEY);
    try {
        schemaStream = this.getClass().getResourceAsStream(xsdPath);
        log.debug("Attempt to validate xml at: " + galleryItemUrl + "with xsd at: " + xsdPath);

        SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaString);
        Schema schema = schemaFactory.newSchema(new StreamSource(schemaStream));

        Validator validator = schema.newValidator();

        // TODO: stuff the input stream into the context for execute()
        InputStream galleryItemInputStream = xmlFetcher.getInputStream(galleryItemUrl);

        validator.validate(new StreamSource(galleryItemInputStream));

        log.debug("Success validating xml at: " + galleryItemUrl);
    } catch (Exception e) {
        log.error("Validation for gadget definition failed.", e);
        ValidationException ve = new ValidationException();
        ve.addError(URL_KEY, "Valid url is required");
        throw ve;
    } finally {
        try {
            if (schemaStream != null) {
                schemaStream.close();
            }
        } catch (IOException ex) {
            log.error("Error closing stream, already closed.", ex);
        }
    }
}

From source file:org.fosstrak.epcis.repository.capture.CaptureOperationsModule.java

/**
 * Validates the given document against the given schema.
 *//*from   w ww  .java 2s .c  om*/
private void validateDocument(Document document, Schema schema) throws SAXException, IOException {
    if (schema != null) {
        Validator validator = schema.newValidator();
        validator.validate(new DOMSource(document));
        LOG.info("Incoming capture request was successfully validated against the EPCISDocument schema");
    } else {
        LOG.warn("Schema validator unavailable. Unable to validate EPCIS capture event against schema!");
    }
}

From source file:org.geoserver.test.GeoServerAbstractTestSupport.java

/**
 * Given a dom and a schema, checks that the dom validates against the schema 
 * of the validation errors instead//from   w  w  w .j  a  v  a 2s  . c  om
 * @param validationErrors
 * @throws IOException 
 * @throws SAXException 
 */
protected void checkValidationErrors(Document dom, Schema schema) throws SAXException, IOException {
    final Validator validator = schema.newValidator();
    final List<Exception> validationErrors = new ArrayList<Exception>();
    validator.setErrorHandler(new ErrorHandler() {

        public void warning(SAXParseException exception) throws SAXException {
            System.out.println(exception.getMessage());
        }

        public void fatalError(SAXParseException exception) throws SAXException {
            validationErrors.add(exception);
        }

        public void error(SAXParseException exception) throws SAXException {
            validationErrors.add(exception);
        }

    });
    validator.validate(new DOMSource(dom));
    if (validationErrors != null && validationErrors.size() > 0) {
        StringBuilder sb = new StringBuilder();
        for (Exception ve : validationErrors) {
            sb.append(ve.getMessage()).append("\n");
        }
        fail(sb.toString());
    }
}

From source file:org.gluu.oxtrust.ldap.service.Shibboleth2ConfService.java

/**
 * @param stream//from   w  w  w. j  a v  a  2s.  c  o m
 * @throws IOException
 * @throws SAXException
 * @throws ParserConfigurationException
 */
public synchronized GluuErrorHandler validateMetadata(InputStream stream)
        throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory newFactory = DocumentBuilderFactory.newInstance();
    newFactory.setCoalescing(false);
    newFactory.setExpandEntityReferences(true);
    newFactory.setIgnoringComments(false);

    newFactory.setIgnoringElementContentWhitespace(false);
    newFactory.setNamespaceAware(true);
    newFactory.setValidating(false);
    DocumentBuilder xmlParser = newFactory.newDocumentBuilder();
    Document xmlDoc = xmlParser.parse(stream);
    String schemaDir = System.getProperty("catalina.home") + File.separator + "conf" + File.separator
            + "shibboleth2" + File.separator + "idp" + File.separator + "schema" + File.separator;
    Schema schema = SchemaBuilder.buildSchema(SchemaLanguage.XML, schemaDir);
    Validator validator = schema.newValidator();
    GluuErrorHandler handler = new GluuErrorHandler();
    validator.setErrorHandler(handler);
    validator.validate(new DOMSource(xmlDoc));

    return handler;

}