Search in sources :

Example 1 with XmlHttpTransaction

use of com.twinsoft.convertigo.beans.transactions.XmlHttpTransaction in project convertigo by convertigo.

the class SwaggerUtils method createRestConnector.

@SuppressWarnings("unused")
private static HttpConnector createRestConnector(JSONObject json) throws Exception {
    try {
        HttpConnector httpConnector = new HttpConnector();
        httpConnector.bNew = true;
        JSONObject info = json.getJSONObject("info");
        httpConnector.setName(StringUtils.normalize(info.getString("title")));
        String host = json.getString("host");
        int index = host.indexOf(":");
        String server = index == -1 ? host : host.substring(0, index);
        int port = index == -1 ? 0 : Integer.parseInt(host.substring(index + 1, 10));
        httpConnector.setServer(server);
        httpConnector.setPort(port <= 0 ? 80 : port);
        String basePath = json.getString("basePath");
        httpConnector.setBaseDir(basePath);
        JSONArray _consumes = new JSONArray();
        if (json.has("consumes")) {
            _consumes = json.getJSONArray("consumes");
        }
        JSONArray _produces = new JSONArray();
        if (json.has("produces")) {
            _produces = json.getJSONArray("produces");
        }
        Map<String, JSONObject> models = new HashMap<String, JSONObject>();
        JSONObject definitions = new JSONObject();
        if (json.has("definitions")) {
            definitions = json.getJSONObject("definitions");
            for (Iterator<String> i = GenericUtils.cast(definitions.keys()); i.hasNext(); ) {
                String key = i.next();
                JSONObject model = definitions.getJSONObject(key);
                models.put(key, model);
            }
        }
        JSONObject paths = json.getJSONObject("paths");
        for (Iterator<String> i1 = GenericUtils.cast(paths.keys()); i1.hasNext(); ) {
            String subDir = i1.next();
            JSONObject path = paths.getJSONObject(subDir);
            for (Iterator<String> i2 = GenericUtils.cast(path.keys()); i2.hasNext(); ) {
                String httpVerb = i2.next();
                JSONObject verb = path.getJSONObject(httpVerb);
                XMLVector<XMLVector<String>> httpParameters = new XMLVector<XMLVector<String>>();
                AbstractHttpTransaction transaction = new HttpTransaction();
                JSONArray consumes = verb.has("consumes") ? verb.getJSONArray("consumes") : _consumes;
                List<String> consumeList = new ArrayList<String>();
                for (int i = 0; i < consumes.length(); i++) {
                    consumeList.add(consumes.getString(i));
                }
                String h_ContentType = null;
                if (consumeList.contains(MimeType.Xml.value())) {
                    h_ContentType = MimeType.Xml.value();
                } else if (consumeList.contains(MimeType.Json.value())) {
                    h_ContentType = MimeType.Json.value();
                } else {
                    h_ContentType = consumeList.size() > 0 ? consumeList.get(0) : MimeType.WwwForm.value();
                }
                JSONArray produces = verb.has("produces") ? verb.getJSONArray("produces") : _produces;
                List<String> produceList = new ArrayList<String>();
                for (int i = 0; i < produces.length(); i++) {
                    produceList.add(produces.getString(i));
                }
                String h_Accept = null;
                if (produceList.contains(h_ContentType)) {
                    h_Accept = h_ContentType;
                } else {
                    if (produceList.contains(MimeType.Xml.value())) {
                        h_Accept = MimeType.Xml.value();
                    } else if (produceList.contains(MimeType.Json.value())) {
                        h_Accept = MimeType.Json.value();
                    }
                }
                if (h_Accept != null) {
                    XMLVector<String> xmlv = new XMLVector<String>();
                    xmlv.add("Accept");
                    xmlv.add(h_Accept);
                    httpParameters.add(xmlv);
                    if (h_Accept.equals(MimeType.Xml.value())) {
                        transaction = new XmlHttpTransaction();
                        ((XmlHttpTransaction) transaction).setXmlEncoding("UTF-8");
                    } else if (h_Accept.equals(MimeType.Json.value())) {
                        transaction = new JsonHttpTransaction();
                        ((JsonHttpTransaction) transaction).setIncludeDataType(false);
                    }
                }
                if (h_ContentType != null) {
                    XMLVector<String> xmlv = new XMLVector<String>();
                    xmlv.add(HeaderName.ContentType.value());
                    xmlv.add(h_ContentType);
                    httpParameters.add(xmlv);
                }
                String operationId = "";
                if (verb.has("operationId")) {
                    operationId = verb.getString("operationId");
                }
                String summary = "";
                if (verb.has("summary")) {
                    summary = verb.getString("summary");
                }
                String description = "";
                if (verb.has("description")) {
                    description = verb.getString("description");
                }
                String name = StringUtils.normalize(operationId);
                if (name.isEmpty()) {
                    name = StringUtils.normalize(summary);
                    if (name.isEmpty()) {
                        name = "operation";
                    }
                }
                String comment = summary;
                if (comment.isEmpty()) {
                    comment = description;
                }
                JSONArray parameters = new JSONArray();
                if (verb.has("parameters")) {
                    parameters = verb.getJSONArray("parameters");
                    for (int i = 0; i < parameters.length(); i++) {
                        JSONObject parameter = (JSONObject) parameters.get(i);
                        String type = "string";
                        if (parameter.has("collectionFormat")) {
                            type = parameter.getString("type");
                        }
                        String collectionFormat = "csv";
                        if (parameter.has("collectionFormat")) {
                            collectionFormat = parameter.getString("collectionFormat");
                        }
                        boolean isMultiValued = type.equalsIgnoreCase("array") && collectionFormat.equals("multi");
                        RequestableHttpVariable httpVariable = isMultiValued ? new RequestableHttpMultiValuedVariable() : new RequestableHttpVariable();
                        httpVariable.bNew = true;
                        httpVariable.setName(parameter.getString("name"));
                        httpVariable.setHttpName(parameter.getString("name"));
                        String in = parameter.getString("in");
                        if (in.equals("query") || in.equals("path") || in.equals("header")) {
                            httpVariable.setHttpMethod(HttpMethodType.GET.name());
                            if (in.equals("header")) {
                                // overrides variable's name : will be treated as dynamic header
                                httpVariable.setName(com.twinsoft.convertigo.engine.enums.Parameter.HttpHeader.getName() + parameter.getString("name"));
                                // do not post on target server
                                httpVariable.setHttpName("");
                            }
                        } else if (in.equals("formData") || in.equals("body")) {
                            httpVariable.setHttpMethod(HttpMethodType.POST.name());
                            if (in.equals("body")) {
                                // overrides variable's name for internal use
                                httpVariable.setName(com.twinsoft.convertigo.engine.enums.Parameter.HttpBody.getName());
                                // add internal __contentType variable
                                RequestableHttpVariable ct = new RequestableHttpVariable();
                                ct.setName(com.twinsoft.convertigo.engine.enums.Parameter.HttpContentType.getName());
                                // do not post on target server
                                ct.setHttpName("");
                                ct.setHttpMethod(HttpMethodType.POST.name());
                                ct.setValueOrNull(null);
                                ct.bNew = true;
                                transaction.addVariable(ct);
                                // 
                                if (parameter.has("schema")) {
                                // String schema = parameter.getString("schema");
                                }
                            }
                        } else {
                            httpVariable.setHttpMethod("");
                        }
                        Object defaultValue = null;
                        if (parameter.has("default")) {
                            defaultValue = parameter.get("default");
                        }
                        if (defaultValue == null && type.equalsIgnoreCase("array")) {
                            JSONObject items = parameter.getJSONObject("items");
                            if (items.has("default")) {
                                defaultValue = items.get("default");
                            }
                        }
                        httpVariable.setValueOrNull(defaultValue);
                        if (parameter.has("description")) {
                            httpVariable.setDescription(parameter.getString("description"));
                        }
                        transaction.addVariable(httpVariable);
                    }
                }
                transaction.bNew = true;
                transaction.setName(name);
                transaction.setComment(comment);
                transaction.setSubDir(subDir);
                transaction.setHttpVerb(HttpMethodType.valueOf(httpVerb.toUpperCase()));
                transaction.setHttpParameters(httpParameters);
                transaction.setHttpInfo(true);
                httpConnector.add(transaction);
            }
        }
        return httpConnector;
    } catch (Throwable t) {
        System.out.println(t);
        throw new Exception("Invalid Swagger format", t);
    }
}
Also used : XmlHttpTransaction(com.twinsoft.convertigo.beans.transactions.XmlHttpTransaction) HttpTransaction(com.twinsoft.convertigo.beans.transactions.HttpTransaction) AbstractHttpTransaction(com.twinsoft.convertigo.beans.transactions.AbstractHttpTransaction) JsonHttpTransaction(com.twinsoft.convertigo.beans.transactions.JsonHttpTransaction) HttpConnector(com.twinsoft.convertigo.beans.connectors.HttpConnector) RequestableHttpVariable(com.twinsoft.convertigo.beans.variables.RequestableHttpVariable) XMLVector(com.twinsoft.convertigo.beans.common.XMLVector) HashMap(java.util.HashMap) XmlHttpTransaction(com.twinsoft.convertigo.beans.transactions.XmlHttpTransaction) JSONArray(org.codehaus.jettison.json.JSONArray) ArrayList(java.util.ArrayList) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) AbstractHttpTransaction(com.twinsoft.convertigo.beans.transactions.AbstractHttpTransaction) JSONObject(org.codehaus.jettison.json.JSONObject) RequestableHttpMultiValuedVariable(com.twinsoft.convertigo.beans.variables.RequestableHttpMultiValuedVariable) JsonHttpTransaction(com.twinsoft.convertigo.beans.transactions.JsonHttpTransaction) JSONObject(org.codehaus.jettison.json.JSONObject)

