Example usage for javax.servlet.http HttpServletResponse SC_SERVICE_UNAVAILABLE

List of usage examples for javax.servlet.http HttpServletResponse SC_SERVICE_UNAVAILABLE

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_SERVICE_UNAVAILABLE.

Prototype

int SC_SERVICE_UNAVAILABLE

To view the source code for javax.servlet.http HttpServletResponse SC_SERVICE_UNAVAILABLE.

Click Source Link

Document

Status code (503) indicating that the HTTP server is temporarily overloaded, and unable to handle the request.

Usage

From source file:com.github.thorqin.webapi.oauth2.OAuthServer.java

public static void responseGetResourceFailed(HttpServletResponse response, OAuthError error,
        String errorDescription, String errorUri) {
    String headContent = "Bearer ";
    headContent += "error=\"" + error.toString().toLowerCase() + "\"";
    if (errorDescription != null)
        headContent += "error_description=\"" + errorDescription + "\"";
    if (errorUri != null)
        headContent += "error_uri=\"" + errorUri + "\"";
    response.setHeader("WWW-Authenticate", headContent);

    switch (error) {
    case INVALID_REQUEST:
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        break;/*from   w w  w  . j a va  2  s . co m*/
    case UNAUTHORIZED_CLIENT:
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        break;
    case ACCESS_DENIED:
    case UNSUPPORTED_RESPONSE_TYPE:
    case INVALID_SCOPE:
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        break;
    case SERVER_ERROR:
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        break;
    case TEMPORARILY_UNAVAILABLE:
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        break;
    }
}

From source file:org.openrepose.filters.translation.TranslationFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (!isInitialized) {
        LOG.error(/*from   w  w w .  ja v  a  2 s  .  c  o m*/
                "Filter has not yet initialized... Please check your configuration files and your artifacts directory.");
        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    } else {
        HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper((HttpServletRequest) request);
        HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(
                (HttpServletResponse) response, MUTABLE, MUTABLE, response.getOutputStream());

        final HandleRequestResult handleRequestResult = handleRequest(requestWrapper, responseWrapper);
        HttpServletRequestWrapper handleRequestWrapper = handleRequestResult.getRequest();
        HttpServletResponseWrapper handleResponseWrapper = handleRequestResult.getResponse();

        switch (handleRequestResult.getFilterAction()) {
        case NOT_SET:
            chain.doFilter(request, response);
            break;
        case PASS:
            chain.doFilter(handleRequestWrapper, handleResponseWrapper);
            handleResponseWrapper.commitToResponse();
            break;
        case PROCESS_RESPONSE:
            chain.doFilter(handleRequestWrapper, handleResponseWrapper);
            handleResponse(handleRequestWrapper, handleResponseWrapper);
            handleResponseWrapper.commitToResponse();
            break;
        case RETURN:
            break;
        }
    }
}

From source file:org.b3log.solo.processor.FeedProcessor.java

/**
 * Blog articles Atom output./* w ww .  j  ava 2 s  . c  o  m*/
 * 
 * @param context the specified context
 */
@RequestProcessing(value = { "/blog-articles-feed.do" }, method = { HTTPRequestMethod.GET,
        HTTPRequestMethod.HEAD })
