Search in sources :

Example 1 with DataContent

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

the class SwaggerUtils method parse.

public static Swagger parse(String requestUrl, UrlMapper urlMapper) {
    Project project = urlMapper.getProject();
    String projectName = project.getName();
    String oasDirUrl = requestUrl.substring(0, requestUrl.indexOf("/" + servletMappingPath)) + "/projects/" + projectName + "/" + jsonSchemaDirectory + "/";
    Swagger swagger = parseCommon(requestUrl, project);
    List<Tag> tags = new ArrayList<Tag>();
    Tag tag = new Tag();
    tag.setName(urlMapper.getProject().getName());
    tag.setDescription(urlMapper.getProject().getComment());
    tags.add(tag);
    swagger.setTags(tags);
    // Security
    Map<String, SecuritySchemeDefinition> securityDefinitions = swagger.getSecurityDefinitions();
    for (UrlAuthentication authentication : urlMapper.getAuthenticationList()) {
        if (AuthenticationType.Basic.equals(authentication.getType())) {
            if (securityDefinitions == null || !securityDefinitions.containsKey("basicAuth")) {
                BasicAuthDefinition basicAuthDefinition = new BasicAuthDefinition();
                swagger.addSecurityDefinition("basicAuth", basicAuthDefinition);
                SecurityRequirement securityRequirement = new SecurityRequirement();
                securityRequirement.requirement("basicAuth", new ArrayList<String>());
                swagger.addSecurity(securityRequirement);
            }
        }
    }
    // Models and Schemas
    Map<String, Model> swagger_models = new HashMap<String, Model>();
    try {
        String models = getModels(oasDirUrl, urlMapper);
        if (!models.isEmpty()) {
            ObjectMapper mapper = Json.mapper();
            JsonNode definitionNode = mapper.readTree(models);
            for (Iterator<Entry<String, JsonNode>> it = GenericUtils.cast(definitionNode.fields()); it.hasNext(); ) {
                Entry<String, JsonNode> entry = it.next();
                swagger_models.put(entry.getKey().toString(), mapper.convertValue(entry.getValue(), Model.class));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        Engine.logEngine.warn("Unexpected exception while reading UrlMapper defined models", e);
    }
    swagger.setDefinitions(swagger_models);
    // Mappings
    Map<String, Path> swagger_paths = new HashMap<String, Path>();
    try {
        for (UrlMapping urlMapping : urlMapper.getMappingList()) {
            Path swagger_path = new Path();
            for (UrlMappingOperation umo : urlMapping.getOperationList()) {
                Operation s_operation = new Operation();
                s_operation.setOperationId(umo.getQName());
                s_operation.setDescription(umo.getComment());
                s_operation.setSummary(umo.getComment());
                // Operation produces
                if (umo instanceof AbstractRestOperation) {
                    DataContent dataOutput = ((AbstractRestOperation) umo).getOutputContent();
                    if (dataOutput.equals(DataContent.toJson)) {
                        s_operation.setProduces(Arrays.asList(MimeType.Json.value()));
                    } else if (dataOutput.equals(DataContent.toXml)) {
                        s_operation.setProduces(Arrays.asList(MimeType.Xml.value()));
                    } else {
                        s_operation.setProduces(Arrays.asList(MimeType.Json.value(), MimeType.Xml.value()));
                    }
                }
                // Operation tags
                List<String> list = Arrays.asList("" + project.getName());
                s_operation.setTags(list);
                // Operation consumes
                List<String> consumes = new ArrayList<String>();
                // Operation parameters
                List<Parameter> s_parameters = new ArrayList<Parameter>();
                // 1 - add path parameters
                for (String pathVarName : urlMapping.getPathVariableNames()) {
                    PathParameter s_parameter = new PathParameter();
                    s_parameter.setName(pathVarName);
                    s_parameter.setRequired(true);
                    s_parameter.setType("string");
                    // retrieve parameter description from bean
                    UrlMappingParameter ump = null;
                    try {
                        ump = umo.getParameterByName(pathVarName);
                    } catch (Exception e) {
                    }
                    if (ump != null && ump.getType() == Type.Path) {
                        s_parameter.setDescription(ump.getComment());
                        s_parameter.setType(ump.getInputType().toLowerCase());
                        Object value = ump.getValueOrNull();
                        if (value != null) {
                            s_parameter.setDefaultValue(String.valueOf(value));
                        }
                    }
                    s_parameters.add(s_parameter);
                }
                // 2 - add other parameters
                for (UrlMappingParameter ump : umo.getParameterList()) {
                    Parameter s_parameter = null;
                    if (ump.getType() == Type.Query) {
                        s_parameter = new QueryParameter();
                    } else if (ump.getType() == Type.Form) {
                        s_parameter = new FormParameter();
                    } else if (ump.getType() == Type.Body) {
                        s_parameter = new BodyParameter();
                        if (ump instanceof IMappingRefModel) {
                            String modelReference = ((IMappingRefModel) ump).getModelReference();
                            if (!modelReference.isEmpty()) {
                                if (modelReference.indexOf(".jsonschema") != -1) {
                                    modelReference = oasDirUrl + modelReference;
                                }
                                RefModel refModel = new RefModel(modelReference);
                                ((BodyParameter) s_parameter).setSchema(refModel);
                            }
                        }
                    } else if (ump.getType() == Type.Header) {
                        s_parameter = new HeaderParameter();
                    } else if (ump.getType() == Type.Path) {
                    // ignore : should have been treated before
                    }
                    if (s_parameter != null) {
                        s_parameter.setName(ump.getName());
                        s_parameter.setDescription(ump.getComment());
                        s_parameter.setRequired(ump.isRequired());
                        if (s_parameter instanceof SerializableParameter) {
                            boolean isArray = ump.isMultiValued() || ump.isArray();
                            String _type = isArray ? "array" : ump.getDataType().name().toLowerCase();
                            String _collectionFormat = ump.isMultiValued() ? "multi" : (isArray ? "csv" : null);
                            Property _items = isArray ? getItems(ump.getDataType()) : null;
                            ((SerializableParameter) s_parameter).setType(_type);
                            ((SerializableParameter) s_parameter).setCollectionFormat(_collectionFormat);
                            ((SerializableParameter) s_parameter).setItems(_items);
                            Object value = ump.getValueOrNull();
                            if (value != null) {
                                String collection = ((SerializableParameter) s_parameter).getCollectionFormat();
                                if (collection != null && collection.equals("multi")) {
                                    Property items = new StringProperty();
                                    // items.setDefault(String.valueOf(value));
                                    ((SerializableParameter) s_parameter).setItems(items);
                                // ((SerializableParameter) s_parameter).setEnumValue(Arrays.asList("val1","val2","val3"));
                                } else {
                                    ((AbstractSerializableParameter<?>) s_parameter).setDefaultValue(String.valueOf(value));
                                }
                            }
                        }
                        DataContent dataInput = ump.getInputContent();
                        if (dataInput.equals(DataContent.toJson)) {
                            if (!consumes.contains(MimeType.Json.value())) {
                                consumes.add(MimeType.Json.value());
                            }
                        } else if (dataInput.equals(DataContent.toXml)) {
                            if (!consumes.contains(MimeType.Xml.value())) {
                                consumes.add(MimeType.Xml.value());
                            }
                        }
                        // swagger-ui workaround for invalid request content-type for POST
                        if (ump.getType() == Type.Form) {
                            if (!DataType.File.equals(ump.getDataType())) {
                                if (!consumes.contains(MimeType.WwwForm.value())) {
                                    consumes.add(MimeType.WwwForm.value());
                                }
                            } else {
                                if (!consumes.contains("multipart/form-data")) {
                                    consumes.add("multipart/form-data");
                                }
                            }
                        }
                        // add parameter
                        if (ump.isExposed()) {
                            s_parameters.add(s_parameter);
                        }
                    }
                }
                s_operation.setParameters(s_parameters);
                if (!consumes.isEmpty()) {
                    s_operation.setConsumes(consumes);
                }
                // Set operation responses
                Map<String, Response> responses = new HashMap<String, Response>();
                for (UrlMappingResponse umr : umo.getResponseList()) {
                    String statusCode = umr.getStatusCode();
                    if (!statusCode.isEmpty()) {
                        if (!responses.containsKey(statusCode)) {
                            Response response = new Response();
                            // response.setDescription(umr.getComment());
                            response.setDescription(umr.getStatusText());
                            if (umr instanceof IMappingRefModel) {
                                String modelReference = ((IMappingRefModel) umr).getModelReference();
                                if (!modelReference.isEmpty()) {
                                    if (modelReference.indexOf(".jsonschema") != -1) {
                                        modelReference = oasDirUrl + modelReference;
                                    }
                                    RefProperty refProperty = new RefProperty(modelReference);
                                    response.setResponseSchema(new PropertyModelConverter().propertyToModel(refProperty));
                                }
                            }
                            responses.put(statusCode, response);
                        }
                    }
                }
                if (responses.isEmpty()) {
                    Response resp200 = new Response();
                    resp200.description("successful operation");
                    responses.put("200", resp200);
                }
                s_operation.setResponses(responses);
                // Add operation to path
                String s_method = umo.getMethod().toLowerCase();
                swagger_path.set(s_method, s_operation);
            }
            swagger_paths.put(urlMapping.getPathWithPrefix(), swagger_path);
        }
    } catch (Exception e) {
        e.printStackTrace();
        Engine.logEngine.error("Unexpected exception while parsing UrlMapper to generate definition", e);
    }
    swagger.setPaths(swagger_paths);
    return swagger;
}
Also used : UrlMapping(com.twinsoft.convertigo.beans.core.UrlMapping) SerializableParameter(io.swagger.models.parameters.SerializableParameter) AbstractSerializableParameter(io.swagger.models.parameters.AbstractSerializableParameter) AbstractRestOperation(com.twinsoft.convertigo.beans.rest.AbstractRestOperation) RefModel(io.swagger.models.RefModel) IMappingRefModel(com.twinsoft.convertigo.beans.core.IMappingRefModel) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) JsonNode(com.fasterxml.jackson.databind.JsonNode) AbstractSerializableParameter(io.swagger.models.parameters.AbstractSerializableParameter) PropertyModelConverter(io.swagger.models.utils.PropertyModelConverter) DataContent(com.twinsoft.convertigo.beans.core.UrlMappingParameter.DataContent) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Project(com.twinsoft.convertigo.beans.core.Project) JSONObject(org.codehaus.jettison.json.JSONObject) IMappingRefModel(com.twinsoft.convertigo.beans.core.IMappingRefModel) QueryParameter(io.swagger.models.parameters.QueryParameter) UrlMappingParameter(com.twinsoft.convertigo.beans.core.UrlMappingParameter) UrlMappingResponse(com.twinsoft.convertigo.beans.core.UrlMappingResponse) StringProperty(io.swagger.models.properties.StringProperty) 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) RefProperty(io.swagger.models.properties.RefProperty) Entry(java.util.Map.Entry) Swagger(io.swagger.models.Swagger) 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) UrlMappingOperation(com.twinsoft.convertigo.beans.core.UrlMappingOperation) SecuritySchemeDefinition(io.swagger.models.auth.SecuritySchemeDefinition) BasicAuthDefinition(io.swagger.models.auth.BasicAuthDefinition) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Response(io.swagger.models.Response) UrlMappingResponse(com.twinsoft.convertigo.beans.core.UrlMappingResponse) 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) Tag(io.swagger.models.Tag) UrlAuthentication(com.twinsoft.convertigo.beans.core.UrlAuthentication) SecurityRequirement(io.swagger.models.SecurityRequirement)