Example 2 with XmlHttpTransaction

use of com.twinsoft.convertigo.beans.transactions.XmlHttpTransaction in project convertigo by convertigo.

the class WsReference method createSoapTransaction.

private static XmlHttpTransaction createSoapTransaction(XmlSchema xmlSchema, WsdlInterface iface, WsdlOperation operation, Project project, HttpConnector httpConnector) throws ParserConfigurationException, SAXException, IOException, EngineException {
    XmlHttpTransaction xmlHttpTransaction = null;
    WsdlRequest request;
    String requestXml;
    String transactionName, comment;
    String operationName;
    if (operation != null) {
        comment = operation.getDescription();
        try {
            comment = (comment.equals("") ? operation.getBindingOperation().getDocumentationElement().getTextContent() : comment);
        } catch (Exception e) {
        }
        operationName = operation.getName();
        transactionName = StringUtils.normalize("C" + operationName);
        xmlHttpTransaction = new XmlHttpTransaction();
        xmlHttpTransaction.bNew = true;
        xmlHttpTransaction.setHttpVerb(HttpMethodType.POST);
        xmlHttpTransaction.setName(transactionName);
        xmlHttpTransaction.setComment(comment);
        // Set encoding (UTF-8 by default)
        xmlHttpTransaction.setEncodingCharSet("UTF-8");
        xmlHttpTransaction.setXmlEncoding("UTF-8");
        // Ignore SOAP elements in response
        xmlHttpTransaction.setIgnoreSoapEnveloppe(true);
        // Adds parameters
        XMLVector<XMLVector<String>> parameters = new XMLVector<XMLVector<String>>();
        XMLVector<String> xmlv;
        xmlv = new XMLVector<String>();
        xmlv.add(HeaderName.ContentType.value());
        xmlv.add(MimeType.TextXml.value());
        parameters.add(xmlv);
        xmlv = new XMLVector<String>();
        xmlv.add("Host");
        xmlv.add(httpConnector.getServer());
        parameters.add(xmlv);
        xmlv = new XMLVector<String>();
        xmlv.add("SOAPAction");
        // fix #4215 - SOAPAction header must be empty
        xmlv.add("");
        parameters.add(xmlv);
        xmlv = new XMLVector<String>();
        xmlv.add("user-agent");
        xmlv.add("Convertigo EMS " + Version.fullProductVersion);
        parameters.add(xmlv);
        xmlHttpTransaction.setHttpParameters(parameters);
        QName qname = null;
        boolean bRPC = false;
        String style = operation.getStyle();
        if (style.toUpperCase().equals("RPC"))
            bRPC = true;
        // Set SOAP response element
        if (bRPC) {
            try {
                MessagePart[] parts = operation.getDefaultResponseParts();
                if (parts.length > 0) {
                    String ename = parts[0].getName();
                    if (parts[0].getPartType().name().equals("CONTENT")) {
                        MessagePart.ContentPart mpcp = (MessagePart.ContentPart) parts[0];
                        qname = mpcp.getSchemaType().getName();
                        if (qname != null) {
                            // response is based on an element defined with a type
                            // operationResponse element name; element name; element type
                            String responseQName = operationName + "Response;" + ename + ";" + "{" + qname.getNamespaceURI() + "}" + qname.getLocalPart();
                            xmlHttpTransaction.setResponseElementQName(responseQName);
                        }
                    }
                }
            } catch (Exception e) {
            }
        } else {
            try {
                qname = operation.getResponseBodyElementQName();
                if (qname != null) {
                    QName refName = new QName(qname.getNamespaceURI(), qname.getLocalPart());
                    xmlHttpTransaction.setXmlElementRefAffectation(new XmlQName(refName));
                }
            } catch (Exception e) {
            }
        }
        // Create request/response
        request = operation.addNewRequest("Test" + transactionName);
        requestXml = operation.createRequest(true);
        request.setRequestContent(requestXml);
        // responseXml = operation.createResponse(true);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document requestDoc = db.parse(new InputSource(new StringReader(requestXml)));
        // Document responseDoc = db.parse(new InputSource(new StringReader(responseXml)));
        Element enveloppe = requestDoc.getDocumentElement();
        String soapenvNamespace = enveloppe.getNamespaceURI();
        // Retrieve variables
        Element header = (Element) requestDoc.getDocumentElement().getElementsByTagNameNS(soapenvNamespace, "Header").item(0);
        Element body = (Element) requestDoc.getDocumentElement().getElementsByTagNameNS(soapenvNamespace, "Body").item(0);
        // System.out.println(XMLUtils.prettyPrintDOM(requestDoc));
        // Extract variables
        List<RequestableHttpVariable> variables = new ArrayList<RequestableHttpVariable>();
        extractSoapVariables(xmlSchema, variables, header, null, false, null);
        extractSoapVariables(xmlSchema, variables, body, null, false, null);
        // Serialize request/response into template xml files
        String projectName = project.getName();
        String connectorName = httpConnector.getName();
        String templateDir = Engine.projectDir(projectName) + "/soap-templates/" + connectorName;
        File dir = new File(templateDir);
        if (!dir.exists())
            dir.mkdirs();
        String requestTemplateName = "/soap-templates/" + connectorName + "/" + xmlHttpTransaction.getName() + ".xml";
        String requestTemplate = Engine.PROJECTS_PATH + "/" + projectName + requestTemplateName;
        xmlHttpTransaction.setRequestTemplate(requestTemplateName);
        saveTemplate(requestDoc, requestTemplate);
        // Adds variables
        for (RequestableHttpVariable variable : variables) {
            // System.out.println("adding "+ variable.getName());
            xmlHttpTransaction.add(variable);
        }
        xmlHttpTransaction.hasChanged = true;
    }
    return xmlHttpTransaction;
}
Also used : InputSource(org.xml.sax.InputSource) RequestableHttpVariable(com.twinsoft.convertigo.beans.variables.RequestableHttpVariable) XMLVector(com.twinsoft.convertigo.beans.common.XMLVector) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) XmlHttpTransaction(com.twinsoft.convertigo.beans.transactions.XmlHttpTransaction) XmlQName(com.twinsoft.convertigo.beans.common.XmlQName) QName(javax.xml.namespace.QName) MessagePart(com.eviware.soapui.model.iface.MessagePart) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) EngineException(com.twinsoft.convertigo.engine.EngineException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) XmlQName(com.twinsoft.convertigo.beans.common.XmlQName) WsdlRequest(com.eviware.soapui.impl.wsdl.WsdlRequest) DocumentBuilder(javax.xml.parsers.DocumentBuilder) StringReader(java.io.StringReader) File(java.io.File)

