Search in sources :

Example 11 with UrlMappingParameter

use of com.twinsoft.convertigo.beans.core.UrlMappingParameter in project convertigo by convertigo.

the class AbstractRestOperation method handleRequest.

@Override
@SuppressWarnings("deprecation")
public String handleRequest(HttpServletRequest request, HttpServletResponse response) throws EngineException {
    String targetRequestableQName = getTargetRequestable();
    if (targetRequestableQName.isEmpty()) {
        throw new EngineException("Mapping operation \"" + getName() + "\" has no target requestable defined");
    }
    StringTokenizer st = new StringTokenizer(targetRequestableQName, ".");
    int count = st.countTokens();
    String projectName = st.nextToken();
    String sequenceName = count == 2 ? st.nextToken() : "";
    String connectorName = count == 3 ? st.nextToken() : "";
    String transactionName = count == 3 ? st.nextToken() : "";
    try {
        Map<String, Object> map = new HashMap<String, Object>();
        String responseContentType = null;
        String content = null;
        try {
            // Check multipart request
            if (ServletFileUpload.isMultipartContent(request)) {
                Engine.logBeans.debug("(AbstractRestOperation) \"" + getName() + "\" Multipart resquest");
                // Create a factory for disk-based file items
                DiskFileItemFactory factory = new DiskFileItemFactory();
                // Set factory constraints
                factory.setSizeThreshold(1000);
                File temporaryFile = File.createTempFile("c8o-multipart-files", ".tmp");
                int cptFile = 0;
                temporaryFile.delete();
                temporaryFile.mkdirs();
                factory.setRepository(temporaryFile);
                Engine.logBeans.debug("(AbstractRestOperation) \"" + getName() + "\" Temporary folder for upload is : " + temporaryFile.getAbsolutePath());
                // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload(factory);
                // Set overall request size constraint
                upload.setSizeMax(EnginePropertiesManager.getPropertyAsLong(PropertyName.FILE_UPLOAD_MAX_REQUEST_SIZE));
                upload.setFileSizeMax(EnginePropertiesManager.getPropertyAsLong(PropertyName.FILE_UPLOAD_MAX_FILE_SIZE));
                // Parse the request
                List<FileItem> items = GenericUtils.cast(upload.parseRequest(request));
                for (FileItem fileItem : items) {
                    String parameterName = fileItem.getFieldName();
                    String parameterValue;
                    if (fileItem.isFormField()) {
                        parameterValue = fileItem.getString();
                        Engine.logBeans.debug("(AbstractRestOperation) \"" + getName() + "\"  Value for field '" + parameterName + "' : " + parameterValue);
                    } else {
                        String name = fileItem.getName().replaceFirst("^.*(?:\\\\|/)(.*?)$", "$1");
                        if (name.length() > 0) {
                            File wDir = new File(temporaryFile, "" + (++cptFile));
                            wDir.mkdirs();
                            File wFile = new File(wDir, name);
                            fileItem.write(wFile);
                            fileItem.delete();
                            parameterValue = wFile.getAbsolutePath();
                            Engine.logBeans.debug("(AbstractRestOperation) \"" + getName() + "\" Temporary uploaded file for field '" + parameterName + "' : " + parameterValue);
                        } else {
                            Engine.logBeans.debug("(AbstractRestOperation) \"" + getName() + "\" No temporary uploaded file for field '" + parameterName + "', empty name");
                            parameterValue = "";
                        }
                    }
                    if (parameterValue != null && !parameterValue.isEmpty()) {
                        UrlMappingParameter param = null;
                        try {
                            param = getParameterByName(parameterName);
                        } catch (Exception e) {
                        }
                        if (param != null) {
                            String variableName = param.getMappedVariableName();
                            if (!variableName.isEmpty()) {
                                parameterName = variableName;
                            }
                        }
                        Object mapValue = map.get(parameterName);
                        if (mapValue == null) {
                            map.put(parameterName, parameterValue);
                        } else {
                            List<String> values = new ArrayList<String>();
                            if (mapValue instanceof String) {
                                values.add((String) mapValue);
                            } else if (mapValue instanceof List) {
                                values.addAll(GenericUtils.cast(mapValue));
                            }
                            values.add(parameterValue);
                            map.put(parameterName, values);
                        }
                    }
                }
            }
            String contextName = request.getParameter(Parameter.Context.getName());
            map.put(Parameter.Context.getName(), new String[] { contextName });
            map.put(Parameter.Project.getName(), new String[] { projectName });
            if (sequenceName.isEmpty()) {
                map.put(Parameter.Connector.getName(), new String[] { connectorName });
                map.put(Parameter.Transaction.getName(), new String[] { transactionName });
            } else {
                map.put(Parameter.Sequence.getName(), new String[] { sequenceName });
                map.put(Parameter.RemoveContext.getName(), new String[] { "" });
                map.put(Parameter.RemoveSession.getName(), new String[] { "" });
            }
            // Add path variables parameters
            Map<String, String> varMap = ((UrlMapping) getParent()).getPathVariableValues(request);
            for (String varName : varMap.keySet()) {
                String varValue = varMap.get(varName);
                map.put(varName, varValue);
            }
            // Add other parameters
            for (UrlMappingParameter param : getParameterList()) {
                String paramName = param.getName();
                String variableName = param.getMappedVariableName();
                Object paramValue = null;
                if (param.getType() == Type.Header) {
                    paramValue = request.getHeader(paramName);
                } else if ((param.getType() == Type.Query || param.getType() == Type.Form)) {
                    String[] pvalues = request.getParameterValues(paramName);
                    if (pvalues != null) {
                        paramValue = pvalues;
                    }
                } else if (param.getType() == Type.Path) {
                    String varValue = varMap.get(param.getName());
                    paramValue = varValue;
                } else if (param.getType() == Type.Body) {
                    if (request.getInputStream() != null) {
                        // Retrieve data
                        paramValue = IOUtils.toString(request.getInputStream(), "UTF-8");
                        // Get input content type
                        DataContent dataInput = param.getInputContent();
                        if (dataInput.equals(DataContent.useHeader)) {
                            String requestContentType = request.getContentType();
                            if (requestContentType == null || MimeType.Xml.is(requestContentType)) {
                                dataInput = DataContent.toXml;
                            } else if (MimeType.Json.is(requestContentType)) {
                                dataInput = DataContent.toJson;
                            }
                        }
                        // Transform input data
                        try {
                            if (dataInput.equals(DataContent.toJson)) {
                                // String modelName = param instanceof IMappingRefModel ? ((IMappingRefModel)param).getModelReference() : "";
                                // String objectName = modelName.isEmpty() ? paramName : modelName;
                                // Document doc = XMLUtils.parseDOMFromString("<"+objectName+"/>");
                                Document doc = XMLUtils.parseDOMFromString("<" + paramName + "/>");
                                Element root = doc.getDocumentElement();
                                JSONObject json = new JSONObject((String) paramValue);
                                XMLUtils.jsonToXml(json, root);
                                paramValue = root.getChildNodes();
                            } else if (dataInput.equals(DataContent.toXml)) {
                                // Document doc = XMLUtils.parseDOMFromString((String)paramValue);
                                // paramValue = doc.getDocumentElement();
                                Document xml = XMLUtils.parseDOMFromString((String) paramValue);
                                if (xml.getDocumentElement().getTagName().equals(paramName)) {
                                    paramValue = xml.getDocumentElement();
                                } else {
                                    NodeList nl = xml.getDocumentElement().getChildNodes();
                                    Document doc = XMLUtils.parseDOMFromString("<" + paramName + "/>");
                                    Element root = doc.getDocumentElement();
                                    for (int i = 0; i < nl.getLength(); i++) {
                                        Node node = nl.item(i);
                                        if (node.getNodeType() == Node.ELEMENT_NODE) {
                                            root.appendChild(doc.adoptNode(node));
                                        }
                                    }
                                    paramValue = doc.getDocumentElement();
                                }
                            }
                        } catch (Exception e) {
                            Engine.logBeans.error("(AbstractRestOperation) \"" + getName() + "\" : unable to decode body", e);
                        }
                    }
                }
                // retrieve default value if necessary
                if (paramValue == null) {
                    paramValue = param.getValueOrNull();
                }
                if (paramValue != null) {
                    // map parameter to variable
                    if (!variableName.isEmpty()) {
                        paramName = variableName;
                    }
                    // add parameter with value to input map
                    if (paramValue instanceof String) {
                        map.put(paramName, new String[] { paramValue.toString() });
                    } else if (paramValue instanceof String[]) {
                        String[] values = (String[]) paramValue;
                        map.put(paramName, values);
                    } else {
                        map.put(paramName, paramValue);
                    }
                } else if (param.isRequired()) {
                    if (param.getType() == Type.Path) {
                    // ignore : already handled
                    } else if (param.getDataType().equals(DataType.File)) {
                    // ignore : already handled
                    } else {
                        Engine.logBeans.warn("(AbstractRestOperation) \"" + getName() + "\" : missing parameter " + param.getName());
                    }
                }
            }
        } catch (IOException ioe) {
            Engine.logBeans.error("(AbstractRestOperation) \"" + getName() + "\" : invalid body", ioe);
            throw ioe;
        }
        // Execute requestable
        Engine.logBeans.debug("(AbstractRestOperation) \"" + getName() + "\" executing requestable \"" + targetRequestableQName + "\"");
        InternalRequester internalRequester = new InternalRequester(map, request);
        request.setAttribute("convertigo.requester", internalRequester);
        Object result = internalRequester.processRequest();
        String encoding = "UTF-8";
        if (result != null) {
            Document xmlHttpDocument = (Document) result;
            // Extract the encoding Char Set from PI
            Node firstChild = xmlHttpDocument.getFirstChild();
            if ((firstChild.getNodeType() == Document.PROCESSING_INSTRUCTION_NODE) && (firstChild.getNodeName().equals("xml"))) {
                String piValue = firstChild.getNodeValue();
                int encodingOffset = piValue.indexOf("encoding=\"");
                if (encodingOffset != -1) {
                    encoding = piValue.substring(encodingOffset + 10);
                    encoding = encoding.substring(0, encoding.length() - 1);
                }
            }
            // Get output content type
            DataContent dataOutput = getOutputContent();
            if (dataOutput.equals(DataContent.useHeader)) {
                String h_Accept = HeaderName.Accept.getHeader(request);
                if (MimeType.Xml.is(h_Accept)) {
                    dataOutput = DataContent.toXml;
                } else if (h_Accept == null || MimeType.Json.is(h_Accept)) {
                    dataOutput = DataContent.toJson;
                }
            }
            // Modify status according to XPath condition of Response beans
            int statusCode = HttpServletResponse.SC_OK;
            String statusText = "";
            if (RequestAttribute.responseStatus.get(request) == null) {
                for (UrlMappingResponse umr : getResponseList()) {
                    if (umr instanceof OperationResponse) {
                        OperationResponse or = (OperationResponse) umr;
                        if (or.isMatching(xmlHttpDocument)) {
                            try {
                                statusCode = Integer.valueOf(or.getStatusCode(), 10);
                                statusText = or.getStatusText();
                            } catch (Exception e) {
                            }
                            break;
                        }
                    }
                }
            }
            if (statusText.isEmpty())
                response.setStatus(statusCode);
            else
                response.setStatus(statusCode, statusText);
            // Transform XML data
            if (dataOutput.equals(DataContent.toJson)) {
                JsonRoot jsonRoot = getProject().getJsonRoot();
                boolean useType = getProject().getJsonOutput() == JsonOutput.useType;
                Document document = useType ? Engine.theApp.schemaManager.makeXmlRestCompliant(xmlHttpDocument) : xmlHttpDocument;
                XMLUtils.logXml(document, Engine.logContext, "Generated Rest XML (useType=" + useType + ")");
                content = XMLUtils.XmlToJson(document.getDocumentElement(), true, useType, jsonRoot);
                responseContentType = MimeType.Json.value();
            } else {
                content = XMLUtils.prettyPrintDOMWithEncoding(xmlHttpDocument, "UTF-8");
                responseContentType = MimeType.Xml.value();
            }
        } else {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        }
        // Set response content-type header
        if (responseContentType != null) {
            HeaderName.ContentType.addHeader(response, responseContentType);
        }
        // Set response content
        if (content != null) {
            response.setCharacterEncoding(encoding);
            if (Engine.logContext.isInfoEnabled()) {
                try {
                    String json = new JSONObject(content).toString(1);
                    int len = json.length();
                    if (len > 5000) {
                        String txt = json.substring(0, 5000) + "\n... (see the complete message in DEBUG log level)";
                        Engine.logContext.info("Generated REST Json:\n" + txt);
                        Engine.logContext.debug("Generated REST Json:\n" + json);
                    } else {
                        Engine.logContext.info("Generated REST Json:\n" + json);
                    }
                } catch (Exception e) {
                }
            }
        }
        return content;
    } catch (Throwable t) {
        throw new EngineException("Operation \"" + getName() + "\" failed to handle request", t);
    } finally {
        if (terminateSession) {
            request.setAttribute("convertigo.requireEndOfContext", true);
        }
    }
}
Also used : UrlMapping(com.twinsoft.convertigo.beans.core.UrlMapping) HashMap(java.util.HashMap) UrlMappingParameter(com.twinsoft.convertigo.beans.core.UrlMappingParameter) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) EngineException(com.twinsoft.convertigo.engine.EngineException) ArrayList(java.util.ArrayList) UrlMappingResponse(com.twinsoft.convertigo.beans.core.UrlMappingResponse) Document(org.w3c.dom.Document) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) DataContent(com.twinsoft.convertigo.beans.core.UrlMappingParameter.DataContent) ArrayList(java.util.ArrayList) NodeList(org.w3c.dom.NodeList) List(java.util.List) NodeList(org.w3c.dom.NodeList) JsonRoot(com.twinsoft.convertigo.engine.enums.JsonOutput.JsonRoot) IOException(java.io.IOException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) IOException(java.io.IOException) EngineException(com.twinsoft.convertigo.engine.EngineException) FileItem(org.apache.commons.fileupload.FileItem) StringTokenizer(java.util.StringTokenizer) JSONObject(org.codehaus.jettison.json.JSONObject) InternalRequester(com.twinsoft.convertigo.engine.requesters.InternalRequester) JSONObject(org.codehaus.jettison.json.JSONObject) File(java.io.File)

