Search in sources :

Example 1 with TASException

use of com.twinsoft.tas.TASException 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 2 with TASException

use of com.twinsoft.tas.TASException in project convertigo by convertigo.

the class HttpSessionListener method valueBound.

public void valueBound(HttpSessionBindingEvent event) {
    try {
        Engine.logEngine.debug("HTTP session starting...");
        HttpSession httpSession = event.getSession();
        String httpSessionID = httpSession.getId();
        httpSessions.put(httpSessionID, httpSession);
        Engine.logEngine.debug("HTTP session started [" + httpSessionID + "]");
        if (Engine.isEngineMode() && !devices.contains(httpSessionID)) {
            int maxCV = KeyManager.getMaxCV(Session.EmulIDSE);
            int currentCV = countSessions();
            if (currentCV > maxCV) {
                if (KeyManager.hasExpired(Session.EmulIDSE)) {
                    Engine.logEngine.warn("The Standard Edition key is expired");
                } else if (KeyManager.isOverflow(Session.EmulIDSE)) {
                    String line = dateFormat.format(new Date()) + "\t" + maxCV + "\t" + currentCV + "\n";
                    try {
                        FileUtils.write(new File(Engine.LOG_PATH + "/Session License exceeded.log"), line, "UTF-8", true);
                    } catch (IOException e1) {
                        Engine.logEngine.error("Failed to write the 'Session License exceeded.log' file", e1);
                    }
                    return;
                }
                Engine.logEngine.error("No more HTTP session available for this Standard Edition.");
                if (DelegateServlet.canDelegate()) {
                    JSONObject json = new JSONObject();
                    json.put("action", "maxSessionExceeded");
                    json.put("currentCV", currentCV);
                    json.put("maxCV", maxCV);
                    DelegateServlet.delegate(json);
                }
                SessionAttribute.exception.set(event.getSession(), new TASException("Max number of sessions exceeded for " + KeyManager.getEmulatorName(Session.EmulIDSE), false, currentCV, maxCV));
                HttpUtils.terminateSession(event.getSession());
            }
        }
    } catch (Exception e) {
        Engine.logEngine.error("Exception during binding HTTP session listener", e);
    }
}
Also used : JSONObject(org.codehaus.jettison.json.JSONObject) TASException(com.twinsoft.tas.TASException) HttpSession(javax.servlet.http.HttpSession) IOException(java.io.IOException) File(java.io.File) Date(java.util.Date) TASException(com.twinsoft.tas.TASException) IOException(java.io.IOException)

Example 3 with TASException

use of com.twinsoft.tas.TASException in project convertigo by convertigo.

the class HttpSessionListener method checkSession.

public static void checkSession(HttpServletRequest request) throws TASException {
    HttpSession httpSession = request.getSession(true);
    SessionAttribute.clientIP.set(httpSession, request.getRemoteAddr());
    String uuid = request.getParameter(Parameter.DeviceUUID.getName());
    if (StringUtils.isNotBlank(uuid)) {
        SessionAttribute.deviceUUID.set(httpSession, uuid);
        if (Engine.isCloudMode() && !uuid.startsWith("web-")) {
            devices.add(httpSession.getId());
        }
    }
    if (!SessionAttribute.sessionListener.has(httpSession)) {
        Engine.logContext.trace("Inserting HTTP session listener into the HTTP session");
        SessionAttribute.sessionListener.set(httpSession, new HttpSessionListener());
        Object t;
        if ((t = SessionAttribute.exception.get(httpSession)) != null) {
            if (t instanceof Throwable) {
                ((Throwable) t).setStackTrace(new StackTraceElement[0]);
                if (t instanceof TASException) {
                    throw (TASException) t;
                }
                throw new RuntimeException((Throwable) t);
            }
        }
    }
}
Also used : TASException(com.twinsoft.tas.TASException) HttpSession(javax.servlet.http.HttpSession) JSONObject(org.codehaus.jettison.json.JSONObject)

Aggregations

TASException (com.twinsoft.tas.TASException)3 HttpSession (javax.servlet.http.HttpSession)3 File (java.io.File)2 IOException (java.io.IOException)2 JSONObject (org.codehaus.jettison.json.JSONObject)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 UrlAuthentication (com.twinsoft.convertigo.beans.core.UrlAuthentication)1 UrlMapper (com.twinsoft.convertigo.beans.core.UrlMapper)1 UrlMappingOperation (com.twinsoft.convertigo.beans.core.UrlMappingOperation)1 EngineException (com.twinsoft.convertigo.engine.EngineException)1 KeyExpiredException (com.twinsoft.convertigo.engine.KeyExpiredException)1 LogParameters (com.twinsoft.convertigo.engine.LogParameters)1 MaxCvsExceededException (com.twinsoft.convertigo.engine.MaxCvsExceededException)1 Requester (com.twinsoft.convertigo.engine.requesters.Requester)1 HttpServletRequestTwsWrapper (com.twinsoft.convertigo.engine.util.HttpServletRequestTwsWrapper)1 Writer (java.io.Writer)1 Date (java.util.Date)1 HashSet (java.util.HashSet)1 ServletException (javax.servlet.ServletException)1