Example usage for javax.xml.validation SchemaFactory newInstance

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

Introduction

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

Prototype

public static SchemaFactory newInstance(String schemaLanguage) 

Source Link

Document

Lookup an implementation of the SchemaFactory that supports the specified schema language and return it.

Usage

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.
  * /*ww  w  .  ja v  a  2  s  .c om*/
  * @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.
 * /*from   www.  jav a  2s  .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   ww w. j  a  v  a 2s. c  o  m*/
}

From source file:org.openengsb.connector.promreport.internal.ProcessFileStore.java

public ProcessFileStore(File rootDirectory) {
    this.processDir = rootDirectory;
    if (!rootDirectory.exists() && !rootDirectory.mkdirs()) {
        throw new RuntimeException("Could not make directory " + rootDirectory.getAbsolutePath());
    } else if (!rootDirectory.isDirectory()) {
        throw new IllegalArgumentException("Root directory '" + rootDirectory + "' is not a directory.");
    }/*  w  w w .ja  v a  2  s  .  c  om*/
    try {
        jaxbContext = JAXBContext.newInstance(WorkflowLog.class);
        xmlif = XMLInputFactory.newInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    try {
        schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
                .newSchema(new URL("http://is.tm.tue.nl/research/processmining/WorkflowLog.xsd"));
    } catch (Exception e) {
        LOGGER.warn("Error during creating of Mxml schema. Continue without schema validation.", e);
    }
}

From source file:org.openhab.tools.analysis.checkstyle.EshInfXmlValidationCheck.java

@Override
public void beginProcessing(String charset) {
    ContentReceviedCallback<Schema> callback = new ContentReceviedCallback<Schema>() {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        @Override// w w w.j a  va 2  s  .  com
        public Schema transform(byte[] content) {
            try {
                InputStream is = new ByteArrayInputStream(content);
                return schemaFactory.newSchema(new StreamSource(is));
            } catch (SAXException e) {
                logger.error("Unable to parse schema ", e);
                return null;
            }
        }
    };

    CachingHttpClient<Schema> cachingClient = new CachingHttpClient<>(callback);

    bindingSchemaFile = getXSD(bindingSchema, cachingClient);
    thingSchemaFile = getXSD(thingSchema, cachingClient);
    configSchemaFile = getXSD(configSchema, cachingClient);

    super.beginProcessing(charset);
}

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

/**
 * Begin of Stream/*from  www  . ja va2s.  c om*/
 */
@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/*from w  w  w .j  a  v a2s .co  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   ww w  . j  a va2s . 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)
 *//*ww  w  .java  2s .co  m*/
@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;/*from   w w  w .j  a  v a 2  s.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);
}