Search in sources :

Example 16 with NamespaceMap

use of org.apache.ws.commons.schema.utils.NamespaceMap 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 17 with NamespaceMap

use of org.apache.ws.commons.schema.utils.NamespaceMap in project convertigo by convertigo.

the class SchemaUtils method createSchemaCollection.

public static XmlSchemaCollection createSchemaCollection() {
    NamespaceMap nsMap = new NamespaceMap();
    nsMap.add("xsd", Constants.URI_2001_SCHEMA_XSD);
    return createSchemaCollection(nsMap);
}
Also used : NamespaceMap(org.apache.ws.commons.schema.utils.NamespaceMap)

Example 18 with NamespaceMap

use of org.apache.ws.commons.schema.utils.NamespaceMap in project convertigo by convertigo.

the class SchemaUtils method getNamespaceMap.

public static NamespaceMap getNamespaceMap(XmlSchema xmlSchema) {
    NamespaceMap namespacesMap = new NamespaceMap();
    NamespacePrefixList namespacePrefixList = xmlSchema.getNamespaceContext();
    if (namespacePrefixList != null) {
        String[] prefixes = namespacePrefixList.getDeclaredPrefixes();
        for (int i = 0; i < prefixes.length; i++) {
            String prefix = prefixes[i];
            String ns = namespacePrefixList.getNamespaceURI(prefix);
            namespacesMap.add(prefix, ns);
        }
    }
    return namespacesMap;
}
Also used : NamespaceMap(org.apache.ws.commons.schema.utils.NamespaceMap) NamespacePrefixList(org.apache.ws.commons.schema.utils.NamespacePrefixList)

Example 19 with NamespaceMap

use of org.apache.ws.commons.schema.utils.NamespaceMap in project cxf by apache.

the class ImportRepairTest method newSchema.