Example 12 with UrlMappingParameter

use of com.twinsoft.convertigo.beans.core.UrlMappingParameter in project convertigo by convertigo.

the class OpenApiUtils method writeOpenApiToFile.

private static void writeOpenApiToFile(final String requestUrl, final UrlMapper urlMapper, final File yamlFile, boolean useExternalRef) throws Exception {
    synchronized (lockObject) {
        if (yamlFile.exists() && Engine.isEngineMode())
            return;
        Long t0 = System.currentTimeMillis();
        Project project = urlMapper.getProject();
        String projectName = project.getName();
        String oasDirUrl = requestUrl.substring(0, requestUrl.indexOf("/" + servletMappingPath)) + "/projects/" + projectName + "/" + jsonSchemaDirectory + "/";
        OpenAPI openAPI = parseCommon(requestUrl, project);
        List<Tag> tags = new ArrayList<>();
        Tag tag = new Tag();
        tag.setName(project.getName());
        tag.setDescription(project.getComment());
        tags.add(tag);
        openAPI.setTags(tags);
        if (openAPI.getComponents() == null) {
            openAPI.components(new Components());
        }
        // Security
        Map<String, SecurityScheme> securitySchemes = openAPI.getComponents().getSecuritySchemes();
        for (UrlAuthentication authentication : urlMapper.getAuthenticationList()) {
            if (AuthenticationType.Basic.equals(authentication.getType())) {
                if (securitySchemes == null || !securitySchemes.containsKey("basicAuth")) {
                    SecurityScheme securitySchemesItem = new SecurityScheme();
                    securitySchemesItem.setType(SecurityScheme.Type.HTTP);
                    securitySchemesItem.setScheme("basic");
                    openAPI.getComponents().addSecuritySchemes("basicAuth", securitySchemesItem);
                    SecurityRequirement securityRequirement = new SecurityRequirement();
                    securityRequirement.addList("basicAuth", new ArrayList<String>());
                    openAPI.addSecurityItem(securityRequirement);
                }
            }
        }
        List<String> refList = new ArrayList<String>();
        List<String> opIdList = new ArrayList<String>();
        // Paths
        Paths paths = new Paths();
        try {
            for (UrlMapping urlMapping : urlMapper.getMappingList()) {
                PathItem item = new PathItem();
                for (UrlMappingOperation umo : urlMapping.getOperationList()) {
                    Operation operation = new Operation();
                    operation.setOperationId(getOperationId(opIdList, umo, false));
                    operation.setDescription(umo.getComment());
                    operation.setSummary(umo.getComment());
                    // Tags
                    List<String> list = Arrays.asList("" + project.getName());
                    operation.setTags(list);
                    // 1 - add path parameters
                    for (String pathVarName : urlMapping.getPathVariableNames()) {
                        PathParameter parameter = new PathParameter();
                        parameter.setName(pathVarName);
                        // retrieve parameter description from bean
                        UrlMappingParameter ump = null;
                        try {
                            ump = umo.getParameterByName(pathVarName);
                        } catch (Exception e) {
                        }
                        if (ump != null && ump.getType() == Type.Path) {
                            parameter.setDescription(ump.getComment());
                            Schema<?> schema = getSchema(ump);
                            if (schema != null) {
                                parameter.setSchema(schema);
                            }
                        }
                        operation.addParametersItem(parameter);
                    }
                    // 2 - add other parameters
                    for (UrlMappingParameter ump : umo.getParameterList()) {
                        Parameter parameter = null;
                        if (ump.getType() == Type.Query) {
                            parameter = new QueryParameter();
                        } else if (ump.getType() == Type.Form) {
                            addFormParameter(operation, ump);
                        } else if (ump.getType() == Type.Body) {
                            addBodyParameter(operation, ump, oasDirUrl, refList, useExternalRef);
                        } else if (ump.getType() == Type.Header) {
                            parameter = new HeaderParameter();
                        } else if (ump.getType() == Type.Path) {
                        // ignore : should have been treated before
                        }
                        if (parameter != null) {
                            // Query | Header
                            parameter.setName(ump.getName());
                            parameter.setDescription(ump.getComment());
                            parameter.setRequired(ump.isRequired());
                            // parameter.setAllowEmptyValue(allowEmptyValue);
                            Schema<?> schema = getSchema(ump);
                            if (schema != null) {
                                parameter.setSchema(schema);
                            }
                            // add parameter
                            if (ump.isExposed()) {
                                operation.addParametersItem(parameter);
                            }
                        }
                    }
                    // Responses
                    List<String> produces = new ArrayList<String>();
                    if (umo instanceof AbstractRestOperation) {
                        DataContent dataOutput = ((AbstractRestOperation) umo).getOutputContent();
                        if (dataOutput.equals(DataContent.toJson)) {
                            produces = Arrays.asList(MimeType.Json.value());
                        } else if (dataOutput.equals(DataContent.toXml)) {
                            produces = Arrays.asList(MimeType.Xml.value());
                        } else {
                            produces = Arrays.asList(MimeType.Json.value(), MimeType.Xml.value());
                        }
                    }
                    ApiResponses responses = new ApiResponses();
                    operation.setResponses(responses);
                    for (UrlMappingResponse umr : umo.getResponseList()) {
                        String statusCode = umr.getStatusCode();
                        if (!statusCode.isEmpty()) {
                            if (!responses.containsKey(statusCode)) {
                                ApiResponse response = new ApiResponse();
                                response.setDescription(umr.getStatusText());
                                responses.addApiResponse(statusCode, response);
                                String modelReference = ((IMappingRefModel) umr).getModelReference();
                                if (!modelReference.isEmpty() && !produces.isEmpty()) {
                                    if (modelReference.indexOf(".jsonschema") != -1) {
                                        modelReference = modelReference.replace(".jsonschema#/definitions/", ".json#/components/schemas/");
                                        modelReference = oasDirUrl + modelReference;
                                    }
                                    Content content = new Content();
                                    response.setContent(content);
                                    for (String mt : produces) {
                                        MediaType mediaType = new MediaType();
                                        content.addMediaType(mt, mediaType);
                                        ObjectSchema schema = new ObjectSchema();
                                        if (!refList.contains(modelReference)) {
                                            refList.add(modelReference);
                                        }
                                        if (!useExternalRef && modelReference.indexOf('#') != -1) {
                                            modelReference = modelReference.substring(modelReference.indexOf('#'));
                                        }
                                        schema.set$ref(modelReference);
                                        mediaType.setSchema(schema);
                                    }
                                }
                            }
                        }
                    }
                    if (umo.getMethod().equals(HttpMethodType.DELETE.name())) {
                        item.setDelete(operation);
                    } else if (umo.getMethod().equals(HttpMethodType.GET.name())) {
                        item.setGet(operation);
                    } else if (umo.getMethod().equals(HttpMethodType.HEAD.name())) {
                        item.setHead(operation);
                    } else if (umo.getMethod().equals(HttpMethodType.OPTIONS.name())) {
                        item.setOptions(operation);
                    } else if (umo.getMethod().equals(HttpMethodType.POST.name())) {
                        item.setPost(operation);
                    } else if (umo.getMethod().equals(HttpMethodType.PUT.name())) {
                        item.setPut(operation);
                    } else if (umo.getMethod().equals(HttpMethodType.TRACE.name())) {
                        item.setTrace(operation);
                    }
                }
                paths.addPathItem(urlMapping.getPathWithPrefix(), item);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Engine.logEngine.error("Unexpected exception while parsing UrlMapper to generate definition", e);
        }
        openAPI.setPaths(paths);
        // Models and Schemas
        try {
            Map<String, JSONObject> modelMap = new HashMap<String, JSONObject>(1000);
            String models = getModels(oasDirUrl, urlMapper, modelMap);
            /*System.out.println("refList");
				for (String keyRef: refList) {
					System.out.println(keyRef);
				}
				System.out.println("modelMap");
				for (String keyRef: modelMap.keySet()) {
					System.out.println(keyRef);
				}*/
            Set<String> done = new HashSet<String>();
            JSONObject jsonModels = new JSONObject(models);
            for (String keyRef : refList) {
                addModelsFromMap(done, modelMap, keyRef, jsonModels);
            }
            OpenAPI oa = new OpenAPI();
            String s = Json.pretty(oa.info(new Info()));
            JSONObject json = new JSONObject(s);
            json.put("components", new JSONObject());
            json.getJSONObject("components").put("schemas", jsonModels);
            JsonNode rootNode = Json.mapper().readTree(json.toString());
            OpenAPIDeserializer ds = new OpenAPIDeserializer();
            SwaggerParseResult result = ds.deserialize(rootNode);
            @SuppressWarnings("rawtypes") Map<String, Schema> map = result.getOpenAPI().getComponents().getSchemas();
            openAPI.getComponents().schemas(map);
            modelMap.clear();
        } catch (Throwable t) {
            t.printStackTrace();
            Engine.logEngine.error("Unexpected exception while parsing UrlMapper to generate models", t);
        }
        // write yaml
        try {
            FileUtils.write(yamlFile, prettyPrintYaml(openAPI), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            Engine.logEngine.error("Unexpected exception while writing project YAML file", e);
        } finally {
            Long t1 = System.currentTimeMillis();
            Engine.logEngine.info("YAML file for " + projectName + " project written in " + (t1 - t0) + " ms");
        }
    }
}
Also used : UrlMapping(com.twinsoft.convertigo.beans.core.UrlMapping) AbstractRestOperation(com.twinsoft.convertigo.beans.rest.AbstractRestOperation) QueryParameter(io.swagger.v3.oas.models.parameters.QueryParameter) OpenAPIDeserializer(io.swagger.v3.parser.util.OpenAPIDeserializer) UrlMappingParameter(com.twinsoft.convertigo.beans.core.UrlMappingParameter) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) 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) ArrayList(java.util.ArrayList) UrlMappingResponse(com.twinsoft.convertigo.beans.core.UrlMappingResponse) JsonNode(com.fasterxml.jackson.databind.JsonNode) 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) ApiResponse(io.swagger.v3.oas.models.responses.ApiResponse) Components(io.swagger.v3.oas.models.Components) PathItem(io.swagger.v3.oas.models.PathItem) ObjectSchema(io.swagger.v3.oas.models.media.ObjectSchema) DataContent(com.twinsoft.convertigo.beans.core.UrlMappingParameter.DataContent) 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) ApiResponses(io.swagger.v3.oas.models.responses.ApiResponses) HashSet(java.util.HashSet) UrlMappingOperation(com.twinsoft.convertigo.beans.core.UrlMappingOperation) SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) Info(io.swagger.v3.oas.models.info.Info) JSONException(org.codehaus.jettison.json.JSONException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Project(com.twinsoft.convertigo.beans.core.Project) JSONObject(org.codehaus.jettison.json.JSONObject) Content(io.swagger.v3.oas.models.media.Content) DataContent(com.twinsoft.convertigo.beans.core.UrlMappingParameter.DataContent) 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) Tag(io.swagger.v3.oas.models.tags.Tag) UrlAuthentication(com.twinsoft.convertigo.beans.core.UrlAuthentication) OpenAPI(io.swagger.v3.oas.models.OpenAPI) IMappingRefModel(com.twinsoft.convertigo.beans.core.IMappingRefModel) SecurityRequirement(io.swagger.v3.oas.models.security.SecurityRequirement)

