Example usage for org.w3c.dom.ls LSResourceResolver LSResourceResolver

List of usage examples for org.w3c.dom.ls LSResourceResolver LSResourceResolver

Introduction

In this page you can find the example usage for org.w3c.dom.ls LSResourceResolver LSResourceResolver.

Prototype

LSResourceResolver

Source Link

Usage

From source file:csiro.pidsvc.mappingstore.Manager.java

/**************************************************************************
 *  Generic processing methods./*from w  w  w .  j a  v  a2  s .  co  m*/
 */

protected void validateRequest(String inputData, String xmlSchemaResourcePath)
        throws IOException, ValidationException {
    try {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        schemaFactory.setResourceResolver(new LSResourceResolver() {
            @Override
            public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId,
                    String baseURI) {
                return new XsdSchemaResolver(type, namespaceURI, publicId, systemId, baseURI);
            }
        });

        Schema schema = schemaFactory
                .newSchema(new StreamSource(getClass().getResourceAsStream(xmlSchemaResourcePath)));
        Validator validator = schema.newValidator();
        _logger.trace("Validating XML Schema.");
        validator.validate(new StreamSource(new StringReader(inputData)));
    } catch (SAXException ex) {
        _logger.debug("Unknown format.", ex);
        throw new ValidationException("Unknown format.", ex);
    }
}

From source file:de.betterform.xml.xforms.model.Model.java

private XSLoader getSchemaLoader()
        throws IllegalAccessException, InstantiationException, ClassNotFoundException {
    // System.setProperty(DOMImplementationRegistry.PROPERTY,
    // "org.apache.xerces.dom.DOMXSImplementationSourceImpl");
    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    XSImplementation implementation = (XSImplementation) registry.getDOMImplementation("XS-Loader");
    XSLoader loader = implementation.createXSLoader(null);

    DOMConfiguration cfg = loader.getConfig();

    cfg.setParameter("resource-resolver", new LSResourceResolver() {
        public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId,
                String baseURI) {
            LSInput input = new LSInput() {
                String systemId;//  w  w w  . j  a  va 2  s . c  o m

                public void setSystemId(String systemId) {
                    this.systemId = systemId;
                }

                public void setStringData(String s) {
                }

                String publicId;

                public void setPublicId(String publicId) {
                    this.publicId = publicId;
                }

                public void setEncoding(String s) {
                }

                public void setCharacterStream(Reader reader) {
                }

                public void setCertifiedText(boolean flag) {
                }

                public void setByteStream(InputStream inputstream) {
                }

                String baseURI;

                public void setBaseURI(String baseURI) {
                    if (baseURI == null || "".equals(baseURI)) {
                        baseURI = getContainer().getProcessor().getBaseURI();
                    }
                    this.baseURI = baseURI;
                }

                public String getSystemId() {
                    return this.systemId;
                }

                public String getStringData() {
                    return null;
                }

                public String getPublicId() {
                    return this.publicId;
                }

                public String getEncoding() {
                    return null;
                }

                public Reader getCharacterStream() {
                    return null;
                }

                public boolean getCertifiedText() {
                    return false;
                }

                public InputStream getByteStream() {
                    if (LOGGER.isTraceEnabled()) {
                        LOGGER.trace("Schema resource\n\t\t publicId '" + publicId + "'\n\t\t systemId '"
                                + systemId + "' requested");
                    }
                    try {
                        String pathToSchema = null;
                        if ("http://www.w3.org/MarkUp/SCHEMA/xml-events-attribs-1.xsd".equals(systemId)) {
                            pathToSchema = "schema/xml-events-attribs-1.xsd";
                        } else if ("http://www.w3.org/2001/XMLSchema.xsd".equals(systemId)) {
                            pathToSchema = "schema/XMLSchema.xsd";
                        } else if ("-//W3C//DTD XMLSCHEMA 200102//EN".equals(publicId)) {
                            pathToSchema = "schema/XMLSchema.dtd";
                        } else if ("datatypes".equals(publicId)) {
                            pathToSchema = "schema/datatypes.dtd";
                        } else if ("http://www.w3.org/2001/xml.xsd".equals(systemId)) {
                            pathToSchema = "schema/xml.xsd";
                        }

                        // LOAD WELL KNOWN SCHEMA
                        if (pathToSchema != null) {
                            if (LOGGER.isTraceEnabled()) {
                                LOGGER.trace("loading Schema '" + pathToSchema + "'\n\n");
                            }
                            return Thread.currentThread().getContextClassLoader()
                                    .getResourceAsStream(pathToSchema);
                        }
                        // LOAD SCHEMA THAT IS NOT(!) YET KNWON TO THE XFORMS PROCESSOR
                        else if (systemId != null && !"".equals(systemId)) {
                            URI schemaURI = new URI(baseURI);
                            schemaURI = schemaURI.resolve(systemId);

                            // ConnectorFactory.getFactory()
                            if (LOGGER.isDebugEnabled()) {
                                LOGGER.debug("loading schema resource '" + schemaURI.toString() + "'\n\n");
                            }
                            return ConnectorFactory.getFactory().getHTTPResourceAsStream(schemaURI);

                        } else {
                            LOGGER.error("resource not known '" + systemId + "'\n\n");
                            return null;
                        }

                    } catch (XFormsException e) {
                        e.printStackTrace();
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                    }
                    return null;
                }

                public String getBaseURI() {
                    return this.baseURI;
                }
            };
            input.setSystemId(systemId);
            input.setBaseURI(baseURI);
            input.setPublicId(publicId);
            return input;
        }
    });
    // END: Patch
    return loader;
}