Example 2 with DataContent

use of com.twinsoft.convertigo.beans.core.UrlMappingParameter.DataContent 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 3 with DataContent

use of com.twinsoft.convertigo.beans.core.UrlMappingParameter.DataContent 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 4 with DataContent

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

the class OpenApiUtils method addBodyParameter.

private static void addBodyParameter(Operation operation, UrlMappingParameter ump, String oasDirUrl, List<String> refList, boolean useExternalRef) {
    RequestBody requestBody = operation.getRequestBody();
    if (requestBody == null) {
        operation.setRequestBody(new RequestBody());
        requestBody = operation.getRequestBody();
        requestBody.content(new Content());
        MediaType mediaType = new MediaType();
        String modelReference = ((IMappingRefModel) ump).getModelReference();
        if (!modelReference.isEmpty()) {
            if (modelReference.indexOf(".jsonschema") != -1) {
                modelReference = modelReference.replace(".jsonschema#/definitions/", ".json#/components/schemas/");
                modelReference = oasDirUrl + modelReference;
            }
            if (!refList.contains(modelReference)) {
                refList.add(modelReference);
            }
            if (!useExternalRef && modelReference.indexOf('#') != -1) {
                modelReference = modelReference.substring(modelReference.indexOf('#'));
            }
            ObjectSchema oschema = new ObjectSchema();
            oschema.set$ref(modelReference);
            mediaType.setSchema(oschema);
        }
        DataContent dataInput = ump.getInputContent();
        if (dataInput.equals(DataContent.toJson)) {
            requestBody.getContent().addMediaType(MimeType.Json.value(), mediaType);
        } else if (dataInput.equals(DataContent.toXml)) {
            requestBody.getContent().addMediaType(MimeType.Xml.value(), mediaType);
        }
    }
}
Also used : ObjectSchema(io.swagger.v3.oas.models.media.ObjectSchema) Content(io.swagger.v3.oas.models.media.Content) DataContent(com.twinsoft.convertigo.beans.core.UrlMappingParameter.DataContent) DataContent(com.twinsoft.convertigo.beans.core.UrlMappingParameter.DataContent) MediaType(io.swagger.v3.oas.models.media.MediaType) IMappingRefModel(com.twinsoft.convertigo.beans.core.IMappingRefModel) RequestBody(io.swagger.v3.oas.models.parameters.RequestBody)