public void blogArticlesAtom(final HTTPRequestContext context) {
    final AtomRenderer renderer = new AtomRenderer();
    context.setRenderer(renderer);

    final Feed feed = new Feed();
    try {
        final JSONObject preference = preferenceQueryService.getPreference();

        final String blogTitle = preference.getString(Preference.BLOG_TITLE);
        final String blogSubtitle = preference.getString(Preference.BLOG_SUBTITLE);
        final String blogHost = preference.getString(Preference.BLOG_HOST);

        feed.setTitle(StringEscapeUtils.escapeXml(blogTitle));
        feed.setSubtitle(StringEscapeUtils.escapeXml(blogSubtitle));
        feed.setUpdated(TimeZones.getTime(preference.getString(Preference.TIME_ZONE_ID)));
        feed.setAuthor(StringEscapeUtils.escapeXml(blogTitle));
        feed.setLink("http://" + blogHost + "/blog-articles-feed.do");
        feed.setId("http://" + blogHost + "/");

        final List<Filter> filters = new ArrayList<Filter>();
        filters.add(new PropertyFilter(Article.ARTICLE_IS_PUBLISHED, FilterOperator.EQUAL, true));
        filters.add(new PropertyFilter(Article.ARTICLE_VIEW_PWD, FilterOperator.EQUAL, ""));
        final Query query = new Query().setCurrentPageNum(1).setPageSize(ENTRY_OUTPUT_CNT)
                .setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters))
                .addSort(Article.ARTICLE_UPDATE_DATE, SortDirection.DESCENDING).setPageCount(1);

        final boolean hasMultipleUsers = Users.getInstance().hasMultipleUsers();
        String authorName = "";

        final JSONObject articleResult = articleRepository.get(query);
        final JSONArray articles = articleResult.getJSONArray(Keys.RESULTS);

        if (!hasMultipleUsers && 0 != articles.length()) {
            authorName = articleUtils.getAuthor(articles.getJSONObject(0)).getString(User.USER_NAME);
        }

        final boolean isFullContent = "fullContent".equals(preference.getString(Preference.FEED_OUTPUT_MODE));

        for (int i = 0; i < articles.length(); i++) {
            final JSONObject article = articles.getJSONObject(i);
            final Entry entry = new Entry();
            feed.addEntry(entry);
            final String title = StringEscapeUtils.escapeXml(article.getString(Article.ARTICLE_TITLE));
            entry.setTitle(title);
            final String summary = isFullContent
                    ? StringEscapeUtils.escapeXml(article.getString(Article.ARTICLE_CONTENT))
                    : StringEscapeUtils.escapeXml(article.optString(Article.ARTICLE_ABSTRACT));
            entry.setSummary(summary);
            final Date updated = (Date) article.get(Article.ARTICLE_UPDATE_DATE);
            entry.setUpdated(updated);

            final String link = "http://" + blogHost + article.getString(Article.ARTICLE_PERMALINK);
            entry.setLink(link);
            entry.setId(link);

            if (hasMultipleUsers) {
                authorName = StringEscapeUtils
                        .escapeXml(articleUtils.getAuthor(article).getString(User.USER_NAME));
            }
            entry.setAuthor(authorName);

            final String tagsString = article.getString(Article.ARTICLE_TAGS_REF);
            final String[] tagStrings = tagsString.split(",");
            for (int j = 0; j < tagStrings.length; j++) {
                final Category catetory = new Category();
                entry.addCatetory(catetory);
                final String tag = tagStrings[j];
                catetory.setTerm(tag);
            }
        }

        renderer.setContent(feed.toString());
    } catch (final Exception e) {
        LOGGER.log(Level.SEVERE, "Get blog article feed error", e);

        try {
            context.getResponse().sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        } catch (final IOException ex) {
            throw new RuntimeException(ex);
        }
    }
}

From source file:org.openrepose.filters.clientauth.common.AuthenticationHandler.java

private FilterDirector authenticate(HttpServletRequest request) {
    final FilterDirector filterDirector = new FilterDirectorImpl();
    filterDirector.setResponseStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
    filterDirector.setFilterAction(FilterAction.RETURN);
    int offset = getCacheOffset();

    final String tracingHeader = request.getHeader(CommonHttpHeader.TRACE_GUID.toString());
    final String authToken = request.getHeader(CommonHttpHeader.AUTH_TOKEN.toString());
    ExtractorResult<String> account = null;
    AuthToken token = null;// w  w w .j a v  a  2s  .com
    String contactId = null;

    if (tenanted) {
        account = extractAccountIdentification(request);
    }

    final boolean allow = allowAccount(account);

    String endpointsInBase64 = "";
    List<AuthGroup> groups = new ArrayList<AuthGroup>();
    try {
        if (!StringUtilities.isBlank(authToken) && allow) {
            token = checkToken(account, authToken);

            if (token == null) {
                token = validateToken(account, StringUriUtilities.encodeUri(authToken), tracingHeader);
                cacheUserInfo(token, offset);
            }
        }

        if (token != null) {
            groups = getAuthGroups(token, offset, tracingHeader);
            contactId = token.getContactId();

            //getting the encoded endpoints to pass into the header, if the endpoints config is not null
            if (endpointsConfiguration != null) {
                endpointsInBase64 = getEndpointsInBase64(token, tracingHeader);
            }
        }
    } catch (AuthServiceOverLimitException ex) {
        LOG.error(FAILURE_AUTH_N + REASON + ex.getMessage());
        LOG.trace("", ex);
        filterDirector.setResponseStatusCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); // (503)
        String retry = ex.getRetryAfter();
        if (retry == null) {
            Calendar retryCalendar = new GregorianCalendar();
            retryCalendar.add(Calendar.SECOND, 5);
            retry = new HttpDate(retryCalendar.getTime()).toRFC1123();
        }
        filterDirector.responseHeaderManager().appendHeader(HttpHeaders.RETRY_AFTER, retry);
        delegationMessage.set(FAILURE_AUTH_N);
    } catch (AuthServiceException ex) {
        LOG.error(FAILURE_AUTH_N + REASON + ex.getMessage());
        LOG.trace("", ex);
        if (ex.getCause() instanceof AkkaServiceClientException
                && ex.getCause().getCause() instanceof TimeoutException) {
            filterDirector.setResponseStatusCode(HttpServletResponse.SC_GATEWAY_TIMEOUT);
        } else {
            filterDirector.setResponseStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
        delegationMessage.set(FAILURE_AUTH_N);
    } catch (Exception ex) {
        LOG.error(FAILURE_AUTH_N, ex);
        filterDirector.setResponseStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        delegationMessage.set(FAILURE_AUTH_N + REASON + ex.getMessage());
    }

    setFilterDirectorValues(authToken, token, delegable, delegableQuality, delegationMessage.get(),
            filterDirector, account == null ? null : account.getResult(), groups, endpointsInBase64, contactId,
            sendAllTenantIds, sendTenantIdQuality);

    delegationMessage.remove();

    return filterDirector;
}