From source file:nl.nn.adapterframework.validation.JavaxXmlValidator.java

/**
 * Returns the {@link Schema} associated with this validator. This is an XSD schema containing knowledge about the
 * schema source as returned by {@link #getSchemaSources(List)}
 *//* w ww.  j  a  va2 s. co  m*/
protected synchronized Schema getSchemaObject(String schemasId,
        List<nl.nn.adapterframework.validation.Schema> schemas) throws ConfigurationException {
    Schema schema = javaxSchemas.get(schemasId);
    if (schema == null) {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        factory.setResourceResolver(new LSResourceResolver() {
            public LSInput resolveResource(String s, String s1, String s2, String s3, String s4) {
                return null;
            }
        });
        try {
            Collection<Source> sources = getSchemaSources(schemas);
            schema = factory.newSchema(sources.toArray(new Source[sources.size()]));
            javaxSchemas.put(schemasId, schema);
        } catch (Exception e) {
            throw new ConfigurationException("cannot read schema's [" + schemasId + "]", e);
        }
    }
    return schema;
}

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  .  j a v  a2  s  .c  o 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.xml.security.stax.ext.XMLSecurityUtils.java

public static Schema loadXMLSecuritySchemas() throws SAXException {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setResourceResolver(new LSResourceResolver() {
        @Override/*from   w ww .  j  a va2 s  .c  o  m*/
        public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId,
                String baseURI) {
            if ("http://www.w3.org/2001/XMLSchema.dtd".equals(systemId)) {
                ConcreteLSInput concreteLSInput = new ConcreteLSInput();
                concreteLSInput.setByteStream(ClassLoaderUtils
                        .getResourceAsStream("bindings/schemas/XMLSchema.dtd", XMLSecurityConstants.class));
                return concreteLSInput;
            } else if ("XMLSchema.dtd".equals(systemId)) {
                ConcreteLSInput concreteLSInput = new ConcreteLSInput();
                concreteLSInput.setByteStream(ClassLoaderUtils
                        .getResourceAsStream("bindings/schemas/XMLSchema.dtd", XMLSecurityConstants.class));
                return concreteLSInput;
            } else if ("datatypes.dtd".equals(systemId)) {
                ConcreteLSInput concreteLSInput = new ConcreteLSInput();
                concreteLSInput.setByteStream(ClassLoaderUtils
                        .getResourceAsStream("bindings/schemas/datatypes.dtd", XMLSecurityConstants.class));
                return concreteLSInput;
            } else if ("http://www.w3.org/TR/2002/REC-xmldsig-core-20020212/xmldsig-core-schema.xsd"
                    .equals(systemId)) {
                ConcreteLSInput concreteLSInput = new ConcreteLSInput();
                concreteLSInput.setByteStream(ClassLoaderUtils.getResourceAsStream(
                        "bindings/schemas/xmldsig-core-schema.xsd", XMLSecurityConstants.class));
                return concreteLSInput;
            } else if ("http://www.w3.org/2001/xml.xsd".equals(systemId)) {
                ConcreteLSInput concreteLSInput = new ConcreteLSInput();
                concreteLSInput.setByteStream(ClassLoaderUtils.getResourceAsStream("bindings/schemas/xml.xsd",
                        XMLSecurityConstants.class));
                return concreteLSInput;
            }
            return null;
        }
    });
    Schema schema = schemaFactory.newSchema(new Source[] {
            new StreamSource(ClassLoaderUtils.getResourceAsStream("bindings/schemas/exc-c14n.xsd",
                    XMLSecurityConstants.class)),
            new StreamSource(ClassLoaderUtils.getResourceAsStream("bindings/schemas/xmldsig-core-schema.xsd",
                    XMLSecurityConstants.class)),
            new StreamSource(ClassLoaderUtils.getResourceAsStream("bindings/schemas/xenc-schema.xsd",
                    XMLSecurityConstants.class)),
            new StreamSource(ClassLoaderUtils.getResourceAsStream("bindings/schemas/xenc-schema-11.xsd",
                    XMLSecurityConstants.class)),
            new StreamSource(ClassLoaderUtils.getResourceAsStream("bindings/schemas/xmldsig11-schema.xsd",
                    XMLSecurityConstants.class)), });
    return schema;
}

From source file:org.codice.ddf.spatial.ogc.wfs.catalog.endpoint.writer.TestFeatureCollectionMessageBodyWriter.java