Example 13 with UrlMappingParameter

use of com.twinsoft.convertigo.beans.core.UrlMappingParameter in project convertigo by convertigo.

the class TreeDropAdapter method paste.

private boolean paste(Node node, TreeObject targetTreeObject) throws EngineException {
    if (targetTreeObject instanceof DatabaseObjectTreeObject) {
        DatabaseObject parent = ((DatabaseObjectTreeObject) targetTreeObject).getObject();
        DatabaseObject databaseObject = paste(node, null, true);
        Element element = (Element) ((Element) node).getElementsByTagName("dnd").item(0);
        // SEQUENCER
        if (parent instanceof Sequence || parent instanceof StepWithExpressions) {
            if (parent instanceof XMLElementStep)
                return false;
            if (parent instanceof IThenElseContainer)
                return false;
            // Add a TransactionStep
            if (databaseObject instanceof Transaction) {
                String projectName = ((Element) element.getElementsByTagName("project").item(0)).getAttribute("name");
                String connectorName = ((Element) element.getElementsByTagName("connector").item(0)).getAttribute("name");
                Transaction transaction = (Transaction) databaseObject;
                TransactionStep transactionStep = new TransactionStep();
                transactionStep.setSourceTransaction(projectName + TransactionStep.SOURCE_SEPARATOR + connectorName + TransactionStep.SOURCE_SEPARATOR + transaction.getName());
                transactionStep.bNew = true;
                parent.add(transactionStep);
                parent.hasChanged = true;
                if (transaction instanceof TransactionWithVariables) {
                    for (Variable variable : ((TransactionWithVariables) transaction).getVariablesList()) {
                        StepVariable stepVariable = variable.isMultiValued() ? new StepMultiValuedVariable() : new StepVariable();
                        stepVariable.setName(variable.getName());
                        stepVariable.setComment(variable.getComment());
                        stepVariable.setDescription(variable.getDescription());
                        stepVariable.setRequired(variable.isRequired());
                        stepVariable.setValueOrNull(variable.getValueOrNull());
                        stepVariable.setVisibility(variable.getVisibility());
                        transactionStep.addVariable(stepVariable);
                    }
                }
                return true;
            } else // Add a SequenceStep
            if (databaseObject instanceof Sequence) {
                String projectName = ((Element) element.getElementsByTagName("project").item(0)).getAttribute("name");
                Sequence seq = (Sequence) databaseObject;
                SequenceStep sequenceStep = new SequenceStep();
                sequenceStep.setSourceSequence(projectName + SequenceStep.SOURCE_SEPARATOR + seq.getName());
                sequenceStep.bNew = true;
                parent.add(sequenceStep);
                parent.hasChanged = true;
                for (Variable variable : seq.getVariablesList()) {
                    StepVariable stepVariable = variable.isMultiValued() ? new StepMultiValuedVariable() : new StepVariable();
                    stepVariable.setName(variable.getName());
                    stepVariable.setComment(variable.getComment());
                    stepVariable.setDescription(variable.getDescription());
                    stepVariable.setRequired(variable.isRequired());
                    stepVariable.setValueOrNull(variable.getValueOrNull());
                    stepVariable.setVisibility(variable.getVisibility());
                    sequenceStep.addVariable(stepVariable);
                }
                return true;
            }
        } else // URLMAPPER
        if (parent instanceof UrlMappingOperation) {
            // Set associated requestable, add all parameters for operation
            if (databaseObject instanceof RequestableObject) {
                String dboQName = "";
                if (databaseObject instanceof Sequence) {
                    dboQName = ((Element) element.getElementsByTagName("project").item(0)).getAttribute("name") + "." + databaseObject.getName();
                } else if (databaseObject instanceof Transaction) {
                    dboQName = ((Element) element.getElementsByTagName("project").item(0)).getAttribute("name") + "." + ((Element) element.getElementsByTagName("connector").item(0)).getAttribute("name") + "." + databaseObject.getName();
                }
                UrlMappingOperation operation = (UrlMappingOperation) parent;
                operation.setTargetRequestable(dboQName);
                if (operation.getComment().isEmpty()) {
                    operation.setComment(databaseObject.getComment());
                }
                operation.hasChanged = true;
                try {
                    StringTokenizer st = new StringTokenizer(dboQName, ".");
                    int count = st.countTokens();
                    Project p = Engine.theApp.databaseObjectsManager.getProjectByName(st.nextToken());
                    List<RequestableVariable> variables = new ArrayList<RequestableVariable>();
                    if (count == 2) {
                        variables = p.getSequenceByName(st.nextToken()).getVariablesList();
                    } else if (count == 3) {
                        variables = ((TransactionWithVariables) p.getConnectorByName(st.nextToken()).getTransactionByName(st.nextToken())).getVariablesList();
                    }
                    for (RequestableVariable variable : variables) {
                        String variableName = variable.getName();
                        Object variableValue = variable.getValueOrNull();
                        UrlMappingParameter parameter = null;
                        try {
                            parameter = operation.getParameterByName(variableName);
                        } catch (Exception e) {
                        }
                        if (parameter == null) {
                            boolean acceptForm = operation.getMethod().equalsIgnoreCase(HttpMethodType.POST.name()) || operation.getMethod().equalsIgnoreCase(HttpMethodType.PUT.name());
                            parameter = acceptForm ? new FormParameter() : new QueryParameter();
                            parameter.setName(variableName);
                            parameter.setComment(variable.getComment());
                            parameter.setArray(false);
                            parameter.setExposed(((RequestableVariable) variable).isWsdl());
                            parameter.setMultiValued(variable.isMultiValued());
                            parameter.setRequired(variable.isRequired());
                            parameter.setValueOrNull(!variable.isMultiValued() ? variableValue : null);
                            parameter.setMappedVariableName(variableName);
                            parameter.bNew = true;
                            operation.add(parameter);
                            operation.hasChanged = true;
                        }
                    }
                } catch (Exception e) {
                }
                return true;
            } else // Add a parameter to mapping operation
            if (databaseObject instanceof RequestableVariable) {
                RequestableVariable variable = (RequestableVariable) databaseObject;
                UrlMappingOperation operation = (UrlMappingOperation) parent;
                UrlMappingParameter parameter = null;
                String variableName = variable.getName();
                Object variableValue = variable.getValueOrNull();
                try {
                    parameter = operation.getParameterByName(variableName);
                } catch (Exception e) {
                }
                if (parameter == null) {
                    boolean acceptForm = operation.getMethod().equalsIgnoreCase(HttpMethodType.POST.name()) || operation.getMethod().equalsIgnoreCase(HttpMethodType.PUT.name());
                    parameter = acceptForm ? new FormParameter() : new QueryParameter();
                    parameter.setName(variableName);
                    parameter.setComment(variable.getComment());
                    parameter.setArray(false);
                    parameter.setExposed(((RequestableVariable) variable).isWsdl());
                    parameter.setMultiValued(variable.isMultiValued());
                    parameter.setRequired(variable.isRequired());
                    parameter.setValueOrNull(!variable.isMultiValued() ? variableValue : null);
                    parameter.setMappedVariableName(variableName);
                    parameter.bNew = true;
                    operation.add(parameter);
                    operation.hasChanged = true;
                }
                return true;
            }
        } else // MOBILE COMPONENTS
        if (parent instanceof com.twinsoft.convertigo.beans.mobile.components.MobileComponent) {
            return pasteMobileComponent(parent, databaseObject, element);
        } else // NGX COMPONENTS
        if (parent instanceof com.twinsoft.convertigo.beans.ngx.components.MobileComponent) {
            return pasteNgxComponent(parent, databaseObject, element);
        }
    }
    return false;
}
Also used : QueryParameter(com.twinsoft.convertigo.beans.rest.QueryParameter) DatabaseObjectTreeObject(com.twinsoft.convertigo.eclipse.views.projectexplorer.model.DatabaseObjectTreeObject) IThenElseContainer(com.twinsoft.convertigo.beans.steps.IThenElseContainer) RequestableVariable(com.twinsoft.convertigo.beans.variables.RequestableVariable) Variable(com.twinsoft.convertigo.beans.core.Variable) StepMultiValuedVariable(com.twinsoft.convertigo.beans.variables.StepMultiValuedVariable) StepVariable(com.twinsoft.convertigo.beans.variables.StepVariable) UrlMappingParameter(com.twinsoft.convertigo.beans.core.UrlMappingParameter) XMLElementStep(com.twinsoft.convertigo.beans.steps.XMLElementStep) Element(org.w3c.dom.Element) StepWithExpressions(com.twinsoft.convertigo.beans.core.StepWithExpressions) StepVariable(com.twinsoft.convertigo.beans.variables.StepVariable) FormParameter(com.twinsoft.convertigo.beans.rest.FormParameter) StepMultiValuedVariable(com.twinsoft.convertigo.beans.variables.StepMultiValuedVariable) DatabaseObject(com.twinsoft.convertigo.beans.core.DatabaseObject) ArrayList(java.util.ArrayList) List(java.util.List) NodeList(org.w3c.dom.NodeList) SequenceStep(com.twinsoft.convertigo.beans.steps.SequenceStep) UrlMappingOperation(com.twinsoft.convertigo.beans.core.UrlMappingOperation) RequestableObject(com.twinsoft.convertigo.beans.core.RequestableObject) RequestableVariable(com.twinsoft.convertigo.beans.variables.RequestableVariable) Sequence(com.twinsoft.convertigo.beans.core.Sequence) IOException(java.io.IOException) ObjectWithSameNameException(com.twinsoft.convertigo.engine.ObjectWithSameNameException) SAXException(org.xml.sax.SAXException) EngineException(com.twinsoft.convertigo.engine.EngineException) InvalidOperationException(com.twinsoft.convertigo.engine.InvalidOperationException) TransactionStep(com.twinsoft.convertigo.beans.steps.TransactionStep) Project(com.twinsoft.convertigo.beans.core.Project) StringTokenizer(java.util.StringTokenizer) Transaction(com.twinsoft.convertigo.beans.core.Transaction) HtmlTransaction(com.twinsoft.convertigo.beans.transactions.HtmlTransaction) TransactionWithVariables(com.twinsoft.convertigo.beans.core.TransactionWithVariables) PropertyTableRowTreeObject(com.twinsoft.convertigo.eclipse.views.projectexplorer.model.PropertyTableRowTreeObject) NgxComponentTreeObject(com.twinsoft.convertigo.eclipse.views.projectexplorer.model.NgxComponentTreeObject) IOrderableTreeObject(com.twinsoft.convertigo.eclipse.views.projectexplorer.model.IOrderableTreeObject) ProjectTreeObject(com.twinsoft.convertigo.eclipse.views.projectexplorer.model.ProjectTreeObject) FolderTreeObject(com.twinsoft.convertigo.eclipse.views.projectexplorer.model.FolderTreeObject) DatabaseObject(com.twinsoft.convertigo.beans.core.DatabaseObject) ObjectsFolderTreeObject(com.twinsoft.convertigo.eclipse.views.projectexplorer.model.ObjectsFolderTreeObject) NgxUIComponentTreeObject(com.twinsoft.convertigo.eclipse.views.projectexplorer.model.NgxUIComponentTreeObject) MobileUIComponentTreeObject(com.twinsoft.convertigo.eclipse.views.projectexplorer.model.MobileUIComponentTreeObject) IPropertyTreeObject(com.twinsoft.convertigo.eclipse.views.projectexplorer.model.IPropertyTreeObject) RequestableObject(com.twinsoft.convertigo.beans.core.RequestableObject) PropertyTableTreeObject(com.twinsoft.convertigo.eclipse.views.projectexplorer.model.PropertyTableTreeObject) TreeObject(com.twinsoft.convertigo.eclipse.views.projectexplorer.model.TreeObject) DatabaseObjectTreeObject(com.twinsoft.convertigo.eclipse.views.projectexplorer.model.DatabaseObjectTreeObject) ScreenClassTreeObject(com.twinsoft.convertigo.eclipse.views.projectexplorer.model.ScreenClassTreeObject) MobileComponentTreeObject(com.twinsoft.convertigo.eclipse.views.projectexplorer.model.MobileComponentTreeObject)