From source file:org.structr.rest.servlet.GraphQLServlet.java

private void assertInitialized() throws FrameworkException {

    if (!Services.getInstance().isInitialized()) {
        throw new FrameworkException(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                "System is not initialized yet");
    }//w w w  . ja  va 2  s. c  o m
}

From source file:org.codice.proxy.http.HttpProxyCamelHttpTransportServlet.java

@Override
protected void service(HttpServletRequest oldRequest, HttpServletResponse response)
        throws ServletException, IOException {

    //Wrap request and clean the query String
    HttpProxyWrappedCleanRequest request = new HttpProxyWrappedCleanRequest(oldRequest);

    log.trace("Service: {}", request);

    // Is there a consumer registered for the request.
    HttpConsumer consumer = resolve(request);

    if (consumer == null) {
        String path = request.getPathInfo();
        log.trace("Service Request Path = {}", path);
        String endpointName = getEndpointNameFromPath(path);
        log.trace("Endpoint Name = {}", endpointName);

        Route route = camelContext.getRoute(endpointName);
        try {/*from w w  w.ja  va2  s. co m*/
            if (route != null) {
                connect((HttpConsumer) route.getConsumer());
            }
        } catch (Exception e) {
            log.debug("Exception while creating consumer", e);
        }
        consumer = resolve(request);
    }

    if (consumer == null) {
        log.debug("No consumer to service request {}", request);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // are we suspended?
    if (consumer.getEndpoint().isSuspended()) {
        log.debug("Consumer suspended, cannot service request {}", request);
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return;
    }

    if (consumer.getEndpoint().getHttpMethodRestrict() != null
            && !consumer.getEndpoint().getHttpMethodRestrict().equals(request.getMethod())) {
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    }

    if ("TRACE".equals(request.getMethod()) && !consumer.getEndpoint().isTraceEnabled()) {
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    }

    // create exchange and set data on it
    Exchange exchange = new DefaultExchange(consumer.getEndpoint(), ExchangePattern.InOut);

    if (consumer.getEndpoint().isBridgeEndpoint()) {
        exchange.setProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.TRUE);
    }
    if (consumer.getEndpoint().isDisableStreamCache()) {
        exchange.setProperty(Exchange.DISABLE_HTTP_STREAM_CACHE, Boolean.TRUE);
    }

    // we override the classloader before building the HttpMessage just in case the binding
    // does some class resolution
    ClassLoader oldTccl = overrideTccl(exchange);
    HttpHelper.setCharsetFromContentType(request.getContentType(), exchange);
    exchange.setIn(new HttpMessage(exchange, request, response));
    // set context path as header
    String contextPath = consumer.getEndpoint().getPath();
    exchange.getIn().setHeader("CamelServletContextPath", contextPath);

    String httpPath = (String) exchange.getIn().getHeader(Exchange.HTTP_PATH);
    // here we just remove the CamelServletContextPath part from the HTTP_PATH
    if (contextPath != null && httpPath.startsWith(contextPath)) {
        exchange.getIn().setHeader(Exchange.HTTP_PATH, httpPath.substring(contextPath.length()));
    }

    // we want to handle the UoW
    try {
        consumer.createUoW(exchange);
    } catch (Exception e) {
        log.error("Error processing request", e);
        throw new ServletException(e);
    }

    try {
        if (log.isTraceEnabled()) {
            log.trace("Processing request for exchangeId: {}", exchange.getExchangeId());
        }
        // process the exchange
        consumer.getProcessor().process(exchange);
    } catch (Exception e) {
        exchange.setException(e);
    }

    try {
        // now lets output to the response
        if (log.isTraceEnabled()) {
            log.trace("Writing response for exchangeId: {}", exchange.getExchangeId());
        }
        Integer bs = consumer.getEndpoint().getResponseBufferSize();
        if (bs != null) {
            log.trace("Using response buffer size: {}", bs);
            response.setBufferSize(bs);
        }
        consumer.getBinding().writeResponse(exchange, response);
    } catch (IOException e) {
        log.error("Error processing request", e);
        throw e;
    } catch (Exception e) {
        log.error("Error processing request", e);
        throw new ServletException(e);
    } finally {
        consumer.doneUoW(exchange);
        restoreTccl(exchange, oldTccl);
    }
}

