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:org.apache.tinkerpop.gremlin.structure.io.IoTest.java

private static void validateXmlAgainstGraphMLXsd(final File file) throws Exception {
    final Source xmlFile = new StreamSource(file);
    final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final Schema schema = schemaFactory.newSchema(IoTest.class.getResource(
            TestHelper.convertPackageToResourcePath(GraphMLResourceAccess.class) + "graphml-1.1.xsd"));
    final Validator validator = schema.newValidator();
    validator.validate(xmlFile);
}

From source file:org.apache.tinkerpop.gremlin.structure.IoTest.java

private void validateXmlAgainstGraphMLXsd(final File file) throws Exception {
    final Source xmlFile = new StreamSource(file);
    final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final Schema schema = schemaFactory
            .newSchema(IoTest.class.getResource(GRAPHML_RESOURCE_PATH_PREFIX + "graphml-1.1.xsd"));
    final Validator validator = schema.newValidator();
    validator.validate(xmlFile);
}

From source file:org.bungeni.editor.system.ValidateConfiguration.java

public List<SAXParseException> validate(File xmlFile, ConfigInfo config) {
    final List<SAXParseException> exceptions = new LinkedList<SAXParseException>();
    try {/* w  w  w. j a v a  2s  .c  o  m*/
        String pathToXSD = config.getXsdPath();
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        factory.setResourceResolver(new ResourceResolver());
        Schema schema = factory.newSchema(new StreamSource(config.getXsdInputStream()));
        Validator validator = schema.newValidator();
        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);
            }
        });
        StreamSource streamXML = new StreamSource(xmlFile);
        validator.validate(streamXML);
    } catch (SAXException ex) {
        log.error("Error during validation", ex);
    } catch (IOException ex) {
        log.error("Error during validation", ex);
    } finally {
    }
    return exceptions;
}

From source file:org.cerberus.crud.service.impl.ImportFileService.java

@Override
public AnswerItem importAndValidateXMLFromInputStream(InputStream filecontent, InputStream schemaContent,
        XMLHandlerEnumType handlerType) {
    AnswerItem answer = new AnswerItem();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK);
    msg.setDescription(/*from ww  w . j a va2s. c  o  m*/
            msg.getDescription().replace("%ITEM%", "Test Data Library").replace("%OPERATION%", "Import"));
    if (schemaContent != null) {
        try {

            //InputStream data = new BufferedInputStream(filecontent);

            String textContent = IOUtils.toString(filecontent);

            Source source = new StreamSource(IOUtils.toInputStream(textContent));
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

            Source sourceschema = new StreamSource(schemaContent);

            Schema schema = factory.newSchema(sourceschema);
            Validator validator = schema.newValidator();
            //is valid
            validator.validate(source);
            //document is valid, then proceed to load the data

            answer.setItem(parseXMLFile(IOUtils.toInputStream(textContent), handlerType));

        } catch (SAXException ex) {
            MyLogger.log(ImportFileService.class.getName(), Level.ERROR,
                    "Unable to parse XML: " + ex.toString());
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_IMPORT_ERROR_FORMAT);
            msg.setDescription(
                    msg.getDescription().replace("%ITEM%", "Test Data Library").replace("%FORMAT%", "XML"));

        } catch (ParserConfigurationException ex) {
            MyLogger.log(ImportFileService.class.getName(), Level.ERROR,
                    "Unable to parse XML: " + ex.toString());
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
            msg.setDescription(msg.getDescription().replace("%DESCRIPTION%",
                    "Unable to parse the XML document. Please try again later."));
        } catch (IOException ex) {
            MyLogger.log(ImportFileService.class.getName(), Level.ERROR,
                    "Unable to parse XML: " + ex.toString());
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
            msg.setDescription(msg.getDescription().replace("%DESCRIPTION%",
                    "Unable to verify if the XML document is valid. Please try again later."));
        }

    }
    answer.setResultMessage(msg);
    return answer;
}

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()) {/*  ww w  . j av 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);/*from  www. j a  va 2 s  .com*/
    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.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;
    Source source = null;/*from   www .  j  a  v a2s  .co m*/
    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  av  a  2s  . 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  .  j a  v a  2s .  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.eclipse.om2m.commons.utils.XmlValidator.java

/**
 * Validates the resource representation according to xsd file.
 * @param representation - resource representation
 * @param xsd - xsd file//  w  w w. ja v  a 2s .  c  o  m
 * @throws SAXException
 * @throws IOException
 */
public void validate(String representaion, String xsd) throws SAXException, IOException {
    Validator validator = schemas.get(xsd).newValidator();
    validator.validate(new StreamSource(new StringReader(representaion)));
}