Example 3 with XmlHttpTransaction

use of com.twinsoft.convertigo.beans.transactions.XmlHttpTransaction in project convertigo by convertigo.

the class WsReference method importSoapWebService.

private static HttpConnector importSoapWebService(Project project, WebServiceReference soapServiceReference) throws Exception {
    List<HttpConnector> connectors = new ArrayList<HttpConnector>();
    HttpConnector firstConnector = null;
    String wsdlUrl = soapServiceReference.getUrlpath();
    WsdlProject wsdlProject = new WsdlProject();
    WsdlInterface[] wsdls = WsdlImporter.importWsdl(wsdlProject, wsdlUrl);
    int len = wsdls.length;
    if (len > 0) {
        WsdlInterface iface = wsdls[len - 1];
        if (iface != null) {
            // Retrieve definition name or first service name
            String definitionName = null;
            try {
                Definition definition = iface.getWsdlContext().getDefinition();
                QName qname = definition.getQName();
                qname = (qname == null ? (QName) definition.getAllServices().keySet().iterator().next() : qname);
                definitionName = qname.getLocalPart();
            } catch (Exception e1) {
                throw new Exception("No service found !");
            }
            // Modify reference's name
            if (soapServiceReference.bNew) {
                // Note : new reference may have already been added to the project (new object wizard)
                // its name must be replaced with a non existing one !
                String newDatabaseObjectName = project.getChildBeanName(project.getReferenceList(), StringUtils.normalize("Import_WS_" + definitionName), true);
                soapServiceReference.setName(newDatabaseObjectName);
            }
            // Retrieve directory for WSDLs to download
            File exportDir = null;
            /* For further use...
				if (!webServiceReference.getFilepath().isEmpty()) {	// for update case
					try {
						exportDir = webServiceReference.getFile().getParentFile();
						if (exportDir.exists()) {
							File destDir = exportDir;
					   		for (int index = 0; destDir.exists(); index++) {
					   			destDir = new File(exportDir.getPath()+ "/v" + index);
					   		}
							Collection<File> files = GenericUtils.cast(FileUtils.listFiles(exportDir, null, false));
							for (File file: files) {
								FileUtils.copyFileToDirectory(file, destDir);
							}
						}
					} catch (Exception ex) {}
				}*/
            if (soapServiceReference.bNew || exportDir == null) {
                // for other cases
                String projectDir = project.getDirPath();
                exportDir = new File(projectDir + "/wsdl/" + definitionName);
                for (int index = 1; exportDir.exists(); index++) {
                    exportDir = new File(projectDir + "/wsdl/" + definitionName + index);
                }
            }
            // Download all needed WSDLs (main one and imported/included ones)
            String wsdlPath = iface.getWsdlContext().export(exportDir.getPath());
            // Modify reference's filePath : path to local main WSDL
            String wsdlUriPath = new File(wsdlPath).toURI().getPath();
            String wsdlLocalPath = ".//" + wsdlUriPath.substring(wsdlUriPath.indexOf("/wsdl") + 1);
            soapServiceReference.setFilepath(wsdlLocalPath);
            soapServiceReference.hasChanged = true;
            // Add reference to project
            if (soapServiceReference.getParent() == null) {
                project.add(soapServiceReference);
            }
            // create an HTTP connector for each binding
            if (soapServiceReference.bNew) {
                for (int i = 0; i < wsdls.length; i++) {
                    iface = wsdls[i];
                    if (iface != null) {
                        Definition definition = iface.getWsdlContext().getDefinition();
                        XmlSchemaCollection xmlSchemaCollection = WSDLUtils.readSchemas(definition);
                        XmlSchema xmlSchema = xmlSchemaCollection.schemaForNamespace(definition.getTargetNamespace());
                        HttpConnector httpConnector = createSoapConnector(iface);
                        if (httpConnector != null) {
                            String bindingName = iface.getBindingName().getLocalPart();
                            String newDatabaseObjectName = project.getChildBeanName(project.getConnectorsList(), StringUtils.normalize(bindingName), true);
                            httpConnector.setName(newDatabaseObjectName);
                            boolean hasDefaultTransaction = false;
                            for (int j = 0; j < iface.getOperationCount(); j++) {
                                WsdlOperation wsdlOperation = (WsdlOperation) iface.getOperationAt(j);
                                XmlHttpTransaction xmlHttpTransaction = createSoapTransaction(xmlSchema, iface, wsdlOperation, project, httpConnector);
                                // Adds transaction
                                if (xmlHttpTransaction != null) {
                                    httpConnector.add(xmlHttpTransaction);
                                    if (!hasDefaultTransaction) {
                                        xmlHttpTransaction.setByDefault();
                                        hasDefaultTransaction = true;
                                    }
                                }
                            }
                            connectors.add(httpConnector);
                        }
                    }
                }
                // add connector(s) to project
                for (HttpConnector httpConnector : connectors) {
                    project.add(httpConnector);
                    if (firstConnector == null) {
                        firstConnector = httpConnector;
                    }
                }
            }
        }
    } else {
        throw new Exception("No interface found !");
    }
    return firstConnector;
}
Also used : HttpConnector(com.twinsoft.convertigo.beans.connectors.HttpConnector) XmlQName(com.twinsoft.convertigo.beans.common.XmlQName) QName(javax.xml.namespace.QName) XmlHttpTransaction(com.twinsoft.convertigo.beans.transactions.XmlHttpTransaction) ArrayList(java.util.ArrayList) Definition(javax.wsdl.Definition) WsdlProject(com.eviware.soapui.impl.wsdl.WsdlProject) XmlSchemaCollection(org.apache.ws.commons.schema.XmlSchemaCollection) SAXException(org.xml.sax.SAXException) EngineException(com.twinsoft.convertigo.engine.EngineException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) WsdlOperation(com.eviware.soapui.impl.wsdl.WsdlOperation) XmlSchema(org.apache.ws.commons.schema.XmlSchema) WsdlInterface(com.eviware.soapui.impl.wsdl.WsdlInterface) File(java.io.File)

