Search in sources :

Example 1 with XmlSchemaWalker

use of com.twinsoft.convertigo.engine.util.XmlSchemaWalker in project convertigo by convertigo.

the class Migration7_0_0 method migrate.

public static void migrate(final String projectName) {
    try {
        Map<String, Reference> referenceMap = new HashMap<String, Reference>();
        XmlSchema projectSchema = null;
        Project project = Engine.theApp.databaseObjectsManager.getOriginalProjectByName(projectName, false);
        // Copy all xsd files to project's xsd directory
        File destDir = new File(project.getXsdDirPath());
        copyXsdOfProject(projectName, destDir);
        String projectWsdlFilePath = Engine.PROJECTS_PATH + "/" + projectName + "/" + projectName + ".wsdl";
        File wsdlFile = new File(projectWsdlFilePath);
        String projectXsdFilePath = Engine.PROJECTS_PATH + "/" + projectName + "/" + projectName + ".xsd";
        File xsdFile = new File(projectXsdFilePath);
        if (xsdFile.exists()) {
            // Load project schema from old XSD file
            XmlSchemaCollection collection = new XmlSchemaCollection();
            collection.setSchemaResolver(new DefaultURIResolver() {

                public InputSource resolveEntity(String targetNamespace, String schemaLocation, String baseUri) {
                    // Case of a c8o project location
                    if (schemaLocation.startsWith("../") && schemaLocation.endsWith(".xsd")) {
                        try {
                            String targetProjectName = schemaLocation.substring(3, schemaLocation.indexOf("/", 3));
                            File pDir = new File(Engine.projectDir(targetProjectName));
                            if (pDir.exists()) {
                                File pFile = new File(Engine.PROJECTS_PATH + schemaLocation.substring(2));
                                // Case c8o project is already migrated
                                if (!pFile.exists()) {
                                    Document doc = Engine.theApp.schemaManager.getSchemaForProject(targetProjectName).getSchemaDocument();
                                    DOMSource source = new DOMSource(doc);
                                    StringWriter writer = new StringWriter();
                                    StreamResult result = new StreamResult(writer);
                                    TransformerFactory.newInstance().newTransformer().transform(source, result);
                                    StringReader reader = new StringReader(writer.toString());
                                    return new InputSource(reader);
                                }
                            }
                            return null;
                        } catch (Exception e) {
                            Engine.logDatabaseObjectManager.warn("[Migration 7.0.0] Unable to find schema location \"" + schemaLocation + "\"", e);
                            return null;
                        }
                    } else if (schemaLocation.indexOf("://") == -1 && schemaLocation.endsWith(".xsd")) {
                        return super.resolveEntity(targetNamespace, schemaLocation, Engine.PROJECTS_PATH + "/" + projectName);
                    }
                    return super.resolveEntity(targetNamespace, schemaLocation, baseUri);
                }
            });
            projectSchema = SchemaUtils.loadSchema(new File(projectXsdFilePath), collection);
            ConvertigoError.updateXmlSchemaObjects(projectSchema);
            SchemaMeta.setCollection(projectSchema, collection);
            for (Connector connector : project.getConnectorsList()) {
                for (Transaction transaction : connector.getTransactionsList()) {
                    try {
                        // Migrate transaction in case of a Web Service consumption project
                        if (transaction instanceof XmlHttpTransaction) {
                            XmlHttpTransaction xmlHttpTransaction = (XmlHttpTransaction) transaction;
                            String reqn = xmlHttpTransaction.getResponseElementQName();
                            if (!reqn.equals("")) {
                                boolean useRef = reqn.indexOf(";") == -1;
                                // Doc/Literal case
                                if (useRef) {
                                    try {
                                        String[] qn = reqn.split(":");
                                        QName refName = new QName(projectSchema.getNamespaceContext().getNamespaceURI(qn[0]), qn[1]);
                                        xmlHttpTransaction.setXmlElementRefAffectation(new XmlQName(refName));
                                    } catch (Exception e) {
                                    }
                                } else // RPC case
                                {
                                    int index, index2;
                                    try {
                                        index = reqn.indexOf(";");
                                        String opName = reqn.substring(0, index);
                                        if ((index2 = reqn.indexOf(";", index + 1)) != -1) {
                                            String eltName = reqn.substring(index + 1, index2);
                                            String eltType = reqn.substring(index2 + 1);
                                            String[] qn = eltType.split(":");
                                            QName typeName = new QName(projectSchema.getNamespaceContext().getNamespaceURI(qn[0]), qn[1]);
                                            String responseElementQName = opName + ";" + eltName + ";" + "{" + typeName.getNamespaceURI() + "}" + typeName.getLocalPart();
                                            xmlHttpTransaction.setResponseElementQName(responseElementQName);
                                        }
                                    } catch (Exception e) {
                                    }
                                }
                            }
                        }
                        // Retrieve required XmlSchemaObjects for transaction
                        QName requestQName = new QName(project.getTargetNamespace(), transaction.getXsdRequestElementName());
                        QName responseQName = new QName(project.getTargetNamespace(), transaction.getXsdResponseElementName());
                        LinkedHashMap<QName, XmlSchemaObject> map = new LinkedHashMap<QName, XmlSchemaObject>();
                        XmlSchemaWalker dw = XmlSchemaWalker.newDependencyWalker(map, true, false);
                        dw.walkByElementRef(projectSchema, requestQName);
                        dw.walkByElementRef(projectSchema, responseQName);
                        // Create transaction schema
                        String targetNamespace = projectSchema.getTargetNamespace();
                        String prefix = projectSchema.getNamespaceContext().getPrefix(targetNamespace);
                        XmlSchema transactionSchema = SchemaUtils.createSchema(prefix, targetNamespace, XsdForm.unqualified.name(), XsdForm.unqualified.name());
                        // Add required prefix declarations
                        List<String> nsList = new LinkedList<String>();
                        for (QName qname : map.keySet()) {
                            String nsURI = qname.getNamespaceURI();
                            if (!nsURI.equals(Constants.URI_2001_SCHEMA_XSD)) {
                                if (!nsList.contains(nsURI)) {
                                    nsList.add(nsURI);
                                }
                            }
                            String nsPrefix = qname.getPrefix();
                            if (!nsURI.equals(targetNamespace)) {
                                NamespaceMap nsMap = SchemaUtils.getNamespaceMap(transactionSchema);
                                if (nsMap.getNamespaceURI(nsPrefix) == null) {
                                    nsMap.add(nsPrefix, nsURI);
                                    transactionSchema.setNamespaceContext(nsMap);
                                }
                            }
                        }
                        // Add required imports
                        for (String namespaceURI : nsList) {
                            XmlSchemaObjectCollection includes = projectSchema.getIncludes();
                            for (int i = 0; i < includes.getCount(); i++) {
                                XmlSchemaObject xmlSchemaObject = includes.getItem(i);
                                if (xmlSchemaObject instanceof XmlSchemaImport) {
                                    if (((XmlSchemaImport) xmlSchemaObject).getNamespace().equals(namespaceURI)) {
                                        // do not allow import with same ns !
                                        if (namespaceURI.equals(project.getTargetNamespace()))
                                            continue;
                                        String location = ((XmlSchemaImport) xmlSchemaObject).getSchemaLocation();
                                        // This is a convertigo project reference
                                        if (location.startsWith("../")) {
                                            // Copy all xsd files to xsd directory
                                            String targetProjectName = location.substring(3, location.indexOf("/", 3));
                                            copyXsdOfProject(targetProjectName, destDir);
                                        }
                                        // Add reference
                                        addReferenceToMap(referenceMap, namespaceURI, location);
                                        // Add import
                                        addImport(transactionSchema, namespaceURI, location);
                                    }
                                }
                            }
                        }
                        QName responseTypeQName = new QName(project.getTargetNamespace(), transaction.getXsdResponseTypeName());
                        // Add required schema objects
                        for (QName qname : map.keySet()) {
                            if (qname.getNamespaceURI().equals(targetNamespace)) {
                                XmlSchemaObject ob = map.get(qname);
                                if (qname.getLocalPart().startsWith("ConvertigoError"))
                                    continue;
                                transactionSchema.getItems().add(ob);
                                // Add missing response error element and attributes
                                if (qname.equals(responseTypeQName)) {
                                    Transaction.addSchemaResponseObjects(transactionSchema, (XmlSchemaComplexType) ob);
                                }
                            }
                        }
                        // Add missing ResponseType (with document)
                        if (map.containsKey(responseTypeQName)) {
                            Transaction.addSchemaResponseType(transactionSchema, transaction);
                        }
                        // Add everything
                        if (map.isEmpty()) {
                            Transaction.addSchemaObjects(transactionSchema, transaction);
                        }
                        // Add c8o error objects (for internal xsd edition only)
                        ConvertigoError.updateXmlSchemaObjects(transactionSchema);
                        // Save schema to file
                        String transactionXsdFilePath = transaction.getSchemaFilePath();
                        new File(transaction.getSchemaFileDirPath()).mkdirs();
                        SchemaUtils.saveSchema(transactionXsdFilePath, transactionSchema);
                    } catch (Exception e) {
                        Engine.logDatabaseObjectManager.error("[Migration 7.0.0] An error occured while migrating transaction \"" + transaction.getName() + "\"", e);
                    }
                    if (transaction instanceof TransactionWithVariables) {
                        TransactionWithVariables transactionVars = (TransactionWithVariables) transaction;
                        handleRequestableVariable(transactionVars.getVariablesList());
                        // Change SQLQuery variables : i.e. {id} --> {{id}}
                        if (transaction instanceof SqlTransaction) {
                            String sqlQuery = ((SqlTransaction) transaction).getSqlQuery();
                            sqlQuery = sqlQuery.replaceAll("\\{([a-zA-Z0-9_]+)\\}", "{{$1}}");
                            ((SqlTransaction) transaction).setSqlQuery(sqlQuery);
                        }
                    }
                }
            }
        } else {
            // Should only happen for projects which version <= 4.6.0
            XmlSchemaCollection collection = new XmlSchemaCollection();
            String prefix = project.getName() + "_ns";
            projectSchema = SchemaUtils.createSchema(prefix, project.getNamespaceUri(), XsdForm.unqualified.name(), XsdForm.unqualified.name());
            ConvertigoError.addXmlSchemaObjects(projectSchema);
            SchemaMeta.setCollection(projectSchema, collection);
            for (Connector connector : project.getConnectorsList()) {
                for (Transaction transaction : connector.getTransactionsList()) {
                    if (transaction instanceof TransactionWithVariables) {
                        TransactionWithVariables transactionVars = (TransactionWithVariables) transaction;
                        handleRequestableVariable(transactionVars.getVariablesList());
                    }
                }
            }
        }
        // Handle sequence objects
        for (Sequence sequence : project.getSequencesList()) {
            handleSteps(projectSchema, referenceMap, sequence.getSteps());
            handleRequestableVariable(sequence.getVariablesList());
        }
        // Add all references to project
        if (!referenceMap.isEmpty()) {
            for (Reference reference : referenceMap.values()) project.add(reference);
        }
        // Delete XSD file
        if (xsdFile.exists())
            xsdFile.delete();
        // Delete WSDL file
        if (wsdlFile.exists())
            wsdlFile.delete();
    } catch (Exception e) {
        Engine.logDatabaseObjectManager.error("[Migration 7.0.0] An error occured while migrating project \"" + projectName + "\"", e);
    }
}
Also used : Connector(com.twinsoft.convertigo.beans.core.Connector) InputSource(org.xml.sax.InputSource) DOMSource(javax.xml.transform.dom.DOMSource) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Document(org.w3c.dom.Document) LinkedHashMap(java.util.LinkedHashMap) XmlSchemaWalker(com.twinsoft.convertigo.engine.util.XmlSchemaWalker) StringWriter(java.io.StringWriter) XmlSchemaObject(org.apache.ws.commons.schema.XmlSchemaObject) DefaultURIResolver(org.apache.ws.commons.schema.resolver.DefaultURIResolver) StringReader(java.io.StringReader) XmlSchemaImport(org.apache.ws.commons.schema.XmlSchemaImport) XmlSchemaObjectCollection(org.apache.ws.commons.schema.XmlSchemaObjectCollection) StreamResult(javax.xml.transform.stream.StreamResult) Reference(com.twinsoft.convertigo.beans.core.Reference) ProjectSchemaReference(com.twinsoft.convertigo.beans.references.ProjectSchemaReference) ImportXsdSchemaReference(com.twinsoft.convertigo.beans.references.ImportXsdSchemaReference) XmlHttpTransaction(com.twinsoft.convertigo.beans.transactions.XmlHttpTransaction) XmlQName(com.twinsoft.convertigo.beans.common.XmlQName) QName(javax.xml.namespace.QName) SqlTransaction(com.twinsoft.convertigo.beans.transactions.SqlTransaction) XmlSchemaSequence(org.apache.ws.commons.schema.XmlSchemaSequence) Sequence(com.twinsoft.convertigo.beans.core.Sequence) XmlSchemaCollection(org.apache.ws.commons.schema.XmlSchemaCollection) EngineException(com.twinsoft.convertigo.engine.EngineException) IOException(java.io.IOException) LinkedList(java.util.LinkedList) Project(com.twinsoft.convertigo.beans.core.Project) XmlQName(com.twinsoft.convertigo.beans.common.XmlQName) SqlTransaction(com.twinsoft.convertigo.beans.transactions.SqlTransaction) XmlHttpTransaction(com.twinsoft.convertigo.beans.transactions.XmlHttpTransaction) Transaction(com.twinsoft.convertigo.beans.core.Transaction) XmlSchema(org.apache.ws.commons.schema.XmlSchema) NamespaceMap(org.apache.ws.commons.schema.utils.NamespaceMap) TransactionWithVariables(com.twinsoft.convertigo.beans.core.TransactionWithVariables) File(java.io.File)

