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:org.sakaiproject.nakamura.http.qos.QoSFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    boolean accepted = false;
    QoSToken qoSToken = getQoSControl(request);
    try {/* ww  w .j a v a2s .c o  m*/
        if (request.getAttribute(suspendedAttributeName) == null) {
            accepted = qoSToken.acquire(waitMs);
            if (accepted) {
                request.setAttribute(suspendedAttributeName, Boolean.FALSE);
            } else {
                LOGGER.debug("Suspending request");
                request.setAttribute(suspendedAttributeName, Boolean.TRUE);
                Continuation continuation = ContinuationSupport.getContinuation((HttpServletRequest) request,
                        qoSToken.getMutex());
                continuation.suspend(qoSToken.getSuspendTime());
                qoSToken.queue(continuation);
                return;
            }
        } else {
            Boolean suspended = (Boolean) request.getAttribute(suspendedAttributeName);

            if (suspended.booleanValue()) {
                request.setAttribute(suspendedAttributeName, Boolean.FALSE);
                if (request.getAttribute("javax.servlet.resumed") == Boolean.TRUE) {
                    qoSToken.acquire();
                    accepted = true;
                } else {
                    // Timeout! try 1 more time.
                    accepted = qoSToken.acquire(waitMs);
                }
            } else {
                // pass through resume of previously accepted request
                qoSToken.acquire();
                accepted = true;
            }
        }

        if (accepted) {
            chain.doFilter(request, response);
        } else {
            ((HttpServletResponse) response).sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        }
    } catch (InterruptedException e) {
        LOGGER.warn("QoS", e);
        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    } finally {
        if (accepted) {
            qoSToken.release();
        }
    }
}

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

protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    final boolean debug = log.isDebugEnabled();
    boolean gotConn = false;
    int connRnd;/*from   w  w w.  ja  v  a2s .  c  o  m*/
    connRnd = this.rand.nextInt();
    String method = req.getParameter("method");
    try {
        gotConn = connManager.get().grabConn(method);
        if (!gotConn) {
            final String msg = new StringBuilder(128).append("Denied request from ").append(req.getRemoteAddr())
                    .append(" availablePermits=").append(connManager.get().getAvailablePermits(method))
                    .append(", method=").append(method).toString();
            if (debug)
                log.debug(msg);
            resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, msg);
            return;
        }
        req.setAttribute(PROP_CONNID, new Integer(connRnd));
        if (debug) {
            log.debug("Accepting request from " + req.getRemoteAddr() + " availablePermits="
                    + connManager.get().getAvailablePermits(method) + " conID=" + connRnd);
        }
        super.service(req, resp);
    } finally {
        if (gotConn) {
            connManager.get().releaseConn(method);
            if (debug)
                log.debug("Releasing request from " + req.getRemoteAddr() + " availablePermits="
                        + connManager.get().getAvailablePermits(method) + " connID=" + connRnd);
        }
    }
}

From source file:org.jitsi.rest.AbstractJSONHandler.java

/**
 * Gets a JSON representation of the {@code Version} of the associated
 * server/service.//from   w  ww  .j  a  v  a  2 s .c  om
 *
 * @param baseRequest the original unwrapped {@link Request} object
 * @param request the request either as the {@code Request} object or a
 * wrapper of that request
 * @param response the response either as the {@code Response} object or a
 * wrapper of that response
 * @throws IOException
 * @throws ServletException
 */