From source file:com.liferay.jsonwebserviceclient.JSONWebServiceClientImpl.java

protected String execute(HttpRequestBase httpRequestBase) throws CredentialException, IOException {

    HttpHost httpHost = new HttpHost(_hostName, _hostPort, _protocol);

    try {/*from  w  ww  . ja  v  a2s . com*/
        if (_closeableHttpClient == null) {
            afterPropertiesSet();
        }

        HttpResponse httpResponse = _closeableHttpClient.execute(httpHost, httpRequestBase);

        StatusLine statusLine = httpResponse.getStatusLine();

        if (statusLine.getStatusCode() == HttpServletResponse.SC_NOT_FOUND) {

            if (_logger.isWarnEnabled()) {
                _logger.warn("Status code " + statusLine.getStatusCode());
            }

            return null;
        } else if (statusLine.getStatusCode() == HttpServletResponse.SC_UNAUTHORIZED) {

            throw new CredentialException("Not authorized to access JSON web service");
        } else if (statusLine.getStatusCode() == HttpServletResponse.SC_SERVICE_UNAVAILABLE) {

            throw new JSONWebServiceUnavailableException("Service unavailable");
        }

        return EntityUtils.toString(httpResponse.getEntity(), Charsets.UTF_8);
    } finally {
        httpRequestBase.releaseConnection();
    }
}

From source file:org.sakaiproject.access.tool.AccessServlet.java

/**
 * handle get and post communication from the user
 * //from   w  w w  .java2 s.com
 * @param req
 *        HttpServletRequest object with the client request
 * @param res
 *        HttpServletResponse object back to the client
 */