Example 2 with XmlSchemaWalker

use of com.twinsoft.convertigo.engine.util.XmlSchemaWalker in project convertigo by convertigo.

the class SchemaManager method makeResponse.

public synchronized Document makeResponse(Document document) {
    try {
        Element documentElement = document.getDocumentElement();
        if (documentElement != null) {
            String project = documentElement.getAttribute("project");
            String sequence = documentElement.getAttribute("sequence");
            String connector = documentElement.getAttribute("connector");
            String transaction = documentElement.getAttribute("transaction");
            XmlSchema schema = getSchemaForProject(project);
            XmlSchemaCollection collection = SchemaMeta.getCollection(schema);
            String targetNamespace = schema.getTargetNamespace();
            String prefix = collection.getNamespaceContext().getPrefix(targetNamespace);
            String requestableName = sequence != null && sequence.length() > 0 ? sequence : connector + "__" + transaction;
            String tagname = prefix + ":" + requestableName + "Response";
            QName qname = new QName(targetNamespace, requestableName + "Response");
            Project p = Engine.theApp.databaseObjectsManager.getOriginalProjectByName(project);
            boolean isIncludeResponseElement = true;
            if (!"".equals(sequence)) {
                try {
                    Sequence seqObj = p.getSequenceByName(sequence);
                    isIncludeResponseElement = seqObj.isIncludeResponseElement();
                } catch (Exception e) {
                }
            }
            Document responseDoc = XMLUtils.getDefaultDocumentBuilder().newDocument();
            Element requestableResponse = responseDoc.createElementNS(targetNamespace, tagname);
            if (isIncludeResponseElement) {
                Node renamed = responseDoc.renameNode(responseDoc.importNode(documentElement, true), "", "response");
                requestableResponse.appendChild(renamed);
            } else {
                NodeList children = documentElement.getChildNodes();
                for (int i = 0; i < children.getLength(); i++) {
                    requestableResponse.appendChild(responseDoc.importNode(children.item(i), true));
                }
            }
            final Map<XmlSchemaObject, List<List<XmlSchemaObject>>> map = new LinkedHashMap<XmlSchemaObject, List<List<XmlSchemaObject>>>();
            new XmlSchemaWalker(true, true) {

                List<XmlSchemaObject> elist = null;

                List<XmlSchemaObject> alist = null;

                Map<QName, XmlSchemaObject> mso = new HashMap<QName, XmlSchemaObject>();

                Map<QName, XmlSchemaObject> mto = new HashMap<QName, XmlSchemaObject>();

                public void init(XmlSchema xmlSchema, QName qname, Element element) {
                    XmlSchemaElement rxe = SchemaMeta.getCollection(xmlSchema).getElementByQName(qname);
                    if (rxe != null) {
                        List<List<XmlSchemaObject>> list = new ArrayList<List<XmlSchemaObject>>();
                        list.add(new ArrayList<XmlSchemaObject>());
                        list.add(new ArrayList<XmlSchemaObject>());
                        map.put(rxe, list);
                        mso.put(qname, rxe);
                        elist = list.get(0);
                        alist = list.get(1);
                        walkElement(xmlSchema, rxe);
                        /*for (XmlSchemaObject xso: map.keySet()) {
								System.out.println(((XmlSchemaElement)xso).getName());
								System.out.print("\t[");
								for (XmlSchemaObject child: map.get(xso).get(1)) {
									System.out.print(((XmlSchemaAttribute)child).getName()+",");
								}
								System.out.println("]");
								for (XmlSchemaObject child: map.get(xso).get(0)) {
									System.out.println("\t"+((XmlSchemaElement)child).getName());
								}
							}*/
                        makeCompliant(rxe, element);
                    }
                }

                protected boolean makeCompliant(XmlSchemaObject xso, Node node) {
                    String tns = node.getNamespaceURI();
                    String nodeName = node.getNodeName();
                    String localName = nodeName.substring(nodeName.indexOf(":") + 1);
                    String xsoName = xso instanceof XmlSchemaElement ? ((XmlSchemaElement) xso).getName() : ((XmlSchemaAttribute) xso).getName();
                    if (xsoName.equals(localName)) {
                        Document doc = node.getOwnerDocument();
                        QName xsoQName = xso instanceof XmlSchemaElement ? ((XmlSchemaElement) xso).getQName() : ((XmlSchemaAttribute) xso).getQName();
                        boolean elementQualified = SchemaMeta.getSchema(xso).getElementFormDefault().getValue().equals("qualified");
                        boolean attributeQualified = SchemaMeta.getSchema(xso).getAttributeFormDefault().getValue().equals("qualified");
                        boolean isQualified = (xsoQName != null && !xsoQName.getNamespaceURI().equals("")) || (xso instanceof XmlSchemaElement ? elementQualified : attributeQualified);
                        // String targetNamespace = SchemaMeta.getSchema(xso).getTargetNamespace();
                        // String prefix = SchemaMeta.getCollection(xso).getNamespaceContext().getPrefix(targetNamespace);
                        String targetNamespace = xsoQName != null && !xsoQName.getNamespaceURI().equals("") ? xsoQName.getNamespaceURI() : SchemaMeta.getSchema(xso).getTargetNamespace();
                        String prefix = SchemaMeta.getCollection(xso).getNamespaceContext().getPrefix(targetNamespace);
                        prefix = prefix == null ? (xsoQName != null && !xsoQName.getNamespaceURI().equals("") ? xsoQName.getPrefix() : "") : prefix;
                        if (isQualified)
                            node = doc.renameNode(node, targetNamespace, prefix + ":" + localName);
                        else
                            node = doc.renameNode(node, "", localName);
                        if (node.getNodeType() == Node.ELEMENT_NODE) {
                            Element element = (Element) node;
                            if (element.hasAttributes()) {
                                NamedNodeMap attributes = element.getAttributes();
                                List<Node> list = new ArrayList<Node>();
                                for (int i = 0; i < attributes.getLength(); i++) {
                                    Node attr = attributes.item(i);
                                    String attrNodeName = attr.getNodeName();
                                    boolean found = false;
                                    for (XmlSchemaObject a : map.get(xso).get(1)) {
                                        if (makeCompliant(a, attr)) {
                                            found = true;
                                            break;
                                        }
                                    }
                                    if (!found) {
                                        if (attrNodeName.equals("xsi:type") || attrNodeName.startsWith("xmlns:") || attrNodeName.endsWith(":encodingStyle")) {
                                            list.add(attr);
                                        }
                                    } else {
                                        if (attrNodeName.startsWith("xsi:")) {
                                            attr = doc.renameNode(attr, Constants.URI_2001_SCHEMA_XSI, attrNodeName);
                                            String attrNodeValue = attr.getNodeValue();
                                            int index = attrNodeValue.indexOf(":");
                                            if (index != -1) {
                                                String pref = attrNodeValue.substring(0, index);
                                                if (attributes.getNamedItem("xmlns:" + pref) == null) {
                                                    String ns = SchemaMeta.getCollection(xso).getNamespaceContext().getNamespaceURI(pref);
                                                    if ("".equals(ns) || ns == null)
                                                        ns = SchemaMeta.getSchema(xso).getTargetNamespace();
                                                    element.setAttributeNS(Constants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:" + pref, ns);
                                                }
                                            }
                                        }
                                        if (attrNodeName.startsWith("xmlns:")) {
                                            attr = doc.renameNode(attr, Constants.XMLNS_ATTRIBUTE_NS_URI, attrNodeName);
                                        }
                                    }
                                }
                                for (Node attr : list) {
                                    element.removeAttributeNode((Attr) attr);
                                }
                            }
                            if (element.hasChildNodes()) {
                                NodeList children = element.getChildNodes();
                                for (int i = 0; i < children.getLength(); i++) {
                                    if (children.item(i).getNodeType() == Node.TEXT_NODE)
                                        continue;
                                    // System.out.println("element: "+children.item(i).getNodeName());
                                    for (XmlSchemaObject e : map.get(xso).get(0)) {
                                        // System.out.println(" test "+((XmlSchemaElement)e).getName());
                                        if (makeCompliant(e, children.item(i))) {
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        return true;
                    } else {
                        // System.out.println(nodeName);
                        if ((tns != null) && !tns.equals("")) {
                            Document doc = node.getOwnerDocument();
                            String prefix = SchemaMeta.getCollection(xso).getNamespaceContext().getPrefix(tns);
                            if ((prefix != null) && !prefix.equals("")) {
                                node = doc.renameNode(node, tns, prefix + ":" + localName);
                            }
                        }
                    }
                    return false;
                }

                @Override
                public void walkByTypeName(XmlSchema xmlSchema, QName qname) {
                    XmlSchemaType obj = SchemaMeta.getCollection(xmlSchema).getTypeByQName(qname);
                    if (obj != null) {
                        if (!mso.containsKey(qname)) {
                            mso.put(qname, obj);
                            super.walkByTypeName(xmlSchema, qname);
                        } else {
                            if (mto.containsKey(qname)) {
                                // System.out.println("\nWalk type "+ qname);
                                elist.addAll(map.get(mto.get(qname)).get(0));
                            }
                        }
                    }
                }

                @Override
                public void walkByElementRef(XmlSchema xmlSchema, QName qname) {
                    XmlSchemaElement obj = SchemaMeta.getCollection(xmlSchema).getElementByQName(qname);
                    if (obj != null) {
                        if (!mso.containsKey(qname)) {
                            mso.put(qname, obj);
                            super.walkByElementRef(xmlSchema, qname);
                        } else {
                            if (mto.containsKey(qname)) {
                                // System.out.println("\nWalk elem ref "+ qname);
                                elist.add(mto.get(qname));
                            }
                        }
                    }
                }

                @Override
                public void walkByAttributeGroupRef(XmlSchema xmlSchema, QName qname) {
                    XmlSchema schema = SchemaMeta.getCollection(xmlSchema).schemaForNamespace(qname.getNamespaceURI());
                    XmlSchemaAttributeGroup obj = (XmlSchemaAttributeGroup) schema.getAttributeGroups().getItem(qname);
                    if (obj != null) {
                        if (!mso.containsKey(qname)) {
                            mso.put(qname, obj);
                            super.walkByAttributeGroupRef(xmlSchema, qname);
                        }
                    }
                }

                @Override
                public void walkByAttributeRef(XmlSchema xmlSchema, QName qname) {
                    XmlSchemaAttribute obj = SchemaMeta.getCollection(xmlSchema).getAttributeByQName(qname);
                    if (obj != null) {
                        if (!mso.containsKey(qname)) {
                            mso.put(qname, obj);
                            super.walkByAttributeRef(xmlSchema, qname);
                        } else {
                            if (mto.containsKey(qname)) {
                                // System.out.println("\nWalk attr ref "+ qname);
                                alist.add(mto.get(qname));
                            }
                        }
                    }
                }

                @Override
                public void walkByGroupRef(XmlSchema xmlSchema, QName qname) {
                    XmlSchema schema = SchemaMeta.getCollection(xmlSchema).schemaForNamespace(qname.getNamespaceURI());
                    XmlSchemaGroup obj = (XmlSchemaGroup) schema.getGroups().getItem(qname);
                    if (obj != null) {
                        if (!mso.containsKey(qname)) {
                            mso.put(qname, obj);
                            super.walkByGroupRef(xmlSchema, qname);
                        }
                    }
                }

                @Override
                protected void walkElement(XmlSchema xmlSchema, XmlSchemaElement obj) {
                    List<XmlSchemaObject> el = elist;
                    List<XmlSchemaObject> al = alist;
                    QName qname = obj.getQName();
                    QName refName = obj.getRefName();
                    QName typeName = obj.getSchemaTypeName();
                    if (refName == null) {
                        el.add(obj);
                        List<List<XmlSchemaObject>> list = new ArrayList<List<XmlSchemaObject>>();
                        list.add(new ArrayList<XmlSchemaObject>());
                        list.add(new ArrayList<XmlSchemaObject>());
                        map.put(obj, list);
                        // System.out.print("\nname="+obj.getName());
                        String ns = SchemaMeta.getSchema(obj).getTargetNamespace();
                        if (typeName != null) {
                            if (!mto.containsKey(typeName)) {
                                if (typeName.getNamespaceURI().equals(Constants.URI_2001_SCHEMA_XSD)) {
                                    typeName = new QName(ns, obj.getName());
                                }
                                mto.put(typeName, obj);
                            // System.out.print("; typeN="+typeName);
                            } else {
                                map.put(obj, map.get(mto.get(typeName)));
                                // type already done
                                return;
                            }
                        } else {
                            if (qname != null) {
                                if (qname.getNamespaceURI().equals("")) {
                                    qname = new QName(ns, obj.getName());
                                }
                            } else
                                qname = new QName(ns, obj.getName());
                            if (!mto.containsKey(qname)) {
                                mto.put(qname, obj);
                            // System.out.print("; qname="+qname);
                            }
                        }
                        elist = list.get(0);
                        alist = list.get(1);
                        super.walkElement(xmlSchema, obj);
                        elist = el;
                        alist = al;
                    } else {
                        super.walkElement(xmlSchema, obj);
                        elist = el;
                        alist = al;
                    }
                }

                @Override
                protected void walkAttribute(XmlSchema xmlSchema, XmlSchemaAttribute obj) {
                    if (obj.getRefName() == null) {
                        alist.add(obj);
                    }
                    super.walkAttribute(xmlSchema, obj);
                }
            }.init(schema, qname, requestableResponse);
            responseDoc.appendChild(requestableResponse);
            // System.out.println(XMLUtils.prettyPrintDOM(responseDoc));
            return responseDoc;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return document;
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) XmlSchemaElement(org.apache.ws.commons.schema.XmlSchemaElement) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) ArrayList(java.util.ArrayList) Document(org.w3c.dom.Document) Attr(org.w3c.dom.Attr) LinkedHashMap(java.util.LinkedHashMap) XmlSchemaWalker(com.twinsoft.convertigo.engine.util.XmlSchemaWalker) XmlSchemaObject(org.apache.ws.commons.schema.XmlSchemaObject) ArrayList(java.util.ArrayList) NodeList(org.w3c.dom.NodeList) List(java.util.List) NamedNodeMap(org.w3c.dom.NamedNodeMap) QName(javax.xml.namespace.QName) XmlSchemaElement(org.apache.ws.commons.schema.XmlSchemaElement) NodeList(org.w3c.dom.NodeList) XmlSchemaAttributeGroup(org.apache.ws.commons.schema.XmlSchemaAttributeGroup) XmlSchemaSequence(org.apache.ws.commons.schema.XmlSchemaSequence) Sequence(com.twinsoft.convertigo.beans.core.Sequence) XmlSchemaType(org.apache.ws.commons.schema.XmlSchemaType) XmlSchemaCollection(org.apache.ws.commons.schema.XmlSchemaCollection) XmlSchemaAttribute(org.apache.ws.commons.schema.XmlSchemaAttribute) SAXException(org.xml.sax.SAXException) Project(com.twinsoft.convertigo.beans.core.Project) XmlSchemaGroup(org.apache.ws.commons.schema.XmlSchemaGroup) XmlSchema(org.apache.ws.commons.schema.XmlSchema)

Example 3 with XmlSchemaWalker

use of com.twinsoft.convertigo.engine.util.XmlSchemaWalker in project convertigo by convertigo.

the class XmlSchemaBuilder method midBuildSchema.

private void midBuildSchema(final int nb) throws EngineException {
    // System.out.println("buildSchema for "+ getTargetNamespace());
    boolean fullSchema = isFull;
    try {
        new WalkHelper() {

            @Override
            protected void walk(DatabaseObject databaseObject) throws Exception {
                if (databaseObject instanceof ISchemaGenerator) {
                    // generate itself and add to the caller list
                    if (databaseObject instanceof ISchemaImportGenerator) {
                        // Import case
                        if (databaseObject instanceof ProjectSchemaReference) {
                            ProjectSchemaReference ref = (ProjectSchemaReference) databaseObject;
                            String targetProjectName = ref.getParser().getProjectName();
                            String tns = Project.getProjectTargetNamespace(targetProjectName);
                            if (collection.schemaForNamespace(tns) == null) {
                                if (SchemaMeta.getXmlSchemaObject(schema, databaseObject) == null) {
                                    XmlSchemaImport schemaImport = new XmlSchemaImport();
                                    schemaImport.setNamespace(tns);
                                    SchemaMeta.setXmlSchemaObject(schema, databaseObject, schemaImport);
                                    XmlSchemaUtils.add(schema, schemaImport);
                                } else {
                                    XmlSchemaBuilder builder = builderExecutor.getBuilderByTargetNamespace(tns);
                                    if (builder != null) {
                                        XmlSchemaUtils.remove(schema, SchemaMeta.getXmlSchemaObject(schema, databaseObject));
                                        XmlSchema xmlSchema = collection.read(builder.schema.getSchemaDocument(), null);
                                        XmlSchemaImport schemaImport = new XmlSchemaImport();
                                        schemaImport.setNamespace(tns);
                                        schemaImport.setSchema(xmlSchema);
                                        SchemaMeta.setXmlSchemaObject(schema, databaseObject, schemaImport);
                                        XmlSchemaUtils.add(schema, schemaImport);
                                    }
                                }
                            }
                        }
                    }
                } else {
                    // doesn't generate schema, just deep walk
                    super.walk(databaseObject);
                }
            }

            @Override
            protected boolean before(DatabaseObject databaseObject, Class<? extends DatabaseObject> dboClass) {
                // just walk references
                return Reference.class.isAssignableFrom(dboClass);
            }
        }.init(project);
        // add missing references import
        if (nb == 1) {
            if (this.equals(builderExecutor.getMainBuilder())) {
                List<String> refs = new ArrayList<String>();
                SchemaManager.getProjectReferences(refs, projectName);
                List<String> missing = new ArrayList<String>();
                missing.addAll(refs);
                missing.remove(projectName);
                for (String pname : refs) {
                    XmlSchemaObjectCollection col = schema.getIncludes();
                    for (int i = 0; i < col.getCount(); i++) {
                        XmlSchemaObject ob = col.getItem(i);
                        if (ob instanceof XmlSchemaImport) {
                            XmlSchemaImport xmlSchemaImport = (XmlSchemaImport) ob;
                            String tns = Project.getProjectTargetNamespace(pname);
                            if (xmlSchemaImport.getNamespace().equals(tns)) {
                                missing.remove(pname);
                            }
                        }
                    }
                }
                for (String pname : missing) {
                    String tns = Project.getProjectTargetNamespace(pname);
                    XmlSchemaBuilder builder = builderExecutor.getBuilderByTargetNamespace(tns);
                    if (builder != null) {
                        XmlSchema xmlSchema = collection.read(builder.schema.getSchemaDocument(), null);
                        XmlSchemaImport schemaImport = new XmlSchemaImport();
                        schemaImport.setNamespace(tns);
                        schemaImport.setSchema(xmlSchema);
                        XmlSchemaUtils.add(schema, schemaImport);
                    }
                }
            }
        }
        new WalkHelper() {

            List<XmlSchemaParticle> particleChildren;

            List<XmlSchemaAttribute> attributeChildren;

            @Override
            protected void walk(DatabaseObject databaseObject) throws Exception {
                // Transaction case
                if (databaseObject instanceof Transaction) {
                    Transaction transaction = (Transaction) databaseObject;
                    String ns = schema.getTargetNamespace();
                    List<QName> partElementQNames = new ArrayList<QName>();
                    partElementQNames.add(new QName(ns, transaction.getXsdRequestElementName()));
                    partElementQNames.add(new QName(ns, transaction.getXsdResponseElementName()));
                    LinkedHashMap<QName, XmlSchemaObject> map = new LinkedHashMap<QName, XmlSchemaObject>();
                    XmlSchemaWalker dw = XmlSchemaWalker.newDependencyWalker(map, true, true);
                    for (QName qname : partElementQNames) {
                        dw.walkByElementRef(schema, qname);
                    }
                    for (QName qname : map.keySet()) {
                        String nsURI = qname.getNamespaceURI();
                        if (nsURI.equals(ns))
                            continue;
                        if (nsURI.equals(Constants.URI_2001_SCHEMA_XSD))
                            continue;
                        SchemaManager.addXmlSchemaImport(collection, schema, nsURI);
                    }
                    map.clear();
                    // add the 'statistics' element
                    if (transaction.getAddStatistics()) {
                        XmlSchemaComplexType xmlSchemaComplexType = (XmlSchemaComplexType) schema.getTypeByName(transaction.getXsdResponseTypeName());
                        XmlSchemaGroupBase xmlSchemaGroupBase = (XmlSchemaGroupBase) xmlSchemaComplexType.getParticle();
                        XmlSchemaType statisticsType = schema.getTypeByName("ConvertigoStatsType");
                        XmlSchemaElement eStatistics = XmlSchemaUtils.makeDynamicReadOnly(databaseObject, new XmlSchemaElement());
                        eStatistics.setName("statistics");
                        eStatistics.setMinOccurs(0);
                        eStatistics.setMaxOccurs(1);
                        eStatistics.setSchemaTypeName(statisticsType.getQName());
                        xmlSchemaGroupBase.getItems().add(eStatistics);
                        SchemaMeta.getReferencedDatabaseObjects(statisticsType).add(transaction);
                    }
                } else // Sequence case
                if (databaseObject instanceof Sequence) {
                    Sequence sequence = (Sequence) databaseObject;
                    // System.out.println("--sequence:"+ sequence.toString());
                    particleChildren = new LinkedList<XmlSchemaParticle>();
                    attributeChildren = new LinkedList<XmlSchemaAttribute>();
                    super.walk(databaseObject);
                    // check for an 'error' element if needed
                    boolean errorFound = false;
                    XmlSchemaType errorType = schema.getTypeByName("ConvertigoError");
                    if (errorType != null) {
                        Set<DatabaseObject> dbos = SchemaMeta.getReferencedDatabaseObjects(errorType);
                        for (DatabaseObject dbo : dbos) {
                            if (dbo instanceof Step) {
                                Step errorStep = (Step) dbo;
                                if (errorStep.getSequence().equals(sequence) && (errorStep instanceof XMLCopyStep || errorStep.getStepNodeName().equals("error"))) {
                                    errorFound = true;
                                    break;
                                }
                            }
                        }
                    }
                    // set particle : choice or sequence
                    XmlSchemaComplexType cType = (XmlSchemaComplexType) schema.getTypeByName(sequence.getComplexTypeAffectation().getLocalPart());
                    XmlSchemaSequence xmlSeq = new XmlSchemaSequence();
                    XmlSchemaChoice xmlChoice = new XmlSchemaChoice();
                    cType.setParticle(errorFound ? xmlSeq : xmlChoice);
                    if (!errorFound) {
                        XmlSchemaElement eError = XmlSchemaUtils.makeDynamicReadOnly(databaseObject, new XmlSchemaElement());
                        eError.setName("error");
                        eError.setMinOccurs(0);
                        eError.setMaxOccurs(1);
                        eError.setSchemaTypeName(errorType.getQName());
                        SchemaMeta.getReferencedDatabaseObjects(errorType).add(sequence);
                        xmlChoice.getItems().add(xmlSeq);
                        xmlChoice.getItems().add(eError);
                    }
                    // add child particles
                    if (!particleChildren.isEmpty()) {
                        for (XmlSchemaParticle child : particleChildren) {
                            xmlSeq.getItems().add(child);
                        }
                    }
                    particleChildren.clear();
                    // add child attributes
                    for (XmlSchemaAttribute attribute : attributeChildren) {
                        cType.getAttributes().add(attribute);
                    }
                    attributeChildren.clear();
                    // add the 'statistics' element
                    if (sequence.getAddStatistics()) {
                        XmlSchemaType statisticsType = schema.getTypeByName("ConvertigoStatsType");
                        XmlSchemaElement eStatistics = XmlSchemaUtils.makeDynamicReadOnly(databaseObject, new XmlSchemaElement());
                        eStatistics.setName("statistics");
                        eStatistics.setMinOccurs(0);
                        eStatistics.setMaxOccurs(1);
                        eStatistics.setSchemaTypeName(statisticsType.getQName());
                        xmlSeq.getItems().add(eStatistics);
                        SchemaMeta.getReferencedDatabaseObjects(statisticsType).add(sequence);
                    }
                // --------------------------- For Further Use -------------------------------------------------//
                // Modify schema to avoid 'cosamb' (same tagname&type in different groupBase at same level)
                // TODO : IfThenElse steps must be modified for xsd:sequence instead of xsd:choice
                // TODO : Then/Else steps must be modified to add minOccurs=0 on xsd:sequence
                // TODO : review/improve cosnoamb(XmlSchema, XmlSchemaGroupBase, XmlSchemaGroupBase) method
                // ---------------------------------------------------------------------------------------------//
                } else // Step case
                if (databaseObject instanceof Step) {
                    Step step = (Step) databaseObject;
                    if (!step.isEnabled()) {
                        // stop walking for disabled steps
                        return;
                    }
                    List<XmlSchemaParticle> parentParticleChildren = particleChildren;
                    List<XmlSchemaAttribute> parentAttributeChildren = attributeChildren;
                    // System.out.println("step:"+ step.toString());
                    if (step instanceof TransactionStep) {
                    // System.out.println("SCHEMA TARGET STEP "+ step.toString() + "(" + step.hashCode() + ")");
                    }
                    if (step.isGenerateSchema() || (fullSchema && step.isXmlOrOutput())) {
                        // System.out.println("-> generate schema...");
                        List<XmlSchemaParticle> myParticleChildren = null;
                        List<XmlSchemaAttribute> myAttributeChildren = null;
                        // is base affected ?
                        @SuppressWarnings("unused") XmlSchemaType base = null;
                        QName baseQName = step instanceof ISimpleTypeAffectation ? ((ISimpleTypeAffectation) step).getSimpleTypeAffectation() : null;
                        if (baseQName != null && baseQName.getLocalPart().length() > 0) {
                            // base = baseQName.getNamespaceURI().length() == 0 ? schema.getTypeByName(baseQName.getLocalPart()) : collection.getTypeByQName(baseQName);
                            base = XmlSchemaBuilder.this.resolveTypeByQName(baseQName);
                        }
                        // is type affected ?
                        XmlSchemaType type = null;
                        QName typeQName = step instanceof IComplexTypeAffectation ? ((IComplexTypeAffectation) step).getComplexTypeAffectation() : null;
                        if (typeQName != null && typeQName.getLocalPart().length() > 0) {
                            // type = typeQName.getNamespaceURI().length() == 0 ? schema.getTypeByName(typeQName.getLocalPart()) : collection.getTypeByQName(typeQName);
                            type = XmlSchemaBuilder.this.resolveTypeByQName(typeQName);
                        }
                        // is element affected ?
                        XmlSchemaElement ref = null;
                        QName refQName = step instanceof IElementRefAffectation ? ((IElementRefAffectation) step).getElementRefAffectation() : null;
                        if (refQName != null && refQName.getLocalPart().length() > 0) {
                            // ref = refQName.getNamespaceURI().length() == 0 ? schema.getElementByName(refQName.getLocalPart()) : collection.getElementByQName(refQName);
                            ref = XmlSchemaBuilder.this.resolveElementByQName(refQName);
                            typeQName = new QName(schema.getTargetNamespace(), refQName.getLocalPart() + "Type");
                            if (ref == null && refQName.getNamespaceURI().equals(schema.getTargetNamespace())) {
                                ref = XmlSchemaUtils.makeDynamic(step, new XmlSchemaElement());
                                ref.setQName(refQName);
                                ref.setName(refQName.getLocalPart());
                                ref.setSchemaTypeName(baseQName);
                                XmlSchemaUtils.add(schema, ref);
                            } else if (ref != null) {
                                ref.setSchemaTypeName(baseQName);
                                // type = typeQName.getNamespaceURI().length() == 0 ? schema.getTypeByName(typeQName.getLocalPart()) : collection.getTypeByQName(typeQName);
                                type = XmlSchemaBuilder.this.resolveTypeByQName(typeQName);
                            }
                        }
                        if (type == null || !SchemaMeta.isReadOnly(type)) {
                            // prepare to receive children
                            if (step instanceof ISchemaParticleGenerator) {
                                myParticleChildren = particleChildren = new LinkedList<XmlSchemaParticle>();
                                if (fullSchema || ((ISchemaParticleGenerator) step).isGenerateElement()) {
                                    myAttributeChildren = attributeChildren = new LinkedList<XmlSchemaAttribute>();
                                }
                            }
                            // deep walk
                            super.walk(step);
                            // generate itself and add to the caller list
                            if (step instanceof ISchemaAttributeGenerator) {
                                // Attribute case
                                XmlSchemaAttribute attribute = ((ISchemaAttributeGenerator) step).getXmlSchemaObject(collection, schema);
                                SchemaMeta.setXmlSchemaObject(schema, step, attribute);
                                parentAttributeChildren.add(attribute);
                            } else if (step instanceof ISchemaParticleGenerator) {
                                if (step instanceof RequestableStep) {
                                    RequestableStep requestableStep = (RequestableStep) step;
                                    String targetProjectName = requestableStep.getProjectName();
                                    Project targetProject = requestableStep.getSequence().getLoadedProject(targetProjectName);
                                    if (targetProject == null) {
                                        Engine.logEngine.warn("(XmlSchemaBuilder) Not complete schema because: Missing required or not loaded project \"" + targetProjectName + "\"");
                                    } else if (step instanceof SequenceStep) {
                                        // SequenceStep case : walk target sequence first
                                        try {
                                            Sequence targetSequence = ((SequenceStep) step).getTargetSequence();
                                            targetProjectName = targetSequence.getProject().getName();
                                            String targetSequenceName = targetSequence.getName();
                                            String stepSequenceName = step.getSequence().getName();
                                            if (projectName.equals(targetProjectName)) {
                                                boolean isAfter = targetSequenceName.compareToIgnoreCase(stepSequenceName) > 0;
                                                if (isAfter) {
                                                    walk(targetSequence);
                                                }
                                            }
                                        } catch (EngineException e) {
                                            if (!e.getMessage().startsWith("There is no ")) {
                                                throw e;
                                            } else {
                                                Engine.logEngine.warn("(XmlSchemaBuilder) Not complete schema because: " + e.getMessage());
                                            }
                                        }
                                    }
                                }
                                // Particle case
                                XmlSchemaParticle particle = ((ISchemaParticleGenerator) step).getXmlSchemaObject(collection, schema);
                                SchemaMeta.setXmlSchemaObject(schema, step, particle);
                                parentParticleChildren.add(particle);
                                // retrieve the xsd:element to add children
                                XmlSchemaElement element = SchemaMeta.getContainerXmlSchemaElement(ref == null ? particle : ref);
                                // retrieve the group to add children if any
                                XmlSchemaGroupBase group = SchemaMeta.getContainerXmlSchemaGroupBase(element != null ? element : particle);
                                // new complexType to enhance the element
                                XmlSchemaComplexType cType = element != null ? (XmlSchemaComplexType) element.getSchemaType() : null;
                                // do something only on case of child
                                if (!myParticleChildren.isEmpty() || (myAttributeChildren != null && !myAttributeChildren.isEmpty())) {
                                    if (cType == null) {
                                        cType = XmlSchemaUtils.makeDynamic(step, new XmlSchemaComplexType(schema));
                                    }
                                    // prepare element children in the group
                                    if (!myParticleChildren.isEmpty()) {
                                        if (group == null) {
                                            group = XmlSchemaUtils.makeDynamic(step, new XmlSchemaSequence());
                                        }
                                        for (XmlSchemaParticle child : myParticleChildren) {
                                            group.getItems().add(child);
                                        }
                                    }
                                    if (element != null) {
                                        XmlSchemaSimpleContentExtension sContentExt = SchemaManager.makeSimpleContentExtension(step, element, cType);
                                        if (sContentExt != null) {
                                            // add attributes
                                            for (XmlSchemaAttribute attribute : myAttributeChildren) {
                                                sContentExt.getAttributes().add(attribute);
                                            }
                                        } else {
                                            // add attributes
                                            for (XmlSchemaAttribute attribute : myAttributeChildren) {
                                                cType.getAttributes().add(attribute);
                                            }
                                            // add elements
                                            if (SchemaMeta.isDynamic(cType) && group != null) {
                                                cType.setParticle(group);
                                            }
                                        }
                                    }
                                }
                                if (element != null) {
                                    // check if the type is named
                                    if (typeQName != null && typeQName.getLocalPart().length() > 0) {
                                        if (cType == null) {
                                            cType = XmlSchemaUtils.makeDynamic(step, new XmlSchemaComplexType(schema));
                                            SchemaManager.makeSimpleContentExtension(step, element, cType);
                                        }
                                        if (type == null) {
                                            // the type doesn't exist, declare it
                                            cType.setName(typeQName.getLocalPart());
                                            schema.addType(cType);
                                            schema.getItems().add(cType);
                                        } else {
                                            // the type already exists, merge it
                                            XmlSchemaComplexType currentCType = (XmlSchemaComplexType) type;
                                            SchemaManager.merge(schema, currentCType, cType);
                                            cType = currentCType;
                                        }
                                        // reference the type in the current element
                                        element.setSchemaTypeName(cType.getQName());
                                        element.setSchemaType(null);
                                    } else if (cType != null && SchemaMeta.isDynamic(cType) && element.getSchemaTypeName() == null) {
                                        // the element contains an anonymous type
                                        element.setSchemaType(cType);
                                    }
                                }
                            } else {
                                XmlSchemaObject object;
                                XmlSchema xmlSchema = null;
                                if (step instanceof XMLCopyStep && !fullSchema) {
                                    final XmlSchemaBuilder fullBuilder = builderExecutor.getBuilder(projectName, true);
                                    if (fullBuilder != null) {
                                        xmlSchema = fullBuilder.getXmlSchema();
                                        XmlSchemaCollection xmlCollection = SchemaMeta.getCollection(xmlSchema);
                                        object = step.getXmlSchemaObject(xmlCollection, xmlSchema);
                                    } else {
                                        xmlSchema = schema;
                                        object = step.getXmlSchemaObject(collection, schema);
                                        SchemaMeta.setXmlSchemaObject(schema, step, object);
                                    }
                                } else {
                                    xmlSchema = schema;
                                    object = step.getXmlSchemaObject(collection, schema);
                                    SchemaMeta.setXmlSchemaObject(schema, step, object);
                                }
                                if (step instanceof XMLCopyStep) {
                                    if (object instanceof XmlSchemaElement) {
                                        XmlSchemaElement xmlSchemaElement = (XmlSchemaElement) object;
                                        QName qname = xmlSchemaElement.getSchemaTypeName();
                                        if (qname != null) {
                                            XmlSchemaType xmlSchemaType = xmlSchema.getTypeByName(qname);
                                            if (xmlSchemaType != null) {
                                                SchemaMeta.getReferencedDatabaseObjects(xmlSchemaType).add(step);
                                            }
                                        }
                                    }
                                }
                                if (object instanceof XmlSchemaParticle) {
                                    particleChildren.add((XmlSchemaParticle) object);
                                } else if (object instanceof XmlSchemaAttribute) {
                                    attributeChildren.add((XmlSchemaAttribute) object);
                                }
                            }
                        } else {
                            // re-use read only type
                            XmlSchemaElement elt = XmlSchemaUtils.makeDynamic(step, new XmlSchemaElement());
                            SchemaMeta.getReferencedDatabaseObjects(type).add(step);
                            SchemaMeta.setXmlSchemaObject(schema, step, elt);
                            elt.setName(step.getStepNodeName());
                            elt.setSchemaTypeName(typeQName);
                            particleChildren.add(elt);
                        }
                    } else // Other case
                    {
                        // doesn't generate schema, just deep walk
                        // System.out.println("-> do not generate schema (deep walk)");
                        super.walk(step);
                    }
                    // restore lists for siblings
                    particleChildren = parentParticleChildren;
                    attributeChildren = parentAttributeChildren;
                } else {
                    // just deep walk
                    super.walk(databaseObject);
                }
            }

            @Override
            protected boolean before(DatabaseObject databaseObject, Class<? extends DatabaseObject> dboClass) {
                // just walk ISchemaGenerator DBO
                return Step.class.isAssignableFrom(dboClass) || Sequence.class.isAssignableFrom(dboClass) || Transaction.class.isAssignableFrom(dboClass) || Connector.class.isAssignableFrom(dboClass);
            }
        }.init(project);
    } catch (Exception e) {
        throw new EngineException("midBuildSchema failed", e);
    }
}
Also used : ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) DatabaseObject(com.twinsoft.convertigo.beans.core.DatabaseObject) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) SequenceStep(com.twinsoft.convertigo.beans.steps.SequenceStep) XmlSchemaElement(org.apache.ws.commons.schema.XmlSchemaElement) XmlSchemaSequence(org.apache.ws.commons.schema.XmlSchemaSequence) Sequence(com.twinsoft.convertigo.beans.core.Sequence) XmlSchemaAttribute(org.apache.ws.commons.schema.XmlSchemaAttribute) XmlSchemaGroupBase(org.apache.ws.commons.schema.XmlSchemaGroupBase) XmlSchemaCollection(org.apache.ws.commons.schema.XmlSchemaCollection) Project(com.twinsoft.convertigo.beans.core.Project) IComplexTypeAffectation(com.twinsoft.convertigo.beans.core.IComplexTypeAffectation) Transaction(com.twinsoft.convertigo.beans.core.Transaction) XmlSchema(org.apache.ws.commons.schema.XmlSchema) RequestableStep(com.twinsoft.convertigo.beans.core.RequestableStep) ISchemaImportGenerator(com.twinsoft.convertigo.beans.core.ISchemaImportGenerator) ISchemaGenerator(com.twinsoft.convertigo.beans.core.ISchemaGenerator) ProjectSchemaReference(com.twinsoft.convertigo.beans.references.ProjectSchemaReference) WalkHelper(com.twinsoft.convertigo.engine.helpers.WalkHelper) Step(com.twinsoft.convertigo.beans.core.Step) RequestableStep(com.twinsoft.convertigo.beans.core.RequestableStep) SequenceStep(com.twinsoft.convertigo.beans.steps.SequenceStep) XMLCopyStep(com.twinsoft.convertigo.beans.steps.XMLCopyStep) TransactionStep(com.twinsoft.convertigo.beans.steps.TransactionStep) ISchemaParticleGenerator(com.twinsoft.convertigo.beans.core.ISchemaParticleGenerator) XMLCopyStep(com.twinsoft.convertigo.beans.steps.XMLCopyStep) XmlSchemaSequence(org.apache.ws.commons.schema.XmlSchemaSequence) IElementRefAffectation(com.twinsoft.convertigo.beans.core.IElementRefAffectation) XmlSchemaWalker(com.twinsoft.convertigo.engine.util.XmlSchemaWalker) XmlSchemaObject(org.apache.ws.commons.schema.XmlSchemaObject) XmlSchemaImport(org.apache.ws.commons.schema.XmlSchemaImport) XmlSchemaChoice(org.apache.ws.commons.schema.XmlSchemaChoice) XmlSchemaObjectCollection(org.apache.ws.commons.schema.XmlSchemaObjectCollection) XmlSchemaSimpleContentExtension(org.apache.ws.commons.schema.XmlSchemaSimpleContentExtension) ISchemaAttributeGenerator(com.twinsoft.convertigo.beans.core.ISchemaAttributeGenerator) Reference(com.twinsoft.convertigo.beans.core.Reference) ProjectSchemaReference(com.twinsoft.convertigo.beans.references.ProjectSchemaReference) QName(javax.xml.namespace.QName) ISimpleTypeAffectation(com.twinsoft.convertigo.beans.core.ISimpleTypeAffectation) XmlSchemaParticle(org.apache.ws.commons.schema.XmlSchemaParticle) XmlSchemaType(org.apache.ws.commons.schema.XmlSchemaType) TransactionStep(com.twinsoft.convertigo.beans.steps.TransactionStep) XmlSchemaComplexType(org.apache.ws.commons.schema.XmlSchemaComplexType)

Example 4 with XmlSchemaWalker

use of com.twinsoft.convertigo.engine.util.XmlSchemaWalker in project convertigo by convertigo.

the class WebServiceServlet method generateWsdlForDocLiteral.

public static String generateWsdlForDocLiteral(String servletURI, String projectName) throws EngineException {
    Engine.logEngine.debug("(WebServiceServlet) Generating WSDL...");
    long timeStart = System.currentTimeMillis();
    String locationPath = servletURI.substring(0, servletURI.indexOf("/.w"));
    String targetNamespace = Project.CONVERTIGO_PROJECTS_NAMESPACEURI + projectName;
    Project project = null;
    // server mode
    if (Engine.isEngineMode()) {
        project = Engine.theApp.databaseObjectsManager.getProjectByName(projectName);
        targetNamespace = project.getTargetNamespace();
    } else // studio mode
    {
        project = Engine.objectsProvider.getProject(projectName);
        targetNamespace = project.getTargetNamespace();
    }
    // Create WSDL definition
    Definition definition = new DefinitionImpl();
    definition.setExtensionRegistry(new PopulatedExtensionRegistry());
    definition.setTargetNamespace(targetNamespace);
    definition.setQName(new QName(targetNamespace, projectName));
    definition.addNamespace("soap", "http://schemas.xmlsoap.org/wsdl/soap/");
    definition.addNamespace("soapenc", "http://schemas.xmlsoap.org/soap/encoding/");
    definition.addNamespace("wsdl", "http://schemas.xmlsoap.org/wsdl/");
    definition.addNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
    definition.addNamespace(projectName + "_ns", targetNamespace);
    // Add WSDL Types
    Types types = definition.createTypes();
    definition.setTypes(types);
    // Add WSDL service
    Service service = definition.createService();
    service.setQName(new QName(targetNamespace, projectName));
    definition.addService(service);
    // Add WSDL binding
    PortType portType = definition.createPortType();
    portType.setQName(new QName(targetNamespace, projectName + "PortType"));
    portType.setUndefined(false);
    definition.addPortType(portType);
    SOAPBindingImpl soapBinding = new SOAPBindingImpl();
    soapBinding.setTransportURI("http://schemas.xmlsoap.org/soap/http");
    soapBinding.setStyle("document");
    Binding binding = definition.createBinding();
    binding.setQName(new QName(targetNamespace, projectName + "SOAPBinding"));
    binding.setUndefined(false);
    definition.addBinding(binding);
    binding.addExtensibilityElement(soapBinding);
    binding.setPortType(portType);
    // Add WSDL port
    SOAPAddress soapAddress = new SOAPAddressImpl();
    soapAddress.setLocationURI(locationPath + "/.wsl");
    Port port = definition.createPort();
    port.setName(projectName + "SOAP");
    port.addExtensibilityElement(soapAddress);
    port.setBinding(binding);
    service.addPort(port);
    // Add all WSDL operations
    // remember qnames for accessibility
    List<QName> partElementQNames = new ArrayList<QName>();
    if (project != null) {
        for (Connector connector : project.getConnectorsList()) {
            for (Transaction transaction : connector.getTransactionsList()) {
                if (transaction.isPublicAccessibility()) {
                    addWsdlOperation(definition, transaction, partElementQNames);
                }
            }
        }
        for (Sequence sequence : project.getSequencesList()) {
            if (sequence.isPublicAccessibility()) {
                addWsdlOperation(definition, sequence, partElementQNames);
            }
        }
    }
    // Add all schemas of project under WSDL Types
    try {
        // Retrieve the only needed schema objects map
        XmlSchemaCollection xmlSchemaCollection = Engine.theApp.schemaManager.getSchemasForProject(projectName);
        XmlSchema projectSchema = xmlSchemaCollection.getXmlSchema(targetNamespace)[0];
        LinkedHashMap<QName, XmlSchemaObject> map = new LinkedHashMap<QName, XmlSchemaObject>();
        XmlSchemaWalker dw = XmlSchemaWalker.newDependencyWalker(map, true, true);
        for (QName qname : partElementQNames) {
            dw.walkByElementRef(projectSchema, qname);
        }
        if (Engine.logEngine.isTraceEnabled()) {
            String message = "";
            for (QName qname : map.keySet()) {
                message += "\n\t" + qname.toString();
            }
            Engine.logEngine.trace("(WebServiceServlet) needed schema objects :" + message);
        }
        // Read schemas into a new Collection in order to modify them
        XmlSchemaCollection wsdlSchemaCollection = new XmlSchemaCollection();
        for (XmlSchema xmlSchema : xmlSchemaCollection.getXmlSchemas()) {
            String tns = xmlSchema.getTargetNamespace();
            if (tns.equals(Constants.URI_2001_SCHEMA_XSD))
                continue;
            if (tns.equals(SchemaUtils.URI_SOAP_ENC))
                continue;
            if (wsdlSchemaCollection.schemaForNamespace(tns) == null) {
                wsdlSchemaCollection.read(xmlSchema.getSchemaDocument(), xmlSchema.getSourceURI(), null);
            }
        }
        // Modify schemas and add them
        Map<String, Schema> schemaMap = new HashMap<String, Schema>();
        for (XmlSchema xmlSchema : wsdlSchemaCollection.getXmlSchemas()) {
            if (xmlSchema.getTargetNamespace().equals(Constants.URI_2001_SCHEMA_XSD))
                continue;
            if (xmlSchema.getTargetNamespace().equals(SchemaUtils.URI_SOAP_ENC))
                continue;
            String tns = xmlSchema.getTargetNamespace();
            // Reduce schema to needed objects
            reduceSchema(xmlSchema, map.keySet());
            // Retrieve schema Element
            Schema wsdlSchema = schemaMap.get(tns);
            if (wsdlSchema == null) {
                wsdlSchema = (Schema) definition.getExtensionRegistry().createExtension(Types.class, SchemaConstants.Q_ELEM_XSD_2001);
                Element schemaElt = xmlSchema.getSchemaDocument().getDocumentElement();
                // Remove 'schemaLocation' attribute on imports
                NodeList importList = schemaElt.getElementsByTagNameNS(Constants.URI_2001_SCHEMA_XSD, "import");
                if (importList.getLength() > 0) {
                    for (int i = 0; i < importList.getLength(); i++) {
                        Element importElt = (Element) importList.item(i);
                        importElt.removeAttribute("schemaLocation");
                    }
                }
                // Remove includes
                NodeList includeList = schemaElt.getElementsByTagNameNS(Constants.URI_2001_SCHEMA_XSD, "include");
                if (includeList.getLength() > 0) {
                    for (int i = 0; i < includeList.getLength(); i++) {
                        schemaElt.removeChild(includeList.item(i));
                    }
                }
                // Add schema Element
                schemaMap.put(tns, wsdlSchema);
                wsdlSchema.setElement(schemaElt);
                types.addExtensibilityElement(wsdlSchema);
            } else {
                // case of schema include (same targetNamespace) or same schema
                Element schemaElt = wsdlSchema.getElement();
                // Add missing attributes
                NamedNodeMap attributeMap = xmlSchema.getSchemaDocument().getDocumentElement().getAttributes();
                for (int i = 0; i < attributeMap.getLength(); i++) {
                    Node node = attributeMap.item(i);
                    if (schemaElt.getAttributes().getNamedItem(node.getNodeName()) == null) {
                        schemaElt.setAttribute(node.getNodeName(), node.getNodeValue());
                    }
                }
                // Add children
                NodeList children = xmlSchema.getSchemaDocument().getDocumentElement().getChildNodes();
                for (int i = 0; i < children.getLength(); i++) {
                    Node node = children.item(i);
                    // Special cases
                    if (node.getNodeType() == Node.ELEMENT_NODE) {
                        Element el = (Element) node;
                        // Do not add include
                        if (el.getTagName().endsWith("include"))
                            continue;
                        // Add import at first
                        if (el.getTagName().endsWith("import")) {
                            String ins = el.getAttribute("namespace");
                            if (!tns.equals(ins) && el.hasAttribute("schemaLocation")) {
                                if (!hasElement(schemaElt, el.getLocalName(), ins))
                                    schemaElt.insertBefore(schemaElt.getOwnerDocument().importNode(el, true), schemaElt.getFirstChild());
                                continue;
                            }
                        }
                        // Else
                        if (!hasElement(schemaElt, el.getLocalName(), el.getAttribute("name")))
                            schemaElt.appendChild(schemaElt.getOwnerDocument().importNode(el, true));
                    } else {
                        // Others
                        schemaElt.appendChild(schemaElt.getOwnerDocument().importNode(node, true));
                    }
                }
            }
        }
    } catch (Exception e1) {
        Engine.logEngine.error("An error occured while adding schemas for WSDL", e1);
    }
    // Write WSDL to string
    WSDLWriter wsdlWriter = new WSDLWriterImpl();
    StringWriter sw = new StringWriter();
    try {
        wsdlWriter.writeWSDL(definition, sw);
    } catch (WSDLException e) {
        Engine.logEngine.error("An error occured while generating WSDL", e);
    }
    String wsdl = sw.toString();
    long timeStop = System.currentTimeMillis();
    System.out.println("Wsdl for " + projectName + " | Times >> total : " + (timeStop - timeStart) + " ms");
    return wsdl;
}
Also used : SOAPAddressImpl(com.ibm.wsdl.extensions.soap.SOAPAddressImpl) Types(javax.wsdl.Types) Connector(com.twinsoft.convertigo.beans.core.Connector) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Port(javax.wsdl.Port) XmlSchema(org.apache.ws.commons.schema.XmlSchema) Schema(javax.wsdl.extensions.schema.Schema) WSDLElement(javax.wsdl.WSDLElement) XmlSchemaElement(org.apache.ws.commons.schema.XmlSchemaElement) SOAPElement(javax.xml.soap.SOAPElement) Element(org.w3c.dom.Element) OMNode(org.apache.axiom.om.OMNode) Node(org.w3c.dom.Node) ArrayList(java.util.ArrayList) WSDLWriter(javax.wsdl.xml.WSDLWriter) LinkedHashMap(java.util.LinkedHashMap) DefinitionImpl(com.ibm.wsdl.DefinitionImpl) XmlSchemaWalker(com.twinsoft.convertigo.engine.util.XmlSchemaWalker) XmlSchemaObject(org.apache.ws.commons.schema.XmlSchemaObject) StringWriter(java.io.StringWriter) Binding(javax.wsdl.Binding) NamedNodeMap(org.w3c.dom.NamedNodeMap) WSDLException(javax.wsdl.WSDLException) QName(javax.xml.namespace.QName) NodeList(org.w3c.dom.NodeList) Definition(javax.wsdl.Definition) Service(javax.wsdl.Service) Sequence(com.twinsoft.convertigo.beans.core.Sequence) XmlSchemaCollection(org.apache.ws.commons.schema.XmlSchemaCollection) ServletException(javax.servlet.ServletException) SOAPException(javax.xml.soap.SOAPException) FileNotFoundException(java.io.FileNotFoundException) EngineException(com.twinsoft.convertigo.engine.EngineException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) WSDLException(javax.wsdl.WSDLException) Project(com.twinsoft.convertigo.beans.core.Project) PopulatedExtensionRegistry(com.ibm.wsdl.extensions.PopulatedExtensionRegistry) Transaction(com.twinsoft.convertigo.beans.core.Transaction) XmlSchema(org.apache.ws.commons.schema.XmlSchema) SOAPAddress(javax.wsdl.extensions.soap.SOAPAddress) WSDLWriterImpl(com.ibm.wsdl.xml.WSDLWriterImpl) SOAPBindingImpl(com.ibm.wsdl.extensions.soap.SOAPBindingImpl) PortType(javax.wsdl.PortType)

Aggregations

Project (com.twinsoft.convertigo.beans.core.Project)4 Sequence (com.twinsoft.convertigo.beans.core.Sequence)4 XmlSchemaWalker (com.twinsoft.convertigo.engine.util.XmlSchemaWalker)4 LinkedHashMap (java.util.LinkedHashMap)4 QName (javax.xml.namespace.QName)4 XmlSchema (org.apache.ws.commons.schema.XmlSchema)4 XmlSchemaCollection (org.apache.ws.commons.schema.XmlSchemaCollection)4 XmlSchemaObject (org.apache.ws.commons.schema.XmlSchemaObject)4 Transaction (com.twinsoft.convertigo.beans.core.Transaction)3 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 XmlSchemaElement (org.apache.ws.commons.schema.XmlSchemaElement)3 XmlSchemaSequence (org.apache.ws.commons.schema.XmlSchemaSequence)3 Connector (com.twinsoft.convertigo.beans.core.Connector)2 Reference (com.twinsoft.convertigo.beans.core.Reference)2 ProjectSchemaReference (com.twinsoft.convertigo.beans.references.ProjectSchemaReference)2 LinkedList (java.util.LinkedList)2 List (java.util.List)2 XmlSchemaAttribute (org.apache.ws.commons.schema.XmlSchemaAttribute)2 XmlSchemaImport (org.apache.ws.commons.schema.XmlSchemaImport)2