protected void doGetVersionJSON(Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    beginResponse(/*target*/ null, baseRequest, request, response);

    BundleContext bundleContext = getBundleContext();
    int status = HttpServletResponse.SC_SERVICE_UNAVAILABLE;

    if (bundleContext != null) {
        VersionService versionService = ServiceUtils.getService(bundleContext, VersionService.class);

        if (versionService != null) {
            org.jitsi.service.version.Version version = versionService.getCurrentVersion();
            JSONObject versionJSONObject = new JSONObject();

            versionJSONObject.put("name", version.getApplicationName());
            versionJSONObject.put("version", version.toString());
            versionJSONObject.put("os", System.getProperty("os.name"));

            Writer writer = response.getWriter();

            response.setStatus(status = HttpServletResponse.SC_OK);
            versionJSONObject.writeJSONString(writer);
        }
    }

    if (response.getStatus() != status)
        response.setStatus(status);

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

From source file:org.b3log.latke.servlet.HTTPRequestDispatcher.java

/**
 * Dispatches with the specified context.
 * //from   w w  w .  j  a v a2  s.  co  m
 * @param context the specified specified context
 * @throws ServletException servlet exception
 * @throws IOException io exception 
 */
public static void dispatch(final HTTPRequestContext context) throws ServletException, IOException {
    final HttpServletRequest request = context.getRequest();

    String requestURI = (String) request.getAttribute(Keys.HttpRequest.REQUEST_URI);

    if (Strings.isEmptyOrNull(requestURI)) {
        requestURI = request.getRequestURI();
    }

    String method = (String) request.getAttribute(Keys.HttpRequest.REQUEST_METHOD);

    if (Strings.isEmptyOrNull(method)) {
        method = request.getMethod();
    }

    LOGGER.log(Level.FINER, "Request[requestURI={0}, method={1}]", new Object[] { requestURI, method });

    try {
        final Object processorMethodRet = RequestProcessors.invoke(requestURI, Latkes.getContextPath(), method,
                context);
    } catch (final Exception e) {
        final String exceptionTypeName = e.getClass().getName();

        LOGGER.log(Level.FINER,
                "Occured error while processing request[requestURI={0}, method={1}, exceptionTypeName={2}, errorMsg={3}]",
                new Object[] { requestURI, method, exceptionTypeName, e.getMessage() });
        if ("com.google.apphosting.api.ApiProxy$OverQuotaException".equals(exceptionTypeName)) {
            PageCaches.removeAll();

            context.getResponse().sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            return;
        }

        throw new ServletException(e);
    } catch (final Error e) {
        final Runtime runtime = Runtime.getRuntime();

        LOGGER.log(Level.FINER, "Memory status[total={0}, max={1}, free={2}]",
                new Object[] { runtime.totalMemory(), runtime.maxMemory(), runtime.freeMemory() });

        LOGGER.log(Level.SEVERE, e.getMessage(), e);

        throw e;
    }

    // XXX: processor method ret?

    final HttpServletResponse response = context.getResponse();

    if (response.isCommitted()) { // Sends rdirect or send error
        final PrintWriter writer = response.getWriter();

        writer.flush();
        writer.close();

        return;
    }

    AbstractHTTPResponseRenderer renderer = context.getRenderer();

    if (null == renderer) {
        renderer = new HTTP404Renderer();
    }

    renderer.render(context);
}

From source file:com.alfaariss.oa.sso.web.WebSSOServlet.java

/**
 * Process the WebSSO HTTP requests./*from ww  w  .  ja v  a2 s  . co m*/
 * @throws IOException 
 * 
 * @see javax.servlet.http.HttpServlet#service(
 *  javax.servlet.http.HttpServletRequest, 
 *  javax.servlet.http.HttpServletResponse)
 *  
 */
