Search in sources :

Example 6 with SchemaCollection

use of org.apache.cxf.common.xmlschema.SchemaCollection in project cxf by apache.

the class WSDLServiceBuilderTest method testSchema.

@Test
public void testSchema() throws Exception {
    setUpBasic();
    SchemaCollection schemas = serviceInfo.getXmlSchemaCollection();
    assertNotNull(schemas);
    assertEquals(1, serviceInfo.getSchemas().size());
    SchemaInfo schemaInfo = serviceInfo.getSchemas().iterator().next();
    assertNotNull(schemaInfo);
    assertEquals(schemaInfo.getNamespaceURI(), "http://apache.org/hello_world_soap_http/types");
    assertEquals(schemas.read(schemaInfo.getElement()).getTargetNamespace(), "http://apache.org/hello_world_soap_http/types");
    // add below code to test the creation of javax.xml.validation.Schema
    // with schema in serviceInfo
    Schema schema = EndpointReferenceUtils.getSchema(serviceInfo);
    assertNotNull(schema);
    control.verify();
}
Also used : Schema(javax.xml.validation.Schema) SchemaCollection(org.apache.cxf.common.xmlschema.SchemaCollection) SchemaInfo(org.apache.cxf.service.model.SchemaInfo) Test(org.junit.Test)

Example 7 with SchemaCollection

use of org.apache.cxf.common.xmlschema.SchemaCollection 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 8 with SchemaCollection

use of org.apache.cxf.common.xmlschema.SchemaCollection in project cxf by apache.

the class WadlGenerator method getSchemaCollection.

