Java Code Examples for javax.servlet.ServletException#getRootCause()

The following examples show how to use javax.servlet.ServletException#getRootCause() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NettyMessageToServletRunnable.java    From spring-boot-protocol with Apache License 2.0 4 votes vote down vote up
@Override
        public void run() {
            ServletHttpServletRequest httpServletRequest = servletHttpExchange.getRequest();
            ServletHttpServletResponse httpServletResponse = servletHttpExchange.getResponse();
            Throwable realThrowable = null;

//            long beginTime = System.currentTimeMillis();
            try {
                ServletRequestDispatcher dispatcher = servletHttpExchange.getServletContext().getRequestDispatcher(httpServletRequest.getRequestURI());
                if (dispatcher == null) {
                    httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
                    return;
                }
//                servletHttpExchange.touch(this);
                dispatcher.dispatch(httpServletRequest, httpServletResponse);

                if(httpServletRequest.isAsync()){
                    ReadListener readListener = httpServletRequest.getInputStream0().getReadListener();
                    if(readListener != null){
                        readListener.onAllDataRead();
                    }
                }
            }catch (ServletException se){
                realThrowable = se.getRootCause();
            }catch (Throwable throwable){
                realThrowable = throwable;
            }finally {
//                long totalTime = System.currentTimeMillis() - beginTime;
//                SERVLET_AND_FILTER_TIME.addAndGet(totalTime);

                /*
                 * Error pages are obtained according to two types: 1. By exception type; 2. By status code
                 */
                if(realThrowable == null) {
                    realThrowable = (Throwable) httpServletRequest.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
                }
                ServletErrorPage errorPage = null;
                ServletErrorPageManager errorPageManager = servletHttpExchange.getServletContext().getErrorPageManager();
                if(realThrowable != null){
                    errorPage = errorPageManager.find(realThrowable);
                    if(errorPage == null) {
                        httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                        errorPage = errorPageManager.find(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    }
                    if(errorPage == null) {
                        errorPage = errorPageManager.find(0);
                    }
                }else if(httpServletResponse.isError()) {
                    errorPage = errorPageManager.find(httpServletResponse.getStatus());
                    if(errorPage == null) {
                        errorPage = errorPageManager.find(0);
                    }
                }
                //Error page
                if(realThrowable != null || errorPage != null) {
                    errorPageManager.handleErrorPage(errorPage, realThrowable, httpServletRequest, httpServletResponse);
                }
                /*
                 * If not asynchronous, or asynchronous has ended
                 * each response object is valid only if it is within the scope of the servlet's service method or the filter's doFilter method, unless the
                 * the request object associated with the component has started asynchronous processing. If the relevant request has already started asynchronous processing, then up to the AsyncContext
                 * complete method is called, and the request object remains valid. To avoid the performance overhead of creating response objects, the container typically recycles the response object.
                 * before the startAsync of the relevant request is invoked, the developer must be aware that the response object reference remains outside the scope described above
                 * circumference may lead to uncertain behavior
                 */
                if(httpServletRequest.isAsync()){
                    ServletAsyncContext asyncContext = httpServletRequest.getAsyncContext();
                    //If the asynchronous execution completes, recycle
                    if(asyncContext.isComplete()){
                        asyncContext.recycle();
                    }else {
                        //Marks the end of execution for the main thread
                        httpServletRequest.getAsyncContext().markIoThreadOverFlag();
                        if(asyncContext.isComplete()) {
                            asyncContext.recycle();
                        }
                    }
                }else {
                    //Not asynchronous direct collection
                    servletHttpExchange.recycle();
                }

                recycle();
//                SERVLET_QUERY_COUNT.incrementAndGet();
            }
        }
 
Example 2
Source File: JspViewHandler.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
public void render(String name, String page, String contentType, String encoding, String info, HttpServletRequest request, HttpServletResponse response) throws ViewHandlerException {
    // some containers call filters on EVERY request, even forwarded ones,
    // so let it know that it came from the control servlet

    if (request == null) {
        throw new ViewHandlerException("Null HttpServletRequest object");
    }
    if (UtilValidate.isEmpty(page)) {
        throw new ViewHandlerException("Null or empty source");
    }

    //Debug.logInfo("Requested Page : " + page, module);
    //Debug.logInfo("Physical Path  : " + context.getRealPath(page));

    // tell the ContextFilter we are forwarding
    request.setAttribute(ContextFilter.FORWARDED_FROM_SERVLET, Boolean.TRUE);
    RequestDispatcher rd = request.getRequestDispatcher(page);

    if (rd == null) {
        Debug.logInfo("HttpServletRequest.getRequestDispatcher() failed; trying ServletContext", module);
        rd = context.getRequestDispatcher(page);
        if (rd == null) {
            Debug.logInfo("ServletContext.getRequestDispatcher() failed; trying ServletContext.getNamedDispatcher(\"jsp\")", module);
            rd = context.getNamedDispatcher("jsp");
            if (rd == null) {
                throw new ViewHandlerException("Source returned a null dispatcher (" + page + ")");
            }
        }
    }

    try {
        rd.include(request, response);
    } catch (IOException ie) {
        throw new ViewHandlerException("IO Error in view", ie);
    } catch (ServletException e) {
        Throwable throwable = e.getRootCause() != null ? e.getRootCause() : e;

        if (throwable instanceof JspException) {
            JspException jspe = (JspException) throwable;

            throwable = jspe.getCause() != null ? jspe.getCause() : jspe;
        }
        Debug.logError(throwable, "ServletException rendering JSP view", module);
        throw new ViewHandlerException(e.getMessage(), throwable);
    }
}
 
Example 3
Source File: ApiFilter.java    From etf-webapp with European Union Public License 1.2 4 votes vote down vote up
@Override
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain filterChain)
        throws ServletException, IOException {

    if (!"localhost".equals(this.allowOrigin)) {
        response.addHeader("Access-Control-Allow-Origin", this.allowOrigin);
        if (!"*".equals(this.allowOrigin)) {
            /**
             * If the server specifies an origin host rather than "*", then it must also include Origin in the Vary response header to indicate to clients that server responses will differ based on the value of the Origin request header.
             */
            response.addHeader("Vary", "Origin");
        }
        if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            response.addHeader("Access-Control-Allow-Credentials", "true");
            response.addHeader("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Authorization");
            response.addHeader("Access-Control-Max-Age", "60");
            response.getWriter().print("OK");
            response.getWriter().flush();
            return;
        }
    }
    try {
        filterChain.doFilter(request, response);
    } catch (final ServletException e) {
        if (e.getRootCause() instanceof MaxUploadSizeExceededException) {
            try {
                Thread.sleep(1500);
            } catch (InterruptedException e1) {
                ExcUtils.suppress(e1);
            }
            final ObjectMapper mapper = new ObjectMapper();
            response.setStatus(413);
            response.setHeader("Content-Type", "application/json");
            mapper.writeValue(response.getWriter(), new ApiError(new LocalizableApiError(
                    "l.max.upload.size.exceeded", false, 413), request.getRequestURL().toString(), applicationContext));
            response.getWriter().flush();
        }
    }
}
 
