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.wso2.carbon.governance.lcm.util.CommonUtil.java

public static Validator getLifecycleSchemaValidator(String schemaPath) {

    if (lifecycleSchemaValidator == null) {
        try {/*  ww w .j  a v  a2 s.  com*/
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = schemaFactory.newSchema(new File(schemaPath));
            lifecycleSchemaValidator = schema.newValidator();
        } catch (SAXException e) {
            log.error("Unable to get a schema validator from the given file path : " + schemaPath);
        }
    }
    return lifecycleSchemaValidator;
}

From source file:org.wso2.carbon.governance.list.util.CommonUtil.java

private static boolean validateRXTContent(String rxtContent, String xsdPath) throws RegistryException {
    try {/*w ww  .  j  a v a 2s .c  om*/
        OMElement rxt = getRXTContentOMElement(rxtContent);
        AXIOMXPath xpath = new AXIOMXPath("//artifactType");
        OMElement c1 = (OMElement) xpath.selectSingleNode(rxt);
        InputStream is = new ByteArrayInputStream(c1.toString().getBytes());
        Source xmlFile = new StreamSource(is);
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(new File(xsdPath));
        Validator validator = schema.newValidator();
        validator.validate(xmlFile);
    } catch (Exception e) {
        log.error("RXT validation fails due to: " + e.getMessage());
        return false;
    }
    return true;
}

From source file:org.wso2.carbon.identity.entitlement.internal.SchemaBuilder.java

/**
 * Builds the policy schema map. There are three schemas.
 *
 * @param configHolder holder EntitlementConfigHolder
 * @throws SAXException if fails/*from   ww w  .j  av a  2 s .  co m*/
 */
public void buildPolicySchema() throws SAXException {

    if (!"true".equalsIgnoreCase((String) configHolder.getEngineProperties()
            .get(EntitlementExtensionBuilder.PDP_SCHEMA_VALIDATION))) {
        log.warn("PDP schema validation disabled.");
        return;
    }

    String[] schemaNSs = new String[] { PDPConstants.XACML_1_POLICY_XMLNS, PDPConstants.XACML_2_POLICY_XMLNS,
            PDPConstants.XACML_3_POLICY_XMLNS };

    for (String schemaNS : schemaNSs) {

        String schemaFile;

        if (PDPConstants.XACML_1_POLICY_XMLNS.equals(schemaNS)) {
            schemaFile = PDPConstants.XACML_1_POLICY_SCHEMA_FILE;
        } else if (PDPConstants.XACML_2_POLICY_XMLNS.equals(schemaNS)) {
            schemaFile = PDPConstants.XACML_2_POLICY_SCHEMA_FILE;
        } else {
            schemaFile = PDPConstants.XACML_3_POLICY_SCHEMA_FILE;
        }

        InputStream schemaFileStream = EntitlementExtensionBuilder.class.getResourceAsStream("/" + schemaFile);
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(new StreamSource(schemaFileStream));
        configHolder.getPolicySchemaMap().put(schemaNS, schema);
    }
}

From source file:org.wso2.carbon.integration.common.tests.utils.DistributionValidationTestUtils.java

public static void validateXml(HashMap<String, Exception> xsdValidateMap, String distributionXml,
        String xsdFile) throws IOException {
    Source schemaFile = new StreamSource(new File(xsdFile));
    Source xmlFile = new StreamSource(new File(distributionXml));
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = null;/*from  w  ww .j a  v a  2s . c o m*/
    try {
        schema = schemaFactory.newSchema(schemaFile);
    } catch (SAXException e) {
        log.error(distributionXml, e);
        xsdValidateMap.put(distributionXml, e);
    }
    if (schema != null) {
        Validator validator = schema.newValidator();
        try {
            validator.validate(xmlFile);
        } catch (SAXException e) {
            log.error(distributionXml, e);
            xsdValidateMap.put(distributionXml, e);
        }
    }
}

From source file:org.wso2.carbon.lcm.core.util.LifecycleUtils.java

/**
 * Method used to get schema validator object for lifecycle configurations.
 * @param schemaPath Schema path in the server extracted directory.
 * @return schema validator object//from w w  w. j  ava  2s.c om
 */
public static synchronized Validator getLifecycleSchemaValidator(String schemaPath) {
    if (lifecycleSchemaValidator != null) {
        return lifecycleSchemaValidator;
    }
    try {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(new File(schemaPath));
        lifecycleSchemaValidator = schema.newValidator();
    } catch (SAXException e) {
        log.error("Unable to get a schema validator from the given file path : " + schemaPath);
    }
    return lifecycleSchemaValidator;
}

From source file:org.xsystem.bpmn2.formats.xml.XMLParser3.java

Schema buildSxema() throws SAXException, IOException {
    final ClassLoader classLoader = this.getClass().getClassLoader();
    //Thread.currentThread().getContextClassLoader();

    try (InputStream is = classLoader.getResourceAsStream("BPMN20/BPMN20.xsd")) {

        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);//"http://www.w3.org/2001/XMLSchema");
        StreamSource ss = new StreamSource(is);
        factory.setResourceResolver(//from  w w w.j  a  v a2s  .c o m
                (String type, String namespaceURI, String publicId, String systemId, String baseURI) -> {
                    InputStream resourceAsStream = classLoader.getResourceAsStream("BPMN20/" + systemId);
                    LSInput ret = new LSInputImpl(publicId, systemId, resourceAsStream);
                    return ret;
                });
        Schema shema = factory.newSchema(ss);
        return shema;
    }
}

From source file:oscar.oscarLab.ca.all.parsers.HRMXMLHandler.java

