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.ibm.jaggr.core.impl.AbstractAggregatorImpl.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
    final String sourceMethod = "doGet"; //$NON-NLS-1$
    boolean isTraceLogging = log.isLoggable(Level.FINER);
    if (isTraceLogging) {
        log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[] { req, resp });
        log.finer("Request URL=" + req.getRequestURI()); //$NON-NLS-1$
    }/*  w ww .  ja v  a2 s  .  c  om*/

    if (isShuttingDown) {
        // Server has been shut-down, or is in the process of shutting down.
        resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        if (isTraceLogging) {
            log.finer("Processing request after server shutdown.  Returning SC_SERVICE_UNAVAILABLE"); //$NON-NLS-1$
            log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
        }
        return;
    }
    resp.addHeader("Server", "JavaScript Aggregator"); //$NON-NLS-1$ //$NON-NLS-2$
    String pathInfo = req.getPathInfo();
    if (pathInfo == null) {
        processAggregatorRequest(req, resp);
    } else {
        boolean processed = false;
        // search resource paths to see if we should treat as aggregator request or resource request
        for (Map.Entry<String, IResource> entry : resourcePaths.entrySet()) {
            String path = entry.getKey();
            if (path.equals(pathInfo) && entry.getValue() == null) {
                processAggregatorRequest(req, resp);
                processed = true;
                break;
            }
            if (pathInfo.startsWith(path)) {
                if ((path.length() == pathInfo.length() || pathInfo.charAt(path.length()) == '/')
                        && entry.getValue() != null) {
                    String resPath = path.length() == pathInfo.length() ? "" //$NON-NLS-1$
                            : pathInfo.substring(path.length() + 1);
                    IResource res = entry.getValue();
                    processResourceRequest(req, resp, res, resPath);
                    processed = true;
                    break;
                }
            }
        }
        if (!processed) {
            resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    if (isTraceLogging) {
        log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
    }
}

From source file:org.jitsi.videobridge.rest.HandlerImpl.java

/**
 * Retrieves a JSON representation of the
 * <tt>DominantSpeakerIdentification</tt> of a specific <tt>Conference</tt>.
 *
 * @param baseRequest the original unwrapped {@link Request} object
 * @param request the request either as the {@code Request} object or a
 * wrapper of that request//from   w w  w  .j  av a  2 s .c  o  m
 * @param response the response either as the {@code Response} object or a
 * wrapper of that response
 * @throws IOException
 * @throws ServletException
 */
private void doGetDominantSpeakerIdentificationJSON(Conference conference, Request baseRequest,
        HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    ConferenceSpeechActivity conferenceSpeechActivity = conference.getSpeechActivity();

    if (conferenceSpeechActivity == null) {
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    } else {
        JSONObject jsonObject = conferenceSpeechActivity.doGetDominantSpeakerIdentificationJSON();

        if (jsonObject != null) {
            response.setStatus(HttpServletResponse.SC_OK);
            jsonObject.writeJSONString(response.getWriter());
        }
    }
}

From source file:jenkins.metrics.api.MetricsRootAction.java

/**
 * Condense the health check into one bit of information
 * for frontend reverse proxies like haproxy.
 *
 * Other health check calls requires authentication, which
 * is not suitable for the haproxy use. But this endpoint
 * only exposes one bit information, it's deemed OK to be exposed
 * unsecurely./*from   w  w w  . j a  v  a 2 s.c om*/
 *
 * return status 200 if everything is OK, 503 (service unavailable) otherwise
 */
@SuppressWarnings("unused") // stapler binding
@Restricted(NoExternalUse.class) // stapler binding
public HttpResponse doHealthcheckOk(StaplerRequest req) {
    long ifModifiedSince = req.getDateHeader("If-Modified-Since");
    long maxAge = getCacheControlMaxAge(req);
    Metrics.HealthCheckData data = Metrics.getHealthCheckData();
    if (data == null || (maxAge != -1 && data.getLastModified() + maxAge < System.currentTimeMillis())) {
        data = new Metrics.HealthCheckData(Metrics.healthCheckRegistry().runHealthChecks());
    } else if (ifModifiedSince != -1 && data.getLastModified() < ifModifiedSince) {
        return HttpResponses.status(HttpServletResponse.SC_NOT_MODIFIED);
    }
    for (HealthCheck.Result result : data.getResults().values()) {
        if (!result.isHealthy()) {
            return new StatusResponse(HttpServletResponse.SC_SERVICE_UNAVAILABLE, data.getLastModified(),
                    data.getExpires());
        }
    }
    return new StatusResponse(HttpServletResponse.SC_OK, data.getLastModified(), data.getExpires());
}

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

/**
 * Shows remove all data page./*from  w  w w  .j ava  2  s . c o  m*/
 * 
 * @param context the specified context
 * @param request the specified HTTP servlet request 
 */
@RequestProcessing(value = "/rm-all-data.do", method = HTTPRequestMethod.GET)
public void removeAllDataGET(final HTTPRequestContext context, final HttpServletRequest request) {
    final TextHTMLRenderer renderer = new TextHTMLRenderer();
    context.setRenderer(renderer);

    try {
        final StringBuilder htmlBuilder = new StringBuilder();
        htmlBuilder.append("<html><head><title>WARNING!</title>");
        htmlBuilder.append("<script type='text/javascript'");
        htmlBuilder.append("src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js'");
        htmlBuilder.append("></script></head><body>");
        htmlBuilder.append("<button id='ok' onclick='remove()'>");
        htmlBuilder.append("Continue to delete ALL DATA</button></body>");
        htmlBuilder.append("<script type='text/javascript'>");
        htmlBuilder.append("function remove() {");
        htmlBuilder.append("$.ajax({type: 'POST',url:'").append(Latkes.getContextPath())
                .append("/rm-all-data.do',");
        htmlBuilder.append("dataType: 'text/html',success: function(result){");
        htmlBuilder.append("$('html').html(result);}});}</script></html>");

        renderer.setContent(htmlBuilder.toString());
    } catch (final Exception e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);

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

From source file:org.jitsi.videobridge.rest.HandlerImpl.java

/**
 * {@inheritDoc}/*  w  ww .  j  av  a 2  s  . co  m*/
 */
@Override
protected void doGetHealthJSON(Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    beginResponse(/* target */ null, baseRequest, request, response);

    Videobridge videobridge = getVideobridge();

    if (videobridge == null) {
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    } else {
        Health.getJSON(videobridge, baseRequest, request, response);
    }

    endResponse(/* target */ null, baseRequest, request, response);
}

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

/**
 * Tag articles Atom output.//from www. j  a va2s .  c  o  m
 * 
 * @param context the specified context
 * @throws IOException io exception 
 */
@RequestProcessing(value = { "/tag-articles-feed.do" }, method = { HTTPRequestMethod.GET,
        HTTPRequestMethod.HEAD })
public void tagArticlesAtom(final HTTPRequestContext context) throws IOException {
    final AtomRenderer renderer = new AtomRenderer();
    context.setRenderer(renderer);

    final HttpServletRequest request = context.getRequest();
    final HttpServletResponse response = context.getResponse();

    final String queryString = request.getQueryString();

    if (Strings.isEmptyOrNull(queryString)) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    final String oIdMap = queryString.split("&")[0];
    final String tagId = oIdMap.split("=")[1];

    final Feed feed = new Feed();
    try {
        final JSONObject tag = tagRepository.get(tagId);
        if (null == tag) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        final String tagTitle = tag.getString(Tag.TAG_TITLE);

        final JSONObject preference = preferenceQueryService.getPreference();
        if (null == preference) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        final String blogTitle = preference.getString(Preference.BLOG_TITLE);
        final String blogSubtitle = preference.getString(Preference.BLOG_SUBTITLE) + ", " + tagTitle;
        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 + "/tag-articles-feed.do");
        feed.setId("http://" + blogHost + "/");

        final JSONObject tagArticleResult = tagArticleRepository.getByTagId(tagId, 1, ENTRY_OUTPUT_CNT);
        final JSONArray tagArticleRelations = tagArticleResult.getJSONArray(Keys.RESULTS);
        if (0 == tagArticleRelations.length()) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        final List<JSONObject> articles = new ArrayList<JSONObject>();
        for (int i = 0; i < tagArticleRelations.length(); i++) {
            final JSONObject tagArticleRelation = tagArticleRelations.getJSONObject(i);
            final String articleId = tagArticleRelation.getString(Article.ARTICLE + "_" + Keys.OBJECT_ID);
            final JSONObject article = articleRepository.get(articleId);
            if (article.getBoolean(Article.ARTICLE_IS_PUBLISHED) // Skips the unpublished article
                    && Strings.isEmptyOrNull(article.optString(Article.ARTICLE_VIEW_PWD))) { // Skips article with password
                articles.add(article);
            }
        }

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

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

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

        for (int i = 0; i < articles.size(); i++) {
            final JSONObject article = articles.get(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);
                catetory.setTerm(tagStrings[j]);
            }
        }

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

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

From source file:org.nuxeo.ecm.core.opencmis.impl.server.NuxeoCmisService.java

@Override
public Progress afterServiceCall() {
    // check if there is a transaction timeout
    // if yes, abort and return a 503 (Service Unavailable)
    if (!TransactionHelper.setTransactionRollbackOnlyIfTimedOut()) {
        return Progress.CONTINUE;
    }// w w w.j  a  v a2 s. c o  m
    HttpServletResponse response = (HttpServletResponse) getCallContext()
            .get(CallContext.HTTP_SERVLET_RESPONSE);
    if (response != null) {
        try {
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Transaction timeout");
        } catch (IOException e) {
            throw new CmisRuntimeException("Failed to set timeout status", e);
        }
    }
    return Progress.STOP;
}

From source file:au.edu.anu.portal.portlets.tweetal.servlet.TweetalServlet.java

public void getTweets(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");
    PrintWriter out = response.getWriter();

    String userToken = request.getParameter("u");
    String userSecret = request.getParameter("s");

    Twitter twitter = twitterLogic.getTwitterAuthForUser(userToken, userSecret);
    if (twitter == null) {
        // no connection
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return;//from  w w  w  . j a v  a2s  .c om
    }

    String cacheKey = userToken;
    Element element = null;

    // force refresh
    boolean force = Boolean.parseBoolean(request.getParameter("force"));
    if (force) {
        log.debug("force refresh for " + userToken);
        // remove tweets cache
        tweetsCache.remove(cacheKey);
    } else {
        element = tweetsCache.get(cacheKey);
    }

    if (element == null) {
        synchronized (tweetsCache) {
            // if it is still null after acquiring lock
            element = tweetsCache.get(cacheKey);

            if (element == null) {
                log.debug("cache miss: getting tweets for " + userToken);
                System.out.println("Last refreshed: " + Calendar.getInstance().getTime());

                try {
                    ResponseList<Status> friendStatus = twitter.getFriendsTimeline();

                    long maxId = Long.MIN_VALUE;

                    JSONObject json = new JSONObject();

                    lastRefreshed = Calendar.getInstance().getTime().toString();

                    if (lastRefreshed == null) {
                        json.element("lastRefreshed", "unable to retrieve last refreshed");
                    } else {
                        json.element("lastRefreshed", lastRefreshed.toString());
                    }

                    User currentUser = twitter.showUser(twitter.getId());
                    Status lastUserStatus = currentUser.getStatus();
                    if (lastUserStatus == null) {
                        json.element("lastStatusUpdate", "unable to retrieve last status");
                    } else {
                        Date lastStatusUpdate = lastUserStatus.getCreatedAt();
                        json.element("lastStatusUpdate", lastStatusUpdate.toString());
                    }

                    for (Status status : friendStatus) {
                        maxId = Math.max(maxId, status.getId());
                        json.accumulate("statusList", getStatusJSON(twitter, status));
                    }

                    if (log.isDebugEnabled()) {
                        log.debug(json.toString(2));
                    }

                    out.print(json.toString());

                    element = new Element(cacheKey,
                            new TweetsCacheElement(System.currentTimeMillis(), maxId, json));

                    tweetsCache.put(element);

                    return;

                } catch (TwitterException e) {
                    log.error("GetTweets: " + e.getStatusCode() + ": " + e.getClass() + e.getMessage());

                    if (e.getStatusCode() == 401) {
                        // invalid credentials
                        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                    } else if (e.getStatusCode() == -1) {
                        // no connection
                        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    } else {
                        // general error
                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    }

                    return;
                }
            }
        }
    }

    // tweets available in cache
    log.debug("cache hit: getting tweets for " + userToken);

    TweetsCacheElement tweets = (TweetsCacheElement) element.getObjectValue();

    // if just refreshed too quickly, don't request update, just use
    // whatever in cache
    long period = System.currentTimeMillis() - tweets.getLastRefresh();
    System.out.println("Already refreshed: " + (period / 1000) + " second(s) ago");

    if (period < 2 * 60 * 1000) {
        log.debug("refreshed too quickly: " + (period / 1000) + " seconds");
        JSONObject json = tweets.getResult();
        lastRefreshed = Calendar.getInstance().getTime().toString();
        json.element("lastRefreshed", lastRefreshed.toString());
        out.print(json.toString());
        return;
    }

    // get new updates since the last id
    long maxId = tweets.lastId;
    try {
        JSONObject json = tweets.getResult();

        ResponseList<Status> friendStatus = twitter.getFriendsTimeline(new Paging(maxId));

        tweets.setLastRefresh(System.currentTimeMillis());

        log.debug(String.format("Got %d new tweets", friendStatus.size()));

        if (friendStatus.size() > 0) {
            JSONArray newTweets = new JSONArray();

            lastRefreshed = Calendar.getInstance().getTime().toString();
            json.element("lastRefreshed", lastRefreshed.toString());

            for (Status status : friendStatus) {
                maxId = Math.max(maxId, status.getId());
                newTweets.add(getStatusJSON(twitter, status));
            }

            if (log.isDebugEnabled()) {
                log.debug("new tweets:\n" + newTweets.toString(2));
            }

            json.getJSONArray("statusList").addAll(0, newTweets);

            tweets.setLastId(maxId);

            User currentUser = twitter.showUser(twitter.getId());
            Status lastUserStatus = currentUser.getStatus();
            if (lastUserStatus == null) {
                json.element("lastStatusUpdate", "unable to retrieve last status");
            } else {
                Date lastStatusUpdate = lastUserStatus.getCreatedAt();
                json.element("lastStatusUpdate", lastStatusUpdate.toString());
            }
        }

        out.print(json.toString());

    } catch (TwitterException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        log.error(e);
    }
}

From source file:com.zimbra.cs.servlet.ZimbraServlet.java

public static void proxyServletRequest(HttpServletRequest req, HttpServletResponse resp, HttpMethod method,
        HttpState state) throws IOException, ServiceException {
    // create an HTTP client with the same cookies
    javax.servlet.http.Cookie cookies[] = req.getCookies();
    String hostname = method.getURI().getHost();
    boolean hasZMAuth = hasZimbraAuthCookie(state);
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals(ZimbraCookie.COOKIE_ZM_AUTH_TOKEN) && hasZMAuth)
                continue;
            state.addCookie(//ww w .j a  va2 s  . co  m
                    new Cookie(hostname, cookies[i].getName(), cookies[i].getValue(), "/", null, false));
        }
    }
    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    if (state != null)
        client.setState(state);

    int hopcount = 0;
    for (Enumeration<?> enm = req.getHeaderNames(); enm.hasMoreElements();) {
        String hname = (String) enm.nextElement(), hlc = hname.toLowerCase();
        if (hlc.equals("x-zimbra-hopcount"))
            try {
                hopcount = Math.max(Integer.parseInt(req.getHeader(hname)), 0);
            } catch (NumberFormatException e) {
            }
        else if (hlc.startsWith("x-") || hlc.startsWith("content-") || hlc.equals("authorization"))
            method.addRequestHeader(hname, req.getHeader(hname));
    }
    if (hopcount >= MAX_PROXY_HOPCOUNT)
        throw ServiceException.TOO_MANY_HOPS(HttpUtil.getFullRequestURL(req));
    method.addRequestHeader("X-Zimbra-Hopcount", Integer.toString(hopcount + 1));
    if (method.getRequestHeader("X-Zimbra-Orig-Url") == null)
        method.addRequestHeader("X-Zimbra-Orig-Url", req.getRequestURL().toString());
    String ua = req.getHeader("User-Agent");
    if (ua != null)
        method.setRequestHeader("User-Agent", ua);

    // dispatch the request and copy over the results
    int statusCode = -1;
    for (int retryCount = 3; statusCode == -1 && retryCount > 0; retryCount--) {
        statusCode = HttpClientUtil.executeMethod(client, method);
    }
    if (statusCode == -1) {
        resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "retry limit reached");
        return;
    } else if (statusCode >= 300) {
        resp.sendError(statusCode, method.getStatusText());
        return;
    }

    Header[] headers = method.getResponseHeaders();
    for (int i = 0; i < headers.length; i++) {
        String hname = headers[i].getName(), hlc = hname.toLowerCase();
        if (hlc.startsWith("x-") || hlc.startsWith("content-") || hlc.startsWith("www-"))
            resp.addHeader(hname, headers[i].getValue());
    }
    InputStream responseStream = method.getResponseBodyAsStream();
    if (responseStream == null || resp.getOutputStream() == null)
        return;
    ByteUtil.copy(method.getResponseBodyAsStream(), false, resp.getOutputStream(), false);
}

From source file:org.jitsi.videobridge.rest.HandlerImpl.java

/**
 * Gets a JSON representation of the <tt>VideobridgeStatistics</tt> of (the
 * associated) <tt>Videobridge</tt>.
 *
 * @param baseRequest the original unwrapped {@link Request} object
 * @param request the request either as the {@code Request} object or a
 * wrapper of that request//w w w  .ja va 2s . com
 * @param response the response either as the {@code Response} object or a
 * wrapper of that response
 * @throws IOException
 * @throws ServletException
 */
private void doGetStatisticsJSON(Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    BundleContext bundleContext = getBundleContext();

    if (bundleContext != null) {
        StatsManager statsManager = ServiceUtils.getService(bundleContext, StatsManager.class);

        if (statsManager != null) {
            Iterator<Statistics> i = statsManager.getStatistics().iterator();
            Statistics statistics = null;

            if (i.hasNext())
                statistics = i.next();

            JSONObject statisticsJSONObject = JSONSerializer.serializeStatistics(statistics);
            Writer writer = response.getWriter();

            response.setStatus(HttpServletResponse.SC_OK);
            if (statisticsJSONObject == null)
                writer.write("null");
            else
                statisticsJSONObject.writeJSONString(writer);

            return;
        }
    }

    response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
}