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.apache.nifi.fingerprint.FingerprintFactoryTest.java

private DocumentBuilder getValidatingDocumentBuilder() {
    final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final Schema schema;
    try {//w  ww.  j ava  2  s.c  om
        schema = schemaFactory.newSchema(FingerprintFactory.class.getResource(FLOW_CONFIG_XSD));
    } catch (final Exception e) {
        throw new RuntimeException("Failed to parse schema for file flow configuration.", e);
    }
    try {
        documentBuilderFactory.setSchema(schema);
        DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
        docBuilder.setErrorHandler(new ErrorHandler() {
            @Override
            public void warning(SAXParseException e) throws SAXException {
                throw e;
            }

            @Override
            public void error(SAXParseException e) throws SAXException {
                throw e;
            }

            @Override
            public void fatalError(SAXParseException e) throws SAXException {
                throw e;
            }
        });
        return docBuilder;
    } catch (final Exception e) {
        throw new RuntimeException("Failed to create document builder for flow configuration.", e);
    }
}

From source file:org.apache.nifi.registry.security.authentication.IdentityProviderFactory.java

private IdentityProviders loadLoginIdentityProvidersConfiguration() throws Exception {
    final File loginIdentityProvidersConfigurationFile = properties.getIdentityProviderConfigurationFile();

    // load the users from the specified file
    if (loginIdentityProvidersConfigurationFile.exists()) {
        try {//from   w ww  .  j a v  a  2s .c o m
            // find the schema
            final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            final Schema schema = schemaFactory
                    .newSchema(IdentityProviders.class.getResource(LOGIN_IDENTITY_PROVIDERS_XSD));

            // attempt to unmarshal
            XMLStreamReader xsr = XmlUtils
                    .createSafeReader(new StreamSource(loginIdentityProvidersConfigurationFile));
            final Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller();
            unmarshaller.setSchema(schema);
            final JAXBElement<IdentityProviders> element = unmarshaller.unmarshal(xsr, IdentityProviders.class);
            return element.getValue();
        } catch (SAXException | JAXBException e) {
            throw new Exception("Unable to load the login identity provider configuration file at: "
                    + loginIdentityProvidersConfigurationFile.getAbsolutePath());
        }
    } else {
        throw new Exception("Unable to find the login identity provider configuration file at "
                + loginIdentityProvidersConfigurationFile.getAbsolutePath());
    }
}

From source file:org.apache.nifi.registry.security.authorization.AuthorizerFactory.java

private Authorizers loadAuthorizersConfiguration() throws Exception {
    final File authorizersConfigurationFile = properties.getAuthorizersConfigurationFile();

    // load the authorizers from the specified file
    if (authorizersConfigurationFile.exists()) {
        try {/*from   w  ww . j av  a2  s. c  o m*/
            // find the schema
            final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            final Schema schema = schemaFactory.newSchema(Authorizers.class.getResource(AUTHORIZERS_XSD));

            // attempt to unmarshal
            final Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller();
            unmarshaller.setSchema(schema);
            final JAXBElement<Authorizers> element = unmarshaller.unmarshal(
                    XmlUtils.createSafeReader(new StreamSource(authorizersConfigurationFile)),
                    Authorizers.class);
            return element.getValue();
        } catch (XMLStreamException | SAXException | JAXBException e) {
            throw new Exception("Unable to load the authorizer configuration file at: "
                    + authorizersConfigurationFile.getAbsolutePath(), e);
        }
    } else {
        throw new Exception("Unable to find the authorizer configuration file at "
                + authorizersConfigurationFile.getAbsolutePath());
    }
}

From source file:org.apache.nifi.registry.security.authorization.file.FileAccessPolicyProvider.java

