Search in sources :

Example 11 with SchemaCollection

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

the class JAXBDataBinding method initialize.

public void initialize(ToolContext c) throws ToolException {
    this.context = c;
    checkEncoding(c);
    SchemaCompiler schemaCompiler = XJC.createSchemaCompiler();
    Bus bus = context.get(Bus.class);
    OASISCatalogManager catalog = bus.getExtension(OASISCatalogManager.class);
    Options opts = null;
    opts = getOptions(schemaCompiler);
    hackInNewInternalizationLogic(schemaCompiler, catalog, opts);
    ClassCollector classCollector = context.get(ClassCollector.class);
    ClassNameAllocatorImpl allocator = new ClassNameAllocatorImpl(classCollector, c.optionSet(ToolConstants.CFG_AUTORESOLVE));
    schemaCompiler.setClassNameAllocator(allocator);
    listener = new JAXBBindErrorListener(context.isVerbose(), context.getErrorListener());
    schemaCompiler.setErrorListener(listener);
    // Collection<SchemaInfo> schemas = serviceInfo.getSchemas();
    List<InputSource> jaxbBindings = context.getJaxbBindingFile();
    SchemaCollection schemas = (SchemaCollection) context.get(ToolConstants.XML_SCHEMA_COLLECTION);
    List<String> args = new ArrayList<>();
    if (context.get(ToolConstants.CFG_NO_ADDRESS_BINDING) == null) {
        // hard code to enable jaxb extensions
        args.add("-extension");
        String name = "/org/apache/cxf/tools/common/jaxb/W3CEPRJaxbBinding.xml";
        if (isJAXB22()) {
            name = "/org/apache/cxf/tools/common/jaxb/W3CEPRJaxbBinding_jaxb22.xml";
        }
        URL bindingFileUrl = getClass().getResource(name);
        InputSource ins = new InputSource(bindingFileUrl.toString());
        opts.addBindFile(ins);
    }
    if (context.get(ToolConstants.CFG_XJC_ARGS) != null) {
        Object o = context.get(ToolConstants.CFG_XJC_ARGS);
        if (o instanceof String) {
            o = new String[] { (String) o };
        }
        String[] xjcArgss = (String[]) o;
        for (String xjcArgs : xjcArgss) {
            StringTokenizer tokenizer = new StringTokenizer(xjcArgs, ",", false);
            while (tokenizer.hasMoreTokens()) {
                String arg = tokenizer.nextToken();
                args.add(arg);
                LOG.log(Level.FINE, "xjc arg:" + arg);
            }
        }
    }
    if (context.get(ToolConstants.CFG_NO_ADDRESS_BINDING) == null || context.get(ToolConstants.CFG_XJC_ARGS) != null) {
        try {
            // keep parseArguments happy, supply dummy required command-line
            // opts
            opts.addGrammar(new InputSource("null"));
            opts.parseArguments(args.toArray(new String[args.size()]));
        } catch (BadCommandLineException e) {
            StringBuilder msg = new StringBuilder("XJC reported 'BadCommandLineException' for -xjc argument:");
            for (String arg : args) {
                msg.append(arg + " ");
            }
            LOG.log(Level.FINE, msg.toString(), e);
            if (opts != null) {
                String pluginUsage = getPluginUsageString(opts);
                msg.append(System.getProperty("line.separator"));
                if (args.contains("-X")) {
                    throw new ToolException(pluginUsage, e);
                }
                msg.append(pluginUsage);
            }
            throw new ToolException(msg.toString(), e);
        }
    }
    if (context.optionSet(ToolConstants.CFG_MARK_GENERATED)) {
        // '-mark-generated' attribute to jaxb xjc.
        try {
            opts.parseArgument(new String[] { "-mark-generated" }, 0);
        } catch (BadCommandLineException e) {
            LOG.log(Level.SEVERE, e.getMessage());
            throw new ToolException(e);
        }
    }
    addSchemas(opts, schemaCompiler, schemas);
    addBindingFiles(opts, jaxbBindings, schemas);
    parseSchemas(schemaCompiler);
    rawJaxbModelGenCode = schemaCompiler.bind();
    addedEnumClassToCollector(schemas, allocator);
    if (context.get(ToolConstants.CFG_DEFAULT_VALUES) != null) {
        String cname = (String) context.get(ToolConstants.CFG_DEFAULT_VALUES);
        if (StringUtils.isEmpty(cname)) {
            defaultValues = new RandomValueProvider();
        } else {
            if (cname.charAt(0) == '=') {
                cname = cname.substring(1);
            }
            try {
                defaultValues = (DefaultValueProvider) Class.forName(cname).newInstance();
            } catch (Exception e) {
                LOG.log(Level.SEVERE, e.getMessage());
                throw new ToolException(e);
            }
        }
    }
    initialized = true;
}
Also used : Bus(org.apache.cxf.Bus) Options(com.sun.tools.xjc.Options) BadCommandLineException(com.sun.tools.xjc.BadCommandLineException) InputSource(org.xml.sax.InputSource) ClassCollector(org.apache.cxf.tools.util.ClassCollector) ArrayList(java.util.ArrayList) SchemaCompiler(com.sun.tools.xjc.api.SchemaCompiler) URL(java.net.URL) 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) StringTokenizer(java.util.StringTokenizer) OASISCatalogManager(org.apache.cxf.catalog.OASISCatalogManager) ToolException(org.apache.cxf.tools.common.ToolException) SchemaCollection(org.apache.cxf.common.xmlschema.SchemaCollection) RandomValueProvider(org.apache.cxf.tools.wsdlto.core.RandomValueProvider)

