Search in sources :

Example 1 with LSResourceResolver

use of org.w3c.dom.ls.LSResourceResolver in project iaf by ibissource.

the class JavaxValidationContext method getSchemaObject.

// protected String validate(Source source, IPipeLineSession session) throws XmlValidatorException, ConfigurationException, PipeRunException {
// init();
// String schemasId = schemasProvider.getSchemasId();
// if (schemasId == null) {
// schemasId = schemasProvider.getSchemasId(session);
// getSchemaObject(schemasId, schemasProvider.getSchemas(session));
// }
// Schema xsd = javaxSchemas.get(schemasId);
// try {
// Validator validator = xsd.newValidator();
// validator.setResourceResolver(new LSResourceResolver() {
// public LSInput resolveResource(String s, String s1, String s2, String s3, String s4) {
// System.out.println("--");
// return null;//To change body of implemented methods Settings | File Templates.
// }
// });
// validator.setErrorHandler(new ErrorHandler() {
// public void warning(SAXParseException e) throws SAXException {
// log.warn(e.getMessage());
// }
// 
// public void error(SAXParseException e) throws SAXException {
// log.error(e.getMessage());
// }
// 
// public void fatalError(SAXParseException e) throws SAXException {
// log.error(e.getMessage());
// }
// });
// //validator.setFeature("http://xml.org/sax/features/namespace-prefixes", true); /// DOESNT" WORK any more?
// validator.validate(source);
// } catch (SAXException e) {
// throw new XmlValidatorException(e.getClass() + " " + e.getMessage());
// } catch (IOException e) {
// throw new XmlValidatorException(e.getMessage(), e);
// }
// return XML_VALIDATOR_VALID_MONITOR_EVENT;
// }
/**
 * Returns the {@link Schema} associated with this validator. This ia an XSD schema containing knowledge about the
 * schema source as returned by {@link #getSchemaSources(List)}
 * @throws ConfigurationException
 */
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;
}
Also used : SchemaFactory(javax.xml.validation.SchemaFactory) LSResourceResolver(org.w3c.dom.ls.LSResourceResolver) ConfigurationException(nl.nn.adapterframework.configuration.ConfigurationException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Schema(javax.xml.validation.Schema) LSInput(org.w3c.dom.ls.LSInput) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) PipeRunException(nl.nn.adapterframework.core.PipeRunException) XMLStreamException(javax.xml.stream.XMLStreamException) IOException(java.io.IOException) ConfigurationException(nl.nn.adapterframework.configuration.ConfigurationException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException)

Example 2 with LSResourceResolver

use of org.w3c.dom.ls.LSResourceResolver in project aries by apache.

the class SimpleNamespaceHandlerSet method getSchema.