@Override
public void initialize(AccessPolicyProviderInitializationContext initializationContext)
        throws SecurityProviderCreationException {
    userGroupProviderLookup = initializationContext.getUserGroupProviderLookup();

    try {//from w w w.j av  a 2  s. c o m
        final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        authorizationsSchema = schemaFactory.newSchema(FileAuthorizer.class.getResource(AUTHORIZATIONS_XSD));
    } catch (Exception e) {
        throw new SecurityProviderCreationException(e);
    }
}

From source file:org.apache.nifi.registry.security.authorization.file.FileUserGroupProvider.java

@Override
public void initialize(UserGroupProviderInitializationContext initializationContext)
        throws SecurityProviderCreationException {
    try {/*from ww  w .j  av a  2s  .  co m*/
        final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        tenantsSchema = schemaFactory.newSchema(FileAuthorizer.class.getResource(TENANTS_XSD));
        //usersSchema = schemaFactory.newSchema(FileAuthorizer.class.getResource(USERS_XSD));
    } catch (Exception e) {
        throw new SecurityProviderCreationException(e);
    }
}

From source file:org.apache.nifi.web.security.spring.LoginIdentityProviderFactoryBean.java

private LoginIdentityProviders loadLoginIdentityProvidersConfiguration() throws Exception {
    final File loginIdentityProvidersConfigurationFile = properties.getLoginIdentityProviderConfigurationFile();

    // load the users from the specified file
    if (loginIdentityProvidersConfigurationFile.exists()) {
        try {/*from  www  .  j  ava 2s. c  o  m*/
            // find the schema
            final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            final Schema schema = schemaFactory
                    .newSchema(LoginIdentityProviders.class.getResource(LOGIN_IDENTITY_PROVIDERS_XSD));

            // attempt to unmarshal
            final Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller();
            unmarshaller.setSchema(schema);
            final JAXBElement<LoginIdentityProviders> element = unmarshaller.unmarshal(
                    new StreamSource(loginIdentityProvidersConfigurationFile), LoginIdentityProviders.class);
            return element.getValue();
        } catch (SAXException | JAXBException e) {
            throw new Exception("Unable to load the login identity provider configuration file at: "
                    + loginIdentityProvidersConfigurationFile.getAbsolutePath());
        }
    } else {
        throw new Exception("Unable to find the login identity provider configuration file at "
                + loginIdentityProvidersConfigurationFile.getAbsolutePath());
    }
}

From source file:org.apache.oozie.cli.OozieCLI.java

/**
 * Validate on client-side. This is only for backward compatibility. Need to removed after <tt>4.2.0</tt> higher version.
 * @param commandLine//from w ww  .java2s .c  o m
 * @throws OozieCLIException
 */