Example 12 with SchemaCollection

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

the class ProcessorUtil method getWrappedElement.

public static List<WrapperElement> getWrappedElement(ToolContext context, QName partElement) {
    List<WrapperElement> qnames = new ArrayList<>();
    ServiceInfo serviceInfo = context.get(ServiceInfo.class);
    SchemaCollection schema = serviceInfo.getXmlSchemaCollection();
    XmlSchemaElement elementByName = schema.getElementByQName(partElement);
    XmlSchemaComplexType type = (XmlSchemaComplexType) elementByName.getSchemaType();
    XmlSchemaSequence seq = (XmlSchemaSequence) type.getParticle();
    qnames.addAll(createWrappedElements(seq));
    // If it's extension
    if (seq == null && type.getContentModel() != null) {
        XmlSchemaContent xmlSchemaConent = type.getContentModel().getContent();
        if (xmlSchemaConent instanceof XmlSchemaComplexContentExtension) {
            XmlSchemaComplexContentExtension extension = (XmlSchemaComplexContentExtension) type.getContentModel().getContent();
            QName baseTypeName = extension.getBaseTypeName();
            XmlSchemaType schemaType = schema.getTypeByQName(baseTypeName);
            if (schemaType instanceof XmlSchemaComplexType) {
                XmlSchemaComplexType complexType = (XmlSchemaComplexType) schemaType;
                if (complexType.getParticle() instanceof XmlSchemaSequence) {
                    seq = (XmlSchemaSequence) complexType.getParticle();
                    qnames.addAll(createWrappedElements(seq));
                }
            }
            if (extension.getParticle() instanceof XmlSchemaSequence) {
                XmlSchemaSequence xmlSchemaSeq = (XmlSchemaSequence) extension.getParticle();
                qnames.addAll(createWrappedElements(xmlSchemaSeq));
            }
        }
    }
    return qnames;
}
Also used : ServiceInfo(org.apache.cxf.service.model.ServiceInfo) XmlSchemaSequence(org.apache.ws.commons.schema.XmlSchemaSequence) XmlSchemaComplexContentExtension(org.apache.ws.commons.schema.XmlSchemaComplexContentExtension) XmlSchemaElement(org.apache.ws.commons.schema.XmlSchemaElement) QName(javax.xml.namespace.QName) XmlSchemaContent(org.apache.ws.commons.schema.XmlSchemaContent) ArrayList(java.util.ArrayList) XmlSchemaComplexType(org.apache.ws.commons.schema.XmlSchemaComplexType) SchemaCollection(org.apache.cxf.common.xmlschema.SchemaCollection) XmlSchemaType(org.apache.ws.commons.schema.XmlSchemaType)