public Schema getSchema() throws SAXException, IOException {
    if (schema == null) {
        final List<StreamSource> schemaSources = new ArrayList<StreamSource>();
        final List<InputStream> streams = new ArrayList<InputStream>();
        try {
            InputStream is = getClass().getResourceAsStream("/org/osgi/service/blueprint/blueprint.xsd");
            streams.add(is);
            schemaSources.add(new StreamSource(is));
            for (URI uri : namespaces.keySet()) {
                is = namespaces.get(uri).openStream();
                streams.add(is);
                schemaSources.add(new StreamSource(is));
            }
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            schemaFactory.setResourceResolver(new LSResourceResolver() {

                public LSInput resolveResource(String type, String namespace, String publicId, String systemId, String baseURI) {
                    try {
                        URL namespaceURL = namespaces.get(URI.create(namespace));
                        if (systemId != null && namespaceURL != null) {
                            URI systemIdUri = namespaceURL.toURI();
                            if (!URI.create(systemId).isAbsolute()) {
                                systemIdUri = systemIdUri.resolve(systemId);
                            }
                            if (!systemIdUri.isAbsolute() && "jar".equals(namespaceURL.getProtocol())) {
                                String urlString = namespaceURL.toString();
                                int jarFragmentIndex = urlString.lastIndexOf('!');
                                if (jarFragmentIndex > 0 && jarFragmentIndex < urlString.length() - 1) {
                                    String jarUrlOnly = urlString.substring(0, jarFragmentIndex);
                                    String oldFragment = urlString.substring(jarFragmentIndex + 1);
                                    String newFragment = URI.create(oldFragment).resolve(systemId).toString();
                                    String newJarUri = jarUrlOnly + '!' + newFragment;
                                    systemIdUri = URI.create(newJarUri);
                                }
                            }
                            InputStream resourceStream = systemIdUri.toURL().openStream();
                            return new LSInputImpl(publicId, systemId, resourceStream);
                        }
                    } catch (Exception ex) {
                    // ignore
                    }
                    return null;
                }
            });
            schema = schemaFactory.newSchema(schemaSources.toArray(new Source[schemaSources.size()]));
        } finally {
            for (InputStream is : streams) {
                is.close();
            }
        }
    }
    return schema;
}
Also used : SchemaFactory(javax.xml.validation.SchemaFactory) InputStream(java.io.InputStream) StreamSource(javax.xml.transform.stream.StreamSource) ArrayList(java.util.ArrayList) URI(java.net.URI) URL(java.net.URL) IOException(java.io.IOException) SAXException(org.xml.sax.SAXException) LSResourceResolver(org.w3c.dom.ls.LSResourceResolver) LSInput(org.w3c.dom.ls.LSInput)

Example 3 with LSResourceResolver

use of org.w3c.dom.ls.LSResourceResolver in project cxf by apache.

the class ImportRepairTest method tryToParseSchemas.

private void tryToParseSchemas() throws Exception {
    // Get DOM Implementation using DOM Registry
    final List<DOMLSInput> inputs = new ArrayList<>();
    final Map<String, LSInput> resolverMap = new HashMap<>();
    for (XmlSchema schema : collection.getXmlSchemas()) {
        if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(schema.getTargetNamespace())) {
            continue;
        }
        Document document = new XmlSchemaSerializer().serializeSchema(schema, false)[0];
        DOMLSInput input = new DOMLSInput(document, schema.getTargetNamespace());
        dumpSchema(document);
        resolverMap.put(schema.getTargetNamespace(), input);
        inputs.add(input);
    }
    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    DOMImplementation impl = registry.getDOMImplementation("XS-Loader");
    try {
        Object schemaLoader = findMethod(impl, "createXSLoader").invoke(impl, new Object[1]);
        DOMConfiguration config = (DOMConfiguration) findMethod(schemaLoader, "getConfig").invoke(schemaLoader);
        config.setParameter("validate", Boolean.TRUE);
        try {
            // bug in the JDK doesn't set this, but accesses it
            config.setParameter("http://www.oracle.com/xml/jaxp/properties/xmlSecurityPropertyManager", Class.forName("com.sun.org.apache.xerces.internal.utils.XMLSecurityPropertyManager").newInstance());
            config.setParameter("http://apache.org/xml/properties/security-manager", Class.forName("com.sun.org.apache.xerces.internal.utils.XMLSecurityManager").newInstance());
        } catch (Throwable t) {
        // ignore
        }
        config.setParameter("error-handler", new DOMErrorHandler() {

            public boolean handleError(DOMError error) {
                LOG.info("Schema parsing error: " + error.getMessage() + " " + error.getType() + " " + error.getLocation().getUri() + " " + error.getLocation().getLineNumber() + ":" + error.getLocation().getColumnNumber());
                throw new DOMErrorException(error);
            }
        });
        config.setParameter("resource-resolver", new LSResourceResolver() {

            public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {
                return resolverMap.get(namespaceURI);
            }
        });
        Method m = findMethod(schemaLoader, "loadInputList");
        String name = m.getParameterTypes()[0].getName() + "Impl";
        name = name.replace("xs.LS", "impl.xs.util.LS");
        Class<?> c = Class.forName(name);
        Object inputList = c.getConstructor(LSInput[].class, Integer.TYPE).newInstance(inputs.toArray(new LSInput[0]), inputs.size());
        findMethod(schemaLoader, "loadInputList").invoke(schemaLoader, inputList);
    } catch (InvocationTargetException ite) {
        throw (Exception) ite.getTargetException();
    }
}
Also used : DOMErrorHandler(org.w3c.dom.DOMErrorHandler) HashMap(java.util.HashMap) DOMError(org.w3c.dom.DOMError) ArrayList(java.util.ArrayList) DOMImplementation(org.w3c.dom.DOMImplementation) DOMConfiguration(org.w3c.dom.DOMConfiguration) XmlSchemaSerializer(org.apache.ws.commons.schema.XmlSchemaSerializer) Method(java.lang.reflect.Method) Document(org.w3c.dom.Document) InvocationTargetException(java.lang.reflect.InvocationTargetException) XmlSchema(org.apache.ws.commons.schema.XmlSchema) LSResourceResolver(org.w3c.dom.ls.LSResourceResolver) LSInput(org.w3c.dom.ls.LSInput) DOMImplementationRegistry(org.w3c.dom.bootstrap.DOMImplementationRegistry)