Example 4
Source File: PortletRequestDispatcherImpl.java    From portals-pluto with Apache License 2.0 4 votes vote down vote up
private void doDispatch(PortletRequest request, PortletResponse response, boolean included) throws PortletException,
      IOException {
   boolean needsFlushAfterForward = false;
   if (!included) {
      String lifecyclePhase = (String) request.getAttribute(PortletRequest.LIFECYCLE_PHASE);
      if (PortletRequest.RENDER_PHASE.equals(lifecyclePhase) || PortletRequest.RESOURCE_PHASE.equals(lifecyclePhase)) {
         needsFlushAfterForward = true;
         ((MimeResponse) response).resetBuffer();
      }
   }

   PortletRequestContext requestContext = (PortletRequestContext) request
         .getAttribute(PortletInvokerService.REQUEST_CONTEXT);
   HttpSession session = null;

   // PLT.10.4.3. Proxied session is created and passed if javax.portlet.servletDefaultSessionScope == PORTLET_SCOPE
   if (isPortletScopeSessionConfigured(requestContext)) {
      String portletWindowId = requestContext.getPortletWindow().getId().getStringId();
      session = ServletPortletSessionProxy.createProxy(requestContext.getServletRequest(), portletWindowId);
   }

   // The servlet request and response wrappers are applied only a single time
   
   HttpServletPortletRequestWrapper req = getWrappedRequest(requestContext.getServletRequest());
   HttpServletPortletResponseWrapper res = getWrappedResponse(requestContext.getServletResponse());

   if (req == null) {
      req = new HttpServletPortletRequestWrapper(requestContext.getServletRequest(),session, request);
   }
   
   if (res == null) {
      res = new HttpServletPortletResponseWrapper(requestContext.getServletResponse(), request, response, included);
   }

   // to control the DispatcherType available in the body of the portlet
   boolean executingReqBody = requestContext.isExecutingRequestBody();
   requestContext.setExecutingRequestBody(false);

   try {
      request.setAttribute(PortletInvokerService.PORTLET_CONFIG, requestContext.getPortletConfig());
      request.setAttribute(PortletInvokerService.PORTLET_REQUEST, request);
      request.setAttribute(PortletInvokerService.PORTLET_RESPONSE, response);

      if (!included) {
         if (namedDispatch) {
            req.startNamed(path);
         } else {
            req.startForward(path);
         }
         if (req.isForwardingPossible()) {
            requestDispatcher.forward(req, res);
         } else {
            // need to "fake" the forward using an include
            requestDispatcher.include(req, res);
         }
      } else {
         if (namedDispatch) {
            req.startNamed(path);
         } else {
            req.startInclude(path);
         }
         requestDispatcher.include(req, res);
      }
      if (needsFlushAfterForward) {
         ((MimeResponse) response).flushBuffer();
      }
   } catch (ServletException sex) {
      if (sex.getRootCause() != null) {
         throw new PortletException(sex.getRootCause());
      }
      throw new PortletException(sex);
   } finally {
      request.removeAttribute(PortletInvokerService.PORTLET_CONFIG);
      request.removeAttribute(PortletInvokerService.PORTLET_REQUEST);
      request.removeAttribute(PortletInvokerService.PORTLET_RESPONSE);
      requestContext.setExecutingRequestBody(executingReqBody);
      req.endDispatch();
   }
}