Search in sources :

Example 11 with AbstractHttpTransaction

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

the class OpenApiUtils method createRestConnector.

public static HttpConnector createRestConnector(OpenAPI openApi) throws Exception {
    try {
        HttpConnector httpConnector = new HttpConnector();
        httpConnector.bNew = true;
        Info info = openApi.getInfo();
        String title = info != null ? info.getTitle() : "";
        title = title == null || title.isEmpty() ? "RestConnector" : title;
        String description = info != null ? info.getDescription() : "";
        description = description == null || description.isEmpty() ? "" : description;
        httpConnector.setName(StringUtils.normalize(title));
        httpConnector.setComment(description);
        String httpUrl = "";
        List<Server> servers = openApi.getServers();
        if (servers.size() > 0) {
            httpUrl = servers.get(0).getUrl();
        }
        httpUrl = httpUrl.isEmpty() ? getConvertigoServeurUrl() : httpUrl;
        UrlFields urlFields = UrlParser.parse(httpUrl);
        if (urlFields != null) {
            String scheme = urlFields.getScheme();
            String host = urlFields.getHost();
            String port = urlFields.getPort();
            String basePath = urlFields.getPath();
            boolean isHttps = "https".equals(scheme);
            httpConnector.setHttps(isHttps);
            httpConnector.setServer(host);
            httpConnector.setPort(port == null ? (isHttps ? 443 : 80) : Integer.valueOf(port));
            httpConnector.setBaseDir(basePath);
        }
        httpConnector.setBaseUrl(httpUrl);
        List<SecurityRequirement> securityRequirements = openApi.getSecurity();
        if (securityRequirements != null && securityRequirements.size() > 0) {
            Map<String, SecurityScheme> securitySchemes = openApi.getComponents().getSecuritySchemes();
            for (SecurityRequirement sr : securityRequirements) {
                for (String s_name : sr.keySet()) {
                    SecurityScheme securityScheme = securitySchemes.get(s_name);
                    if (securityScheme != null) {
                        String scheme = securityScheme.getScheme() == null ? "" : securityScheme.getScheme();
                        boolean isBasicScheme = scheme.toLowerCase().equals("basic");
                        boolean isHttpType = securityScheme.getType().equals(SecurityScheme.Type.HTTP);
                        if (isHttpType && isBasicScheme) {
                            httpConnector.setAuthenticationType(AuthenticationMode.Basic);
                            break;
                        }
                    }
                }
            }
        }
        Paths paths = openApi.getPaths();
        if (paths != null) {
            AbstractHttpTransaction defTransaction = null;
            for (Entry<String, PathItem> entry : paths.entrySet()) {
                HttpMethodType httpMethodType = null;
                Operation operation = null;
                String customHttpVerb = "";
                String subDir = entry.getKey();
                PathItem pathItem = entry.getValue();
                Map<HttpMethod, Operation> operationMap = pathItem.readOperationsMap();
                for (HttpMethod httpMethod : operationMap.keySet()) {
                    operation = operationMap.get(httpMethod);
                    if (httpMethod.equals(HttpMethod.GET)) {
                        httpMethodType = HttpMethodType.GET;
                    } else if (httpMethod.equals(HttpMethod.POST)) {
                        httpMethodType = HttpMethodType.POST;
                    } else if (httpMethod.equals(HttpMethod.PUT)) {
                        httpMethodType = HttpMethodType.PUT;
                    } else if (httpMethod.equals(HttpMethod.PATCH)) {
                        httpMethodType = HttpMethodType.PUT;
                        customHttpVerb = "PATCH";
                    } else if (httpMethod.equals(HttpMethod.DELETE)) {
                        httpMethodType = HttpMethodType.DELETE;
                    } else if (httpMethod.equals(HttpMethod.HEAD)) {
                        httpMethodType = HttpMethodType.HEAD;
                    } else if (httpMethod.equals(HttpMethod.TRACE)) {
                        httpMethodType = HttpMethodType.TRACE;
                    } else if (httpMethod.equals(HttpMethod.OPTIONS)) {
                        httpMethodType = HttpMethodType.OPTIONS;
                    } else {
                        httpMethodType = null;
                    }
                    if (operation != null && httpMethodType != null) {
                        String operationId = operation.getOperationId();
                        String operationDesc = operation.getDescription();
                        String summary = operation.getSummary();
                        String name = StringUtils.normalize(subDir + ":" + (customHttpVerb.isEmpty() ? httpMethodType.toString() : customHttpVerb));
                        if (name.isEmpty()) {
                            name = StringUtils.normalize(operationId);
                            if (name.isEmpty()) {
                                name = StringUtils.normalize(summary);
                                if (name.isEmpty()) {
                                    name = "operation";
                                }
                            }
                        }
                        String comment = org.apache.commons.lang3.StringUtils.isNotBlank(summary) && !"null".equals(summary) ? summary : (org.apache.commons.lang3.StringUtils.isNotBlank(operationDesc) && !"null".equals(operationDesc) ? operationDesc : "");
                        XMLVector<XMLVector<String>> httpParameters = new XMLVector<XMLVector<String>>();
                        AbstractHttpTransaction transaction = new HttpTransaction();
                        String h_ContentType = MimeType.WwwForm.value();
                        /*if (consumeList != null) {
								if (consumeList.contains(MimeType.Json.value())) {
									h_ContentType = MimeType.Json.value();
								}
								else if (consumeList.contains(MimeType.Xml.value())) {
									h_ContentType = MimeType.Xml.value();
								}
								else {
									h_ContentType = consumeList.size() > 0 ? 
											consumeList.get(0) : MimeType.WwwForm.value();
								}
							}*/
                        String 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);
                            }
                        }
                        // Add variables
                        boolean hasBodyVariable = false;
                        RequestBody body = operation.getRequestBody();
                        if (body != null) {
                            Map<String, MediaType> medias = body.getContent();
                            for (String contentType : medias.keySet()) {
                                MediaType mediaType = medias.get(contentType);
                                Schema<?> mediaSchema = mediaType.getSchema();
                                List<String> requiredList = mediaSchema.getRequired();
                                if (contentType.equals("application/x-www-form-urlencoded")) {
                                    @SuppressWarnings("rawtypes") Map<String, Schema> properties = mediaSchema.getProperties();
                                    if (properties != null) {
                                        for (String p_name : properties.keySet()) {
                                            Schema<?> schema = properties.get(p_name);
                                            String p_description = schema.getDescription();
                                            boolean p_required = requiredList == null ? false : requiredList.contains(p_name);
                                            boolean isMultiValued = false;
                                            if (schema instanceof ArraySchema) {
                                                isMultiValued = true;
                                            }
                                            RequestableHttpVariable httpVariable = isMultiValued ? new RequestableHttpMultiValuedVariable() : new RequestableHttpVariable();
                                            httpVariable.bNew = true;
                                            httpVariable.setHttpMethod(HttpMethodType.POST.name());
                                            httpVariable.setName(p_name);
                                            httpVariable.setDescription(p_name);
                                            httpVariable.setHttpName(p_name);
                                            httpVariable.setRequired(p_required);
                                            httpVariable.setComment(p_description == null ? "" : p_description);
                                            if (schema instanceof FileSchema) {
                                                httpVariable.setDoFileUploadMode(DoFileUploadMode.multipartFormData);
                                            }
                                            Object defaultValue = schema.getDefault();
                                            if (defaultValue == null && p_required) {
                                                defaultValue = "";
                                            }
                                            httpVariable.setValueOrNull(defaultValue);
                                            transaction.addVariable(httpVariable);
                                        }
                                    }
                                } else if (!hasBodyVariable) {
                                    RequestableHttpVariable httpVariable = new RequestableHttpVariable();
                                    httpVariable.bNew = true;
                                    httpVariable.setHttpMethod(HttpMethodType.POST.name());
                                    httpVariable.setRequired(true);
                                    // overrides variable's name for internal use
                                    httpVariable.setName(com.twinsoft.convertigo.engine.enums.Parameter.HttpBody.getName());
                                    Object defaultValue = null;
                                    httpVariable.setValueOrNull(defaultValue);
                                    transaction.addVariable(httpVariable);
                                    h_ContentType = contentType;
                                    hasBodyVariable = true;
                                }
                            }
                        }
                        List<Parameter> parameters = operation.getParameters();
                        if (parameters != null) {
                            for (Parameter parameter : parameters) {
                                String p_name = parameter.getName();
                                String p_description = parameter.getDescription();
                                boolean p_required = parameter.getRequired();
                                boolean isMultiValued = false;
                                Schema<?> schema = parameter.getSchema();
                                if (schema instanceof ArraySchema) {
                                    isMultiValued = true;
                                }
                                RequestableHttpVariable httpVariable = isMultiValued ? new RequestableHttpMultiValuedVariable() : new RequestableHttpVariable();
                                httpVariable.bNew = true;
                                httpVariable.setName(p_name);
                                httpVariable.setDescription(p_name);
                                httpVariable.setHttpName(p_name);
                                httpVariable.setRequired(p_required);
                                httpVariable.setComment(p_description == null ? "" : p_description);
                                if (parameter instanceof QueryParameter || parameter instanceof PathParameter || parameter instanceof HeaderParameter) {
                                    httpVariable.setHttpMethod(HttpMethodType.GET.name());
                                    if (parameter instanceof HeaderParameter) {
                                        // overrides variable's name : will be treated as dynamic header
                                        httpVariable.setName(com.twinsoft.convertigo.engine.enums.Parameter.HttpHeader.getName() + p_name);
                                        // do not post on target server
                                        httpVariable.setHttpName("");
                                    }
                                    if (parameter instanceof PathParameter) {
                                        // do not post on target server
                                        httpVariable.setHttpName("");
                                    }
                                } else {
                                    httpVariable.setHttpMethod("");
                                }
                                Object defaultValue = schema.getDefault();
                                if (defaultValue == null && p_required) {
                                    defaultValue = "";
                                }
                                httpVariable.setValueOrNull(defaultValue);
                                transaction.addVariable(httpVariable);
                            }
                        }
                        // Set Content-Type
                        if (h_ContentType != null) {
                            XMLVector<String> xmlv = new XMLVector<String>();
                            xmlv.add(HeaderName.ContentType.value());
                            xmlv.add(hasBodyVariable ? h_ContentType : MimeType.WwwForm.value());
                            httpParameters.add(xmlv);
                        }
                        transaction.bNew = true;
                        transaction.setName(name);
                        transaction.setComment(comment);
                        transaction.setSubDir(subDir);
                        transaction.setHttpVerb(httpMethodType);
                        transaction.setCustomHttpVerb(customHttpVerb);
                        transaction.setHttpParameters(httpParameters);
                        transaction.setHttpInfo(true);
                        httpConnector.add(transaction);
                        if (defTransaction == null) {
                            defTransaction = transaction;
                            httpConnector.setDefaultTransaction(defTransaction);
                        }
                    }
                }
            }
        }
        return httpConnector;
    } catch (Throwable t) {
        Engine.logEngine.error("Unable to create connector", t);
        throw new Exception("Unable to create connector", t);
    }
}
Also used : XmlHttpTransaction(com.twinsoft.convertigo.beans.transactions.XmlHttpTransaction) JsonHttpTransaction(com.twinsoft.convertigo.beans.transactions.JsonHttpTransaction) HttpTransaction(com.twinsoft.convertigo.beans.transactions.HttpTransaction) AbstractHttpTransaction(com.twinsoft.convertigo.beans.transactions.AbstractHttpTransaction) HttpConnector(com.twinsoft.convertigo.beans.connectors.HttpConnector) RequestableHttpVariable(com.twinsoft.convertigo.beans.variables.RequestableHttpVariable) QueryParameter(io.swagger.v3.oas.models.parameters.QueryParameter) XMLVector(com.twinsoft.convertigo.beans.common.XMLVector) Server(io.swagger.v3.oas.models.servers.Server) HttpMethodType(com.twinsoft.convertigo.engine.enums.HttpMethodType) IntegerSchema(io.swagger.v3.oas.models.media.IntegerSchema) ArraySchema(io.swagger.v3.oas.models.media.ArraySchema) FileSchema(io.swagger.v3.oas.models.media.FileSchema) BooleanSchema(io.swagger.v3.oas.models.media.BooleanSchema) StringSchema(io.swagger.v3.oas.models.media.StringSchema) ObjectSchema(io.swagger.v3.oas.models.media.ObjectSchema) NumberSchema(io.swagger.v3.oas.models.media.NumberSchema) XmlSchema(org.apache.ws.commons.schema.XmlSchema) Schema(io.swagger.v3.oas.models.media.Schema) UrlMappingOperation(com.twinsoft.convertigo.beans.core.UrlMappingOperation) Operation(io.swagger.v3.oas.models.Operation) AbstractRestOperation(com.twinsoft.convertigo.beans.rest.AbstractRestOperation) PathParameter(io.swagger.v3.oas.models.parameters.PathParameter) AbstractHttpTransaction(com.twinsoft.convertigo.beans.transactions.AbstractHttpTransaction) PathItem(io.swagger.v3.oas.models.PathItem) ArraySchema(io.swagger.v3.oas.models.media.ArraySchema) MediaType(io.swagger.v3.oas.models.media.MediaType) Paths(io.swagger.v3.oas.models.Paths) HeaderParameter(io.swagger.v3.oas.models.parameters.HeaderParameter) SecurityScheme(io.swagger.v3.oas.models.security.SecurityScheme) FileSchema(io.swagger.v3.oas.models.media.FileSchema) RequestBody(io.swagger.v3.oas.models.parameters.RequestBody) UrlFields(com.twinsoft.convertigo.engine.util.UrlParser.UrlFields) XmlHttpTransaction(com.twinsoft.convertigo.beans.transactions.XmlHttpTransaction) Info(io.swagger.v3.oas.models.info.Info) JSONException(org.codehaus.jettison.json.JSONException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) RequestableHttpMultiValuedVariable(com.twinsoft.convertigo.beans.variables.RequestableHttpMultiValuedVariable) HeaderParameter(io.swagger.v3.oas.models.parameters.HeaderParameter) PathParameter(io.swagger.v3.oas.models.parameters.PathParameter) LinkParameter(io.swagger.v3.oas.models.links.LinkParameter) Parameter(io.swagger.v3.oas.models.parameters.Parameter) QueryParameter(io.swagger.v3.oas.models.parameters.QueryParameter) UrlMappingParameter(com.twinsoft.convertigo.beans.core.UrlMappingParameter) JsonHttpTransaction(com.twinsoft.convertigo.beans.transactions.JsonHttpTransaction) JSONObject(org.codehaus.jettison.json.JSONObject) HttpMethod(io.swagger.v3.oas.models.PathItem.HttpMethod) SecurityRequirement(io.swagger.v3.oas.models.security.SecurityRequirement)