@Override
public void service(HttpServletRequest oRequest, HttpServletResponse oResponse)
        throws ServletException, IOException {
    try {
        if (_defaultSSOProfile == null)
            oResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, oRequest.getRequestURI());

        String sTarget = resolveTarget(oRequest);
        if (sTarget == null)
            _defaultSSOProfile.service(oRequest, oResponse);
        else {
            ISSOProfile ssoProfile = _mapSSOProfiles.get(sTarget);
            if (ssoProfile != null & (ssoProfile instanceof IService)) {
                ((IService) ssoProfile).service(oRequest, oResponse);
            } else {//if profile not found by target, then use default profile
                _defaultSSOProfile.service(oRequest, oResponse);
            }
        }

        //send okay if no response is sent yet
        if (!oResponse.isCommitted())
            oResponse.sendError(HttpServletResponse.SC_OK);
    } catch (OAException e) {
        _logger.error("Could not process request", e);
        if (!oResponse.isCommitted())
            oResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (Exception e) {
        _logger.fatal("Could not process request due to internal error", e);
        if (!oResponse.isCommitted())
            oResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:org.jahia.bin.errors.ErrorLoggingFilter.java

protected static void handle(HttpServletRequest request, HttpServletResponse response) {

    // add request information
    request.setAttribute("org.jahia.exception.requestInfo", getRequestInfo(request));

    logDebugInfo(request, response);/*w  w  w. j av  a 2s .  c o  m*/

    if (HttpServletResponse.SC_SERVICE_UNAVAILABLE == (Integer) request
            .getAttribute("javax.servlet.error.status_code")
            && (StringUtils.equals(ErrorServlet.MAINTENANCE_MODE,
                    (String) request.getAttribute("javax.servlet.error.message"))
                    || StringUtils.equals(ErrorServlet.LICENSE_TERMS_VIOLATION_MODE,
                            (String) request.getAttribute("javax.servlet.error.message")))) {
        return;
    }

    logException(request, response);

    dumpToFile(request);

    if (isMailServiceEnabled() && isEmailAlertRequired(request, response)) {
        emailAlert(request, response);
    }
}

From source file:org.apache.nifi.processors.standard.servlets.ListenHTTPServlet.java

@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    final ProcessContext context = processContext;

    ProcessSessionFactory sessionFactory;
    do {//from w w  w. j  a v a2  s . co m
        sessionFactory = sessionFactoryHolder.get();
        if (sessionFactory == null) {
            try {
                Thread.sleep(10);
            } catch (final InterruptedException e) {
            }
        }
    } while (sessionFactory == null);

    final ProcessSession session = sessionFactory.createSession();
    FlowFile flowFile = null;
    String holdUuid = null;
    String foundSubject = null;
    try {
        final long n = filesReceived.getAndIncrement() % FILES_BEFORE_CHECKING_DESTINATION_SPACE;
        if (n == 0 || !spaceAvailable.get()) {
            if (context.getAvailableRelationships().isEmpty()) {
                spaceAvailable.set(false);
                if (logger.isDebugEnabled()) {
                    logger.debug("Received request from " + request.getRemoteHost()
                            + " but no space available; Indicating Service Unavailable");
                }
                response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                return;
            } else {
                spaceAvailable.set(true);
            }
        }
        response.setHeader("Content-Type", MediaType.TEXT_PLAIN);

        final boolean contentGzipped = Boolean.parseBoolean(request.getHeader(GZIPPED_HEADER));

        final X509Certificate[] certs = (X509Certificate[]) request
                .getAttribute("javax.servlet.request.X509Certificate");
        foundSubject = DEFAULT_FOUND_SUBJECT;
        if (certs != null && certs.length > 0) {
            for (final X509Certificate cert : certs) {
                foundSubject = cert.getSubjectDN().getName();
                if (authorizedPattern.matcher(foundSubject).matches()) {
                    break;
                } else {
                    logger.warn("Rejecting transfer attempt from " + foundSubject
                            + " because the DN is not authorized, host=" + request.getRemoteHost());
                    response.sendError(HttpServletResponse.SC_FORBIDDEN, "not allowed based on dn");
                    return;
                }
            }
        }

        final String destinationVersion = request.getHeader(PROTOCOL_VERSION_HEADER);
        Integer protocolVersion = null;
        if (destinationVersion != null) {
            try {
                protocolVersion = Integer.valueOf(destinationVersion);
            } catch (final NumberFormatException e) {
                // Value was invalid. Treat as if the header were missing.
            }
        }

        final boolean destinationIsLegacyNiFi = (protocolVersion == null);
        final boolean createHold = Boolean.parseBoolean(request.getHeader(FLOWFILE_CONFIRMATION_HEADER));
        final String contentType = request.getContentType();

        final InputStream unthrottled = contentGzipped ? new GZIPInputStream(request.getInputStream())
                : request.getInputStream();

        final InputStream in = (streamThrottler == null) ? unthrottled
                : streamThrottler.newThrottledInputStream(unthrottled);

        if (logger.isDebugEnabled()) {
            logger.debug("Received request from " + request.getRemoteHost() + ", createHold=" + createHold
                    + ", content-type=" + contentType + ", gzip=" + contentGzipped);
        }

        final AtomicBoolean hasMoreData = new AtomicBoolean(false);
        final FlowFileUnpackager unpackager;
        if (APPLICATION_FLOW_FILE_V3.equals(contentType)) {
            unpackager = new FlowFileUnpackagerV3();
        } else if (APPLICATION_FLOW_FILE_V2.equals(contentType)) {
            unpackager = new FlowFileUnpackagerV2();
        } else if (APPLICATION_FLOW_FILE_V1.equals(contentType)) {
            unpackager = new FlowFileUnpackagerV1();
        } else {
            unpackager = null;
        }

        final Set<FlowFile> flowFileSet = new HashSet<>();

        do {
            final long startNanos = System.nanoTime();
            final Map<String, String> attributes = new HashMap<>();
            flowFile = session.create();
            flowFile = session.write(flowFile, new OutputStreamCallback() {
                @Override
                public void process(final OutputStream rawOut) throws IOException {
                    try (final BufferedOutputStream bos = new BufferedOutputStream(rawOut, 65536)) {
                        if (unpackager == null) {
                            IOUtils.copy(in, bos);
                            hasMoreData.set(false);
                        } else {
                            attributes.putAll(unpackager.unpackageFlowFile(in, bos));

                            if (destinationIsLegacyNiFi) {
                                if (attributes.containsKey("nf.file.name")) {
                                    // for backward compatibility with old nifi...
                                    attributes.put(CoreAttributes.FILENAME.key(),
                                            attributes.remove("nf.file.name"));
                                }

                                if (attributes.containsKey("nf.file.path")) {
                                    attributes.put(CoreAttributes.PATH.key(),
                                            attributes.remove("nf.file.path"));
                                }
                            }

                            hasMoreData.set(unpackager.hasMoreData());
                        }
                    }
                }
            });

            final long transferNanos = System.nanoTime() - startNanos;
            final long transferMillis = TimeUnit.MILLISECONDS.convert(transferNanos, TimeUnit.NANOSECONDS);

            // put metadata on flowfile
            final String nameVal = request.getHeader(CoreAttributes.FILENAME.key());
            if (StringUtils.isNotBlank(nameVal)) {
                attributes.put(CoreAttributes.FILENAME.key(), nameVal);
            }

            // put arbitrary headers on flow file
            for (Enumeration<String> headerEnum = request.getHeaderNames(); headerEnum.hasMoreElements();) {
                String headerName = headerEnum.nextElement();
                if (headerPattern != null && headerPattern.matcher(headerName).matches()) {
                    String headerValue = request.getHeader(headerName);
                    attributes.put(headerName, headerValue);
                }
            }

            String sourceSystemFlowFileIdentifier = attributes.get(CoreAttributes.UUID.key());
            if (sourceSystemFlowFileIdentifier != null) {
                sourceSystemFlowFileIdentifier = "urn:nifi:" + sourceSystemFlowFileIdentifier;

                // If we receveied a UUID, we want to give the FlowFile a new UUID and register the sending system's
                // identifier as the SourceSystemFlowFileIdentifier field in the Provenance RECEIVE event
                attributes.put(CoreAttributes.UUID.key(), UUID.randomUUID().toString());
            }

            flowFile = session.putAllAttributes(flowFile, attributes);
            session.getProvenanceReporter().receive(flowFile, request.getRequestURL().toString(),
                    sourceSystemFlowFileIdentifier, "Remote DN=" + foundSubject, transferMillis);
            flowFile = session.putAttribute(flowFile, "restlistener.remote.source.host",
                    request.getRemoteHost());
            flowFile = session.putAttribute(flowFile, "restlistener.remote.user.dn", foundSubject);
            flowFileSet.add(flowFile);

            if (holdUuid == null) {
                holdUuid = flowFile.getAttribute(CoreAttributes.UUID.key());
            }
        } while (hasMoreData.get());

        if (createHold) {
            String uuid = (holdUuid == null) ? UUID.randomUUID().toString() : holdUuid;

            if (flowFileMap.containsKey(uuid)) {
                uuid = UUID.randomUUID().toString();
            }

            final FlowFileEntryTimeWrapper wrapper = new FlowFileEntryTimeWrapper(session, flowFileSet,
                    System.currentTimeMillis());
            FlowFileEntryTimeWrapper previousWrapper;
            do {
                previousWrapper = flowFileMap.putIfAbsent(uuid, wrapper);
                if (previousWrapper != null) {
                    uuid = UUID.randomUUID().toString();
                }
            } while (previousWrapper != null);

            response.setStatus(HttpServletResponse.SC_SEE_OTHER);
            final String ackUri = "/" + basePath + "/holds/" + uuid;
            response.addHeader(LOCATION_HEADER_NAME, ackUri);
            response.addHeader(LOCATION_URI_INTENT_NAME, LOCATION_URI_INTENT_VALUE);
            response.getOutputStream().write(ackUri.getBytes("UTF-8"));
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "Ingested {} from Remote Host: [{}] Port [{}] SubjectDN [{}]; placed hold on these {} files with ID {}",
                        new Object[] { flowFileSet, request.getRemoteHost(), request.getRemotePort(),
                                foundSubject, flowFileSet.size(), uuid });
            }
        } else {
            response.setStatus(HttpServletResponse.SC_OK);
            logger.info(
                    "Received from Remote Host: [{}] Port [{}] SubjectDN [{}]; transferring to 'success' {}",
                    new Object[] { request.getRemoteHost(), request.getRemotePort(), foundSubject, flowFile });

            session.transfer(flowFileSet, ListenHTTP.RELATIONSHIP_SUCCESS);
            session.commit();
        }
    } catch (final Throwable t) {
        session.rollback();
        if (flowFile == null) {
            logger.error("Unable to receive file from Remote Host: [{}] SubjectDN [{}] due to {}",
                    new Object[] { request.getRemoteHost(), foundSubject, t });
        } else {
            logger.error("Unable to receive file {} from Remote Host: [{}] SubjectDN [{}] due to {}",
                    new Object[] { flowFile, request.getRemoteHost(), foundSubject, t });
        }
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, t.toString());
    }
}