public void init(String hl7Body) throws HL7Exception {

    // this.version = p.getVersion(hl7Body);
    logger.info("A NEW HRM XML PARSER OBJECT INSTANTIATED TO PARSE HL7 FILE " + hl7Body);

    try {/*from   w  w w  .ja  va2s.  c om*/
        ByteArrayInputStream byeArrayInputStream = new ByteArrayInputStream(hl7Body.getBytes());

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

        // Load a WXS schema, represented by a Schema instance.
        Source schemaFile = new StreamSource(new File(SFTPConnector.OMD_directory + "report_manager_cds.xsd"));
        Schema schema = factory.newSchema(schemaFile); //new File(SFTPConnector.OMD_directory + "report_manager_cds.xsd"));

        JAXBContext jc = JAXBContext.newInstance("oscar.hospitalReportManager.xsd");
        Unmarshaller u = jc.createUnmarshaller();
        root = (OmdCds) u.unmarshal(byeArrayInputStream);
        pr = root.getPatientRecord();

    } catch (Exception e) {
        logger.error("error", e);
    }

    headers = new ArrayList<String>();

}

From source file:se.mithlond.services.shared.test.entity.PlainJaxbContextRule.java

/**
 * Acquires a JAXB Schema from the provided JAXBContext.
 *
 * @param ctx The context for which am XSD should be constructed.
 * @return A tuple holding the constructed XSD from the provided JAXBContext, and
 * the LSResourceResolver synthesized during the way.
 * @throws NullPointerException     if ctx was {@code null}.
 * @throws IllegalArgumentException if a JAXB-related exception occurred while extracting the schema.
 *//*from   w  w  w  .j a v  a 2s.  c om*/
public static Tuple<Schema, LSResourceResolver> generateTransientXSD(final JAXBContext ctx)
        throws NullPointerException, IllegalArgumentException {

    // Check sanity
    org.apache.commons.lang3.Validate.notNull(ctx, "Cannot handle null ctx argument.");

    final SortedMap<String, ByteArrayOutputStream> namespace2SchemaMap = new TreeMap<>();

    try {
        ctx.generateSchema(new SchemaOutputResolver() {

            /**
             * {@inheritDoc}
             */
            @Override
            public Result createOutput(final String namespaceUri, final String suggestedFileName)
                    throws IOException {

                // The types should really be annotated with @XmlType(namespace = "... something ...")
                // to avoid using the default ("") namespace.
                if (namespaceUri.isEmpty()) {
                    log.warn("Received empty namespaceUri while resolving a generated schema. "
                            + "Did you forget to add a @XmlType(namespace = \"... something ...\") annotation "
                            + "to your class?");
                }

                // Create the result ByteArrayOutputStream
                final ByteArrayOutputStream out = new ByteArrayOutputStream();
                final StreamResult toReturn = new StreamResult(out);
                toReturn.setSystemId("");

                // Map the namespaceUri to the schemaResult.
                namespace2SchemaMap.put(namespaceUri, out);

                // All done.
                return toReturn;
            }
        });
    } catch (IOException e) {
        throw new IllegalArgumentException("Could not acquire Schema snippets.", e);
    }

    // Convert to an array of StreamSource.
    final MappedSchemaResourceResolver resourceResolver = new MappedSchemaResourceResolver();
    final StreamSource[] schemaSources = new StreamSource[namespace2SchemaMap.size()];
    int counter = 0;
    for (Map.Entry<String, ByteArrayOutputStream> current : namespace2SchemaMap.entrySet()) {

        final byte[] schemaSnippetAsBytes = current.getValue().toByteArray();
        resourceResolver.addNamespace2SchemaEntry(current.getKey(), new String(schemaSnippetAsBytes));

        if (log.isDebugEnabled()) {
            log.info("Generated schema [" + (counter + 1) + "/" + schemaSources.length + "]:\n "
                    + new String(schemaSnippetAsBytes));
        }

        // Copy the schema source to the schemaSources array.
        schemaSources[counter] = new StreamSource(new ByteArrayInputStream(schemaSnippetAsBytes), "");

        // Increase the counter
        counter++;
    }

    try {

        // All done.
        final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        schemaFactory.setResourceResolver(resourceResolver);
        final Schema transientSchema = schemaFactory.newSchema(schemaSources);

        // All done.
        return new Tuple<>(transientSchema, resourceResolver);

    } catch (final SAXException e) {
        throw new IllegalArgumentException("Could not create Schema from snippets.", e);
    }
}

From source file:se.skl.skltpservices.npoadapter.mapper.AbstractMapper.java

protected void initialiseValidator(String... xsds) {
    List<Source> schemaFiles = new ArrayList<Source>();
    for (String xsd : xsds) {
        schemaFiles.add(new StreamSource(getClass().getResourceAsStream(xsd)));
    }//from w  w w.  jav  a  2s  . c o  m

    // Note - SchemaFactory is not threadsafe
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    try {
        // Note - Schema is threadsafe
        schema = factory.newSchema(schemaFiles.toArray(new StreamSource[schemaFiles.size()]));
    } catch (SAXException s) {
        throw new RuntimeException(
                new InstantiationException("Failed to instantiate schema: " + s.getMessage()));
    }

}

From source file:sernet.verinice.service.XmlRightsService.java

private Schema getSchema() {
    if (schema == null) {
        SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
        try {/*from  w w  w  . ja v a 2s . co m*/
            schema = sf.newSchema(getAuthConfigurationSchema().getURL());
        } catch (Exception e) {
            log.error("Error while creating schema.", e);
        }
    }
    return schema;
}