Search in sources :

Example 6 with UrlMapper

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

the class RestApiServlet method service.

@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    if (request.getCharacterEncoding() == null) {
        try {
            // Set encoding if needed
            request.setCharacterEncoding("UTF-8");
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }
    try {
        if (EnginePropertiesManager.getPropertyAsBoolean(PropertyName.XSRF_API)) {
            HttpUtils.checkXSRF(request, response);
        }
        HttpSessionListener.checkSession(request);
    } catch (Throwable e) {
        throw new ServletException(e.getMessage(), e);
    }
    if (Engine.isEngineMode() && KeyManager.getCV(Session.EmulIDURLMAPPER) < 1) {
        String msg;
        if (KeyManager.has(Session.EmulIDURLMAPPER) && KeyManager.hasExpired(Session.EmulIDURLMAPPER)) {
            Engine.logEngine.error(msg = "Key expired for the URL Mapper.");
            throw new ServletException(new KeyExpiredException(msg));
        }
        Engine.logEngine.error(msg = "No key for the URL Mapper.");
        throw new ServletException(new MaxCvsExceededException(msg));
    }
    HttpServletRequestTwsWrapper wrapped_request = new HttpServletRequestTwsWrapper(request);
    request = wrapped_request;
    try {
        HttpSessionListener.checkSession(request);
    } catch (TASException e) {
        HttpUtils.terminateSession(request.getSession());
        throw new RuntimeException(e);
    }
    HttpSession httpSession = request.getSession();
    LogParameters logParameters = GenericUtils.cast(httpSession.getAttribute(RestApiServlet.class.getCanonicalName()));
    if (logParameters == null) {
        httpSession.setAttribute(RestApiServlet.class.getCanonicalName(), logParameters = new LogParameters());
        logParameters.put(mdcKeys.ContextID.toString().toLowerCase(), httpSession.getId());
    }
    Log4jHelper.mdcSet(logParameters);
    logParameters.put(mdcKeys.ClientIP.toString().toLowerCase(), request.getRemoteAddr());
    String encoded = request.getParameter(Parameter.RsaEncoded.getName());
    if (encoded != null) {
        String query = Engine.theApp.rsaManager.decrypt(encoded, request.getSession());
        wrapped_request.clearParameters();
        wrapped_request.addQuery(query);
    }
    String method = request.getMethod();
    String uri = request.getRequestURI();
    String query = request.getQueryString();
    Engine.logEngine.debug("(RestApiServlet) Requested URI: " + method + " " + uri);
    boolean isYaml = request.getParameter("YAML") != null;
    boolean isJson = request.getParameter("JSON") != null;
    if ("GET".equalsIgnoreCase(method) && (query == null || query.isEmpty()) && (uri.endsWith("/" + SwaggerUtils.servletMappingPath) || uri.endsWith("/" + OpenApiUtils.servletMappingPath))) {
        isJson = true;
    }
    // Generate YAML/JSON definition (swagger specific)
    if ("GET".equalsIgnoreCase(method) && (isYaml || isJson)) {
        try {
            String requestUrl = HttpUtils.originalRequestURL(request);
            // force endpoint in definition
            try {
                String endPointUrl = EnginePropertiesManager.getProperty(PropertyName.APPLICATION_SERVER_CONVERTIGO_ENDPOINT);
                if (endPointUrl != null && !endPointUrl.isEmpty()) {
                    requestUrl = endPointUrl + (uri.indexOf("/" + SwaggerUtils.servletMappingPath) != -1 ? uri.substring(uri.indexOf("/" + SwaggerUtils.servletMappingPath)) : uri.substring(uri.indexOf("/" + OpenApiUtils.servletMappingPath)));
                    Engine.logEngine.debug("(RestApiServlet) Force requestUrl: " + requestUrl);
                } else {
                    Engine.logEngine.debug("(RestApiServlet) Set requestUrl: " + requestUrl);
                }
            } catch (Throwable t) {
                Engine.logEngine.error("(RestApiServlet) Unable to retrieve server endpoint url: ", t);
            }
            Engine.logEngine.debug("(RestApiServlet) Projects path: " + new File(Engine.PROJECTS_PATH).getAbsolutePath());
            String output = uri.indexOf("/" + SwaggerUtils.servletMappingPath) != -1 ? buildSwaggerDefinition(requestUrl, request.getParameter("__project"), isYaml) : buildOpenApiDefinition(requestUrl, request.getParameter("__project"), isYaml);
            response.setCharacterEncoding("UTF-8");
            response.setContentType((isYaml ? MimeType.Yaml : MimeType.Json).value());
            Writer writer = response.getWriter();
            writer.write(output);
            Engine.logEngine.debug("(RestApiServlet) Definition sent :\n" + output);
        } catch (Exception e) {
            throw new ServletException(e);
        }
    } else // Handle REST request
    {
        long t0 = System.currentTimeMillis();
        try {
            Collection<UrlMapper> collection = RestApiManager.getInstance().getUrlMappers();
            if (collection.size() > 0) {
                if (method.equalsIgnoreCase("OPTIONS")) {
                    String origin = HeaderName.Origin.getHeader(request);
                    if (origin != null) {
                        Set<String> methods = new HashSet<String>();
                        String corsOrigin = null;
                        for (UrlMapper urlMapper : collection) {
                            String co = HttpUtils.filterCorsOrigin(urlMapper.getProject().getCorsOrigin(), origin);
                            if (co != null) {
                                if (corsOrigin == null || co.length() > corsOrigin.length()) {
                                    corsOrigin = co;
                                }
                                urlMapper.addMatchingMethods(wrapped_request, methods);
                            }
                        }
                        HttpUtils.applyCorsHeaders(request, response, corsOrigin, String.join(", ", methods));
                    }
                    response.setStatus(HttpServletResponse.SC_NO_CONTENT);
                    return;
                }
                // Found a matching operation
                UrlMappingOperation urlMappingOperation = null;
                List<UrlAuthentication> urlAuthentications = null;
                for (UrlMapper urlMapper : collection) {
                    urlMappingOperation = urlMapper.getMatchingOperation(request);
                    if (urlMappingOperation != null) {
                        urlAuthentications = urlMapper.getAuthenticationList();
                        break;
                    }
                }
                // Handle request
                if (urlMappingOperation != null) {
                    StringBuffer buf;
                    // Request headers
                    if (Engine.logEngine.isDebugEnabled()) {
                        buf = new StringBuffer();
                        buf.append("(RestApiServlet) Request headers:\n");
                        Enumeration<String> headerNames = request.getHeaderNames();
                        while (headerNames.hasMoreElements()) {
                            String headerName = headerNames.nextElement();
                            String headerValue = request.getHeader(headerName);
                            buf.append(" " + headerName + "=" + headerValue + "\n");
                        }
                        Engine.logEngine.debug(buf.toString());
                        Engine.logEngine.debug("(RestApiServlet) Request parameters: " + Collections.list(request.getParameterNames()));
                    }
                    // The response content
                    String content = null;
                    // Check for authentication
                    if (urlMappingOperation.isTargetAuthenticationContextRequired()) {
                        // Case Authentications are defined for mapper
                        if (urlAuthentications != null) {
                            boolean authenticated = false;
                            int len = urlAuthentications.size();
                            if (len > 0) {
                                for (UrlAuthentication urlAuthentication : urlAuthentications) {
                                    // Handle Auth request
                                    response.reset();
                                    RequestAttribute.responseHeader.set(request, new HashMap<String, String>());
                                    RequestAttribute.responseStatus.set(request, new HashMap<Integer, String>());
                                    urlAuthentication.handleAuthRequest(request, response);
                                    // Check user has been authenticated
                                    authenticated = SessionAttribute.authenticatedUser.string(request.getSession()) != null;
                                    if (authenticated) {
                                        break;
                                    }
                                }
                                // Handle User request
                                if (authenticated) {
                                    response.reset();
                                    RequestAttribute.responseHeader.set(request, new HashMap<String, String>());
                                    RequestAttribute.responseStatus.set(request, new HashMap<Integer, String>());
                                    content = urlMappingOperation.handleRequest(request, response);
                                }
                            } else // HTTP authentication required
                            {
                                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                            }
                        } else // HTTP authentication required
                        {
                            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                        }
                    } else // Handle User request
                    {
                        content = urlMappingOperation.handleRequest(request, response);
                    }
                    // Set response status
                    ServletUtils.applyCustomStatus(request, response);
                    Engine.logEngine.debug("(RestApiServlet) Response status code: " + response.getStatus());
                    // Set response headers
                    ServletUtils.applyCustomHeaders(request, response);
                    if (Engine.logEngine.isDebugEnabled()) {
                        buf = new StringBuffer();
                        buf.append("(RestApiServlet) Response headers:\n");
                        Collection<String> headerNames = response.getHeaderNames();
                        for (String headerName : headerNames) {
                            String headerValue = response.getHeader(headerName);
                            buf.append(" " + headerName + "=" + headerValue + "\n");
                        }
                        Engine.logEngine.debug(buf.toString());
                    }
                    // terminate session to avoid max session exceeded (case new session initiated for authentication)
                    if (response.getStatus() == HttpServletResponse.SC_UNAUTHORIZED) {
                        if (urlMappingOperation instanceof com.twinsoft.convertigo.beans.rest.AbstractRestOperation) {
                            com.twinsoft.convertigo.beans.rest.AbstractRestOperation aro = (com.twinsoft.convertigo.beans.rest.AbstractRestOperation) urlMappingOperation;
                            if (aro.isTerminateSession()) {
                                Engine.logEngine.debug("(RestApiServlet) requireEndOfContext because of required authentication");
                                request.setAttribute("convertigo.requireEndOfContext", true);
                            }
                        }
                    }
                    if (content != null) {
                        Writer writer = response.getWriter();
                        writer.write(content);
                    }
                    Engine.logEngine.debug("(RestApiServlet) Request successfully handled");
                } else {
                    Engine.logEngine.debug("(RestApiServlet) No matching operation for request");
                    super.service(request, response);
                }
            } else {
                Engine.logEngine.debug("(RestApiServlet) No mapping defined");
                super.service(request, response);
            }
        } catch (Exception e) {
            throw new ServletException(e);
        } finally {
            Requester requester = (Requester) request.getAttribute("convertigo.requester");
            if (requester != null) {
                Engine.logEngine.debug("(RestApiServlet) processRequestEnd, onFinally");
                processRequestEnd(request, requester);
                onFinally(request);
            } else {
                Engine.logEngine.debug("(RestApiServlet) terminate session");
                try {
                    HttpUtils.terminateSession(httpSession);
                } catch (Exception e) {
                    Engine.logEngine.warn("(RestApiServlet) unabled to terminate session", e);
                }
            }
            long t1 = System.currentTimeMillis();
            Engine.theApp.pluginsManager.fireHttpServletRequestEnd(request, t0, t1);
        }
    }
}
Also used : TASException(com.twinsoft.tas.TASException) ServletException(javax.servlet.ServletException) Requester(com.twinsoft.convertigo.engine.requesters.Requester) MaxCvsExceededException(com.twinsoft.convertigo.engine.MaxCvsExceededException) HttpServletRequestTwsWrapper(com.twinsoft.convertigo.engine.util.HttpServletRequestTwsWrapper) HashSet(java.util.HashSet) UrlMapper(com.twinsoft.convertigo.beans.core.UrlMapper) UrlMappingOperation(com.twinsoft.convertigo.beans.core.UrlMappingOperation) HttpSession(javax.servlet.http.HttpSession) ServletException(javax.servlet.ServletException) MaxCvsExceededException(com.twinsoft.convertigo.engine.MaxCvsExceededException) TASException(com.twinsoft.tas.TASException) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) KeyExpiredException(com.twinsoft.convertigo.engine.KeyExpiredException) EngineException(com.twinsoft.convertigo.engine.EngineException) KeyExpiredException(com.twinsoft.convertigo.engine.KeyExpiredException) LogParameters(com.twinsoft.convertigo.engine.LogParameters) UrlAuthentication(com.twinsoft.convertigo.beans.core.UrlAuthentication) File(java.io.File) Writer(java.io.Writer)