From source file:com.epam.wilma.test.server.ExampleHandler.java

private void generateErrorCode(final String path, final HttpServletResponse httpServletResponse)
        throws ServletException, IOException {
    if (PATH_TO_TIMEOUT.equals(path)) {
        try {//  w  w w. java 2  s  .co m
            Thread.sleep(WAIT_IN_MILLIS);
        } catch (Exception e) {
            throw new ServletException("Thread's wait failed....", e);
        }
    } else if (PATH_INTERNAL_SERVER_ERROR.equals(path)) {
        httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } else if (PATH_SERVICE_UNAVAILABLE.equals(path)) {
        httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    } else if (PATH_BAD_GATWAY.equals(path)) {
        httpServletResponse.sendError(HttpServletResponse.SC_BAD_GATEWAY);
    } else if (PATH_NOT_IMPLEMENTED.equals(path)) {
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
    }

}

From source file:ar.com.zauber.commons.web.proxy.HttpClientRequestProxy.java

/**
 * Mtodo que se puede overridear en el caso de necesitar otro comportamiento al
 * producirse un error de conexin./* w  w  w.ja  v  a2s.c  o  m*/
 * 
 * @param request
 * @param response
 * @param method
 * @param e
 * @throws Exception .
 */
protected void onConnectionException(final HttpServletRequest request, final HttpServletResponse response,
        final HttpMethod method, final ConnectException e) throws Exception {
    response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, e.getMessage());
}

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