Example 12 with AbstractHttpTransaction

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

the class SwaggerUtils method createRestConnector.

public static HttpConnector createRestConnector(Swagger swagger) throws Exception {
    try {
        HttpConnector httpConnector = new HttpConnector();
        httpConnector.bNew = true;
        Info info = swagger.getInfo();
        String title = info != null ? info.getTitle() : "";
        title = title == null || title.isEmpty() ? "RestConnector" : title;
        httpConnector.setName(StringUtils.normalize(title));
        boolean isHttps = false;
        for (Scheme scheme : swagger.getSchemes()) {
            if (scheme.equals(Scheme.HTTPS)) {
                isHttps = true;
            }
        }
        String host = swagger.getHost();
        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.setHttps(isHttps);
        httpConnector.setServer(server);
        httpConnector.setPort(port <= 0 ? (isHttps ? 443 : 80) : port);
        String basePath = swagger.getBasePath();
        httpConnector.setBaseDir(basePath);
        Map<String, SecuritySchemeDefinition> securityMap = swagger.getSecurityDefinitions();
        if (securityMap != null && securityMap.size() > 0) {
            for (String securityName : securityMap.keySet()) {
                SecuritySchemeDefinition securityScheme = securityMap.get(securityName);
                if (securityScheme != null) {
                    boolean isBasicScheme = securityScheme.getType().toLowerCase().equals("basic");
                    if (isBasicScheme) {
                        httpConnector.setAuthenticationType(AuthenticationMode.Basic);
                        break;
                    }
                }
            }
        }
        List<String> _consumeList = swagger.getConsumes();
        List<String> _produceList = swagger.getProduces();
        // Map<String, Model> models = swagger.getDefinitions();
        Map<String, Path> paths = swagger.getPaths();
        for (String subDir : paths.keySet()) {
            Path path = paths.get(subDir);
            // Add transactions
            List<Operation> operations = path.getOperations();
            for (Operation operation : operations) {
                HttpMethodType httpMethodType = null;
                if (operation.equals(path.getGet())) {
                    httpMethodType = HttpMethodType.GET;
                } else if (operation.equals(path.getPost())) {
                    httpMethodType = HttpMethodType.POST;
                } else if (operation.equals(path.getPut())) {
                    httpMethodType = HttpMethodType.PUT;
                } else if (operation.equals(path.getDelete())) {
                    httpMethodType = HttpMethodType.DELETE;
                } else if (operation.equals(path.getHead())) {
                    httpMethodType = HttpMethodType.HEAD;
                } else if (operation.equals(path.getOptions())) {
                    httpMethodType = HttpMethodType.OPTIONS;
                } else {
                    httpMethodType = null;
                }
                if (httpMethodType != null) {
                    List<String> consumeList = operation.getConsumes();
                    consumeList = consumeList == null || consumeList.isEmpty() ? _consumeList : consumeList;
                    List<String> produceList = operation.getProduces();
                    produceList = produceList == null || produceList.isEmpty() ? _produceList : produceList;
                    String operationId = operation.getOperationId();
                    String description = operation.getDescription();
                    String summary = operation.getSummary();
                    String name = StringUtils.normalize(subDir + ":" + httpMethodType.toString());
                    if (name.isEmpty()) {
                        name = StringUtils.normalize(operationId);
                        if (name.isEmpty()) {
                            name = StringUtils.normalize(summary);
                            if (name.isEmpty()) {
                                name = "operation";
                            }
                        }
                    }
                    String comment = summary;
                    if (comment == null)
                        comment = "";
                    if (comment.isEmpty()) {
                        comment = description;
                    }
                    XMLVector<XMLVector<String>> httpParameters = new XMLVector<XMLVector<String>>();
                    AbstractHttpTransaction transaction = new HttpTransaction();
                    String h_ContentType = MimeType.WwwForm.value();
                    if (consumeList != null) {
                        if (consumeList.contains(MimeType.Json.value())) {
                            h_ContentType = MimeType.Json.value();
                        } else if (consumeList.contains(MimeType.Xml.value())) {
                            h_ContentType = MimeType.Xml.value();
                        } else {
                            h_ContentType = consumeList.size() > 0 ? consumeList.get(0) : MimeType.WwwForm.value();
                        }
                    }
                    String h_Accept = MimeType.Json.value();
                    if (produceList != null) {
                        if (produceList.contains(h_ContentType)) {
                            h_Accept = h_ContentType;
                        } else {
                            if (produceList.contains(MimeType.Json.value())) {
                                h_Accept = MimeType.Json.value();
                            } else if (produceList.contains(MimeType.Xml.value())) {
                                h_Accept = MimeType.Xml.value();
                            }
                        }
                        if (consumeList == null && h_Accept != null) {
                            h_ContentType = h_Accept;
                        }
                    }
                    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);
                        }
                    }
                    // Add variables
                    boolean hasBodyVariable = false;
                    List<io.swagger.models.parameters.Parameter> parameters = operation.getParameters();
                    for (io.swagger.models.parameters.Parameter parameter : parameters) {
                        // String p_access = parameter.getAccess();
                        String p_description = parameter.getDescription();
                        // String p_in = parameter.getIn();
                        String p_name = parameter.getName();
                        // String p_pattern = parameter.getPattern();
                        boolean p_required = parameter.getRequired();
                        // Map<String,Object> p_extensions = parameter.getVendorExtensions();
                        boolean isMultiValued = false;
                        if (parameter instanceof SerializableParameter) {
                            SerializableParameter serializable = (SerializableParameter) parameter;
                            if (serializable.getType().equalsIgnoreCase("array")) {
                                if (serializable.getCollectionFormat().equalsIgnoreCase("multi")) {
                                    isMultiValued = true;
                                }
                            }
                        }
                        RequestableHttpVariable httpVariable = isMultiValued ? new RequestableHttpMultiValuedVariable() : new RequestableHttpVariable();
                        httpVariable.bNew = true;
                        httpVariable.setName(p_name);
                        httpVariable.setHttpName(p_name);
                        httpVariable.setRequired(p_required);
                        if (parameter instanceof QueryParameter || parameter instanceof PathParameter || parameter instanceof HeaderParameter) {
                            httpVariable.setHttpMethod(HttpMethodType.GET.name());
                            if (parameter instanceof HeaderParameter) {
                                // overrides variable's name : will be treated as dynamic header
                                httpVariable.setName(com.twinsoft.convertigo.engine.enums.Parameter.HttpHeader.getName() + p_name);
                                // do not post on target server
                                httpVariable.setHttpName("");
                            }
                            if (parameter instanceof PathParameter) {
                                // do not post on target server
                                httpVariable.setHttpName("");
                            }
                        } else if (parameter instanceof FormParameter || parameter instanceof BodyParameter) {
                            httpVariable.setHttpMethod(HttpMethodType.POST.name());
                            if (parameter instanceof FormParameter) {
                                FormParameter formParameter = (FormParameter) parameter;
                                if (formParameter.getType().equalsIgnoreCase("file")) {
                                    httpVariable.setDoFileUploadMode(DoFileUploadMode.multipartFormData);
                                }
                            } else if (parameter instanceof BodyParameter) {
                                hasBodyVariable = true;
                                // 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(Parameter.HttpContentType.getName());
									ct.setHttpMethod(HttpMethodType.POST.name());
									ct.setValueOrNull(null);
									ct.bNew = true;
									transaction.addVariable(ct);*/
                                BodyParameter bodyParameter = (BodyParameter) parameter;
                                Model model = bodyParameter.getSchema();
                                if (model != null) {
                                }
                            }
                        } else {
                            httpVariable.setHttpMethod("");
                        }
                        Object defaultValue = null;
                        if (parameter instanceof AbstractSerializableParameter<?>) {
                            defaultValue = ((AbstractSerializableParameter<?>) parameter).getDefaultValue();
                        }
                        if (defaultValue == null && parameter instanceof SerializableParameter) {
                            SerializableParameter serializable = (SerializableParameter) parameter;
                            if (serializable.getType().equalsIgnoreCase("array")) {
                                Property items = serializable.getItems();
                                try {
                                    Class<?> c = items.getClass();
                                    defaultValue = c.getMethod("getDefault").invoke(items);
                                } catch (Exception e) {
                                }
                            }
                        }
                        if (defaultValue == null && p_required) {
                            defaultValue = "";
                        }
                        httpVariable.setValueOrNull(defaultValue);
                        if (p_description != null) {
                            httpVariable.setDescription(p_description);
                            httpVariable.setComment(p_description);
                        }
                        transaction.addVariable(httpVariable);
                    }
                    // Set Content-Type
                    if (h_ContentType != null) {
                        XMLVector<String> xmlv = new XMLVector<String>();
                        xmlv.add(HeaderName.ContentType.value());
                        xmlv.add(hasBodyVariable ? h_ContentType : MimeType.WwwForm.value());
                        httpParameters.add(xmlv);
                    }
                    transaction.bNew = true;
                    transaction.setName(name);
                    transaction.setComment(comment);
                    transaction.setSubDir(subDir);
                    transaction.setHttpVerb(httpMethodType);
                    transaction.setHttpParameters(httpParameters);
                    transaction.setHttpInfo(true);
                    httpConnector.add(transaction);
                }
            }
        }
        return httpConnector;
    } catch (Throwable t) {
        Engine.logEngine.error("Unable to create connector", t);
        throw new Exception("Unable to create connector", t);
    }
}
Also used : SerializableParameter(io.swagger.models.parameters.SerializableParameter) AbstractSerializableParameter(io.swagger.models.parameters.AbstractSerializableParameter) 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) QueryParameter(io.swagger.models.parameters.QueryParameter) Scheme(io.swagger.models.Scheme) XMLVector(com.twinsoft.convertigo.beans.common.XMLVector) HttpMethodType(com.twinsoft.convertigo.engine.enums.HttpMethodType) Operation(io.swagger.models.Operation) AbstractRestOperation(com.twinsoft.convertigo.beans.rest.AbstractRestOperation) UrlMappingOperation(com.twinsoft.convertigo.beans.core.UrlMappingOperation) BodyParameter(io.swagger.models.parameters.BodyParameter) PathParameter(io.swagger.models.parameters.PathParameter) FormParameter(io.swagger.models.parameters.FormParameter) AbstractHttpTransaction(com.twinsoft.convertigo.beans.transactions.AbstractHttpTransaction) AbstractSerializableParameter(io.swagger.models.parameters.AbstractSerializableParameter) HeaderParameter(io.swagger.models.parameters.HeaderParameter) StringProperty(io.swagger.models.properties.StringProperty) Property(io.swagger.models.properties.Property) DoubleProperty(io.swagger.models.properties.DoubleProperty) RefProperty(io.swagger.models.properties.RefProperty) IntegerProperty(io.swagger.models.properties.IntegerProperty) BooleanProperty(io.swagger.models.properties.BooleanProperty) Path(io.swagger.models.Path) XmlHttpTransaction(com.twinsoft.convertigo.beans.transactions.XmlHttpTransaction) Parameter(io.swagger.models.parameters.Parameter) SecuritySchemeDefinition(io.swagger.models.auth.SecuritySchemeDefinition) Info(io.swagger.models.Info) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) RequestableHttpMultiValuedVariable(com.twinsoft.convertigo.beans.variables.RequestableHttpMultiValuedVariable) Model(io.swagger.models.Model) RefModel(io.swagger.models.RefModel) IMappingRefModel(com.twinsoft.convertigo.beans.core.IMappingRefModel) SerializableParameter(io.swagger.models.parameters.SerializableParameter) FormParameter(io.swagger.models.parameters.FormParameter) PathParameter(io.swagger.models.parameters.PathParameter) Parameter(io.swagger.models.parameters.Parameter) QueryParameter(io.swagger.models.parameters.QueryParameter) AbstractSerializableParameter(io.swagger.models.parameters.AbstractSerializableParameter) HeaderParameter(io.swagger.models.parameters.HeaderParameter) BodyParameter(io.swagger.models.parameters.BodyParameter) UrlMappingParameter(com.twinsoft.convertigo.beans.core.UrlMappingParameter) JsonHttpTransaction(com.twinsoft.convertigo.beans.transactions.JsonHttpTransaction) JSONObject(org.codehaus.jettison.json.JSONObject)