Example 14 with UrlMappingParameter

use of com.twinsoft.convertigo.beans.core.UrlMappingParameter in project convertigo by convertigo.

the class UrlMappingTreeObject method treeObjectPropertyChanged.

@Override
public void treeObjectPropertyChanged(TreeObjectEvent treeObjectEvent) {
    super.treeObjectPropertyChanged(treeObjectEvent);
    String propertyName = (String) treeObjectEvent.propertyName;
    propertyName = ((propertyName == null) ? "" : propertyName);
    TreeObject treeObject = (TreeObject) treeObjectEvent.getSource();
    if (treeObject instanceof DatabaseObjectTreeObject) {
        DatabaseObject databaseObject = (DatabaseObject) treeObject.getObject();
        // Case Mapping path has changed
        if ("path".equals(propertyName)) {
            if (treeObject.equals(this)) {
                try {
                    UrlMapping urlMapping = (UrlMapping) databaseObject;
                    String oldPath = (String) treeObjectEvent.oldValue;
                    List<String> oldPathVariableNames = urlMapping.getPathVariableNames(oldPath);
                    List<String> newPathVariableNames = urlMapping.getPathVariableNames();
                    if (!oldPathVariableNames.equals(newPathVariableNames)) {
                        int oldLen = oldPathVariableNames.size();
                        int newLen = newPathVariableNames.size();
                        /*MessageBox messageBox = new MessageBox(viewer.getControl().getShell(), SWT.ICON_QUESTION | SWT.YES | SWT.NO); 
							messageBox.setMessage("Do you really want to update mapping path parameters?");
							messageBox.setText("Update parameters\"?");
							int ret = messageBox.open();*/
                        int ret = SWT.YES;
                        if (ret == SWT.YES) {
                            // case of deletion
                            if (newLen < oldLen) {
                                for (String variableName : oldPathVariableNames) {
                                    if (!newPathVariableNames.contains(variableName)) {
                                        for (UrlMappingOperation operation : urlMapping.getOperationList()) {
                                            for (UrlMappingParameter parameter : operation.getParameterList()) {
                                                if (parameter.getName().equals(variableName)) {
                                                    if (parameter.getType().equals(Type.Path)) {
                                                        try {
                                                            parameter.delete();
                                                            operation.remove(parameter);
                                                            operation.hasChanged = true;
                                                        } catch (EngineException e) {
                                                            ConvertigoPlugin.logException(e, "Error when deleting the parameter \"" + variableName + "\"");
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            } else // case of rename
                            if (newLen == oldLen) {
                                for (int i = 0; i < oldLen; i++) {
                                    String variableName = oldPathVariableNames.get(i);
                                    for (UrlMappingOperation operation : urlMapping.getOperationList()) {
                                        for (UrlMappingParameter parameter : operation.getParameterList()) {
                                            if (parameter.getName().equals(variableName)) {
                                                if (parameter.getType().equals(Type.Path)) {
                                                    try {
                                                        parameter.setName(newPathVariableNames.get(i));
                                                        parameter.hasChanged = true;
                                                    } catch (EngineException e) {
                                                        ConvertigoPlugin.logException(e, "Error when renaming the parameter \"" + variableName + "\"");
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            } else // case of creation
                            {
                                for (String variableName : newPathVariableNames) {
                                    for (UrlMappingOperation operation : urlMapping.getOperationList()) {
                                        UrlMappingParameter parameter = null;
                                        try {
                                            parameter = operation.getParameterByName(variableName);
                                        } catch (EngineException e) {
                                            try {
                                                parameter = new PathParameter();
                                                parameter.setName(variableName);
                                                parameter.bNew = true;
                                                operation.add(parameter);
                                            } catch (EngineException ex) {
                                                ConvertigoPlugin.logException(ex, "Error when adding the parameter \"" + variableName + "\"");
                                            }
                                        }
                                    }
                                }
                            }
                            getProjectExplorerView().reloadTreeObject(this);
                        }
                    }
                } catch (Exception e) {
                    ConvertigoPlugin.logWarning(e, "Could not reload in tree Mapping \"" + databaseObject.getName() + "\" !");
                }
            }
        }
    }
}
Also used : UrlMapping(com.twinsoft.convertigo.beans.core.UrlMapping) UrlMappingOperation(com.twinsoft.convertigo.beans.core.UrlMappingOperation) UrlMappingParameter(com.twinsoft.convertigo.beans.core.UrlMappingParameter) EngineException(com.twinsoft.convertigo.engine.EngineException) DatabaseObject(com.twinsoft.convertigo.beans.core.DatabaseObject) PathParameter(com.twinsoft.convertigo.beans.rest.PathParameter) EngineException(com.twinsoft.convertigo.engine.EngineException)

Example 15 with UrlMappingParameter

use of com.twinsoft.convertigo.beans.core.UrlMappingParameter in project convertigo by convertigo.

the class UrlMappingTreeObject method treeObjectAdded.

@Override
public void treeObjectAdded(TreeObjectEvent treeObjectEvent) {
    super.treeObjectAdded(treeObjectEvent);
    TreeObject treeObject = (TreeObject) treeObjectEvent.getSource();
    if (treeObject instanceof DatabaseObjectTreeObject) {
        DatabaseObject databaseObject = (DatabaseObject) treeObject.getObject();
        try {
            boolean needReload = false;
            UrlMapping urlMapping = getObject();
            // An UrlMappingOperation has been added : add all path parameters
            if (databaseObject instanceof UrlMappingOperation) {
                if (urlMapping.equals(databaseObject.getParent())) {
                    UrlMappingOperation operation = (UrlMappingOperation) databaseObject;
                    if (operation.bNew) {
                        for (String variableName : urlMapping.getPathVariableNames()) {
                            UrlMappingParameter parameter = null;
                            try {
                                parameter = operation.getParameterByName(variableName);
                            } catch (EngineException e) {
                                try {
                                    parameter = new PathParameter();
                                    parameter.setName(variableName);
                                    parameter.bNew = true;
                                    operation.add(parameter);
                                    operation.hasChanged = true;
                                    needReload = true;
                                } catch (EngineException ex) {
                                    ConvertigoPlugin.logException(ex, "Error when adding the parameter \"" + variableName + "\"");
                                }
                            }
                        }
                    }
                    if (needReload) {
                        getProjectExplorerView().reloadTreeObject(this);
                    }
                }
            }
        } catch (Exception e) {
            ConvertigoPlugin.logWarning(e, "Could not reload in tree Mapping \"" + databaseObject.getName() + "\" !");
        }
    }
}
Also used : UrlMapping(com.twinsoft.convertigo.beans.core.UrlMapping) UrlMappingOperation(com.twinsoft.convertigo.beans.core.UrlMappingOperation) UrlMappingParameter(com.twinsoft.convertigo.beans.core.UrlMappingParameter) EngineException(com.twinsoft.convertigo.engine.EngineException) DatabaseObject(com.twinsoft.convertigo.beans.core.DatabaseObject) PathParameter(com.twinsoft.convertigo.beans.rest.PathParameter) EngineException(com.twinsoft.convertigo.engine.EngineException)

Aggregations

UrlMappingParameter (com.twinsoft.convertigo.beans.core.UrlMappingParameter)15 UrlMappingOperation (com.twinsoft.convertigo.beans.core.UrlMappingOperation)13 EngineException (com.twinsoft.convertigo.engine.EngineException)10 DatabaseObject (com.twinsoft.convertigo.beans.core.DatabaseObject)9 DatabaseObjectTreeObject (com.twinsoft.convertigo.eclipse.views.projectexplorer.model.DatabaseObjectTreeObject)7 TreeObject (com.twinsoft.convertigo.eclipse.views.projectexplorer.model.TreeObject)7 UrlMapping (com.twinsoft.convertigo.beans.core.UrlMapping)6 Project (com.twinsoft.convertigo.beans.core.Project)5 ProjectExplorerView (com.twinsoft.convertigo.eclipse.views.projectexplorer.ProjectExplorerView)5 UrlMappingParameterTreeObject (com.twinsoft.convertigo.eclipse.views.projectexplorer.model.UrlMappingParameterTreeObject)5 IOException (java.io.IOException)5 ArrayList (java.util.ArrayList)5 Cursor (org.eclipse.swt.graphics.Cursor)5 Display (org.eclipse.swt.widgets.Display)5 Shell (org.eclipse.swt.widgets.Shell)5 UrlMappingResponse (com.twinsoft.convertigo.beans.core.UrlMappingResponse)4 TreeParent (com.twinsoft.convertigo.eclipse.views.projectexplorer.TreeParent)4 RequestableObject (com.twinsoft.convertigo.beans.core.RequestableObject)3 Sequence (com.twinsoft.convertigo.beans.core.Sequence)3 Transaction (com.twinsoft.convertigo.beans.core.Transaction)3