Example 4 with LSResourceResolver

use of org.w3c.dom.ls.LSResourceResolver in project cxf by apache.

the class SchemaHandler method createSchema.

public static Schema createSchema(List<String> locations, String catalogLocation, final Bus bus) {
    SchemaFactory factory = SchemaFactory.newInstance(Constants.URI_2001_SCHEMA_XSD);
    try {
        List<Source> sources = new ArrayList<>();
        for (String loc : locations) {
            final List<URL> schemaURLs;
            if (loc.lastIndexOf('.') == -1 || loc.lastIndexOf('*') != -1) {
                schemaURLs = ClasspathScanner.findResources(loc, "xsd");
            } else {
                URL url = ResourceUtils.getResourceURL(loc, bus);
                schemaURLs = url != null ? Collections.singletonList(url) : Collections.emptyList();
            }
            if (schemaURLs.isEmpty()) {
                throw new IllegalArgumentException("Cannot find XML schema location: " + loc);
            }
            for (URL schemaURL : schemaURLs) {
                Reader r = new BufferedReader(new InputStreamReader(schemaURL.openStream(), StandardCharsets.UTF_8));
                StreamSource source = new StreamSource(r);
                source.setSystemId(schemaURL.toString());
                sources.add(source);
            }
        }
        if (sources.isEmpty()) {
            return null;
        }
        final OASISCatalogManager catalogResolver = OASISCatalogManager.getCatalogManager(bus);
        if (catalogResolver != null) {
            catalogLocation = catalogLocation == null ? SchemaHandler.DEFAULT_CATALOG_LOCATION : catalogLocation;
            URL catalogURL = ResourceUtils.getResourceURL(catalogLocation, bus);
            if (catalogURL != null) {
                try {
                    catalogResolver.loadCatalog(catalogURL);
                    factory.setResourceResolver(new LSResourceResolver() {

                        public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {
                            try {
                                String resolvedLocation = catalogResolver.resolveSystem(systemId);
                                if (resolvedLocation == null) {
                                    resolvedLocation = catalogResolver.resolveURI(namespaceURI);
                                }
                                if (resolvedLocation == null) {
                                    resolvedLocation = catalogResolver.resolvePublic(publicId != null ? publicId : namespaceURI, systemId);
                                }
                                if (resolvedLocation != null) {
                                    InputStream resourceStream = ResourceUtils.getResourceStream(resolvedLocation, bus);
                                    if (resourceStream != null) {
                                        return new LSInputImpl(publicId, systemId, resourceStream);
                                    }
                                }
                            } catch (Exception ex) {
                            // ignore
                            }
                            return null;
                        }
                    });
                } catch (IOException ex) {
                    throw new IllegalArgumentException("Catalog " + catalogLocation + " can not be loaded", ex);
                }
            }
        }
        return factory.newSchema(sources.toArray(new Source[0]));
    } catch (Exception ex) {
        throw new IllegalArgumentException("Failed to load XML schema : " + ex.getMessage(), ex);
    }
}
Also used : SchemaFactory(javax.xml.validation.SchemaFactory) LSInputImpl(org.apache.cxf.common.xmlschema.LSInputImpl) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) StreamSource(javax.xml.transform.stream.StreamSource) ArrayList(java.util.ArrayList) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) URL(java.net.URL) IOException(java.io.IOException) LSResourceResolver(org.w3c.dom.ls.LSResourceResolver) LSInput(org.w3c.dom.ls.LSInput) BufferedReader(java.io.BufferedReader) OASISCatalogManager(org.apache.cxf.catalog.OASISCatalogManager)