private SchemaCollection getSchemaCollection(ResourceTypes resourceTypes, JAXBContext context) {
    if (context == null) {
        return null;
    }
    SchemaCollection xmlSchemaCollection = new SchemaCollection();
    Collection<DOMSource> schemas = new HashSet<>();
    List<String> targetNamespaces = new ArrayList<>();
    try {
        for (DOMResult r : JAXBUtils.generateJaxbSchemas(context, CastUtils.cast(Collections.emptyMap(), String.class, DOMResult.class))) {
            Document doc = (Document) r.getNode();
            ElementQNameResolver theResolver = createElementQNameResolver(context);
            String tns = doc.getDocumentElement().getAttribute("targetNamespace");
            String tnsPrefix = doc.getDocumentElement().lookupPrefix(tns);
            if (tnsPrefix == null) {
                String tnsDecl = doc.getDocumentElement().getAttribute("xmlns:tns");
                tnsPrefix = tnsDecl != null && tnsDecl.equals(tns) ? "tns:" : "";
            } else {
                tnsPrefix += ":";
            }
            if (supportJaxbXmlType) {
                for (Class<?> cls : resourceTypes.getAllTypes().keySet()) {
                    if (isXmlRoot(cls)) {
                        continue;
                    }
                    XmlType root = cls.getAnnotation(XmlType.class);
                    if (root != null) {
                        QName typeName = theResolver.resolve(cls, new Annotation[] {}, Collections.<Class<?>, QName>emptyMap());
                        if (typeName != null && tns.equals(typeName.getNamespaceURI())) {
                            QName elementName = resourceTypes.getXmlNameMap().get(cls);
                            if (elementName == null) {
                                elementName = typeName;
                            }
                            Element newElement = doc.createElementNS(Constants.URI_2001_SCHEMA_XSD, "xs:element");
                            newElement.setAttribute("name", elementName.getLocalPart());
                            newElement.setAttribute("type", tnsPrefix + typeName.getLocalPart());
                            if (Modifier.isAbstract(cls.getModifiers()) && resourceTypes.getSubstitutions().values().contains(cls)) {
                                newElement.setAttribute("abstract", "true");
                            }
                            doc.getDocumentElement().appendChild(newElement);
                        }
                    }
                }
                if (supportJaxbSubstitutions) {
                    for (Map.Entry<Class<?>, Class<?>> entry : resourceTypes.getSubstitutions().entrySet()) {
                        QName typeName = theResolver.resolve(entry.getKey(), new Annotation[] {}, Collections.<Class<?>, QName>emptyMap());
                        for (Element element : DOMUtils.findAllElementsByTagNameNS(doc.getDocumentElement(), Constants.URI_2001_SCHEMA_XSD, "element")) {
                            if (element.getAttribute("name").equals(typeName.getLocalPart())) {
                                QName groupName = theResolver.resolve(entry.getValue(), new Annotation[] {}, Collections.<Class<?>, QName>emptyMap());
                                if (groupName != null) {
                                    element.setAttribute("substitutionGroup", tnsPrefix + groupName.getLocalPart());
                                }
                            }
                        }
                    }
                }
            }
            if (supportCollections && !resourceTypes.getCollectionMap().isEmpty()) {
                for (Map.Entry<Class<?>, QName> entry : resourceTypes.getCollectionMap().entrySet()) {
                    QName colQName = entry.getValue();
                    if (colQName == null) {
                        colQName = theResolver.resolve(entry.getKey(), new Annotation[] {}, Collections.<Class<?>, QName>emptyMap());
                        if (colQName != null) {
                            colQName = new QName(colQName.getNamespaceURI(), colQName.getLocalPart() + "s", colQName.getPrefix());
                        }
                    }
                    if (colQName == null) {
                        continue;
                    }
                    if (tns.equals(colQName.getNamespaceURI())) {
                        QName typeName = theResolver.resolve(entry.getKey(), new Annotation[] {}, Collections.<Class<?>, QName>emptyMap());
                        if (typeName != null) {
                            Element newElement = doc.createElementNS(Constants.URI_2001_SCHEMA_XSD, "xs:element");
                            newElement.setAttribute("name", colQName.getLocalPart());
                            Element ctElement = doc.createElementNS(Constants.URI_2001_SCHEMA_XSD, "xs:complexType");
                            newElement.appendChild(ctElement);
                            Element seqElement = doc.createElementNS(Constants.URI_2001_SCHEMA_XSD, "xs:sequence");
                            ctElement.appendChild(seqElement);
                            Element xsElement = doc.createElementNS(Constants.URI_2001_SCHEMA_XSD, "xs:element");
                            seqElement.appendChild(xsElement);
                            xsElement.setAttribute("ref", tnsPrefix + typeName.getLocalPart());
                            xsElement.setAttribute("minOccurs", "0");
                            xsElement.setAttribute("maxOccurs", "unbounded");
                            doc.getDocumentElement().appendChild(newElement);
                        }
                    }
                }
            }
            DOMSource source = new DOMSource(doc, r.getSystemId());
            schemas.add(source);
            if (!StringUtils.isEmpty(tns)) {
                targetNamespaces.add(tns);
            }
        }
    } catch (IOException e) {
        LOG.fine("No schema can be generated");
        return null;
    }
    boolean hackAroundEmptyNamespaceIssue = false;
    for (DOMSource r : schemas) {
        hackAroundEmptyNamespaceIssue = addSchemaDocument(xmlSchemaCollection, targetNamespaces, (Document) r.getNode(), r.getSystemId(), hackAroundEmptyNamespaceIssue);
    }
    return xmlSchemaCollection;
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) DOMResult(javax.xml.transform.dom.DOMResult) QName(javax.xml.namespace.QName) XmlRootElement(javax.xml.bind.annotation.XmlRootElement) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Document(org.w3c.dom.Document) Annotation(java.lang.annotation.Annotation) XmlType(javax.xml.bind.annotation.XmlType) SchemaCollection(org.apache.cxf.common.xmlschema.SchemaCollection) MetadataMap(org.apache.cxf.jaxrs.impl.MetadataMap) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) IdentityHashMap(java.util.IdentityHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 9 with SchemaCollection

use of org.apache.cxf.common.xmlschema.SchemaCollection in project cxf by apache.

the class JavaScriptContainer method execute.

@SuppressWarnings("unchecked")
public void execute() throws ToolException {
    if (hasInfoOption()) {
        return;
    }
    buildToolContext();
    validate(context);
    WSDLConstants.WSDLVersion version = getWSDLVersion();
    String wsdlURL = (String) context.get(ToolConstants.CFG_WSDLURL);
    List<ServiceInfo> serviceList = (List<ServiceInfo>) context.get(ToolConstants.SERVICE_LIST);
    if (serviceList == null) {
        serviceList = new ArrayList<>();
        PluginLoader pluginLoader = PluginLoader.newInstance();
        // for JavaScript generation, we always use JAX-WS.
        FrontEndProfile frontend = pluginLoader.getFrontEndProfile("jaxws");
        // Build the ServiceModel from the WSDLModel
        if (version == WSDLConstants.WSDLVersion.WSDL11) {
            AbstractWSDLBuilder builder = frontend.getWSDLBuilder();
            builder.setContext(context);
            builder.setBus(getBus());
            context.put(Bus.class, getBus());
            builder.build(URIParserUtil.getAbsoluteURI(wsdlURL));
            builder.customize();
            Definition definition = builder.getWSDLModel();
            context.put(Definition.class, definition);
            builder.validate(definition);
            WSDLServiceBuilder serviceBuilder = new WSDLServiceBuilder(getBus());
            String serviceName = (String) context.get(ToolConstants.CFG_SERVICENAME);
            if (serviceName != null) {
                List<ServiceInfo> services = serviceBuilder.buildServices(definition, getServiceQName(definition));
                serviceList.addAll(services);
            } else if (definition.getServices().size() > 0) {
                serviceList = serviceBuilder.buildServices(definition);
            } else {
                serviceList = serviceBuilder.buildMockServices(definition);
            }
        } else {
            // TODO: wsdl2.0 support
            throw new ToolException("Only WSDL 1.1 supported");
        }
    }
    if (serviceList.isEmpty()) {
        throw new ToolException("Did not find any services in WSDL");
    }
    Map<String, InterfaceInfo> interfaces = new LinkedHashMap<String, InterfaceInfo>();
    ServiceInfo service0 = serviceList.get(0);
    SchemaCollection schemaCollection = service0.getXmlSchemaCollection();
    context.put(ToolConstants.XML_SCHEMA_COLLECTION, schemaCollection);
    context.put(ToolConstants.PORTTYPE_MAP, interfaces);
    context.put(ClassCollector.class, new ClassCollector());
    WSDLToJavaScriptProcessor processor = new WSDLToJavaScriptProcessor();
    for (ServiceInfo service : serviceList) {
        context.put(ServiceInfo.class, service);
        validate(service);
        processor.setEnvironment(context);
        processor.process();
    }
}
Also used : AbstractWSDLBuilder(org.apache.cxf.tools.wsdlto.core.AbstractWSDLBuilder) ClassCollector(org.apache.cxf.tools.util.ClassCollector) Definition(javax.wsdl.Definition) FrontEndProfile(org.apache.cxf.tools.wsdlto.core.FrontEndProfile) LinkedHashMap(java.util.LinkedHashMap) ServiceInfo(org.apache.cxf.service.model.ServiceInfo) WSDLConstants(org.apache.cxf.wsdl.WSDLConstants) WSDLServiceBuilder(org.apache.cxf.wsdl11.WSDLServiceBuilder) ArrayList(java.util.ArrayList) List(java.util.List) ToolException(org.apache.cxf.tools.common.ToolException) InterfaceInfo(org.apache.cxf.service.model.InterfaceInfo) SchemaCollection(org.apache.cxf.common.xmlschema.SchemaCollection) PluginLoader(org.apache.cxf.tools.wsdlto.core.PluginLoader)

Example 10 with SchemaCollection

use of org.apache.cxf.common.xmlschema.SchemaCollection in project cxf by apache.

the class ValidatorUtil method getSchemaList.

/**
 * Get a list of schemas found in a wsdl Document.
 * The list will include any schemas from imported wsdls.
 *
 * @param document The wsdl Document.
 * @param baseURI The URI of the wsdl. Allows schemas with relative
 *                paths to be resolved.
 * @return XmlSchemaCollection list
 * @throws IOException
 * @throws SAXException
 */
public static List<SchemaCollection> getSchemaList(Document document, String baseURI) throws IOException, SAXException {
    List<SchemaCollection> schemaList = new ArrayList<>();
    if (document == null) {
        return schemaList;
    }
    synchronized (document) {
        // URL might need encoding for special characters.
        baseURI = URLEncoder.encode(baseURI, "utf-8");
        SchemaCollection schemaCol = new SchemaCollection();
        schemaCol.setBaseUri(baseURI);
        List<Element> elemList = DOMUtils.findAllElementsByTagNameNS(document.getDocumentElement(), WSDLConstants.NS_SCHEMA_XSD, "schema");
        for (Element schemaEl : elemList) {
            String tns = schemaEl.getAttribute("targetNamespace");
            try {
                schemaCol.read(schemaEl, tns);
            } catch (RuntimeException ex) {
                LOG.log(Level.WARNING, "SCHEMA_READ_FAIL", tns);
                // in the baseURI here.
                try {
                    schemaCol.read(schemaEl, baseURI);
                } catch (RuntimeException ex2) {
                    LOG.log(Level.WARNING, "SCHEMA_READ_FAIL", baseURI);
                    continue;
                }
            }
        }
        schemaList.add(schemaCol);
        // Now add schemas from imported wsdl files.
        Map<String, Document> wsdlImports = getImportedWsdlMap(document, baseURI);
        for (Document wsdlImport : wsdlImports.values()) {
            schemaList.addAll(getSchemaList(wsdlImport, baseURI));
        }
    }
    return schemaList;
}
Also used : Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) SchemaCollection(org.apache.cxf.common.xmlschema.SchemaCollection) Document(org.w3c.dom.Document)

Aggregations

SchemaCollection (org.apache.cxf.common.xmlschema.SchemaCollection)23 ServiceInfo (org.apache.cxf.service.model.ServiceInfo)12 QName (javax.xml.namespace.QName)8 ArrayList (java.util.ArrayList)7 IOException (java.io.IOException)6 MessagePartInfo (org.apache.cxf.service.model.MessagePartInfo)6 XmlSchemaElement (org.apache.ws.commons.schema.XmlSchemaElement)5 HashMap (java.util.HashMap)4 LinkedHashMap (java.util.LinkedHashMap)4 Definition (javax.wsdl.Definition)4 Message (org.apache.cxf.common.i18n.Message)4 XmlSchema (org.apache.ws.commons.schema.XmlSchema)4 HashSet (java.util.HashSet)3 List (java.util.List)3 Map (java.util.Map)3 SchemaInfo (org.apache.cxf.service.model.SchemaInfo)3 ToolException (org.apache.cxf.tools.common.ToolException)3 XmlSchemaType (org.apache.ws.commons.schema.XmlSchemaType)3 File (java.io.File)2 URL (java.net.URL)2