Example 13 with SchemaCollection

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

the class ProcessorUtil method isSchemaFormQualified.

public static boolean isSchemaFormQualified(ToolContext context, QName partElement) {
    ServiceInfo serviceInfo = context.get(ServiceInfo.class);
    SchemaCollection schemaCol = serviceInfo.getXmlSchemaCollection();
    XmlSchema schema = schemaCol.getSchemaForElement(partElement);
    if (schema != null) {
        return schema.getElementFormDefault() == XmlSchemaForm.QUALIFIED;
    }
    return false;
}
Also used : ServiceInfo(org.apache.cxf.service.model.ServiceInfo) XmlSchema(org.apache.ws.commons.schema.XmlSchema) SchemaCollection(org.apache.cxf.common.xmlschema.SchemaCollection)

Example 14 with SchemaCollection

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

the class WSDLToJavaContainer method processWsdl.

private void processWsdl() {
    validate(context);
    FrontEndProfile frontend = context.get(FrontEndProfile.class);
    if (frontend == null) {
        throw new ToolException(new Message("FOUND_NO_FRONTEND", LOG));
    }
    WSDLConstants.WSDLVersion version = getWSDLVersion();
    String wsdlURL = (String) context.get(ToolConstants.CFG_WSDLURL);
    @SuppressWarnings("unchecked") List<ServiceInfo> serviceList = (List<ServiceInfo>) context.get(ToolConstants.SERVICE_LIST);
    if (serviceList == null) {
        serviceList = new ArrayList<>();
        // 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());
            wsdlURL = URIParserUtil.getAbsoluteURI(wsdlURL);
            builder.build(wsdlURL);
            builder.customize();
            Definition definition = builder.getWSDLModel();
            context.put(Definition.class, definition);
            builder.validate(definition);
            WSDLServiceBuilder serviceBuilder = new WSDLServiceBuilder(getBus());
            if (context.isVerbose()) {
                serviceBuilder.setUnwrapLogLevel(Level.INFO);
            }
            serviceBuilder.setIgnoreUnknownBindings(true);
            String allowRefs = (String) context.get(ToolConstants.CFG_ALLOW_ELEMENT_REFS);
            if (!StringUtils.isEmpty(allowRefs) || context.optionSet(ToolConstants.CFG_ALLOW_ELEMENT_REFS)) {
                if (allowRefs.length() > 0 && allowRefs.charAt(0) == '=') {
                    allowRefs = allowRefs.substring(1);
                }
                if (StringUtils.isEmpty(allowRefs)) {
                    allowRefs = "true";
                }
                serviceBuilder.setAllowElementRefs(Boolean.valueOf(allowRefs));
            }
            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);
            }
            // remove definition from cache so that won't fail when encounter same wsdl file
            // name but different wsdl content(CXF-3340)
            getBus().getExtension(WSDLManager.class).removeDefinition(definition);
        } else {
        // TODO: wsdl2.0 support
        }
    }
    context.put(ToolConstants.SERVICE_LIST, serviceList);
    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, createClassCollector());
    Processor processor = frontend.getProcessor();
    if (processor instanceof ClassNameProcessor) {
        processor.setEnvironment(context);
        for (ServiceInfo service : serviceList) {
            context.put(ServiceInfo.class, service);
            ((ClassNameProcessor) processor).processClassNames();
            context.put(ServiceInfo.class, null);
        }
    }
    if (context.optionSet(ToolConstants.CFG_NO_TYPES)) {
        context.remove(ToolConstants.CFG_TYPES);
        context.remove(ToolConstants.CFG_ALL);
        context.remove(ToolConstants.CFG_COMPILE);
    }
    generateTypes();
    if (context.getErrorListener().getErrorCount() > 0) {
        return;
    }
    for (ServiceInfo service : serviceList) {
        context.put(ServiceInfo.class, service);
        if (context.basicValidateWSDL()) {
            validate(service);
        }
        if (context.getErrorListener().getErrorCount() == 0) {
            // Build the JavaModel from the ServiceModel
            processor.setEnvironment(context);
            processor.process();
        }
    }
    if (context.getErrorListener().getErrorCount() > 0) {
        return;
    }
    if (context.optionSet(ToolConstants.CFG_CLIENT_JAR)) {
        enforceWSDLLocation(context);
    }
    if (!isSuppressCodeGen()) {
        // Generate artifacts
        for (FrontEndGenerator generator : frontend.getGenerators()) {
            generator.generate(context);
        }
    }
    context.remove(ToolConstants.SERVICE_LIST);
    // Build projects: compile classes and copy resources etc.
    if (context.optionSet(ToolConstants.CFG_COMPILE)) {
        new ClassUtils().compile(context);
    }
    if (context.isExcludeNamespaceEnabled()) {
        try {
            removeExcludeFiles();
        } catch (IOException e) {
            throw new ToolException(e);
        }
    }
    if (context.optionSet(ToolConstants.CFG_CLIENT_JAR)) {
        processClientJar(context);
    }
}
Also used : AbstractWSDLBuilder(org.apache.cxf.tools.wsdlto.core.AbstractWSDLBuilder) ClassNameProcessor(org.apache.cxf.tools.common.ClassNameProcessor) Processor(org.apache.cxf.tools.common.Processor) Message(org.apache.cxf.common.i18n.Message) Definition(javax.wsdl.Definition) IOException(java.io.IOException) ClassUtils(org.apache.cxf.tools.common.ClassUtils) 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) FrontEndGenerator(org.apache.cxf.tools.common.FrontEndGenerator) WSDLManager(org.apache.cxf.wsdl.WSDLManager) ClassNameProcessor(org.apache.cxf.tools.common.ClassNameProcessor) List(java.util.List) ArrayList(java.util.ArrayList) ToolException(org.apache.cxf.tools.common.ToolException) InterfaceInfo(org.apache.cxf.service.model.InterfaceInfo) SchemaCollection(org.apache.cxf.common.xmlschema.SchemaCollection)