Example 13 with AbstractHttpTransaction

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

the class HttpConnector method getData.

public byte[] getData(Context context, String sUrl) throws IOException, EngineException {
    HttpMethod method = null;
    try {
        // Fire event for plugins
        long t0 = System.currentTimeMillis();
        Engine.theApp.pluginsManager.fireHttpConnectorGetDataStart(context);
        Engine.logBeans.trace("(HttpConnector) Retrieving data as a bytes array...");
        Engine.logBeans.debug("(HttpConnector) Connecting to: " + sUrl);
        // Setting the referer
        referer = sUrl;
        Engine.logBeans.debug("(HttpConnector) Https: " + https);
        URL url = new URL(sUrl);
        String host = url.getHost();
        int port = url.getPort();
        if (sUrl.toLowerCase().startsWith("https:")) {
            if (!https) {
                Engine.logBeans.debug("(HttpConnector) Setting up SSL properties");
                certificateManager.collectStoreInformation(context);
            }
            if (port == -1)
                port = 443;
            Engine.logBeans.debug("(HttpConnector) Host: " + host + ":" + port);
            Engine.logBeans.debug("(HttpConnector) CertificateManager has changed: " + certificateManager.hasChanged);
            if (certificateManager.hasChanged || (!host.equalsIgnoreCase(hostConfiguration.getHost())) || (hostConfiguration.getPort() != port)) {
                Engine.logBeans.debug("(HttpConnector) Using MySSLSocketFactory for creating the SSL socket");
                Protocol myhttps = new Protocol("https", MySSLSocketFactory.getSSLSocketFactory(certificateManager.keyStore, certificateManager.keyStorePassword, certificateManager.trustStore, certificateManager.trustStorePassword, this.trustAllServerCertificates), port);
                hostConfiguration.setHost(host, port, myhttps);
            }
            sUrl = url.getFile();
            Engine.logBeans.debug("(HttpConnector) Updated URL for SSL purposes: " + sUrl);
        } else {
            Engine.logBeans.debug("(HttpConnector) Host: " + host + ":" + port);
            hostConfiguration.setHost(host, port);
        }
        // Retrieving httpState
        getHttpState(context);
        // Proxy configuration
        Engine.theApp.proxyManager.setProxy(hostConfiguration, httpState, url);
        AbstractHttpTransaction httpTransaction = (AbstractHttpTransaction) context.transaction;
        // Retrieve HTTP method
        HttpMethodType httpVerb = httpTransaction.getHttpVerb();
        String sHttpVerb = httpVerb.name();
        final String sCustomHttpVerb = httpTransaction.getCustomHttpVerb();
        if (sCustomHttpVerb.length() > 0) {
            Engine.logBeans.debug("(HttpConnector) HTTP verb: " + sHttpVerb + " overridden to '" + sCustomHttpVerb + "'");
            switch(httpVerb) {
                case GET:
                    method = new GetMethod(sUrl) {

                        @Override
                        public String getName() {
                            return sCustomHttpVerb;
                        }
                    };
                    break;
                case POST:
                    method = new PostMethod(sUrl) {

                        @Override
                        public String getName() {
                            return sCustomHttpVerb;
                        }
                    };
                    break;
                case PUT:
                    method = new PutMethod(sUrl) {

                        @Override
                        public String getName() {
                            return sCustomHttpVerb;
                        }
                    };
                    break;
                case DELETE:
                    method = new DeleteMethod(sUrl) {

                        @Override
                        public String getName() {
                            return sCustomHttpVerb;
                        }
                    };
                    break;
                case HEAD:
                    method = new HeadMethod(sUrl) {

                        @Override
                        public String getName() {
                            return sCustomHttpVerb;
                        }
                    };
                    break;
                case OPTIONS:
                    method = new OptionsMethod(sUrl) {

                        @Override
                        public String getName() {
                            return sCustomHttpVerb;
                        }
                    };
                    break;
                case TRACE:
                    method = new TraceMethod(sUrl) {

                        @Override
                        public String getName() {
                            return sCustomHttpVerb;
                        }
                    };
                    break;
            }
        } else {
            Engine.logBeans.debug("(HttpConnector) HTTP verb: " + sHttpVerb);
            switch(httpVerb) {
                case GET:
                    method = new GetMethod(sUrl);
                    break;
                case POST:
                    method = new PostMethod(sUrl);
                    break;
                case PUT:
                    method = new PutMethod(sUrl);
                    break;
                case DELETE:
                    method = new DeleteMethod(sUrl);
                    break;
                case HEAD:
                    method = new HeadMethod(sUrl);
                    break;
                case OPTIONS:
                    method = new OptionsMethod(sUrl);
                    break;
                case TRACE:
                    method = new TraceMethod(sUrl);
                    break;
            }
        }
        // Setting HTTP parameters
        boolean hasUserAgent = false;
        for (List<String> httpParameter : httpParameters) {
            String key = httpParameter.get(0);
            String value = httpParameter.get(1);
            if (key.equalsIgnoreCase("host") && !value.equals(host)) {
                value = host;
            }
            if (!key.startsWith(DYNAMIC_HEADER_PREFIX)) {
                method.setRequestHeader(key, value);
            }
            if (HeaderName.UserAgent.is(key)) {
                hasUserAgent = true;
            }
        }
        // set user-agent header if not found
        if (!hasUserAgent) {
            HeaderName.UserAgent.setRequestHeader(method, getUserAgent(context));
        }
        // Setting POST or PUT parameters if any
        Engine.logBeans.debug("(HttpConnector) Setting " + httpVerb + " data");
        if (method instanceof EntityEnclosingMethod) {
            EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) method;
            AbstractHttpTransaction transaction = (AbstractHttpTransaction) context.requestedObject;
            if (doMultipartFormData) {
                RequestableHttpVariable body = (RequestableHttpVariable) httpTransaction.getVariable(Parameter.HttpBody.getName());
                if (body != null && body.getDoFileUploadMode() == DoFileUploadMode.multipartFormData) {
                    String stringValue = httpTransaction.getParameterStringValue(Parameter.HttpBody.getName());
                    String filepath = Engine.theApp.filePropertyManager.getFilepathFromProperty(stringValue, getProject().getName());
                    File file = new File(filepath);
                    if (file.exists()) {
                        HeaderName.ContentType.setRequestHeader(method, contentType);
                        entityEnclosingMethod.setRequestEntity(new FileRequestEntity(file, contentType));
                    } else {
                        throw new FileNotFoundException(file.getAbsolutePath());
                    }
                } else {
                    List<Part> parts = new LinkedList<Part>();
                    for (RequestableVariable variable : transaction.getVariablesList()) {
                        if (variable instanceof RequestableHttpVariable) {
                            RequestableHttpVariable httpVariable = (RequestableHttpVariable) variable;
                            if ("POST".equals(httpVariable.getHttpMethod())) {
                                Object httpObjectVariableValue = transaction.getVariableValue(httpVariable.getName());
                                if (httpVariable.isMultiValued()) {
                                    if (httpObjectVariableValue instanceof Collection<?>) {
                                        for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) {
                                            addFormDataPart(parts, httpVariable, httpVariableValue);
                                        }
                                    }
                                } else {
                                    addFormDataPart(parts, httpVariable, httpObjectVariableValue);
                                }
                            }
                        }
                    }
                    MultipartRequestEntity mre = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), entityEnclosingMethod.getParams());
                    HeaderName.ContentType.setRequestHeader(method, mre.getContentType());
                    entityEnclosingMethod.setRequestEntity(mre);
                }
            } else if (MimeType.TextXml.is(contentType)) {
                final MimeMultipart[] mp = { null };
                for (RequestableVariable variable : transaction.getVariablesList()) {
                    if (variable instanceof RequestableHttpVariable) {
                        RequestableHttpVariable httpVariable = (RequestableHttpVariable) variable;
                        if (httpVariable.getDoFileUploadMode() == DoFileUploadMode.MTOM) {
                            Engine.logBeans.trace("(HttpConnector) Variable " + httpVariable.getName() + " detected as MTOM");
                            MimeMultipart mimeMultipart = mp[0];
                            try {
                                if (mimeMultipart == null) {
                                    Engine.logBeans.debug("(HttpConnector) Preparing the MTOM request");
                                    mimeMultipart = new MimeMultipart("related; type=\"application/xop+xml\"");
                                    MimeBodyPart bp = new MimeBodyPart();
                                    bp.setText(postQuery, "UTF-8");
                                    bp.setHeader(HeaderName.ContentType.value(), contentType);
                                    mimeMultipart.addBodyPart(bp);
                                }
                                Object httpObjectVariableValue = transaction.getVariableValue(httpVariable.getName());
                                if (httpVariable.isMultiValued()) {
                                    if (httpObjectVariableValue instanceof Collection<?>) {
                                        for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) {
                                            addMtomPart(mimeMultipart, httpVariable, httpVariableValue);
                                        }
                                    }
                                } else {
                                    addMtomPart(mimeMultipart, httpVariable, httpObjectVariableValue);
                                }
                                mp[0] = mimeMultipart;
                            } catch (Exception e) {
                                Engine.logBeans.warn("(HttpConnector) Failed to add MTOM part for " + httpVariable.getName(), e);
                            }
                        }
                    }
                }
                if (mp[0] == null) {
                    entityEnclosingMethod.setRequestEntity(new StringRequestEntity(postQuery, MimeType.TextXml.value(), "UTF-8"));
                } else {
                    Engine.logBeans.debug("(HttpConnector) Commit the MTOM request with the ContentType: " + mp[0].getContentType());
                    HeaderName.ContentType.setRequestHeader(method, mp[0].getContentType());
                    entityEnclosingMethod.setRequestEntity(new RequestEntity() {

                        @Override
                        public void writeRequest(OutputStream outputStream) throws IOException {
                            try {
                                mp[0].writeTo(outputStream);
                            } catch (MessagingException e) {
                                new IOException(e);
                            }
                        }

                        @Override
                        public boolean isRepeatable() {
                            return true;
                        }

                        @Override
                        public String getContentType() {
                            return mp[0].getContentType();
                        }

                        @Override
                        public long getContentLength() {
                            return -1;
                        }
                    });
                }
            } else {
                String charset = httpTransaction.getComputedUrlEncodingCharset();
                HeaderName.ContentType.setRequestHeader(method, contentType);
                entityEnclosingMethod.setRequestEntity(new StringRequestEntity(postQuery, contentType, charset));
            }
        }
        // Getting the result
        Engine.logBeans.debug("(HttpConnector) HttpClient: getting response body");
        byte[] result = executeMethod(method, context);
        long length = result != null ? result.length : 0;
        if (context.transaction instanceof DownloadHttpTransaction) {
            try {
                length = (long) context.get("__downloadedFileLength");
            } catch (Exception e) {
            }
        }
        Engine.logBeans.debug("(HttpConnector) Total read bytes: " + length);
        // Fire event for plugins
        long t1 = System.currentTimeMillis();
        Engine.theApp.pluginsManager.fireHttpConnectorGetDataEnd(context, t0, t1);
        StringBuilder sb = new StringBuilder();
        sb.append("HTTP result {ContentType: " + context.contentType + ", Length: " + length + "}\n\n");
        if (result != null && context.contentType != null && (context.contentType.startsWith("text/") || context.contentType.startsWith("application/xml") || context.contentType.startsWith("application/json"))) {
            sb.append(new String(result, "UTF-8"));
        }
        fireDataChanged(new ConnectorEvent(this, sb.toString()));
        return result;
    } finally {
        if (method != null)
            method.releaseConnection();
    }
}
Also used : RequestableHttpVariable(com.twinsoft.convertigo.beans.variables.RequestableHttpVariable) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) HttpMethodType(com.twinsoft.convertigo.engine.enums.HttpMethodType) PostMethod(org.apache.commons.httpclient.methods.PostMethod) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) FileNotFoundException(java.io.FileNotFoundException) URL(java.net.URL) AbstractHttpTransaction(com.twinsoft.convertigo.beans.transactions.AbstractHttpTransaction) HeadMethod(org.apache.commons.httpclient.methods.HeadMethod) OptionsMethod(org.apache.commons.httpclient.methods.OptionsMethod) MimeMultipart(javax.mail.internet.MimeMultipart) BigMimeMultipart(com.twinsoft.convertigo.engine.util.BigMimeMultipart) Protocol(org.apache.commons.httpclient.protocol.Protocol) DeleteMethod(org.apache.commons.httpclient.methods.DeleteMethod) ConnectorEvent(com.twinsoft.convertigo.beans.core.ConnectorEvent) MessagingException(javax.mail.MessagingException) TraceMethod(org.apache.commons.httpclient.methods.TraceMethod) EntityEnclosingMethod(org.apache.commons.httpclient.methods.EntityEnclosingMethod) RequestableVariable(com.twinsoft.convertigo.beans.variables.RequestableVariable) IOException(java.io.IOException) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) LinkedList(java.util.LinkedList) URIException(org.apache.commons.httpclient.URIException) SocketTimeoutException(java.net.SocketTimeoutException) OAuthException(oauth.signpost.exception.OAuthException) IOException(java.io.IOException) JSONException(org.codehaus.jettison.json.JSONException) MessagingException(javax.mail.MessagingException) FileNotFoundException(java.io.FileNotFoundException) EngineException(com.twinsoft.convertigo.engine.EngineException) MalformedURLException(java.net.MalformedURLException) FileRequestEntity(org.apache.commons.httpclient.methods.FileRequestEntity) DownloadHttpTransaction(com.twinsoft.convertigo.beans.transactions.DownloadHttpTransaction) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) MimePart(javax.mail.internet.MimePart) Part(org.apache.commons.httpclient.methods.multipart.Part) MimeBodyPart(javax.mail.internet.MimeBodyPart) GetMethod(org.apache.commons.httpclient.methods.GetMethod) PutMethod(org.apache.commons.httpclient.methods.PutMethod) Collection(java.util.Collection) MimeBodyPart(javax.mail.internet.MimeBodyPart) RequestEntity(org.apache.commons.httpclient.methods.RequestEntity) FileRequestEntity(org.apache.commons.httpclient.methods.FileRequestEntity) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) File(java.io.File) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 14 with AbstractHttpTransaction

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