@Test
public void testWriteToGeneratesGMLConformantXml() throws IOException, WebApplicationException, SAXException {

    FeatureCollectionMessageBodyWriter wtr = new FeatureCollectionMessageBodyWriter();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    wtr.writeTo(getWfsFeatureCollection(), null, null, null, null, null, stream);
    String actual = stream.toString();

    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setResourceResolver(new LSResourceResolver() {

        private Map<String, String> schemaLocations;

        private Map<String, LSInput> inputs;

        {//from   ww w  .jav a2 s  .  c o  m
            inputs = new HashMap<String, LSInput>();

            schemaLocations = new HashMap<String, String>();

            schemaLocations.put("xml.xsd", "/w3/1999/xml.xsd");
            schemaLocations.put("xlink.xsd", "/w3/1999/xlink.xsd");
            schemaLocations.put("geometry.xsd", "/gml/2.1.2/geometry.xsd");
            schemaLocations.put("feature.xsd", "/gml/2.1.2/feature.xsd");
            schemaLocations.put("gml.xsd", "/gml/2.1.2/gml.xsd");
            schemaLocations.put("expr.xsd", "/filter/1.0.0/expr.xsd");
            schemaLocations.put("filter.xsd", "/filter/1.0.0/filter.xsd");
            schemaLocations.put("filterCapabilities.xsd", "/filter/1.0.0/filterCapabilties.xsd");
            schemaLocations.put("WFS-capabilities.xsd", "/wfs/1.0.0/WFS-capabilities.xsd");
            schemaLocations.put("OGC-exception.xsd", "/wfs/1.0.0/OGC-exception.xsd");
            schemaLocations.put("WFS-basic.xsd", "/wfs/1.0.0/WFS-basic.xsd");
            schemaLocations.put("WFS-transaction.xsd", "/wfs/1.0.0/WFS-transaction.xsd");
            schemaLocations.put("wfs.xsd", "/wfs/1.0.0/wfs.xsd");
        }

        @Override
        public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId,
                String baseURI) {
            String fileName = new java.io.File(systemId).getName();
            if (inputs.containsKey(fileName)) {
                return inputs.get(fileName);
            }

            LSInput input = new DOMInputImpl();
            InputStream is = getClass().getResourceAsStream(schemaLocations.get(fileName));
            input.setByteStream(is);
            input.setBaseURI(baseURI);
            input.setSystemId(systemId);
            inputs.put(fileName, input);
            return input;
        }
    });

    Source wfsSchemaSource = new StreamSource(getClass().getResourceAsStream("/wfs/1.0.0/wfs.xsd"));
    Source testSchemaSource = new StreamSource(getClass().getResourceAsStream("/schema.xsd"));

    Schema schema = schemaFactory.newSchema(new Source[] { wfsSchemaSource, testSchemaSource });

    try {
        schema.newValidator().validate(new StreamSource(new StringReader(actual)));
    } catch (Exception e) {
        fail("Generated GML Response does not conform to WFS Schema" + e.getMessage());
    }
}

From source file:org.jboss.cdi.tck.test.shrinkwrap.descriptors.ejb.EjbJarDescriptorBuilderTest.java

@Test
public void testDescriptorIsValid()
        throws ParserConfigurationException, SAXException, DescriptorExportException, IOException {

    EjbJarDescriptor ejbJarDescriptor = new EjbJarDescriptorBuilder().messageDrivenBeans(
            newMessageDriven("TestQueue", QueueMessageDrivenBean.class.getName())
                    .addActivationConfigProperty("acknowledgeMode", "Auto-acknowledge")
                    .addActivationConfigProperty("destinationType", "javax.jms.Queue")
                    .addActivationConfigProperty("destinationLookup", "test_queue"),
            newMessageDriven("TestTopic", TopicMessageDrivenBean.class.getName())
                    .addActivationConfigProperty("acknowledgeMode", "Auto-acknowledge")
                    .addActivationConfigProperty("destinationType", "javax.jms.Topic")
                    .addActivationConfigProperty("destinationLookup", "test_topic"))
            .build();/*from w w  w.ja v a  2  s. c  om*/

    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setResourceResolver(new LSResourceResolver() {

        @Override
        public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId,
                String baseURI) {
            try {
                if (systemId.startsWith("http")) {
                    // Ugly workaround for xml.xsd
                    systemId = StringUtils.substringAfterLast(systemId, "/");
                }
                return new Input(publicId, systemId,
                        new FileInputStream(new File("src/test/resources/xsd", systemId)));
            } catch (FileNotFoundException e) {
                throw new IllegalStateException();
            }
        }
    });
    schemaFactory.setErrorHandler(new ErrorHandler() {

        @Override
        public void warning(SAXParseException exception) throws SAXException {
        }

        @Override
        public void fatalError(SAXParseException exception) throws SAXException {
            throw exception;
        }

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

    Source schemaFile = new StreamSource(
            new FileInputStream(new File("src/test/resources/xsd", "ejb-jar_3_1.xsd")));
    Schema schema = schemaFactory.newSchema(schemaFile);
    Validator validator = schema.newValidator();
    validator
            .validate(new StreamSource(new ByteArrayInputStream(ejbJarDescriptor.exportAsString().getBytes())));
}