Search in sources :

Example 1 with OASISCatalogManager

use of org.apache.cxf.catalog.OASISCatalogManager 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);
    Schema s = null;
    try {
        List<Source> sources = new ArrayList<>();
        for (String loc : locations) {
            List<URL> schemaURLs = new LinkedList<URL>();
            if (loc.lastIndexOf(".") == -1 || loc.lastIndexOf('*') != -1) {
                schemaURLs = ClasspathScanner.findResources(loc, "xsd");
            } else {
                URL url = ResourceUtils.getResourceURL(loc, bus);
                if (url != null) {
                    schemaURLs.add(url);
                }
            }
            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);
                }
            }
        }
        s = factory.newSchema(sources.toArray(new Source[sources.size()]));
    } catch (Exception ex) {
        throw new IllegalArgumentException("Failed to load XML schema : " + ex.getMessage(), ex);
    }
    return s;
}
Also used : SchemaFactory(javax.xml.validation.SchemaFactory) LSInputImpl(org.apache.cxf.common.xmlschema.LSInputImpl) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Schema(javax.xml.validation.Schema) 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) LinkedList(java.util.LinkedList) 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 2 with OASISCatalogManager

use of org.apache.cxf.catalog.OASISCatalogManager in project cxf by apache.

the class WSDLGetUtils method updateDefinition.

protected void updateDefinition(Bus bus, Definition def, Map<String, Definition> done, Map<String, SchemaReference> doneSchemas, String base, String docBase, String parentResolvedLocation) {
    OASISCatalogManager catalogs = OASISCatalogManager.getCatalogManager(bus);
    Collection<List<?>> imports = CastUtils.cast((Collection<?>) def.getImports().values());
    for (List<?> lst : imports) {
        List<Import> impLst = CastUtils.cast(lst);
        for (Import imp : impLst) {
            String start = imp.getLocationURI();
            String decodedStart;
            try {
                decodedStart = URLDecoder.decode(start, "utf-8");
            } catch (UnsupportedEncodingException e) {
                throw new WSDLQueryException(new org.apache.cxf.common.i18n.Message("COULD_NOT_PROVIDE_WSDL", LOG, start), e);
            }
            String resolvedSchemaLocation = resolveWithCatalogs(catalogs, start, base);
            if (resolvedSchemaLocation == null) {
                try {
                    // check to see if it's already in a URL format.  If so, leave it.
                    new URL(start);
                } catch (MalformedURLException e) {
                    try {
                        start = getLocationURI(start, docBase);
                        decodedStart = URLDecoder.decode(start, "utf-8");
                    } catch (Exception e1) {
                    // ignore
                    }
                    if (done.put(decodedStart, imp.getDefinition()) == null) {
                        if (imp.getDefinition() != null && imp.getDefinition().getDocumentBaseURI() != null) {
                            done.put(imp.getDefinition().getDocumentBaseURI(), imp.getDefinition());
                        }
                        updateDefinition(bus, imp.getDefinition(), done, doneSchemas, base, start, null);
                    }
                }
            } else {
                if (done.put(decodedStart, imp.getDefinition()) == null) {
                    done.put(resolvedSchemaLocation, imp.getDefinition());
                    if (imp.getDefinition() != null && imp.getDefinition().getDocumentBaseURI() != null) {
                        done.put(imp.getDefinition().getDocumentBaseURI(), imp.getDefinition());
                    }
                    updateDefinition(bus, imp.getDefinition(), done, doneSchemas, base, start, resolvedSchemaLocation);
                }
            }
        }
    }
    /* This doesn't actually work.   Setting setSchemaLocationURI on the import
        * for some reason doesn't actually result in the new URI being written
        * */
    Types types = def.getTypes();
    if (types != null) {
        for (ExtensibilityElement el : CastUtils.cast(types.getExtensibilityElements(), ExtensibilityElement.class)) {
            if (el instanceof Schema) {
                updateSchemaImports(bus, (Schema) el, docBase, doneSchemas, base, parentResolvedLocation);
            }
        }
    }
}
Also used : Types(javax.wsdl.Types) MalformedURLException(java.net.MalformedURLException) SchemaImport(javax.wsdl.extensions.schema.SchemaImport) Import(javax.wsdl.Import) Message(org.apache.cxf.message.Message) Schema(javax.wsdl.extensions.schema.Schema) UnsupportedEncodingException(java.io.UnsupportedEncodingException) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) XMLStreamException(javax.xml.stream.XMLStreamException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) MalformedURLException(java.net.MalformedURLException) WSDLException(javax.wsdl.WSDLException) ExtensibilityElement(javax.wsdl.extensions.ExtensibilityElement) OASISCatalogManager(org.apache.cxf.catalog.OASISCatalogManager) List(java.util.List)