Example 7 with UrlMapper

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

the class RestApiServlet method buildSwaggerDefinition.

private static String buildSwaggerDefinition(String requestUrl, String projectName, boolean isYaml) throws EngineException, JsonProcessingException {
    String definition = null;
    // Build a given project definition
    if (projectName != null) {
        UrlMapper urlMapper = RestApiManager.getInstance().getUrlMapper(projectName);
        if (urlMapper != null) {
            definition = isYaml ? SwaggerUtils.getYamlDefinition(requestUrl, urlMapper) : SwaggerUtils.getJsonDefinition(requestUrl, urlMapper);
        } else {
            Engine.logEngine.warn("Project \"" + projectName + "\" does not contain any UrlMapper.");
            definition = isYaml ? SwaggerUtils.getYamlDefinition(requestUrl, projectName) : SwaggerUtils.getJsonDefinition(requestUrl, projectName);
        }
    } else // Build all project definitions
    {
        Collection<UrlMapper> collection = RestApiManager.getInstance().getUrlMappers();
        definition = isYaml ? SwaggerUtils.getYamlDefinition(requestUrl, collection) : SwaggerUtils.getJsonDefinition(requestUrl, collection);
    }
    return definition;
}
Also used : UrlMapper(com.twinsoft.convertigo.beans.core.UrlMapper)