Example 4 with XmlHttpTransaction

use of com.twinsoft.convertigo.beans.transactions.XmlHttpTransaction 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 5 with XmlHttpTransaction

use of com.twinsoft.convertigo.beans.transactions.XmlHttpTransaction in project convertigo by convertigo.

the class UpdateXSDTypesAction method run.

public void run() {
    final Display display = Display.getDefault();
    Cursor waitCursor = new Cursor(display, SWT.CURSOR_WAIT);
    Shell shell = getParentShell();
    shell.setCursor(waitCursor);
    try {
        ProjectExplorerView explorerView = getProjectExplorerView();
        if (explorerView != null) {
            TreeObject treeObject = explorerView.getFirstSelectedTreeObject();
            ProjectTreeObject projectTreeObject = treeObject.getProjectTreeObject();
            MessageBox messageBox = new MessageBox(shell, SWT.YES | SWT.NO | SWT.CANCEL | SWT.ICON_QUESTION | SWT.APPLICATION_MODAL);
            String message = "Do you really want to extract the schema?\nWarning: the previous one will be replaced.";
            messageBox.setMessage(message);
            if (messageBox.open() == SWT.YES) {
                RequestableObject requestable = (RequestableObject) treeObject.getObject();
                String requestableName = StringUtils.normalize(requestable.getName(), true);
                Document document = null;
                String result = null;
                if (!(requestableName.equals(requestable.getName()))) {
                    throw new Exception("Requestable name should be normalized");
                }
                if (requestable instanceof Transaction) {
                    Connector connector = (Connector) requestable.getParent();
                    String connectorName = StringUtils.normalize(connector.getName(), true);
                    if (!(connectorName.equals(connector.getName()))) {
                        throw new Exception("Connector name should be normalized");
                    }
                    if (connector.getDefaultTransaction() == null) {
                        throw new Exception("Connector must have a default transaction");
                    }
                    if (requestable instanceof HtmlTransaction) {
                        if (extract) {
                            ConnectorEditor connectorEditor = projectTreeObject.getConnectorEditor(connector);
                            if (connectorEditor == null) {
                                ConvertigoPlugin.infoMessageBox("Please open connector first.");
                                return;
                            }
                            document = connectorEditor.getLastGeneratedDocument();
                            if (document == null) {
                                ConvertigoPlugin.infoMessageBox("You should first generate the XML document before trying to extract the XSD types.");
                                return;
                            }
                            result = requestable.generateXsdTypes(document, extract);
                        } else {
                            HtmlTransaction defaultTransaction = (HtmlTransaction) connector.getDefaultTransaction();
                            String defaultTransactionName = StringUtils.normalize(defaultTransaction.getName(), true);
                            if (!(defaultTransactionName.equals(defaultTransaction.getName()))) {
                                throw new Exception("Default transaction name should be normalized");
                            }
                            String defaultXsdTypes = defaultTransaction.generateXsdTypes(null, false);
                            if (requestable.equals(defaultTransaction))
                                result = defaultXsdTypes;
                            else {
                                TransactionXSDTypesDialog dlg = new TransactionXSDTypesDialog(shell, requestable);
                                if (dlg.open() == Window.OK) {
                                    result = dlg.result;
                                    result += defaultXsdTypes;
                                }
                            }
                        }
                    } else {
                        if (extract) {
                            ConnectorEditor connectorEditor = projectTreeObject.getConnectorEditor(connector);
                            if (connectorEditor == null) {
                                ConvertigoPlugin.infoMessageBox("Please open connector first.");
                                return;
                            }
                            document = connectorEditor.getLastGeneratedDocument();
                            if (document == null) {
                                ConvertigoPlugin.infoMessageBox("You should first generate the XML document before trying to extract the XSD types.");
                                return;
                            }
                            String prefix = requestable.getXsdTypePrefix();
                            document.getDocumentElement().setAttribute("transaction", prefix + requestableName);
                        }
                        if (requestable instanceof XmlHttpTransaction) {
                            XmlHttpTransaction xmlHttpTransaction = (XmlHttpTransaction) requestable;
                            XmlQName xmlQName = xmlHttpTransaction.getXmlElementRefAffectation();
                            String reqn = xmlHttpTransaction.getResponseElementQName();
                            if (extract && ((!xmlQName.isEmpty()) || (!reqn.equals("")))) {
                                if (!xmlQName.isEmpty()) {
                                    ConvertigoPlugin.infoMessageBox("You should first unset 'Assigned element QName' property.");
                                    return;
                                }
                                if (!reqn.equals("")) {
                                    ConvertigoPlugin.infoMessageBox("You should first unset 'Schema of XML response root element' property.");
                                    return;
                                }
                            }
                        }
                        result = requestable.generateXsdTypes(document, extract);
                    }
                }
                if ((result != null) && (!result.equals(""))) {
                    String xsdTypes = result;
                    if (requestable instanceof Transaction) {
                        if (requestable instanceof XmlHttpTransaction) {
                            XmlHttpTransaction xmlHttpTransaction = (XmlHttpTransaction) requestable;
                            XmlQName xmlQName = xmlHttpTransaction.getXmlElementRefAffectation();
                            String reqn = xmlHttpTransaction.getResponseElementQName();
                            if (!extract && ((!xmlQName.isEmpty()) || (!reqn.equals("")))) {
                                // ignore
                                ;
                            } else
                                ((Transaction) requestable).writeSchemaToFile(xsdTypes);
                        } else
                            ((Transaction) requestable).writeSchemaToFile(xsdTypes);
                    }
                    requestable.hasChanged = true;
                    Engine.theApp.schemaManager.clearCache(requestable.getProject().getName());
                    explorerView.refreshFirstSelectedTreeObject();
                    explorerView.objectSelected(new CompositeEvent(requestable));
                }
            }
        }
    } catch (Throwable e) {
        ConvertigoPlugin.logException(e, "Unable to update schema!");
    } finally {
        shell.setCursor(null);
        waitCursor.dispose();
    }
}
Also used : Connector(com.twinsoft.convertigo.beans.core.Connector) ProjectExplorerView(com.twinsoft.convertigo.eclipse.views.projectexplorer.ProjectExplorerView) RequestableObject(com.twinsoft.convertigo.beans.core.RequestableObject) XmlHttpTransaction(com.twinsoft.convertigo.beans.transactions.XmlHttpTransaction) HtmlTransaction(com.twinsoft.convertigo.beans.transactions.HtmlTransaction) Cursor(org.eclipse.swt.graphics.Cursor) Document(org.w3c.dom.Document) ConnectorEditor(com.twinsoft.convertigo.eclipse.editors.connector.ConnectorEditor) MessageBox(org.eclipse.swt.widgets.MessageBox) XmlQName(com.twinsoft.convertigo.beans.common.XmlQName) Shell(org.eclipse.swt.widgets.Shell) HtmlTransaction(com.twinsoft.convertigo.beans.transactions.HtmlTransaction) XmlHttpTransaction(com.twinsoft.convertigo.beans.transactions.XmlHttpTransaction) Transaction(com.twinsoft.convertigo.beans.core.Transaction) TransactionXSDTypesDialog(com.twinsoft.convertigo.eclipse.dialogs.TransactionXSDTypesDialog) TreeObject(com.twinsoft.convertigo.eclipse.views.projectexplorer.model.TreeObject) ProjectTreeObject(com.twinsoft.convertigo.eclipse.views.projectexplorer.model.ProjectTreeObject) ProjectTreeObject(com.twinsoft.convertigo.eclipse.views.projectexplorer.model.ProjectTreeObject) CompositeEvent(com.twinsoft.convertigo.eclipse.editors.CompositeEvent) Display(org.eclipse.swt.widgets.Display)

