Example usage for javax.servlet UnavailableException isPermanent

List of usage examples for javax.servlet UnavailableException isPermanent

Introduction

In this page you can find the example usage for javax.servlet UnavailableException isPermanent.

Prototype


public boolean isPermanent() 

Source Link

Document

Returns a boolean indicating whether the servlet is permanently unavailable.

Usage

From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.ServletHolder.java

private Servlet makeUnavailable(UnavailableException e) throws UnavailableException {
    _unavailableEx = e;/* ww  w.  j a  v  a2 s  .co  m*/
    _unavailable = -1;
    if (e.isPermanent())
        _unavailable = -1;
    else {
        if (_unavailableEx.getUnavailableSeconds() > 0)
            _unavailable = System.currentTimeMillis() + 1000 * _unavailableEx.getUnavailableSeconds();
        else
            _unavailable = System.currentTimeMillis() + 5000; // TODO configure
    }

    throw _unavailableEx;
}

From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.ServletHandler.java

/** Handle request.
 * @param pathInContext/*from  w  w  w .  j  a v  a2  s. c  o m*/
 * @param pathParams
 * @param httpRequest
 * @param httpResponse 
 * @exception IOException 
 */
public void handle(String pathInContext, String pathParams, HttpRequest httpRequest, HttpResponse httpResponse)
        throws IOException {
    if (!isStarted())
        return;

    // Handle TRACE
    if (HttpRequest.__TRACE.equals(httpRequest.getMethod())) {
        handleTrace(httpRequest, httpResponse);
        return;
    }

    // Look for existing request/response objects (from enterScope call)
    ServletHttpRequest request = (ServletHttpRequest) httpRequest.getWrapper();
    ServletHttpResponse response = (ServletHttpResponse) httpResponse.getWrapper();
    if (request == null) {
        // Not in ServletHttpContext, but bumble on anyway
        request = new ServletHttpRequest(this, pathInContext, httpRequest);
        response = new ServletHttpResponse(request, httpResponse);
        httpRequest.setWrapper(request);
        httpResponse.setWrapper(response);
    } else {
        request.recycle(this, pathInContext);
        response.recycle();
    }

    // Look for the servlet
    Map.Entry servlet = getHolderEntry(pathInContext);
    ServletHolder servletHolder = servlet == null ? null : (ServletHolder) servlet.getValue();
    if (log.isDebugEnabled())
        log.debug("servlet=" + servlet);

    try {
        // Adjust request paths
        if (servlet != null) {
            String servletPathSpec = (String) servlet.getKey();
            request.setServletPaths(PathMap.pathMatch(servletPathSpec, pathInContext),
                    PathMap.pathInfo(servletPathSpec, pathInContext), servletHolder);
        }

        // Handle the session ID
        request.setRequestedSessionId(pathParams);
        HttpSession session = request.getSession(false);
        if (session != null)
            ((SessionManager.Session) session).access();
        if (log.isDebugEnabled())
            log.debug("session=" + session);

        // Do that funky filter and servlet thang!
        if (servletHolder != null)
            dispatch(pathInContext, request, response, servletHolder, Dispatcher.__REQUEST);
    } catch (Exception e) {
        log.debug(LogSupport.EXCEPTION, e);

        Throwable th = e;
        while (th instanceof ServletException) {
            log.warn(LogSupport.EXCEPTION, th);
            Throwable cause = ((ServletException) th).getRootCause();
            if (cause == th || cause == null)
                break;
            th = cause;
        }

        if (th instanceof HttpException)
            throw (HttpException) th;
        if (th instanceof EOFException)
            throw (IOException) th;
        else if (log.isDebugEnabled() || !(th instanceof java.io.IOException)) {
            if (_contextLog != null) {
                if (th instanceof RuntimeException)
                    _contextLog.error(httpRequest.getURI() + ": ", th);
                else
                    _contextLog.warn(httpRequest.getURI() + ": ", th);
            }

            if (log.isDebugEnabled()) {
                if (th instanceof RuntimeException)
                    log.error(httpRequest.getURI() + ": ", th);
                else
                    log.warn(httpRequest.getURI() + ": ", th);
                log.debug(httpRequest);
            }
        }

        httpResponse.getHttpConnection().forceClose();
        if (!httpResponse.isCommitted()) {
            request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION_TYPE, th.getClass());
            request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION, th);
            if (th instanceof UnavailableException) {
                UnavailableException ue = (UnavailableException) th;
                if (ue.isPermanent())
                    response.sendError(HttpResponse.__404_Not_Found, e.getMessage());
                else
                    response.sendError(HttpResponse.__503_Service_Unavailable, e.getMessage());
            } else
                response.sendError(HttpResponse.__500_Internal_Server_Error, e.getMessage());
        } else if (log.isDebugEnabled())
            log.debug("Response already committed for handling " + th);
    } catch (Error e) {
        log.warn("Error for " + httpRequest.getURI(), e);
        if (log.isDebugEnabled())
            log.debug(httpRequest);

        httpResponse.getHttpConnection().forceClose();
        if (!httpResponse.isCommitted()) {
            request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION_TYPE, e.getClass());
            request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION, e);
            response.sendError(HttpResponse.__500_Internal_Server_Error, e.getMessage());
        } else if (log.isDebugEnabled())
            log.debug("Response already committed for handling ", e);
    } finally {
        if (servletHolder != null && response != null) {
            response.complete();
        }
    }
}