Example 15 with SchemaCollection

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

the class WSDLToJavaContainer method generateLocalWSDL.

@SuppressWarnings("unchecked")
private void generateLocalWSDL(ToolContext context) {
    String outputdir = (String) context.get(ToolConstants.CFG_CLASSDIR);
    File wsdlFile = new File(outputdir, (String) context.get(ToolConstants.CFG_WSDLLOCATION));
    Definition def = context.get(Definition.class);
    try {
        // get imported schemas
        int xsdCount = 0;
        SchemaCollection schemas = (SchemaCollection) context.get(ToolConstants.XML_SCHEMA_COLLECTION);
        Map<String, String> sourceMap = new HashMap<>();
        for (XmlSchema imp : schemas.getXmlSchemas()) {
            if (imp.getSourceURI() != null && !imp.getSourceURI().contains(".wsdl#")) {
                String schemaFileName = "schema" + (++xsdCount) + ".xsd";
                sourceMap.put(imp.getTargetNamespace(), schemaFileName);
            }
        }
        // get imported wsdls
        int wsdlImportCount = 0;
        List<Definition> defs = (List<Definition>) context.get(ToolConstants.IMPORTED_DEFINITION);
        Map<String, String> importWSDLMap = new HashMap<>();
        for (Definition importDef : defs) {
            File importedWsdlFile = null;
            if (!StringUtils.isEmpty(importDef.getDocumentBaseURI())) {
                importedWsdlFile = new File(importDef.getDocumentBaseURI());
            } else {
                importedWsdlFile = new File(importDef.getQName().getLocalPart() + ".wsdl");
            }
            if (!FileUtils.isValidFileName(importedWsdlFile.getName())) {
                importedWsdlFile = new File("import" + (++wsdlImportCount) + ".wsdl");
            }
            importWSDLMap.put(importDef.getTargetNamespace(), importedWsdlFile.getName());
        }
        OutputStreamCreator outputStreamCreator = null;
        if (context.get(OutputStreamCreator.class) != null) {
            outputStreamCreator = context.get(OutputStreamCreator.class);
        } else {
            outputStreamCreator = new OutputStreamCreator();
            context.put(OutputStreamCreator.class, outputStreamCreator);
        }
        Writer os = null;
        for (XmlSchema imp : schemas.getXmlSchemas()) {
            if (imp.getSourceURI() != null && !imp.getSourceURI().contains(".wsdl#")) {
                String schemaFileName = sourceMap.get(imp.getTargetNamespace());
                File impfile = new File(wsdlFile.getParentFile(), schemaFileName);
                Element el = imp.getSchemaDocument().getDocumentElement();
                updateImports(el, sourceMap);
                os = new FileWriterUtil(impfile.getParent(), context.get(OutputStreamCreator.class)).getWriter(impfile, StandardCharsets.UTF_8.name());
                StaxUtils.writeTo(el, os, 2);
                os.close();
            }
        }
        // change the import location in wsdl file
        OutputStream wsdloutput = new BufferedOutputStream(Files.newOutputStream(wsdlFile.toPath()));
        WSDLWriter wsdlWriter = WSDLFactory.newInstance().newWSDLWriter();
        LoadingByteArrayOutputStream bout = new LoadingByteArrayOutputStream();
        wsdlWriter.writeWSDL(def, bout);
        Element defEle = StaxUtils.read(bout.createInputStream()).getDocumentElement();
        List<Element> xsdElements = DOMUtils.findAllElementsByTagNameNS(defEle, WSDLConstants.NS_SCHEMA_XSD, "schema");
        for (Element xsdEle : xsdElements) {
            updateImports(xsdEle, sourceMap);
        }
        updateWSDLImports(defEle, importWSDLMap);
        StaxUtils.writeTo(defEle, wsdloutput);
        wsdloutput.close();
        for (Definition importDef : defs) {
            File importWsdlFile = new File(outputdir, importWSDLMap.get(importDef.getTargetNamespace()));
            OutputStream wsdlOs = new BufferedOutputStream(Files.newOutputStream(importWsdlFile.toPath()));
            bout = new LoadingByteArrayOutputStream();
            wsdlWriter.writeWSDL(importDef, bout);
            Element importEle = StaxUtils.read(bout.createInputStream()).getDocumentElement();
            xsdElements = DOMUtils.findAllElementsByTagNameNS(importEle, WSDLConstants.NS_SCHEMA_XSD, "schema");
            for (Element xsdEle : xsdElements) {
                updateImports(xsdEle, sourceMap);
            }
            updateWSDLImports(importEle, importWSDLMap);
            StaxUtils.writeTo(importEle, wsdlOs);
            wsdlOs.close();
        }
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, "FAILED_TO_GEN_LOCAL_WSDL", ex);
        Message msg = new Message("FAILED_TO_GEN_LOCAL_WSDL", LOG);
        throw new ToolException(msg, ex);
    }
}
Also used : Message(org.apache.cxf.common.i18n.Message) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) FileWriterUtil(org.apache.cxf.tools.util.FileWriterUtil) Element(org.w3c.dom.Element) LoadingByteArrayOutputStream(org.apache.cxf.helpers.LoadingByteArrayOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) JarOutputStream(java.util.jar.JarOutputStream) OutputStream(java.io.OutputStream) Definition(javax.wsdl.Definition) WSDLWriter(javax.wsdl.xml.WSDLWriter) BadUsageException(org.apache.cxf.tools.common.toolspec.parser.BadUsageException) IOException(java.io.IOException) ToolException(org.apache.cxf.tools.common.ToolException) LoadingByteArrayOutputStream(org.apache.cxf.helpers.LoadingByteArrayOutputStream) XmlSchema(org.apache.ws.commons.schema.XmlSchema) List(java.util.List) ArrayList(java.util.ArrayList) OutputStreamCreator(org.apache.cxf.tools.util.OutputStreamCreator) ToolException(org.apache.cxf.tools.common.ToolException) SchemaCollection(org.apache.cxf.common.xmlschema.SchemaCollection) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream) Writer(java.io.Writer) WSDLWriter(javax.wsdl.xml.WSDLWriter)

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