public void updateUserStatus(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");
    String userStatus = request.getParameter("t");
    String statusId = request.getParameter("d");

    log.debug("userStatus: " + userStatus);
    log.debug("statusId: " + statusId);

    Twitter twitter = twitterLogic.getTwitterAuthForUser(userToken, userSecret);
    if (twitter == null) {
        // no connection
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return;/*w w  w .ja v a2s  .co  m*/
    }

    try {
        Status status = null;

        // update user status
        if (StringUtils.isNotBlank(statusId)) {
            status = twitter.updateStatus(userStatus, Long.parseLong(statusId));
        } else {
            status = twitter.updateStatus(userStatus);
        }
        if (status == null) {
            log.error("Status is null.");
            // general error
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }

        JSONObject json = new JSONObject();
        JSONObject statusJSON = getStatusJSON(twitter, status);

        User currentUser = twitter.showUser(twitter.getId());
        Status lastUserStatus = currentUser.getStatus();

        // return as an array even though only it contains only one element, 
        // so we can reuse the same Trimpath template (Denny)
        JSONArray statusList = new JSONArray();
        statusList.add(statusJSON);
        json.put("statusList", statusList);
        lastRefreshed = Calendar.getInstance().getTime().toString();

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

        if (lastUserStatus == null) {
            json.element("lastStatusUpdate", "unable to retrieve last status");
        } else {
            Date lastStatusUpdate = lastUserStatus.getCreatedAt();
            json.element("lastStatusUpdate", lastStatusUpdate.toString());

        }

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

        out.print(json.toString());

    } 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);
        }
    }
}