From source file:org.apache.catalina.core.StandardWrapper.java

/**
 * Process an UnavailableException, marking this servlet as unavailable
 * for the specified amount of time./*w  w  w  .j a  va  2 s .  c  o m*/
 *
 * @param unavailable The exception that occurred, or <code>null</code>
 *  to mark this servlet as permanently unavailable
 */
public void unavailable(UnavailableException unavailable) {
    getServletContext().log(sm.getString("standardWrapper.unavailable", getName()));
    if (unavailable == null)
        setAvailable(Long.MAX_VALUE);
    else if (unavailable.isPermanent())
        setAvailable(Long.MAX_VALUE);
    else {
        int unavailableSeconds = unavailable.getUnavailableSeconds();
        if (unavailableSeconds <= 0)
            unavailableSeconds = 60; // Arbitrary default
        setAvailable(System.currentTimeMillis() + (unavailableSeconds * 1000L));
    }

}

From source file:org.eclipse.gyrex.http.jetty.internal.app.ApplicationHandlerCollection.java

@Override
public void handle(final String target, final Request baseRequest, final HttpServletRequest request,
        final HttpServletResponse response) throws IOException, ServletException {
    // don't do anything if already processed
    if (response.isCommitted() || baseRequest.isHandled())
        return;/*  www .  ja  va  2 s. c  o  m*/

    final Iterator<Handler> handlers = this.handlers.iterator();
    if (!handlers.hasNext())
        return;

    final ThroughputMetric requestsMetric = metrics.getRequestsMetric();
    final long requestStart = requestsMetric.requestStarted();
    try {
        doHandle(target, baseRequest, request, response);
        if (response instanceof Response) {
            final int status = ((Response) response).getStatus();
            if (HttpStatus.isServerError(status)) {
                metrics.getRequestsMetric().requestFailed();
                metrics.error(status, ((Response) response).getReason());
            } else {
                metrics.getRequestsMetric().requestFinished(((Response) response).getContentCount(),
                        System.currentTimeMillis() - requestStart);
            }
        } else {
            metrics.getRequestsMetric().requestFinished(0, System.currentTimeMillis() - requestStart);
        }
    } catch (final EofException | RuntimeIOException | ContinuationThrowable e) {
        metrics.getRequestsMetric().requestFailed();
        throw e;
    } catch (final Exception e) {
        metrics.getRequestsMetric().requestFailed();

        final DispatcherType type = baseRequest.getDispatcherType();
        if (!(DispatcherType.REQUEST.equals(type) || DispatcherType.ASYNC.equals(type))) {
            if (e instanceof IOException)
                throw (IOException) e;
            if (e instanceof RuntimeException)
                throw (RuntimeException) e;
            if (e instanceof ServletException)
                throw (ServletException) e;
        }

        // handle or log exception
        else if (e instanceof RuntimeIOException)
            throw (RuntimeIOException) e;
        else if (e instanceof EofException)
            throw (EofException) e;
        else if ((e instanceof IOException) || (e instanceof UnavailableException)
                || (e instanceof IllegalStateException)) {
            if (Platform.inDebugMode()) {
                LOG.debug("Exception processing request {}: {}", request.getRequestURI(),
                        ExceptionUtils.getMessage(e), e);
                LOG.debug(request.toString());
            }
        } else {
            LOG.error("Exception processing request {}: {}",
                    new Object[] { request.getRequestURI(), ExceptionUtils.getRootCauseMessage(e), e });
            if (Platform.inDebugMode()) {
                LOG.debug(request.toString());
            }
        }

        // send error response if possible
        if (!response.isCommitted()) {
            request.setAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE, e.getClass());
            request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, e);
            if (e instanceof UnavailableException) {
                final UnavailableException ue = (UnavailableException) e;
                if (ue.isPermanent()) {
                    response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
                } else {
                    response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, e.getMessage());
                }
            } else if (e instanceof IllegalStateException) {
                response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, e.getMessage());
            } else {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
            }
        } else {
            // give up
            if (JettyDebug.debug) {
                LOG.debug("Response already committed for handling {}", ExceptionUtils.getMessage(e));
            }
        }
    } catch (final Error e) {
        metrics.getRequestsMetric().requestFailed();

        // only handle some errors
        if (!((e instanceof LinkageError) || (e instanceof AssertionError)))
            throw e;

        final DispatcherType type = baseRequest.getDispatcherType();
        if (!(DispatcherType.REQUEST.equals(type) || DispatcherType.ASYNC.equals(type)))
            throw e;

        LOG.error("Error processing request {}: {}",
                new Object[] { request.getRequestURI(), ExceptionUtils.getRootCauseMessage(e), e });
        if (JettyDebug.debug) {
            LOG.debug(request.toString());
        }

        // TODO httpResponse.getHttpConnection().forceClose();
        if (!response.isCommitted()) {
            request.setAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE, e.getClass());
            request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        } else {
            if (JettyDebug.debug) {
                LOG.debug("Response already committed for handling {}", ExceptionUtils.getMessage(e));
            }
        }
    }
}