Aggregations

XmlHttpTransaction (com.twinsoft.convertigo.beans.transactions.XmlHttpTransaction)8 HttpConnector (com.twinsoft.convertigo.beans.connectors.HttpConnector)5 XMLVector (com.twinsoft.convertigo.beans.common.XMLVector)4 XmlQName (com.twinsoft.convertigo.beans.common.XmlQName)4 HttpTransaction (com.twinsoft.convertigo.beans.transactions.HttpTransaction)4 JsonHttpTransaction (com.twinsoft.convertigo.beans.transactions.JsonHttpTransaction)4 RequestableHttpVariable (com.twinsoft.convertigo.beans.variables.RequestableHttpVariable)4 IOException (java.io.IOException)4 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)3 Connector (com.twinsoft.convertigo.beans.core.Connector)3 Transaction (com.twinsoft.convertigo.beans.core.Transaction)3 AbstractHttpTransaction (com.twinsoft.convertigo.beans.transactions.AbstractHttpTransaction)3 RequestableHttpMultiValuedVariable (com.twinsoft.convertigo.beans.variables.RequestableHttpMultiValuedVariable)3 EngineException (com.twinsoft.convertigo.engine.EngineException)3 File (java.io.File)3 ArrayList (java.util.ArrayList)3 QName (javax.xml.namespace.QName)3 Sequence (com.twinsoft.convertigo.beans.core.Sequence)2 TransactionWithVariables (com.twinsoft.convertigo.beans.core.TransactionWithVariables)2 UrlMappingOperation (com.twinsoft.convertigo.beans.core.UrlMappingOperation)2