Example usage for javax.xml.validation SchemaFactory newSchema

List of usage examples for javax.xml.validation SchemaFactory newSchema

Introduction

In this page you can find the example usage for javax.xml.validation SchemaFactory newSchema.

Prototype

public abstract Schema newSchema(Source[] schemas) throws SAXException;

Source Link

Document

Parses the specified source(s) as a schema and returns it as a schema.

Usage

From source file:org.ojbc.util.xml.XmlUtils.java

public static Document validateInstance(String rootXsdPath, Document docXmlToValidate,
        IEPDFullPathResourceResolver fullPathResolver, List<String> additionalSchemaRelativePaths)
        throws Exception {

    List<String> schemaPaths = new ArrayList<String>();
    schemaPaths.add(rootXsdPath);/*from  ww w  . j  a  va2s . c  o  m*/
    schemaPaths.addAll(additionalSchemaRelativePaths);

    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setResourceResolver(fullPathResolver);

    Source[] sources = new Source[schemaPaths.size()];
    int i = 0;
    for (String path : schemaPaths) {
        sources[i++] = new StreamSource(XmlUtils.class.getClassLoader().getResourceAsStream(path));
    }

    Schema schema = schemaFactory.newSchema(sources);

    Validator v = schema.newValidator();

    try {
        v.validate(new DOMSource(docXmlToValidate));

    } catch (Exception e) {
        try {
            e.printStackTrace();
            System.err.println("FAILED Input Doc: \n");
            XmlUtils.printNode(docXmlToValidate);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        throw e;
    }
    return docXmlToValidate;
}

From source file:org.ojbc.util.xml.XmlUtils.java

/**
  * Validate a document against an IEPD. Note that this does not require the xsi namespace location attributes to be set in the instance.
  * /*from  w ww  .j  ava 2s .  com*/
  * @param schemaPathList
  *            the paths to all schemas necessary to validate the instance; this is the equivalent of specifying these schemas in an xsi:schemaLocation attribute in the instance
  *                       
  * @param Never_Used_TODO_Remove 
  * 
  *            
  * @param rootSchemaFileName
  *            the name of the document/exchange schema
  * @param d
  *            the document to validate
  * @param iepdResourceResolver
  *            the resource resolver to use
  * @return the document that was validated
  * @throws Exception
  *             if the document is not valid
  */
public static void validateInstance(Document d, LSResourceResolver iepdResourceResolver,
        List<String> schemaPathList) throws SAXException, Exception {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setResourceResolver(iepdResourceResolver);

    List<Source> sourceList = new ArrayList<Source>();

    for (String schemaPath : schemaPathList) {

        InputStream schemaInStream = XmlUtils.class.getClassLoader().getResourceAsStream(schemaPath);

        StreamSource schemaStreamSource = new StreamSource(schemaInStream);

        sourceList.add(schemaStreamSource);
    }

    Source[] schemaSourcesArray = sourceList.toArray(new Source[] {});

    try {
        Schema schema = schemaFactory.newSchema(schemaSourcesArray);

        Validator validator = schema.newValidator();

        validator.validate(new DOMSource(d));

    } catch (Exception e) {
        try {
            e.printStackTrace();
            System.err.println("Input document:");
            XmlUtils.printNode(d);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        throw e;
    }
}

From source file:org.openbravo.test.webservice.BaseWSTest.java

/**
 * Validates the xml against the generated schema.
 * //w ww.j a v  a  2 s .  c o m
 * @param xml
 *          the xml to validate
 */
protected void validateXML(String xml) {
    final Reader schemaReader = new StringReader(getXMLSchema());
    final Reader xmlReader = new StringReader(xml);
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setValidating(false);
        factory.setNamespaceAware(true);

        SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

        factory.setSchema(schemaFactory.newSchema(new Source[] { new StreamSource(schemaReader) }));

        SAXParser parser = factory.newSAXParser();

        XMLReader reader = parser.getXMLReader();
        reader.setErrorHandler(new SimpleErrorHandler());
        reader.parse(new InputSource(xmlReader));
    } catch (Exception e) {
        throw new OBException(e);
    }

}

From source file:org.openehealth.ipf.commons.xml.XsdValidator.java

protected synchronized void createSchema(String schemaResource) throws SAXException, IOException {
    if (!cachedSchemas.containsKey(schemaResource)) {
        // SchemaFactory is neither thread-safe nor reentrant
        SchemaFactory factory = SchemaFactory.newInstance(getSchemaLanguage());

        // Register resource resolver to resolve external XML schemas
        factory.setResourceResolver(lrri);
        Schema schema = factory.newSchema(schemaSource(schemaResource));
        cachedSchemas.put(schemaResource, schema);
    }//from   w ww. j av  a  2s .  c  o  m
}

From source file:org.openmainframe.ade.ext.output.ExtJaxbAnalyzedIntervalV2XmlStorer.java

/**
 * Begin of Stream//from ww  w  .j ava  2 s. c  o m
 */
@Override
public void beginOfStream() throws AdeException, AdeFlowException {
    if (s_marshaller == null) {
        JAXBContext jaxbContext;
        try {
            jaxbContext = JAXBContext.newInstance(ADEEXT_JAXB_CONTEXT);
        } catch (JAXBException e) {
            throw new AdeInternalException(
                    "failed to create JAXBContext object for package " + Arrays.toString(ADEEXT_JAXB_CONTEXT),
                    e);
        }
        try {
            s_marshaller = jaxbContext.createMarshaller();
        } catch (JAXBException e) {
            throw new AdeInternalException("failed to create JAXB Marshaller object", e);
        }
        try {
            s_marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, m_formatXMLOutput);
            s_marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
            s_marshaller.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, XML_INTERVAL_V2_XSD);

        } catch (PropertyException e) {
            throw new AdeInternalException("failed to set formatted output for JAXB Marshaller object", e);
        }

        SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);

        File xmlParent = Ade.getAde().getConfigProperties().getXsltDir().getAbsoluteFile();
        xmlParent = xmlParent.getParentFile();
        File intervalSchema = new File(xmlParent, XML_INTERVAL_V2_XSD);

        Schema schema;
        try {
            URL analyzedIntervalSchema = intervalSchema.toURI().toURL();
            schema = sf.newSchema(analyzedIntervalSchema);
        } catch (SAXException e) {
            throw new AdeInternalException("failed to create XML Schemal for event log analysis results", e);
        } catch (MalformedURLException e) {
            throw new AdeInternalException(
                    "failed to create URL from Schema path: " + intervalSchema.getAbsolutePath(), e);
        }
        s_marshaller.setSchema(schema);
    }
    m_xmlMetaData = new XMLMetaDataRetriever();
}