private XmlSchema newSchema(String uri) {
    XmlSchema schema = collection.newXmlSchemaInCollection(uri);
    NamespaceMap map = new NamespaceMap();
    map.add("", XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schema.setNamespaceContext(map);
    return schema;
}
Also used : XmlSchema(org.apache.ws.commons.schema.XmlSchema) NamespaceMap(org.apache.ws.commons.schema.utils.NamespaceMap)

Example 20 with NamespaceMap

use of org.apache.ws.commons.schema.utils.NamespaceMap in project cxf by apache.

the class AegisDatabinding method createSchemas.

private void createSchemas(Service s, Set<AegisType> deps) {
    Map<String, Set<AegisType>> tns2Type = new HashMap<>();
    for (AegisType t : deps) {
        String ns = t.getSchemaType().getNamespaceURI();
        Set<AegisType> types = tns2Type.get(ns);
        if (types == null) {
            types = new HashSet<>();
            tns2Type.put(ns, types);
        }
        types.add(t);
    }
    for (ServiceInfo si : s.getServiceInfos()) {
        SchemaCollection col = si.getXmlSchemaCollection();
        if (col.getXmlSchemas().length > 1) {
            // someone has already filled in the types
            continue;
        }
    }
    Map<String, String> namespaceMap = getDeclaredNamespaceMappings();
    for (ServiceInfo si : s.getServiceInfos()) {
        // these two must be recalculated per-service-info!
        boolean needXmimeSchema = false;
        boolean needTypesSchema = false;
        for (Map.Entry<String, Set<AegisType>> entry : tns2Type.entrySet()) {
            String schemaNamespaceUri = entry.getKey();
            if (Constants.URI_2001_SCHEMA_XSD.equals(schemaNamespaceUri)) {
                continue;
            }
            if (AegisContext.UTILITY_TYPES_SCHEMA_NS.equals(schemaNamespaceUri)) {
                // we handle this separately.
                continue;
            }
            if (AbstractXOPType.XML_MIME_NS.equals(schemaNamespaceUri)) {
                // similiarly.
                continue;
            }
            SchemaInfo schemaInfo = si.addNewSchema(entry.getKey());
            XmlSchema schema = schemaInfo.getSchema();
            NamespaceMap xmlsNamespaceMap = new NamespaceMap();
            // user-requested prefix mappings.
            if (namespaceMap != null) {
                for (Map.Entry<String, String> e : namespaceMap.entrySet()) {
                    xmlsNamespaceMap.add(e.getValue(), e.getKey());
                }
            }
            // tns: is conventional, and besides we have unit tests that are hardcoded to it.
            if (!xmlsNamespaceMap.containsKey(WSDLConstants.CONVENTIONAL_TNS_PREFIX) && // if some wants something other than TNS, they get it.
            !xmlsNamespaceMap.containsValue(entry.getKey())) {
                xmlsNamespaceMap.add(WSDLConstants.CONVENTIONAL_TNS_PREFIX, entry.getKey());
            }
            // ditto for xsd: instead of just namespace= for the schema schema.
            if (!xmlsNamespaceMap.containsKey("xsd") && !xmlsNamespaceMap.containsValue(Constants.URI_2001_SCHEMA_XSD)) {
                xmlsNamespaceMap.add("xsd", Constants.URI_2001_SCHEMA_XSD);
            }
            schema.setNamespaceContext(xmlsNamespaceMap);
            schema.setTargetNamespace(entry.getKey());
            schema.setElementFormDefault(XmlSchemaForm.QUALIFIED);
            schema.setAttributeFormDefault(XmlSchemaForm.QUALIFIED);
            for (AegisType t : entry.getValue()) {
                try {
                    t.writeSchema(schema);
                } catch (XmlSchemaException ex) {
                    QName name = t.getSchemaType();
                    String expected = " Schema for namespace '" + name.getNamespaceURI() + "' already contains type '" + name.getLocalPart() + "'";
                    String message = ex.getMessage();
                    if (expected.equals(message)) {
                        continue;
                    }
                    throw ex;
                }
            }
            if (schemaImportsXmime(schema)) {
                needXmimeSchema = true;
            }
            if (AegisContext.schemaImportsUtilityTypes(schema)) {
                needTypesSchema = true;
            }
        }
        if (needXmimeSchema) {
            XmlSchema schema = aegisContext.addXmimeSchemaDocument(si.getXmlSchemaCollection().getXmlSchemaCollection());
            SchemaInfo schemaInfo = new SchemaInfo(schema.getTargetNamespace());
            schemaInfo.setSchema(schema);
            si.addSchema(schemaInfo);
        }
        if (needTypesSchema) {
            XmlSchema schema = aegisContext.addTypesSchemaDocument(si.getXmlSchemaCollection().getXmlSchemaCollection());
            SchemaInfo schemaInfo = new SchemaInfo(schema.getTargetNamespace());
            schemaInfo.setSchema(schema);
            si.addSchema(schemaInfo);
        }
        // it's quite likely that the code in Aegis missed at least one ...
        si.getXmlSchemaCollection().addCrossImports();
    }
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) HashMap(java.util.HashMap) AegisType(org.apache.cxf.aegis.type.AegisType) XmlSchemaException(org.apache.ws.commons.schema.XmlSchemaException) QName(javax.xml.namespace.QName) ServiceInfo(org.apache.cxf.service.model.ServiceInfo) XmlSchema(org.apache.ws.commons.schema.XmlSchema) NamespaceMap(org.apache.ws.commons.schema.utils.NamespaceMap) SchemaCollection(org.apache.cxf.common.xmlschema.SchemaCollection) HashMap(java.util.HashMap) Map(java.util.Map) NamespaceMap(org.apache.ws.commons.schema.utils.NamespaceMap) SchemaInfo(org.apache.cxf.service.model.SchemaInfo)

Aggregations

NamespaceMap (org.apache.ws.commons.schema.utils.NamespaceMap)38 XmlSchema (org.apache.ws.commons.schema.XmlSchema)23 QName (javax.xml.namespace.QName)14 XmlSchemaElement (org.apache.ws.commons.schema.XmlSchemaElement)10 XmlSchemaImport (org.apache.ws.commons.schema.XmlSchemaImport)10 XmlSchemaSequence (org.apache.ws.commons.schema.XmlSchemaSequence)9 XmlSchemaComplexType (org.apache.ws.commons.schema.XmlSchemaComplexType)8 IOException (java.io.IOException)6 SchemaInfo (org.apache.cxf.service.model.SchemaInfo)6 XmlSchemaCollection (org.apache.ws.commons.schema.XmlSchemaCollection)6 ArrayList (java.util.ArrayList)5 HashMap (java.util.HashMap)5 List (java.util.List)5 XmlSchemaObject (org.apache.ws.commons.schema.XmlSchemaObject)5 GenericArrayType (java.lang.reflect.GenericArrayType)4 Method (java.lang.reflect.Method)4 XmlSchemaComplexContentExtension (org.apache.ws.commons.schema.XmlSchemaComplexContentExtension)4 XmlSchemaObjectCollection (org.apache.ws.commons.schema.XmlSchemaObjectCollection)4 XmlSchemaSimpleType (org.apache.ws.commons.schema.XmlSchemaSimpleType)4 XmlSchemaType (org.apache.ws.commons.schema.XmlSchemaType)4