Example 3 with OASISCatalogManager

use of org.apache.cxf.catalog.OASISCatalogManager in project cxf by apache.

the class DynamicClientFactory method createClient.

public Client createClient(String wsdlUrl, QName service, ClassLoader classLoader, QName port, List<String> bindingFiles) {
    if (classLoader == null) {
        classLoader = Thread.currentThread().getContextClassLoader();
    }
    LOG.log(Level.FINE, "Creating client from WSDL " + wsdlUrl);
    WSDLServiceFactory sf = (service == null) ? (new WSDLServiceFactory(bus, wsdlUrl)) : (new WSDLServiceFactory(bus, wsdlUrl, service));
    sf.setAllowElementRefs(allowRefs);
    Service svc = sf.create();
    // all SI's should have the same schemas
    SchemaCollection schemas = svc.getServiceInfos().get(0).getXmlSchemaCollection();
    SchemaCompiler compiler = createSchemaCompiler();
    InnerErrorListener listener = new InnerErrorListener(wsdlUrl);
    Object elForRun = ReflectionInvokationHandler.createProxyWrapper(listener, JAXBUtils.getParamClass(compiler, "setErrorListener"));
    compiler.setErrorListener(elForRun);
    OASISCatalogManager catalog = bus.getExtension(OASISCatalogManager.class);
    hackInNewInternalizationLogic(compiler, catalog);
    addSchemas(compiler.getOptions(), compiler, svc.getServiceInfos(), schemas);
    addBindingFiles(bindingFiles, compiler);
    S2JJAXBModel intermediateModel = compiler.bind();
    listener.throwException();
    JCodeModel codeModel = intermediateModel.generateCode(null, elForRun);
    StringBuilder sb = new StringBuilder();
    boolean firstnt = false;
    for (Iterator<JPackage> packages = codeModel.packages(); packages.hasNext(); ) {
        JPackage jpackage = packages.next();
        if (!isValidPackage(jpackage)) {
            continue;
        }
        if (firstnt) {
            sb.append(':');
        } else {
            firstnt = true;
        }
        sb.append(jpackage.name());
    }
    JAXBUtils.logGeneratedClassNames(LOG, codeModel);
    String packageList = sb.toString();
    // our hashcode + timestamp ought to be enough.
    String stem = toString() + "-" + System.currentTimeMillis();
    File src = new File(tmpdir, stem + "-src");
    if (!src.mkdir()) {
        throw new IllegalStateException("Unable to create working directory " + src.getPath());
    }
    try {
        Object writer = JAXBUtils.createFileCodeWriter(src);
        codeModel.build(writer);
    } catch (Exception e) {
        throw new IllegalStateException("Unable to write generated Java files for schemas: " + e.getMessage(), e);
    }
    File classes = new File(tmpdir, stem + "-classes");
    if (!classes.mkdir()) {
        throw new IllegalStateException("Unable to create working directory " + classes.getPath());
    }
    StringBuilder classPath = new StringBuilder();
    try {
        setupClasspath(classPath, classLoader);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
    List<File> srcFiles = FileUtils.getFilesRecurse(src, ".+\\.java$");
    if (!srcFiles.isEmpty() && !compileJavaSrc(classPath.toString(), srcFiles, classes.toString())) {
        LOG.log(Level.SEVERE, new Message("COULD_NOT_COMPILE_SRC", LOG, wsdlUrl).toString());
    }
    FileUtils.removeDir(src);
    URL[] urls = null;
    try {
        urls = new URL[] { classes.toURI().toURL() };
    } catch (MalformedURLException mue) {
        throw new IllegalStateException("Internal error; a directory returns a malformed URL: " + mue.getMessage(), mue);
    }
    final ClassLoader cl = ClassLoaderUtils.getURLClassLoader(urls, classLoader);
    JAXBContext context;
    Map<String, Object> contextProperties = jaxbContextProperties;
    if (contextProperties == null) {
        contextProperties = Collections.emptyMap();
    }
    try {
        if (StringUtils.isEmpty(packageList)) {
            context = JAXBContext.newInstance(new Class[0], contextProperties);
        } else {
            context = JAXBContext.newInstance(packageList, cl, contextProperties);
        }
    } catch (JAXBException jbe) {
        throw new IllegalStateException("Unable to create JAXBContext for generated packages: " + jbe.getMessage(), jbe);
    }
    JAXBDataBinding databinding = new JAXBDataBinding();
    databinding.setContext(context);
    svc.setDataBinding(databinding);
    ClientImpl client = new DynamicClientImpl(bus, svc, port, getEndpointImplFactory(), cl);
    ServiceInfo svcfo = client.getEndpoint().getEndpointInfo().getService();
    // Setup the new classloader!
    ClassLoaderUtils.setThreadContextClassloader(cl);
    TypeClassInitializer visitor = new TypeClassInitializer(svcfo, intermediateModel, allowWrapperOps());
    visitor.walk();
    // delete the classes files
    FileUtils.removeDir(classes);
    return client;
}
Also used : MalformedURLException(java.net.MalformedURLException) Message(org.apache.cxf.common.i18n.Message) JAXBContext(javax.xml.bind.JAXBContext) SchemaCompiler(org.apache.cxf.common.jaxb.JAXBUtils.SchemaCompiler) URL(java.net.URL) ServiceInfo(org.apache.cxf.service.model.ServiceInfo) OASISCatalogManager(org.apache.cxf.catalog.OASISCatalogManager) URLClassLoader(java.net.URLClassLoader) S2JJAXBModel(org.apache.cxf.common.jaxb.JAXBUtils.S2JJAXBModel) JAXBDataBinding(org.apache.cxf.jaxb.JAXBDataBinding) WSDLServiceFactory(org.apache.cxf.wsdl11.WSDLServiceFactory) JAXBException(javax.xml.bind.JAXBException) JPackage(org.apache.cxf.common.jaxb.JAXBUtils.JPackage) Service(org.apache.cxf.service.Service) ClientImpl(org.apache.cxf.endpoint.ClientImpl) JCodeModel(org.apache.cxf.common.jaxb.JAXBUtils.JCodeModel) URISyntaxException(java.net.URISyntaxException) XMLStreamException(javax.xml.stream.XMLStreamException) JAXBException(javax.xml.bind.JAXBException) SAXException(org.xml.sax.SAXException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) XmlSchemaSerializerException(org.apache.ws.commons.schema.XmlSchemaSerializer.XmlSchemaSerializerException) DOMException(org.w3c.dom.DOMException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) SAXParseException(org.xml.sax.SAXParseException) ServiceConstructionException(org.apache.cxf.service.factory.ServiceConstructionException) JDefinedClass(org.apache.cxf.common.jaxb.JAXBUtils.JDefinedClass) SchemaCollection(org.apache.cxf.common.xmlschema.SchemaCollection) JarFile(java.util.jar.JarFile) File(java.io.File)

Example 4 with OASISCatalogManager

use of org.apache.cxf.catalog.OASISCatalogManager in project cxf by apache.

the class WSDLGetUtils method processSchemaReference.

private void processSchemaReference(SchemaReference schemaReference, Bus bus, Schema schema, String docBase, Map<String, SchemaReference> doneSchemas, String base, String parentResolved) {
    OASISCatalogManager catalogs = OASISCatalogManager.getCatalogManager(bus);
    String start = findSchemaLocation(doneSchemas, schemaReference, docBase);
    String origLocation = schemaReference.getSchemaLocationURI();
    if (start != null) {
        String decodedStart;
        String decodedOrigLocation;
        // canonical representation of the import URL for lookup.
        try {
            decodedStart = URLDecoder.decode(start, "utf-8");
            decodedOrigLocation = URLDecoder.decode(origLocation, "utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new WSDLQueryException(new org.apache.cxf.common.i18n.Message("COULD_NOT_PROVIDE_WSDL", LOG, start), e);
        }
        if (!doneSchemas.containsKey(decodedStart)) {
            String resolvedSchemaLocation = resolveWithCatalogs(catalogs, start, base);
            if (resolvedSchemaLocation == null) {
                resolvedSchemaLocation = resolveWithCatalogs(catalogs, schemaReference.getSchemaLocationURI(), base);
            }
            if (resolvedSchemaLocation == null) {
                try {
                    // check to see if it's already in a URL format.  If so, leave it.
                    new URL(start);
                } catch (MalformedURLException e) {
                    doneSchemas.put(decodedStart, schemaReference);
                    doneSchemas.put(schemaReference.getReferencedSchema().getDocumentBaseURI(), schemaReference);
                    if (!doneSchemas.containsKey(decodedOrigLocation)) {
                        doneSchemas.put(decodedOrigLocation, schemaReference);
                    }
                    try {
                        if (!(new URI(origLocation).isAbsolute()) && parentResolved != null) {
                            resolvedSchemaLocation = resolveRelativePath(parentResolved, decodedOrigLocation);
                            doneSchemas.put(resolvedSchemaLocation, schemaReference);
                        }
                    } catch (URISyntaxException e1) {
                    // ignore
                    }
                    updateSchemaImports(bus, schemaReference.getReferencedSchema(), start, doneSchemas, base, resolvedSchemaLocation);
                }
            } else if (doneSchemas.put(decodedStart, schemaReference) == null) {
                doneSchemas.put(resolvedSchemaLocation, schemaReference);
                String p = getAndSaveRelativeSchemaLocationIfCatalogResolved(doneSchemas, resolvedSchemaLocation, schema, schemaReference);
                updateSchemaImports(bus, schemaReference.getReferencedSchema(), p, doneSchemas, base, resolvedSchemaLocation);
            }
        }
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) Message(org.apache.cxf.message.Message) OASISCatalogManager(org.apache.cxf.catalog.OASISCatalogManager) UnsupportedEncodingException(java.io.UnsupportedEncodingException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) URL(java.net.URL)

Example 5 with OASISCatalogManager

use of org.apache.cxf.catalog.OASISCatalogManager in project cxf by apache.

the class JAXBDataBinding method addSchemas.

private void addSchemas(Options opts, SchemaCompiler schemaCompiler, SchemaCollection schemaCollection) {
    Set<String> ids = new HashSet<>();
    @SuppressWarnings("unchecked") List<ServiceInfo> serviceList = (List<ServiceInfo>) context.get(ToolConstants.SERVICE_LIST);
    for (ServiceInfo si : serviceList) {
        for (SchemaInfo sci : si.getSchemas()) {
            String key = sci.getSystemId();
            if (ids.contains(key)) {
                continue;
            }
            ids.add(key);
        }
    }
    Bus bus = context.get(Bus.class);
    OASISCatalogManager catalog = bus.getExtension(OASISCatalogManager.class);
    for (XmlSchema schema : schemaCollection.getXmlSchemas()) {
        if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(schema.getTargetNamespace())) {
            continue;
        }
        String key = schema.getSourceURI();
        if (ids.contains(key)) {
            continue;
        }
        if (!key.startsWith("file:") && !key.startsWith("jar:")) {
            XmlSchemaSerializer xser = new XmlSchemaSerializer();
            xser.setExtReg(schemaCollection.getExtReg());
            Document[] docs;
            try {
                docs = xser.serializeSchema(schema, false);
            } catch (XmlSchemaSerializerException e) {
                throw new RuntimeException(e);
            }
            Element ele = docs[0].getDocumentElement();
            if (context.fullValidateWSDL()) {
                String uri = null;
                try {
                    uri = docs[0].getDocumentURI();
                } catch (Throwable ex) {
                // ignore - DOM level 3
                }
                validateSchema(ele, uri, catalog, schemaCollection);
            }
            ele = removeImportElement(ele, key, catalog);
            try {
                docs[0].setDocumentURI(key);
            } catch (Throwable t) {
            // ignore - DOM level 3
            }
            InputSource is = new InputSource((InputStream) null);
            // key = key.replaceFirst("#types[0-9]+$", "");
            is.setSystemId(key);
            is.setPublicId(key);
            opts.addGrammar(is);
            try {
                schemaCompiler.parseSchema(key, createNoCDATAReader(StaxUtils.createXMLStreamReader(ele, key)));
            } catch (XMLStreamException e) {
                throw new ToolException(e);
            }
        }
    }
    for (XmlSchema schema : schemaCollection.getXmlSchemas()) {
        if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(schema.getTargetNamespace())) {
            continue;
        }
        String key = schema.getSourceURI();
        String tns = schema.getTargetNamespace();
        String ltns = schema.getLogicalTargetNamespace();
        // accepting also a null tns (e.g., reported by apache.ws.xmlschema for no-namespace)
        if (ids.contains(key) || (tns == null && !StringUtils.isEmpty(ltns))) {
            continue;
        }
        if (key.startsWith("file:") || key.startsWith("jar:")) {
            InputStream in = null;
            try {
                if (key.startsWith("file:")) {
                    in = Files.newInputStream(new File(new URI(key)).toPath());
                } else {
                    in = new URL(key).openStream();
                }
                XMLStreamReader reader = StaxUtils.createXMLStreamReader(key, in);
                reader = createNoCDATAReader(new LocationFilterReader(reader, catalog));
                InputSource is = new InputSource(key);
                opts.addGrammar(is);
                schemaCompiler.parseSchema(key, reader);
                reader.close();
            } catch (RuntimeException ex) {
                throw ex;
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                    // ignore
                    }
                }
            }
        }
    }
    addSchemasForServiceInfos(catalog, serviceList, opts, schemaCompiler, schemaCollection);
}
Also used : InputSource(org.xml.sax.InputSource) XMLStreamReader(javax.xml.stream.XMLStreamReader) Element(org.w3c.dom.Element) Document(org.w3c.dom.Document) URI(java.net.URI) URL(java.net.URL) ServiceInfo(org.apache.cxf.service.model.ServiceInfo) OASISCatalogManager(org.apache.cxf.catalog.OASISCatalogManager) ArrayList(java.util.ArrayList) List(java.util.List) NodeList(org.w3c.dom.NodeList) ToolException(org.apache.cxf.tools.common.ToolException) HashSet(java.util.HashSet) SchemaInfo(org.apache.cxf.service.model.SchemaInfo) Bus(org.apache.cxf.Bus) InputStream(java.io.InputStream) XmlSchemaSerializer(org.apache.ws.commons.schema.XmlSchemaSerializer) IOException(java.io.IOException) XMLStreamException(javax.xml.stream.XMLStreamException) IOException(java.io.IOException) ToolException(org.apache.cxf.tools.common.ToolException) SAXException(org.xml.sax.SAXException) XmlSchemaSerializerException(org.apache.ws.commons.schema.XmlSchemaSerializer.XmlSchemaSerializerException) DOMException(org.w3c.dom.DOMException) BadCommandLineException(com.sun.tools.xjc.BadCommandLineException) SAXParseException(org.xml.sax.SAXParseException) XMLStreamException(javax.xml.stream.XMLStreamException) XmlSchema(org.apache.ws.commons.schema.XmlSchema) XmlSchemaSerializerException(org.apache.ws.commons.schema.XmlSchemaSerializer.XmlSchemaSerializerException) File(java.io.File)

Aggregations

OASISCatalogManager (org.apache.cxf.catalog.OASISCatalogManager)14 URL (java.net.URL)10 IOException (java.io.IOException)9 URISyntaxException (java.net.URISyntaxException)6 XMLStreamException (javax.xml.stream.XMLStreamException)6 Bus (org.apache.cxf.Bus)5 ToolException (org.apache.cxf.tools.common.ToolException)5 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 MalformedURLException (java.net.MalformedURLException)4 URI (java.net.URI)4 Message (org.apache.cxf.common.i18n.Message)4 XmlSchemaSerializerException (org.apache.ws.commons.schema.XmlSchemaSerializer.XmlSchemaSerializerException)4 DOMException (org.w3c.dom.DOMException)4 SAXException (org.xml.sax.SAXException)4 SAXParseException (org.xml.sax.SAXParseException)4 File (java.io.File)3 InputStream (java.io.InputStream)3 ArrayList (java.util.ArrayList)3 WSDLException (javax.wsdl.WSDLException)3 ServiceInfo (org.apache.cxf.service.model.ServiceInfo)3