the class HttpConnector method doExecuteMethod.

protected int doExecuteMethod(final HttpMethod method, Context context) throws ConnectionException, URIException, MalformedURLException {
    int statuscode = -1;
    // Tells the method to automatically handle authentication.
    method.setDoAuthentication(true);
    // Tells the method to automatically handle redirection.
    method.setFollowRedirects(false);
    HttpPool httpPool = ((AbstractHttpTransaction) context.transaction).getHttpPool();
    HttpClient httpClient = context.getHttpClient3(httpPool);
    try {
        // Display the cookies
        if (handleCookie) {
            Cookie[] cookies = httpState.getCookies();
            if (Engine.logBeans.isTraceEnabled())
                Engine.logBeans.trace("(HttpConnector) HttpClient request cookies:" + Arrays.asList(cookies).toString());
        }
        forwardHeader(new HeaderForwarder() {

            public void add(String name, String value, String forwardPolicy) {
                if (HttpConnector.HTTP_HEADER_FORWARD_POLICY_IGNORE.equals(forwardPolicy)) {
                    Header exHeader = method.getRequestHeader(name);
                    if (exHeader != null) {
                        // Nothing to do
                        Engine.logEngine.debug("(WebViewer) Forwarding header '" + name + "' has been ignored due to forward policy");
                    } else {
                        method.setRequestHeader(name, value);
                        Engine.logEngine.debug("(WebViewer) Header forwarded and added: " + name + "=" + value);
                    }
                } else if (HttpConnector.HTTP_HEADER_FORWARD_POLICY_REPLACE.equals(forwardPolicy)) {
                    method.setRequestHeader(name, value);
                    Engine.logEngine.debug("(WebViewer) Header forwarded and replaced: " + name + "=" + value);
                } else if (HttpConnector.HTTP_HEADER_FORWARD_POLICY_MERGE.equals(forwardPolicy)) {
                    Header exHeader = method.getRequestHeader(name);
                    if (exHeader != null)
                        value = exHeader.getValue() + ", " + value;
                    method.setRequestHeader(name, value);
                    Engine.logEngine.debug("(WebViewer) Header forwarded and merged: " + name + "=" + value);
                }
            }
        });
        // handle oAuthSignatures if any
        if (oAuthKey != null && oAuthSecret != null && oAuthToken != null && oAuthTokenSecret != null) {
            oAuthConsumer = new HttpOAuthConsumer(oAuthKey, oAuthSecret, hostConfiguration);
            oAuthConsumer.setTokenWithSecret(oAuthToken, oAuthTokenSecret);
            oAuthConsumer.sign(method);
            oAuthConsumer = null;
        }
        HttpUtils.logCurrentHttpConnection(httpClient, hostConfiguration, httpPool);
        hostConfiguration.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, (int) context.requestedObject.getResponseTimeout() * 1000);
        hostConfiguration.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, (int) context.requestedObject.getResponseTimeout() * 1000);
        Engine.logBeans.debug("(HttpConnector) HttpClient: executing method...");
        statuscode = httpClient.executeMethod(hostConfiguration, method, httpState);
        Engine.logBeans.debug("(HttpConnector) HttpClient: end of method successfull");
        // Display the cookies
        if (handleCookie) {
            Cookie[] cookies = httpState.getCookies();
            if (Engine.logBeans.isTraceEnabled())
                Engine.logBeans.trace("(HttpConnector) HttpClient response cookies:" + Arrays.asList(cookies).toString());
        }
    } catch (SocketTimeoutException e) {
        throw new ConnectionException("Timeout reached (" + context.requestedObject.getResponseTimeout() + " sec)");
    } catch (IOException e) {
        if (!context.requestedObject.runningThread.bContinue) {
            return statuscode;
        }
        HttpUtils.logCurrentHttpConnection(httpClient, hostConfiguration, httpPool);
        Engine.logBeans.warn("(HttpConnector) HttpClient: connection error to " + sUrl + ": " + e.getMessage());
    } catch (OAuthException eee) {
        throw new ConnectionException("OAuth Connection error to " + sUrl, eee);
    }
    return statuscode;
}
Also used : Cookie(org.apache.commons.httpclient.Cookie) OAuthException(oauth.signpost.exception.OAuthException) IOException(java.io.IOException) HttpPool(com.twinsoft.convertigo.engine.enums.HttpPool) AbstractHttpTransaction(com.twinsoft.convertigo.beans.transactions.AbstractHttpTransaction) SocketTimeoutException(java.net.SocketTimeoutException) Header(org.apache.commons.httpclient.Header) HttpClient(org.apache.commons.httpclient.HttpClient) HttpOAuthConsumer(com.twinsoft.convertigo.engine.oauth.HttpOAuthConsumer)