@Deprecated
@VisibleForTesting
void validateCommandV41(CommandLine commandLine) throws OozieCLIException {
    String[] args = commandLine.getArgs();
    if (args.length != 1) {
        throw new OozieCLIException("One file must be specified");
    }
    File file = new File(args[0]);
    if (file.exists()) {
        try {
            List<StreamSource> sources = new ArrayList<StreamSource>();
            sources.add(new StreamSource(Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("oozie-workflow-0.1.xsd")));
            sources.add(new StreamSource(Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("shell-action-0.1.xsd")));
            sources.add(new StreamSource(Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("shell-action-0.2.xsd")));
            sources.add(new StreamSource(Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("shell-action-0.3.xsd")));
            sources.add(new StreamSource(Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("email-action-0.1.xsd")));
            sources.add(new StreamSource(Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("email-action-0.2.xsd")));
            sources.add(new StreamSource(Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("distcp-action-0.1.xsd")));
            sources.add(new StreamSource(Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("distcp-action-0.2.xsd")));
            sources.add(new StreamSource(Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("oozie-workflow-0.2.xsd")));
            sources.add(new StreamSource(Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("oozie-workflow-0.2.5.xsd")));
            sources.add(new StreamSource(Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("oozie-workflow-0.3.xsd")));
            sources.add(new StreamSource(Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("oozie-workflow-0.4.xsd")));
            sources.add(new StreamSource(Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("oozie-workflow-0.4.5.xsd")));
            sources.add(new StreamSource(Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("oozie-workflow-0.5.xsd")));
            sources.add(new StreamSource(Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("oozie-coordinator-0.1.xsd")));
            sources.add(new StreamSource(Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("oozie-coordinator-0.2.xsd")));
            sources.add(new StreamSource(Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("oozie-coordinator-0.3.xsd")));
            sources.add(new StreamSource(Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("oozie-coordinator-0.4.xsd")));
            sources.add(new StreamSource(Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("oozie-bundle-0.1.xsd")));
            sources.add(new StreamSource(Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("oozie-bundle-0.2.xsd")));
            sources.add(new StreamSource(
                    Thread.currentThread().getContextClassLoader().getResourceAsStream("oozie-sla-0.1.xsd")));
            sources.add(new StreamSource(
                    Thread.currentThread().getContextClassLoader().getResourceAsStream("oozie-sla-0.2.xsd")));
            sources.add(new StreamSource(
                    Thread.currentThread().getContextClassLoader().getResourceAsStream("hive-action-0.2.xsd")));
            sources.add(new StreamSource(
                    Thread.currentThread().getContextClassLoader().getResourceAsStream("hive-action-0.3.xsd")));
            sources.add(new StreamSource(
                    Thread.currentThread().getContextClassLoader().getResourceAsStream("hive-action-0.4.xsd")));
            sources.add(new StreamSource(
                    Thread.currentThread().getContextClassLoader().getResourceAsStream("hive-action-0.5.xsd")));
            sources.add(new StreamSource(
                    Thread.currentThread().getContextClassLoader().getResourceAsStream("hive-action-0.6.xsd")));
            sources.add(new StreamSource(Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("sqoop-action-0.2.xsd")));
            sources.add(new StreamSource(Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("sqoop-action-0.3.xsd")));
            sources.add(new StreamSource(Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("sqoop-action-0.4.xsd")));
            sources.add(new StreamSource(
                    Thread.currentThread().getContextClassLoader().getResourceAsStream("ssh-action-0.1.xsd")));
            sources.add(new StreamSource(
                    Thread.currentThread().getContextClassLoader().getResourceAsStream("ssh-action-0.2.xsd")));
            sources.add(new StreamSource(Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("hive2-action-0.1.xsd")));
            sources.add(new StreamSource(Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("hive2-action-0.2.xsd")));
            sources.add(new StreamSource(Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("spark-action-0.1.xsd")));
            sources.add(new StreamSource(Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("spark-action-0.2.xsd")));
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = factory.newSchema(sources.toArray(new StreamSource[sources.size()]));
            Validator validator = schema.newValidator();
            validator.validate(new StreamSource(new FileReader(file)));
            System.out.println("Valid workflow-app");
        } catch (Exception ex) {
            throw new OozieCLIException("Invalid app definition, " + ex.toString(), ex);
        }
    } else {
        throw new OozieCLIException("File does not exists");
    }
}

From source file:org.apache.servicemix.jbi.deployer.descriptor.DescriptorFactory.java

/**
 * Build a jbi descriptor from the specified binary data.
 * The descriptor is validated against the schema, but no
 * semantic validation is performed./*from www  .j  a va  2 s .  co m*/
 *
 * @param bytes hold the content of the JBI descriptor xml document
 * @return the Descriptor object
 */