Aggregations

DataContent (com.twinsoft.convertigo.beans.core.UrlMappingParameter.DataContent)4 IMappingRefModel (com.twinsoft.convertigo.beans.core.IMappingRefModel)3 UrlMapping (com.twinsoft.convertigo.beans.core.UrlMapping)3 UrlMappingParameter (com.twinsoft.convertigo.beans.core.UrlMappingParameter)3 UrlMappingResponse (com.twinsoft.convertigo.beans.core.UrlMappingResponse)3 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)2 Project (com.twinsoft.convertigo.beans.core.Project)2 UrlAuthentication (com.twinsoft.convertigo.beans.core.UrlAuthentication)2 UrlMappingOperation (com.twinsoft.convertigo.beans.core.UrlMappingOperation)2 AbstractRestOperation (com.twinsoft.convertigo.beans.rest.AbstractRestOperation)2 Content (io.swagger.v3.oas.models.media.Content)2 MediaType (io.swagger.v3.oas.models.media.MediaType)2 ObjectSchema (io.swagger.v3.oas.models.media.ObjectSchema)2 JSONObject (org.codehaus.jettison.json.JSONObject)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 EngineException (com.twinsoft.convertigo.engine.EngineException)1 JsonRoot (com.twinsoft.convertigo.engine.enums.JsonOutput.JsonRoot)1