public void dispatch(HttpServletRequest req, HttpServletResponse res) throws ServletException {
    ParameterParser params = (ParameterParser) req.getAttribute(ATTR_PARAMS);

    // get the path info
    String path = params.getPath();
    if (path == null)
        path = "";

    if (!m_ready) {
        sendError(res, HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return;
    }

    // send the sample copyright screen
    if (COPYRIGHT_PATH.equals(path)) {
        respondCopyrightAlertDemo(req, res);
        return;
    }

    // send the real copyright screen for some entity (encoded in the request parameter)
    if (COPYRIGHT_REQUIRE.equals(path)) {
        String acceptedRef = req.getParameter(COPYRIGHT_ACCEPT_REF);
        String returnPath = req.getParameter(COPYRIGHT_ACCEPT_URL);

        Reference aRef = entityManager.newReference(acceptedRef);

        // get the properties - but use a security advisor to avoid needing end-user permission to the resource
        securityService.pushAdvisor(new SecurityAdvisor() {
            public SecurityAdvice isAllowed(String userId, String function, String reference) {
                return SecurityAdvice.ALLOWED;
            }
        });
        ResourceProperties props = aRef.getProperties();
        securityService.popAdvisor();

        // send the copyright agreement interface
        if (props == null) {
            sendError(res, HttpServletResponse.SC_NOT_FOUND);
        }

        setVmReference("validator", new Validator(), req);
        setVmReference("props", props, req);
        setVmReference("tlang", rb, req);

        String acceptPath = Web.returnUrl(req,
                COPYRIGHT_ACCEPT + "?" + COPYRIGHT_ACCEPT_REF + "=" + Validator.escapeUrl(aRef.getReference())
                        + "&" + COPYRIGHT_ACCEPT_URL + "=" + Validator.escapeUrl(returnPath));

        setVmReference("accept", acceptPath, req);
        res.setContentType("text/html; charset=UTF-8");
        includeVm("vm/access/copyrightAlert.vm", req, res);
        return;
    }

    // make sure we have a collection for accepted copyright agreements
    Collection accepted = (Collection) sessionManager.getCurrentSession()
            .getAttribute(COPYRIGHT_ACCEPTED_REFS_ATTR);
    if (accepted == null) {
        accepted = new Vector();
        sessionManager.getCurrentSession().setAttribute(COPYRIGHT_ACCEPTED_REFS_ATTR, accepted);
    }

    // for accepted copyright, mark it and redirect to the entity's access URL
    if (COPYRIGHT_ACCEPT.equals(path)) {
        String acceptedRef = req.getParameter(COPYRIGHT_ACCEPT_REF);
        Reference aRef = entityManager.newReference(acceptedRef);

        // save this with the session's other accepted refs
        accepted.add(aRef.getReference());

        // redirect to the original URL
        String returnPath = Validator.escapeUrl(req.getParameter(COPYRIGHT_ACCEPT_URL));

        try {
            res.sendRedirect(Web.returnUrl(req, returnPath));
        } catch (IOException e) {
            sendError(res, HttpServletResponse.SC_NOT_FOUND);
        }
        return;
    }

    // pre-process the path
    String origPath = path;
    path = preProcessPath(path, req);

    // what is being requested?
    Reference ref = entityManager.newReference(path);

    // get the incoming information
    AccessServletInfo info = newInfo(req);

    // let the entity producer handle it
    try {
        // make sure we have a valid reference with an entity producer we can talk to
        EntityProducer service = ref.getEntityProducer();
        if (service == null)
            throw new EntityNotDefinedException(ref.getReference());

        // get the producer's HttpAccess helper, it might not support one
        HttpAccess access = service.getHttpAccess();
        if (access == null)
            throw new EntityNotDefinedException(ref.getReference());

        // let the helper do the work
        access.handleAccess(req, res, ref, accepted);
    } catch (EntityNotDefinedException e) {
        // the request was not valid in some way
        M_log.debug("dispatch(): ref: " + ref.getReference(), e);
        sendError(res, HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    catch (EntityPermissionException e) {
        // the end user does not have permission - offer a login if there is no user id yet established
        // if not permitted, and the user is the anon user, let them login
        if (sessionManager.getCurrentSessionUserId() == null) {
            try {
                doLogin(req, res, origPath);
            } catch (IOException ioex) {
            }
            return;
        }

        // otherwise reject the request
        M_log.debug("dispatch(): ref: " + ref.getReference(), e);
        sendError(res, HttpServletResponse.SC_FORBIDDEN);
    }

    catch (EntityAccessOverloadException e) {
        M_log.info("dispatch(): ref: " + ref.getReference(), e);
        sendError(res, HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    }

    catch (EntityCopyrightException e) {
        // redirect to the copyright agreement interface for this entity
        try {
            // TODO: send back using a form of the request URL, encoding the real reference, and the requested reference
            // Note: refs / requests with servlet parameters (?x=y...) are NOT supported -ggolden
            String redirPath = COPYRIGHT_REQUIRE + "?" + COPYRIGHT_ACCEPT_REF + "="
                    + Validator.escapeUrl(e.getReference()) + "&" + COPYRIGHT_ACCEPT_URL + "="
                    + Validator.escapeUrl(req.getPathInfo());
            res.sendRedirect(Web.returnUrl(req, redirPath));
        } catch (IOException ee) {
        }
        return;
    }

    catch (Throwable e) {
        M_log.warn("dispatch(): exception: ", e);
        sendError(res, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    finally {
        // log
        if (M_log.isDebugEnabled())
            M_log.debug("from:" + req.getRemoteAddr() + " path:" + params.getPath() + " options: "
                    + info.optionsString() + " time: " + info.getElapsedTime());
    }
}

From source file:org.tinygroup.jspengine.servlet.JspServletWrapper.java

public void service(HttpServletRequest request, HttpServletResponse response, boolean precompile)
        throws ServletException, IOException {

    try {/*from   www . j  a  va  2s .c  o m*/

        if (ctxt.isRemoved()) {
            jspFileNotFound(request, response);
            return;
        }

        if ((available > 0L) && (available < Long.MAX_VALUE)) {
            response.setDateHeader("Retry-After", available);
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                    Localizer.getMessage("jsp.error.unavailable"));
        }

        /*
         * (1) Compile
         */
        // BEGIN S1AS 6181923
        // if (options.getDevelopment() || firstTime) {
        // END S1AS 6181923
        // BEGIN S1AS 6181923
        if (!options.getUsePrecompiled() && (options.getDevelopment() || firstTime)) {
            // END S1AS 6181923
            synchronized (this) {
                firstTime = false;

                // The following sets reload to true, if necessary
                ctxt.compile();
            }
        } else {
            if (compileException != null) {
                // Throw cached compilation exception
                throw compileException;
            }
        }

        /*
         * (2) (Re)load servlet class file
         */
        getServlet();

        // If a page is to be precompiled only, return.
        if (precompile) {
            return;
        }

        /*
         * (3) Service request
         */
        if (theServlet instanceof SingleThreadModel) {
            // sync on the wrapper so that the freshness
            // of the page is determined right before servicing
            synchronized (this) {
                theServlet.service(request, response);
            }
        } else {
            theServlet.service(request, response);
        }

    } catch (UnavailableException ex) {
        String includeRequestUri = (String) request.getAttribute("javax.servlet.include.request_uri");
        if (includeRequestUri != null) {
            // This file was included. Throw an exception as
            // a response.sendError() will be ignored by the
            // servlet engine.
            throw ex;
        } else {
            int unavailableSeconds = ex.getUnavailableSeconds();
            if (unavailableSeconds <= 0) {
                unavailableSeconds = 60; // Arbitrary default
            }
            available = System.currentTimeMillis() + (unavailableSeconds * 1000L);
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, ex.getMessage());
        }
    } catch (ServletException ex) {
        throw ex;
    } catch (IOException ex) {
        throw ex;
    } catch (IllegalStateException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new JasperException(ex);
    }
}

From source file:org.hyperic.lather.server.LatherServlet.java

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ByteArrayInputStream bIs;//from  www  .  j  av a2 s.c o m
    DataInputStream dIs;
    LatherXCoder xCoder;
    LatherValue val;
    String[] method, args, argsClass;
    LatherContext ctx;
    byte[] decodedArgs;
    Class<?> valClass;

    ctx = new LatherContext();
    ctx.setCallerIP(req.getRemoteAddr());
    ctx.setRequestTime(System.currentTimeMillis());

    xCoder = new LatherXCoder();

    method = req.getParameterValues("method");
    args = req.getParameterValues("args");
    argsClass = req.getParameterValues("argsClass");

    if (method == null || args == null || argsClass == null || method.length != 1 || args.length != 1
            || argsClass.length != 1) {
        String msg = "Invalid Lather request made from " + req.getRemoteAddr();
        log.error(msg);
        resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, msg);
        return;
    }

    if (log.isDebugEnabled()) {
        log.debug("Invoking method '" + method[0] + "' for connID=" + req.getAttribute(PROP_CONNID));
    }

    try {
        valClass = Class.forName(argsClass[0], true, xCoder.getClass().getClassLoader());
    } catch (ClassNotFoundException exc) {
        String msg = "Lather request from " + req.getRemoteAddr() + " required an argument object of class '"
                + argsClass[0] + "' which could not be found";
        log.error(msg);
        resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, msg);
        return;
    }

    decodedArgs = Base64.decode(args[0]);
    bIs = new ByteArrayInputStream(decodedArgs);
    dIs = new DataInputStream(bIs);

    try {
        val = xCoder.decode(dIs, valClass);
    } catch (LatherRemoteException exc) {
        LatherServlet.issueErrorResponse(resp, exc.toString());
        return;
    }

    this.doServiceCall(req, resp, method[0], val, xCoder, ctx);
}