Example 8 with UrlMapper

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

the class ModelObjectEditorComposite method fillList.

private void fillList(Project project, String referenceModel) {
    if (project != null) {
        UrlMapper urlMapper = project.getUrlMapper();
        if (urlMapper != null) {
            java.util.List<String> modelList = new ArrayList<String>();
            try {
                String mapperModels = urlMapper.getModels();
                JSONObject json = mapperModels.isEmpty() ? new JSONObject() : new JSONObject(mapperModels);
                Iterator<?> it = json.keys();
                while (it.hasNext()) {
                    modelList.add((String) it.next());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                String projectName = project.getName();
                File targetDir = new File(Engine.PROJECTS_PATH + "/" + projectName + "/" + SwaggerUtils.jsonSchemaDirectory);
                RestApiServlet.buildSwaggerDefinition(projectName, false);
                Collection<File> jsonschemas = FileUtils.listFiles(targetDir, new String[] { "jsonschema" }, false);
                for (File file : jsonschemas) {
                    String id = file.getName() + "#";
                    if (file.getName().equals(projectName + ".jsonschema"))
                        continue;
                    String content = FileUtils.readFileToString(file, "UTF-8");
                    JSONObject json = new JSONObject(content);
                    JSONObject definitions = json.getJSONObject("definitions");
                    Iterator<?> it = definitions.keys();
                    while (it.hasNext()) {
                        String key = (String) it.next();
                        modelList.add(id + "/definitions/" + key);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            modelList.add("");
            Collections.sort(modelList);
            int index = 0, selected = -1;
            for (String ref : modelList) {
                list.add(ref);
                if (ref.equalsIgnoreCase(referenceModel)) {
                    selected = index;
                }
                index++;
            }
            if (selected != -1) {
                list.setSelection(selected);
            }
        }
    }
}
Also used : UrlMapper(com.twinsoft.convertigo.beans.core.UrlMapper) JSONObject(org.codehaus.jettison.json.JSONObject) ArrayList(java.util.ArrayList) File(java.io.File) Point(org.eclipse.swt.graphics.Point)

Example 9 with UrlMapper

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

the class OpenApiUtils method parse.

@SuppressWarnings("rawtypes")
public static OpenAPI parse(String requestUrl, Collection<UrlMapper> collection) {
    OpenAPI openAPI = parseCommon(requestUrl, null);
    List<Tag> tags = new ArrayList<>();
    Components components = new Components();
    components.callbacks(new HashMap<String, Callback>());
    components.examples(new HashMap<String, Example>());
    components.extensions(new HashMap<String, Object>());
    components.headers(new HashMap<String, Header>());
    components.links(new HashMap<String, Link>());
    components.parameters(new HashMap<String, Parameter>());
    components.requestBodies(new HashMap<String, RequestBody>());
    components.responses(new HashMap<String, ApiResponse>());
    components.schemas(new HashMap<String, Schema>());
    components.securitySchemes(new HashMap<String, SecurityScheme>());
    Paths paths = new Paths();
    for (UrlMapper urlMapper : collection) {
        if (urlMapper != null) {
            OpenAPI _openAPI = parse(requestUrl, urlMapper);
            if (_openAPI != null) {
                try {
                    tags.addAll(_openAPI.getTags());
                } catch (Exception e) {
                }
                try {
                    paths.putAll(_openAPI.getPaths());
                } catch (Exception e) {
                }
                Components _components = _openAPI.getComponents();
                if (_components != null) {
                    try {
                        components.getCallbacks().putAll(_components.getCallbacks());
                    } catch (Exception e) {
                    }
                    try {
                        components.getExamples().putAll(_components.getExamples());
                    } catch (Exception e) {
                    }
                    try {
                        components.getExtensions().putAll(_components.getExtensions());
                    } catch (Exception e) {
                    }
                    try {
                        components.getHeaders().putAll(_components.getHeaders());
                    } catch (Exception e) {
                    }
                    try {
                        components.getLinks().putAll(_components.getLinks());
                    } catch (Exception e) {
                    }
                    try {
                        components.getParameters().putAll(_components.getParameters());
                    } catch (Exception e) {
                    }
                    try {
                        components.getRequestBodies().putAll(_components.getRequestBodies());
                    } catch (Exception e) {
                    }
                    try {
                        components.getResponses().putAll(_components.getResponses());
                    } catch (Exception e) {
                    }
                    try {
                        components.getSchemas().putAll(_components.getSchemas());
                    } catch (Exception e) {
                    }
                    try {
                        components.getSecuritySchemes().putAll(_components.getSecuritySchemes());
                    } catch (Exception e) {
                    }
                }
            }
        }
    }
    openAPI.setTags(tags);
    openAPI.setPaths(paths);
    openAPI.setComponents(components);
    return openAPI;
}
Also used : 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) ApiResponse(io.swagger.v3.oas.models.responses.ApiResponse) Components(io.swagger.v3.oas.models.Components) Example(io.swagger.v3.oas.models.examples.Example) Paths(io.swagger.v3.oas.models.Paths) SecurityScheme(io.swagger.v3.oas.models.security.SecurityScheme) RequestBody(io.swagger.v3.oas.models.parameters.RequestBody) UrlMapper(com.twinsoft.convertigo.beans.core.UrlMapper) JSONException(org.codehaus.jettison.json.JSONException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Callback(io.swagger.v3.oas.models.callbacks.Callback) Header(io.swagger.v3.oas.models.headers.Header) 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) JSONObject(org.codehaus.jettison.json.JSONObject) Tag(io.swagger.v3.oas.models.tags.Tag) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Link(io.swagger.v3.oas.models.links.Link)

Example 10 with UrlMapper

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

the class SwaggerUtils method parse.

public static Swagger parse(String requestUrl, Collection<UrlMapper> collection) {
    Swagger swagger = parseCommon(requestUrl, null);
    List<Tag> tags = new ArrayList<Tag>();
    Map<String, Path> paths = new HashMap<String, Path>();
    Map<String, Model> models = new HashMap<String, Model>();
    for (UrlMapper urlMapper : collection) {
        if (urlMapper != null) {
            Swagger p_swagger = parse(requestUrl, urlMapper);
            if (p_swagger != null) {
                if (p_swagger != null) {
                    tags.addAll(p_swagger.getTags());
                    paths.putAll(p_swagger.getPaths());
                    models.putAll(p_swagger.getDefinitions());
                }
            }
        }
    }
    swagger.setTags(tags);
    swagger.setPaths(paths);
    swagger.setDefinitions(models);
    return swagger;
}
Also used : Path(io.swagger.models.Path) UrlMapper(com.twinsoft.convertigo.beans.core.UrlMapper) HashMap(java.util.HashMap) Swagger(io.swagger.models.Swagger) ArrayList(java.util.ArrayList) Model(io.swagger.models.Model) RefModel(io.swagger.models.RefModel) IMappingRefModel(com.twinsoft.convertigo.beans.core.IMappingRefModel) Tag(io.swagger.models.Tag)

Aggregations

UrlMapper (com.twinsoft.convertigo.beans.core.UrlMapper)13 ArrayList (java.util.ArrayList)8 UrlMapping (com.twinsoft.convertigo.beans.core.UrlMapping)6 UrlMappingOperation (com.twinsoft.convertigo.beans.core.UrlMappingOperation)6 Project (com.twinsoft.convertigo.beans.core.Project)5 Sequence (com.twinsoft.convertigo.beans.core.Sequence)5 Step (com.twinsoft.convertigo.beans.core.Step)5 EngineException (com.twinsoft.convertigo.engine.EngineException)5 RequestableStep (com.twinsoft.convertigo.beans.core.RequestableStep)4 BlockStep (com.twinsoft.convertigo.beans.steps.BlockStep)4 BranchStep (com.twinsoft.convertigo.beans.steps.BranchStep)4 ElseStep (com.twinsoft.convertigo.beans.steps.ElseStep)4 SequenceStep (com.twinsoft.convertigo.beans.steps.SequenceStep)4 ThenStep (com.twinsoft.convertigo.beans.steps.ThenStep)4 TransactionStep (com.twinsoft.convertigo.beans.steps.TransactionStep)4 XMLComplexStep (com.twinsoft.convertigo.beans.steps.XMLComplexStep)4 ProjectExplorerView (com.twinsoft.convertigo.eclipse.views.projectexplorer.ProjectExplorerView)4 InformationNode (com.twinsoft.convertigo.eclipse.views.references.model.InformationNode)4 IsUsedByNode (com.twinsoft.convertigo.eclipse.views.references.model.IsUsedByNode)4 MapperNode (com.twinsoft.convertigo.eclipse.views.references.model.MapperNode)4