From source file:org.openmainframe.ade.ext.output.ExtJaxbAnalyzedPeriodV2XmlStorer.java

/**
 * Begin of Stream/* ww  w .  j  av  a2s.c  o  m*/
 */
@Override
public void beginOfStream() throws AdeException, AdeFlowException {
    if (s_marshaller == null) {
        JAXBContext jaxbContext;
        try {
            jaxbContext = JAXBContext.newInstance(ADEEXT_JAXB_CONTEXT);
        } catch (JAXBException e) {
            throw new AdeInternalException(
                    "failed to create JAXBContext object for package " + Arrays.toString(ADEEXT_JAXB_CONTEXT),
                    e);
        }
        try {
            s_marshaller = jaxbContext.createMarshaller();
        } catch (JAXBException e) {
            throw new AdeInternalException("failed to create JAXB Marshaller object", e);
        }
        try {
            s_marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, m_formatXMLOutput);
            s_marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
            s_marshaller.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, XML_PLEX_V2_XSD);
        } catch (PropertyException e) {
            throw new AdeInternalException("failed to set formatted output for JAXB Marshaller object", e);
        }

        SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);

        File xmlParent = Ade.getAde().getConfigProperties().getXsltDir().getAbsoluteFile();
        xmlParent = xmlParent.getParentFile();
        File systemSchema = new File(xmlParent, XML_PLEX_V2_XSD);

        Schema schema;
        try {
            URL systemSchemaURL = systemSchema.toURI().toURL();
            schema = sf.newSchema(systemSchemaURL);
        } catch (SAXException e) {
            throw new AdeInternalException("failed to create XML Schemal for event log analysis results", e);
        } catch (MalformedURLException e) {
            throw new AdeInternalException(
                    "failed to create URL from Schema path: " + systemSchema.getAbsolutePath(), e);
        }
        s_marshaller.setSchema(schema);
    }

    /* Retrieve the Model Data Here.  Force refresh, in case the Model's Analysis Group Change without impacting
     * the model internal ID. */
    m_xmlMetaData.retrieveXMLMetaData(m_lastKnownModelInternalID, true, m_framingFlowType.getDuration());

    /* Write out the period when it's begin of stream, within a period */
    if (m_inPeriod) {
        writePeriod();
    }
}

From source file:org.openmainframe.ade.main.AdeUtilMain.java