From source file:org.ireland.jnetty.webapp.ErrorPageManager.java

public void sendServletErrorImpl(Throwable e, ServletRequest req, ServletResponse res) throws IOException {
    HttpServletResponse response = (HttpServletResponse) res;
    HttpServletRequest request = (HttpServletRequest) req;
    Throwable rootExn = e;/*www  .  j  av  a2 s  .co  m*/
    Throwable errorPageExn = null;
    LineMap lineMap = null;

    try {
        response.reset();
    } catch (IllegalStateException e1) {
    }

    if (req.isAsyncStarted()) {
        AsyncContext async = req.getAsyncContext();

        if (async != null)
            async.complete();
    }

    if (response instanceof HttpServletResponseImpl) {
        HttpServletResponseImpl resFacade = (HttpServletResponseImpl) response;
        resFacade.killCache();
        resFacade.setNoCache(true);
    }

    if (rootExn instanceof ClientDisconnectException)
        throw (ClientDisconnectException) rootExn;

    String location = null;

    String title = "500 Servlet Exception";
    boolean isBadRequest = false;
    boolean doStackTrace = true;
    boolean isCompileException = false;
    boolean isServletException = false;
    Throwable compileException = null;
    String lineMessage = null;

    boolean lookupErrorPage = true;

    while (true) {
        if (rootExn instanceof LineMapException)
            lineMap = ((LineMapException) rootExn).getLineMap();

        if (lookupErrorPage) {
            errorPageExn = rootExn;
        }

        if (rootExn instanceof DisplayableException) {
            doStackTrace = false;
            isCompileException = true;
            if (compileException == null)
                compileException = rootExn;
        } else if (rootExn instanceof CompileException) {
            doStackTrace = false;
            isCompileException = true;

            if (compileException == null) // ! isLineCompileException)
                compileException = rootExn;
        } else if (rootExn instanceof LineException) {
            if (lineMessage == null)
                lineMessage = rootExn.getMessage();
        }

        if (rootExn instanceof BadRequestException) {
            isBadRequest = true;
        }

        if (rootExn instanceof OutOfMemoryError) {
            String msg = "TcpSocketLink OutOfMemory";

            ShutdownSystem.shutdownOutOfMemory(msg);
        }

        if (location != null || !lookupErrorPage) {
        } else if (rootExn instanceof LineMapException && rootExn instanceof ServletException
                && !(rootExn instanceof LineCompileException) && rootExn.getCause() != null) {
            // hack to deal with JSP wrapping
        } else if (!isServletException) {
            // SRV.9.9.2 Servlet 2.4
            // location = getErrorPage(rootExn, ServletException.class);
            location = getErrorPage(rootExn);
            isServletException = true;
        } else {
            location = getErrorPage(rootExn);
            lookupErrorPage = false;
        }

        if (location != null)
            lookupErrorPage = false;

        if (isBadRequest)
            break;

        Throwable cause = null;
        if (rootExn instanceof ServletException && !(rootExn instanceof LineCompileException))
            cause = ((ServletException) rootExn).getRootCause();
        else {
            lookupErrorPage = false;
            cause = rootExn.getCause();
        }

        if (cause != null)
            rootExn = cause;
        else {
            break;
        }
    }

    if (location == null && lookupErrorPage) {
        location = getErrorPage(rootExn);
    }

    if (location == null)
        location = getErrorPage(500);

    if (isBadRequest) {
        // server/05a0, server/0532

        if (rootExn instanceof CompileException)
            title = rootExn.getMessage();
        else
            title = String.valueOf(rootExn);

        doStackTrace = false;
        isBadRequest = true;

        if (request instanceof CauchoRequest)
            ((CauchoRequest) request).killKeepalive("bad request: " + rootExn);

        response.resetBuffer();

        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);

        /*
         * if (location == null) log.warn(e.toString());
         */
    } else if (rootExn instanceof UnavailableException) {
        UnavailableException unAvail = (UnavailableException) rootExn;

        if (unAvail.isPermanent()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            title = "404 Not Found";

            if (location == null)
                location = getErrorPage(HttpServletResponse.SC_NOT_FOUND);
        } else {
            response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            title = "503 Unavailable";

            if (unAvail.getUnavailableSeconds() > 0)
                response.setIntHeader("Retry-After", unAvail.getUnavailableSeconds());

            if (location == null)
                location = getErrorPage(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        }
    } else {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    if (location == null)
        location = _defaultLocation;

    if (log.isTraceEnabled())
        log.trace(e.toString(), e);
    else if (isCompileException) {
        if (isBadRequest)
            log.trace(BadRequestException.class.getSimpleName() + ": " + compileException.getMessage());
        else
            log.trace(compileException.getMessage());
    } else if (!doStackTrace)
        log.trace(rootExn.toString());
    else
        log.trace(e.toString(), e);

    if (location != null) {
        if (errorPageExn == null)
            errorPageExn = rootExn;

        request.setAttribute(JSP_EXCEPTION, errorPageExn);
        request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, errorPageExn);
        request.setAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE, errorPageExn.getClass());
        if (request instanceof HttpServletRequest)
            request.setAttribute(RequestDispatcher.ERROR_REQUEST_URI,
                    ((HttpServletRequest) request).getRequestURI());

        String servletName = getServletName(request);

        if (servletName != null)
            request.setAttribute(RequestDispatcher.ERROR_SERVLET_NAME, servletName);

        request.setAttribute(RequestDispatcher.ERROR_STATUS_CODE, new Integer(500));
        request.setAttribute(RequestDispatcher.ERROR_MESSAGE, errorPageExn.getMessage());

        try {
            RequestDispatcher disp = null;
            // can't use filters because of error pages due to filters
            // or security.

            WebApp webApp = getWebApp();

            if (webApp != null)
                disp = webApp.getRequestDispatcher(location);
            else if (_host != null)
                disp = _host.getWebAppContainer().getRequestDispatcher(location);

            if (disp != null) {
                ((RequestDispatcherImpl) disp).error(request, response);
                return;
            }
        } catch (Throwable e1) {
            log.info(e1.toString(), e1);
            rootExn = e1;
        }
    }

    response.setContentType("text/html");

    String encoding = CharacterEncoding.getLocalEncoding();

    if (encoding != null)
        response.setCharacterEncoding(encoding);
    else {
        Locale locale = Locale.getDefault();
        if (!"ISO-8859-1".equals(Encoding.getMimeName(locale)))
            response.setLocale(Locale.getDefault());
        else
            response.setCharacterEncoding("utf-8");
    }

    PrintWriter out;

    try {
        out = response.getWriter();
    } catch (IllegalStateException e1) {
        log.trace(e1.toString(), e1);

        out = new PrintWriter(new OutputStreamWriter(response.getOutputStream()));
    }

    if (isDevelopmentModeErrorPage()) {
        out.println("<html>");
        if (!response.isCommitted())
            out.println("<head><title>" + escapeHtml(title) + "</title></head>");
        out.println("<body>");
        out.println("<h1>" + escapeHtml(title) + "</h1>");

        out.println("<code><pre>");

        if (debug && !CurrentTime.isTest())
            doStackTrace = true;

        if (doStackTrace) {
            out.println("<script language='javascript' type='text/javascript'>");
            out.println("function show() { document.getElementById('trace').style.display = ''; }");
            out.println("</script>");
            out.print("<a style=\"text-decoration\" href=\"javascript:show();\">[show]</a> ");
        }

        if (compileException instanceof DisplayableException) {
            // ioc/0000
            // XXX: dispExn.print doesn't normalize user.name
            // dispExn.print(out);
            out.println(escapeHtml(compileException.getMessage()));
        } else if (compileException != null)
            out.println(escapeHtml(compileException.getMessage()));
        else
            out.println(escapeHtml(rootExn.toString()));

        if (doStackTrace) {
            out.println("<span id=\"trace\" style=\"display:none\">");
            printStackTrace(out, lineMessage, e, rootExn, lineMap);
            out.println("</span>");
        }

        /*
         * if (doStackTrace || debug) { printStackTrace(out, lineMessage, e, rootExn, lineMap); }
         */

        out.println("</pre></code>");

        printVersion(out);

        out.println("</body></html>");
    } else { // non-development mode
        out.println("<html>");
        out.println("<title>Server Error</title>");
        out.println("<body>");
        out.println("<h1>Server Error</h1>");
        out.println("<p>The server is temporarily unavailable due to an");
        out.println("internal error.  Please notify the system administrator");
        out.println("of this problem.</p>");

        out.println("<pre><code>");
        out.println("Date: " + QDate.formatISO8601(CurrentTime.getCurrentTime()));

        out.println("</code></pre>");

        printVersion(out);

        out.println("</body></html>");
    }

    String userAgent = request.getHeader("User-Agent");

    if (userAgent != null && userAgent.indexOf("MSIE") >= 0) {
        out.print(MSIE_PADDING);
    }

    out.close();
}