Example 15 with AbstractHttpTransaction

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

the class WebServiceTranslator method addElement.

private void addElement(SOAPMessage responseMessage, SOAPEnvelope soapEnvelope, Context context, Element elementToAdd, SOAPElement soapElement) throws SOAPException {
    SOAPElement soapMethodResponseElement = (SOAPElement) soapEnvelope.getBody().getFirstChild();
    String targetNamespace = soapMethodResponseElement.getNamespaceURI();
    String prefix = soapMethodResponseElement.getPrefix();
    String nodeType = elementToAdd.getAttribute("type");
    SOAPElement childSoapElement = soapElement;
    boolean elementAdded = true;
    boolean bTable = false;
    if (nodeType.equals("table")) {
        bTable = true;
        /*childSoapElement = soapElement.addChildElement("ArrayOf" + context.transactionName + "_" + tableName + "_Row", "");

            if (!context.httpServletRequest.getServletPath().endsWith(".wsl")) {
            	childSoapElement.addAttribute(soapEnvelope.createName("xsi:type"), "soapenc:Array");
            }*/
        childSoapElement = soapElement.addChildElement(elementToAdd.getNodeName());
    } else if (nodeType.equals("row")) {
        /*String elementType = context.transactionName + "_" + tableName + "_Row";
			childSoapElement = soapElement.addChildElement(elementType, "");*/
        childSoapElement = soapElement.addChildElement(elementToAdd.getNodeName());
    } else if (nodeType.equals("attachment")) {
        childSoapElement = soapElement.addChildElement(elementToAdd.getNodeName());
        if (context.requestedObject instanceof AbstractHttpTransaction) {
            AttachmentDetails attachment = AttachmentManager.getAttachment(elementToAdd);
            if (attachment != null) {
                byte[] raw = attachment.getData();
                if (raw != null)
                    childSoapElement.addTextNode(Base64.encodeBase64String(raw));
            }
        /* DON'T WORK YET *\
				AttachmentPart ap = responseMessage.createAttachmentPart(new ByteArrayInputStream(raw), elementToAdd.getAttribute("content-type"));
				ap.setContentId(key);
				ap.setContentLocation(elementToAdd.getAttribute("url"));
				responseMessage.addAttachmentPart(ap);
				\* DON'T WORK YET */
        }
    } else {
        String elementNodeName = elementToAdd.getNodeName();
        String elementNodeNsUri = elementToAdd.getNamespaceURI();
        String elementNodePrefix = getPrefix(context.projectName, elementNodeNsUri);
        XmlSchemaElement xmlSchemaElement = getXmlSchemaElementByName(context.projectName, elementNodeName);
        boolean isGlobal = xmlSchemaElement != null;
        if (isGlobal) {
            elementNodeNsUri = xmlSchemaElement.getQName().getNamespaceURI();
            elementNodePrefix = getPrefix(context.projectName, elementNodeNsUri);
        }
        // }
        if ("http://schemas.xmlsoap.org/soap/envelope/".equals(elementToAdd.getNamespaceURI()) || "http://schemas.xmlsoap.org/soap/envelope/".equals(elementToAdd.getParentNode().getNamespaceURI()) || elementToAdd.getParentNode().getNodeName().toUpperCase().indexOf("NS0:") != -1 || elementNodeName.toUpperCase().indexOf("NS0:") != -1) {
            elementAdded = false;
        } else {
            if (XsdForm.qualified == context.project.getSchemaElementForm() || isGlobal) {
                if (elementNodePrefix == null) {
                    childSoapElement = soapElement.addChildElement(soapEnvelope.createName(elementNodeName, prefix, targetNamespace));
                } else {
                    childSoapElement = soapElement.addChildElement(soapEnvelope.createName(elementNodeName, elementNodePrefix, elementNodeNsUri));
                }
            } else {
                childSoapElement = soapElement.addChildElement(elementNodeName);
            }
        }
    }
    if (elementAdded && elementToAdd.hasAttributes()) {
        addAttributes(responseMessage, soapEnvelope, context, elementToAdd.getAttributes(), childSoapElement);
    }
    if (elementToAdd.hasChildNodes()) {
        NodeList childNodes = elementToAdd.getChildNodes();
        int len = childNodes.getLength();
        if (bTable) {
        /*if (!context.httpServletRequest.getServletPath().endsWith(".wsl")) {
	            	childSoapElement.addAttribute(soapEnvelope.createName("soapenc:arrayType"), context.projectName+"_ns:" + context.transactionName + "_" + tableName + "_Row[" + (len - 1) + "]");
	            }*/
        }
        org.w3c.dom.Node node;
        Element childElement;
        for (int i = 0; i < len; i++) {
            node = childNodes.item(i);
            switch(node.getNodeType()) {
                case org.w3c.dom.Node.ELEMENT_NODE:
                    childElement = (Element) node;
                    addElement(responseMessage, soapEnvelope, context, childElement, childSoapElement);
                    break;
                case org.w3c.dom.Node.CDATA_SECTION_NODE:
                case org.w3c.dom.Node.TEXT_NODE:
                    String text = node.getNodeValue();
                    text = (text == null) ? "" : text;
                    childSoapElement.addTextNode(text);
                    break;
                default:
                    break;
            }
        }
    /*org.w3c.dom.Node node;
			Element childElement;
			for (int i = 0 ; i < len ; i++) {
				node = childNodes.item(i);
				if (node instanceof Element) {
					childElement = (Element) node;
					addElement(responseMessage, soapEnvelope, context, childElement, childSoapElement);
				}
				else if (node instanceof CDATASection) {
					Node textNode = XMLUtils.findChildNode(elementToAdd, org.w3c.dom.Node.CDATA_SECTION_NODE);
					String text = textNode.getNodeValue();
					if (text == null) {
						text = "";
					}
					childSoapElement.addTextNode(text);
				}
				else {
					Node textNode = XMLUtils.findChildNode(elementToAdd, org.w3c.dom.Node.TEXT_NODE);
					if (textNode != null) {
						String text = textNode.getNodeValue();
						if (text == null) {
							text = "";
						}
						childSoapElement.addTextNode(text);
					}
				}
			}*/
    }
}
Also used : XmlSchemaElement(org.apache.ws.commons.schema.XmlSchemaElement) NodeList(org.w3c.dom.NodeList) XmlSchemaElement(org.apache.ws.commons.schema.XmlSchemaElement) SOAPElement(javax.xml.soap.SOAPElement) Element(org.w3c.dom.Element) AbstractHttpTransaction(com.twinsoft.convertigo.beans.transactions.AbstractHttpTransaction) Node(org.w3c.dom.Node) SOAPElement(javax.xml.soap.SOAPElement) AttachmentDetails(com.twinsoft.convertigo.engine.AttachmentManager.AttachmentDetails)