public static Descriptor buildDescriptor(final byte[] bytes) {
    try {
        // Validate descriptor
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XSD_SCHEMA_LANGUAGE);
        Schema schema = schemaFactory.newSchema(DescriptorFactory.class.getResource(JBI_DESCRIPTOR_XSD));
        Validator validator = schema.newValidator();
        validator.setErrorHandler(new ErrorHandler() {
            public void warning(SAXParseException exception) throws SAXException {
                //log.debug("Validation warning on " + url + ": " + exception);
            }

            public void error(SAXParseException exception) throws SAXException {
                //log.info("Validation error on " + url + ": " + exception);
            }

            public void fatalError(SAXParseException exception) throws SAXException {
                throw exception;
            }
        });
        validator.validate(new StreamSource(new ByteArrayInputStream(bytes)));
        // Parse descriptor
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder docBuilder = factory.newDocumentBuilder();
        Document doc = docBuilder.parse(new ByteArrayInputStream(bytes));
        Element jbi = doc.getDocumentElement();
        Descriptor desc = new Descriptor();
        desc.setVersion(Double.parseDouble(getAttribute(jbi, VERSION)));
        Element child = getFirstChildElement(jbi);
        if (COMPONENT.equals(child.getLocalName())) {
            ComponentDesc component = new ComponentDesc();
            component.setType(child.getAttribute(TYPE));
            component.setComponentClassLoaderDelegation(getAttribute(child, COMPONENT_CLASS_LOADER_DELEGATION));
            component.setBootstrapClassLoaderDelegation(getAttribute(child, BOOTSTRAP_CLASS_LOADER_DELEGATION));
            List<SharedLibraryList> sls = new ArrayList<SharedLibraryList>();
            DocumentFragment ext = null;
            for (Element e = getFirstChildElement(child); e != null; e = getNextSiblingElement(e)) {
                if (IDENTIFICATION.equals(e.getLocalName())) {
                    component.setIdentification(readIdentification(e));
                } else if (COMPONENT_CLASS_NAME.equals(e.getLocalName())) {
                    component.setComponentClassName(getText(e));
                    component.setDescription(getAttribute(e, DESCRIPTION));
                } else if (COMPONENT_CLASS_PATH.equals(e.getLocalName())) {
                    ClassPath componentClassPath = new ClassPath();
                    ArrayList<String> l = new ArrayList<String>();
                    for (Element e2 = getFirstChildElement(e); e2 != null; e2 = getNextSiblingElement(e2)) {
                        if (PATH_ELEMENT.equals(e2.getLocalName())) {
                            l.add(getText(e2));
                        }
                    }
                    componentClassPath.setPathList(l);
                    component.setComponentClassPath(componentClassPath);
                } else if (BOOTSTRAP_CLASS_NAME.equals(e.getLocalName())) {
                    component.setBootstrapClassName(getText(e));
                } else if (BOOTSTRAP_CLASS_PATH.equals(e.getLocalName())) {
                    ClassPath bootstrapClassPath = new ClassPath();
                    ArrayList<String> l = new ArrayList<String>();
                    for (Element e2 = getFirstChildElement(e); e2 != null; e2 = getNextSiblingElement(e2)) {
                        if (PATH_ELEMENT.equals(e2.getLocalName())) {
                            l.add(getText(e2));
                        }
                    }
                    bootstrapClassPath.setPathList(l);
                    component.setBootstrapClassPath(bootstrapClassPath);
                } else if (SHARED_LIBRARY.equals(e.getLocalName())) {
                    SharedLibraryList sl = new SharedLibraryList();
                    sl.setName(getText(e));
                    sl.setVersion(getAttribute(e, VERSION));
                    sls.add(sl);
                } else {
                    if (ext == null) {
                        ext = doc.createDocumentFragment();
                    }
                    ext.appendChild(e);
                }
            }
            component.setSharedLibraries(sls.toArray(new SharedLibraryList[sls.size()]));
            if (ext != null) {
                InstallationDescriptorExtension descriptorExtension = new InstallationDescriptorExtension();
                descriptorExtension.setDescriptorExtension(ext);
                component.setDescriptorExtension(descriptorExtension);
            }
            desc.setComponent(component);
        } else if (SHARED_LIBRARY.equals(child.getLocalName())) {
            SharedLibraryDesc sharedLibrary = new SharedLibraryDesc();
            sharedLibrary.setClassLoaderDelegation(getAttribute(child, CLASS_LOADER_DELEGATION));
            sharedLibrary.setVersion(getAttribute(child, VERSION));
            for (Element e = getFirstChildElement(child); e != null; e = getNextSiblingElement(e)) {
                if (IDENTIFICATION.equals(e.getLocalName())) {
                    sharedLibrary.setIdentification(readIdentification(e));
                } else if (SHARED_LIBRARY_CLASS_PATH.equals(e.getLocalName())) {
                    ClassPath sharedLibraryClassPath = new ClassPath();
                    ArrayList<String> l = new ArrayList<String>();
                    for (Element e2 = getFirstChildElement(e); e2 != null; e2 = getNextSiblingElement(e2)) {
                        if (PATH_ELEMENT.equals(e2.getLocalName())) {
                            l.add(getText(e2));
                        }
                    }
                    sharedLibraryClassPath.setPathList(l);
                    sharedLibrary.setSharedLibraryClassPath(sharedLibraryClassPath);
                }
            }
            desc.setSharedLibrary(sharedLibrary);
        } else if (SERVICE_ASSEMBLY.equals(child.getLocalName())) {
            ServiceAssemblyDesc serviceAssembly = new ServiceAssemblyDesc();
            ArrayList<ServiceUnitDesc> sus = new ArrayList<ServiceUnitDesc>();
            for (Element e = getFirstChildElement(child); e != null; e = getNextSiblingElement(e)) {
                if (IDENTIFICATION.equals(e.getLocalName())) {
                    serviceAssembly.setIdentification(readIdentification(e));
                } else if (SERVICE_UNIT.equals(e.getLocalName())) {
                    ServiceUnitDesc su = new ServiceUnitDesc();
                    for (Element e2 = getFirstChildElement(e); e2 != null; e2 = getNextSiblingElement(e2)) {
                        if (IDENTIFICATION.equals(e2.getLocalName())) {
                            su.setIdentification(readIdentification(e2));
                        } else if (TARGET.equals(e2.getLocalName())) {
                            Target target = new Target();
                            for (Element e3 = getFirstChildElement(e2); e3 != null; e3 = getNextSiblingElement(
                                    e3)) {
                                if (ARTIFACTS_ZIP.equals(e3.getLocalName())) {
                                    target.setArtifactsZip(getText(e3));
                                } else if (COMPONENT_NAME.equals(e3.getLocalName())) {
                                    target.setComponentName(getText(e3));
                                }
                            }
                            su.setTarget(target);
                        }
                    }
                    sus.add(su);
                } else if (CONNECTIONS.equals(e.getLocalName())) {
                    Connections connections = new Connections();
                    ArrayList<Connection> cns = new ArrayList<Connection>();
                    for (Element e2 = getFirstChildElement(e); e2 != null; e2 = getNextSiblingElement(e2)) {
                        if (CONNECTION.equals(e2.getLocalName())) {
                            Connection cn = new Connection();
                            for (Element e3 = getFirstChildElement(e2); e3 != null; e3 = getNextSiblingElement(
                                    e3)) {
                                if (CONSUMER.equals(e3.getLocalName())) {
                                    Consumer consumer = new Consumer();
                                    consumer.setInterfaceName(readAttributeQName(e3, INTERFACE_NAME));
                                    consumer.setServiceName(readAttributeQName(e3, SERVICE_NAME));
                                    consumer.setEndpointName(getAttribute(e3, ENDPOINT_NAME));
                                    cn.setConsumer(consumer);
                                } else if (PROVIDER.equals(e3.getLocalName())) {
                                    Provider provider = new Provider();
                                    provider.setServiceName(readAttributeQName(e3, SERVICE_NAME));
                                    provider.setEndpointName(getAttribute(e3, ENDPOINT_NAME));
                                    cn.setProvider(provider);
                                }
                            }
                            cns.add(cn);
                        }
                    }
                    connections.setConnections(cns.toArray(new Connection[cns.size()]));
                    serviceAssembly.setConnections(connections);
                }
            }
            serviceAssembly.setServiceUnits(sus.toArray(new ServiceUnitDesc[sus.size()]));
            desc.setServiceAssembly(serviceAssembly);
        } else if (SERVICES.equals(child.getLocalName())) {
            Services services = new Services();
            services.setBindingComponent(
                    Boolean.valueOf(getAttribute(child, BINDING_COMPONENT)).booleanValue());
            ArrayList<Provides> provides = new ArrayList<Provides>();
            ArrayList<Consumes> consumes = new ArrayList<Consumes>();
            for (Element e = getFirstChildElement(child); e != null; e = getNextSiblingElement(e)) {
                if (PROVIDES.equals(e.getLocalName())) {
                    Provides p = new Provides();
                    p.setInterfaceName(readAttributeQName(e, INTERFACE_NAME));
                    p.setServiceName(readAttributeQName(e, SERVICE_NAME));
                    p.setEndpointName(getAttribute(e, ENDPOINT_NAME));
                    provides.add(p);
                } else if (CONSUMES.equals(e.getLocalName())) {
                    Consumes c = new Consumes();
                    c.setInterfaceName(readAttributeQName(e, INTERFACE_NAME));
                    c.setServiceName(readAttributeQName(e, SERVICE_NAME));
                    c.setEndpointName(getAttribute(e, ENDPOINT_NAME));
                    c.setLinkType(getAttribute(e, LINK_TYPE));
                    consumes.add(c);
                }
            }
            services.setProvides(provides.toArray(new Provides[provides.size()]));
            services.setConsumes(consumes.toArray(new Consumes[consumes.size()]));
            desc.setServices(services);
        }
        checkDescriptor(desc);
        return desc;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.shindig.social.opensocial.util.XSDValidator.java

/**
 * Validate a xml input stream against a supplied schema.
 *
 * @param xml/*from   w  w  w  .  jav  a  2s .co  m*/
 *          a stream containing the xml
 * @param schema
 *          a stream containing the schema
 * @return a list of errors or warnings, a 0 lenght string if none.
 */
public static String validate(InputStream xml, InputStream schema) {

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(true);
    final StringBuilder errors = new StringBuilder();
    try {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA);
        Schema s = schemaFactory.newSchema(new StreamSource(schema));

        Validator validator = s.newValidator();
        final LSResourceResolver lsr = validator.getResourceResolver();
        validator.setResourceResolver(new LSResourceResolver() {

            public LSInput resolveResource(String arg0, String arg1, String arg2, String arg3, String arg4) {
                log.info("resolveResource(" + arg0 + ',' + arg1 + ',' + arg2 + ',' + arg3 + ',' + arg4 + ')');
                return lsr.resolveResource(arg0, arg1, arg2, arg3, arg4);
            }

        });

        validator.validate(new StreamSource(xml));
    } catch (IOException e) {
    } catch (SAXException e) {
        errors.append(e.getMessage()).append('\n');
    }

    return errors.toString();
}

From source file:org.apache.stratos.adc.mgt.utils.PolicyHolder.java

public void validate(final OMElement omElement, final File schemaFile) throws SAXException, IOException {

    Element sourceElement;// w w  w .  j  a  v a  2  s  .com

    // if the OMElement is created using DOM implementation use it
    if (omElement instanceof ElementImpl) {
        sourceElement = (Element) omElement;
    } else { // else convert from llom to dom
        sourceElement = getDOMElement(omElement);
    }

    // Create a SchemaFactory capable of understanding WXS schemas.

    // Load a WXS schema, represented by a Schema instance.
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Source source = new StreamSource(schemaFile);

    // Create a Validator object, which can be used to validate
    // an instance document.
    Schema schema = factory.newSchema(source);
    Validator validator = schema.newValidator();

    // Validate the DOM tree.
    validator.validate(new DOMSource(sourceElement));
}