protected void validateGood(File file) throws IOException, SAXException, AdeException {
    System.out.println("Starting");

    String fileName_Flowlayout_xsd = Ade.getAde().getConfigProperties().getXsltDir()
            + FLOW_LAYOUT_XSD_File_Name;
    Source schemaFile = new StreamSource(fileName_Flowlayout_xsd);
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema mSchema = sf.newSchema(schemaFile);

    System.out.println("Validating " + file.getPath());
    Validator val = mSchema.newValidator();
    FileInputStream fis = new FileInputStream(file);
    StreamSource streamSource = new StreamSource(fis);

    try {/*from   w ww  .jav  a2  s  .c om*/
        val.validate(streamSource);
    } catch (SAXParseException e) {
        System.out.println(e);
        throw e;
    }
    System.out.println("SUCCESS!");
}

From source file:org.openmrs.module.radiology.report.template.XsdMrrtReportTemplateValidator.java

/**
 * @see MrrtReportTemplateValidator#validate(String)
 *///from  ww  w  .  j  av a2 s. c om
@Override
public void validate(String mrrtTemplate) throws IOException {

    final Document document = Jsoup.parse(mrrtTemplate, "");
    final Elements metatags = document.getElementsByTag("meta");
    ValidationResult validationResult = metaTagsValidationEngine.run(metatags);

    final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final Schema schema;
    final Validator validator;
    try (InputStream in = IOUtils.toInputStream(mrrtTemplate)) {
        schema = factory.newSchema(getSchemaFile());
        validator = schema.newValidator();
        validator.setErrorHandler(new ErrorHandler() {

            @Override
            public void warning(SAXParseException exception) throws SAXException {
                log.debug(exception.getMessage(), exception);
                validationResult.addError(exception.getMessage(), "");
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                log.debug(exception.getMessage(), exception);
                validationResult.addError(exception.getMessage(), "");
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                log.debug(exception.getMessage(), exception);
                validationResult.addError(exception.getMessage(), "");
            }
        });
        validator.validate(new StreamSource(in));
        validationResult.assertOk();
    } catch (SAXException e) {
        log.error(e.getMessage(), e);
        throw new APIException("radiology.report.template.validation.error", null, e);
    }
}

From source file:org.opennms.core.test.xml.XmlTest.java

protected void validateXmlString(final String xml) throws Exception {
    if (getSchemaFile() == null) {
        LOG.warn("skipping validation, schema file not set");
        return;/* www  .j  a  v  a 2s. c o  m*/
    }

    final SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    final File schemaFile = new File(getSchemaFile());
    LOG.debug("Validating using schema file: {}", schemaFile);
    final Schema schema = schemaFactory.newSchema(schemaFile);

    final SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    saxParserFactory.setValidating(true);
    saxParserFactory.setNamespaceAware(true);
    saxParserFactory.setSchema(schema);

    assertTrue("make sure our SAX implementation can validate", saxParserFactory.isValidating());

    final Validator validator = schema.newValidator();
    final ByteArrayInputStream inputStream = new ByteArrayInputStream(xml.getBytes());
    final Source source = new StreamSource(inputStream);

    validator.validate(source);
}

From source file:org.opennms.core.test.xml.XmlTest.java

@Test
public void validateJaxbXmlAgainstSchema() throws Exception {
    final String schemaFile = getSchemaFile();
    if (schemaFile == null) {
        LOG.warn("Skipping validation.");
        return;/*  w  ww  . j a v  a  2  s .  com*/
    }
    LOG.debug("Validating against XSD: {}", schemaFile);
    javax.xml.bind.Unmarshaller unmarshaller = JaxbUtils.getUnmarshallerFor(getSampleClass(), null, true);
    final SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    final Schema schema = factory.newSchema(new StreamSource(schemaFile));
    unmarshaller.setSchema(schema);
    unmarshaller.setEventHandler(new ValidationEventHandler() {
        @Override
        public boolean handleEvent(final ValidationEvent event) {
            LOG.warn("Received validation event: {}", event, event.getLinkedException());
            return false;
        }
    });
    try {
        final InputSource inputSource = new InputSource(getSampleXmlInputStream());
        final XMLFilter filter = JaxbUtils.getXMLFilterForClass(getSampleClass());
        final SAXSource source = new SAXSource(filter, inputSource);
        @SuppressWarnings("unchecked")
        T obj = (T) unmarshaller.unmarshal(source);
        assertNotNull(obj);
    } finally {
        unmarshaller.setSchema(null);
    }
}