Aggregations

AbstractHttpTransaction (com.twinsoft.convertigo.beans.transactions.AbstractHttpTransaction)16 RequestableHttpVariable (com.twinsoft.convertigo.beans.variables.RequestableHttpVariable)9 EngineException (com.twinsoft.convertigo.engine.EngineException)7 IOException (java.io.IOException)7 DatabaseObject (com.twinsoft.convertigo.beans.core.DatabaseObject)5 RequestableVariable (com.twinsoft.convertigo.beans.variables.RequestableVariable)4 SocketTimeoutException (java.net.SocketTimeoutException)4 OAuthException (oauth.signpost.exception.OAuthException)4 JSONException (org.codehaus.jettison.json.JSONException)4 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)3 XMLVector (com.twinsoft.convertigo.beans.common.XMLVector)3 HttpConnector (com.twinsoft.convertigo.beans.connectors.HttpConnector)3 SqlTransaction (com.twinsoft.convertigo.beans.transactions.SqlTransaction)3 HttpMethodType (com.twinsoft.convertigo.engine.enums.HttpMethodType)3 File (java.io.File)3 FileInputStream (java.io.FileInputStream)3 ArrayList (java.util.ArrayList)3 PartInitException (org.eclipse.ui.PartInitException)3 Element (org.w3c.dom.Element)3 ScreenClass (com.twinsoft.convertigo.beans.core.ScreenClass)2