Example 5 with LSResourceResolver

use of org.w3c.dom.ls.LSResourceResolver in project cxf by apache.

the class JAXBDataBinding method validateSchema.

public void validateSchema(Element ele, String uri, final OASISCatalogManager catalog, final SchemaCollection schemaCollection) throws ToolException {
    SchemaFactory schemaFact = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFact.setResourceResolver(new LSResourceResolver() {

        public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {
            String s = JAXBDataBinding.mapSchemaLocation(systemId, baseURI, catalog);
            LOG.fine("validating: " + namespaceURI + " " + systemId + " " + baseURI + " " + s);
            if (s == null) {
                XmlSchema sc = schemaCollection.getSchemaByTargetNamespace(namespaceURI);
                if (sc != null) {
                    StringWriter writer = new StringWriter();
                    sc.write(writer);
                    InputSource src = new InputSource(new StringReader(writer.toString()));
                    src.setSystemId(sc.getSourceURI());
                    return new LSInputSAXWrapper(src);
                }
                throw new ToolException("Schema not found for namespace: " + namespaceURI);
            }
            return new LSInputSAXWrapper(new InputSource(s));
        }
    });
    DOMSource domSrc = new DOMSource(ele, uri);
    try {
        schemaFact.newSchema(domSrc);
    } catch (SAXException e) {
        if (e.getLocalizedMessage().indexOf("src-resolve.4.2") > -1) {
        // Ignore schema resolve error and do nothing
        } else {
            // e.printStackTrace();
            throw new ToolException("Schema Error : " + e.getLocalizedMessage(), e);
        }
    }
}
Also used : SchemaFactory(javax.xml.validation.SchemaFactory) InputSource(org.xml.sax.InputSource) DOMSource(javax.xml.transform.dom.DOMSource) StringWriter(java.io.StringWriter) LSResourceResolver(org.w3c.dom.ls.LSResourceResolver) XmlSchema(org.apache.ws.commons.schema.XmlSchema) LSInput(org.w3c.dom.ls.LSInput) StringReader(java.io.StringReader) LSInputSAXWrapper(com.sun.tools.xjc.reader.xmlschema.parser.LSInputSAXWrapper) ToolException(org.apache.cxf.tools.common.ToolException) SAXException(org.xml.sax.SAXException)

Aggregations

LSResourceResolver (org.w3c.dom.ls.LSResourceResolver)8 LSInput (org.w3c.dom.ls.LSInput)7 SchemaFactory (javax.xml.validation.SchemaFactory)5 ArrayList (java.util.ArrayList)4 StreamSource (javax.xml.transform.stream.StreamSource)4 IOException (java.io.IOException)3 URL (java.net.URL)3 XmlSchema (org.apache.ws.commons.schema.XmlSchema)3 SAXException (org.xml.sax.SAXException)3 InputStream (java.io.InputStream)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 Method (java.lang.reflect.Method)2 HashMap (java.util.HashMap)2 Source (javax.xml.transform.Source)2 Schema (javax.xml.validation.Schema)2 XmlSchemaSerializer (org.apache.ws.commons.schema.XmlSchemaSerializer)2 DOMConfiguration (org.w3c.dom.DOMConfiguration)2 Document (org.w3c.dom.Document)2 LSInputSAXWrapper (com.sun.tools.xjc.reader.xmlschema.parser.LSInputSAXWrapper)1 BufferedReader (java.io.BufferedReader)1