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.pentaho.test.platform.web.GetImageIT.java

@Test
public void testParameterEmpty() throws ServletException, IOException {
    when(request.getParameter(RESOURCE_PARAM)).thenReturn(null);

    servlet.service(request, response);/*www .  j a v  a2 s. c o  m*/

    verify(response).setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    verify(servlet).error(matches(".*ERROR_0001.*"));
}

From source file:org.wso2.carbon.identity.sso.cas.saml.request.CASSAMLIdentityRequestFactory.java

@Override
public HttpIdentityResponse.HttpIdentityResponseBuilder handleException(FrameworkClientException exception,
        HttpServletRequest request, HttpServletResponse response) {
    String errorResponse;/*from  ww  w. jav a 2  s .co  m*/
    HttpIdentityResponse.HttpIdentityResponseBuilder builder = new HttpIdentityResponse.HttpIdentityResponseBuilder();
    if (((CAS2ClientException) exception).getAcsUrl() != null) {
        try {
            Map<String, String[]> queryParams = new HashMap();
            String genericErrorPage = IdentityUtil.getServerURL(CASSSOConstants.NOTIFICATION_ENDPOINT, false,
                    false);
            queryParams.put(CASSSOConstants.STATUS,
                    new String[] { URLEncoder.encode(((CAS2ClientException) exception).getExceptionStatus(),
                            StandardCharsets.UTF_8.name()) });
            queryParams.put(CASSSOConstants.STATUS_MSG,
                    new String[] { URLEncoder.encode(((CAS2ClientException) exception).getExceptionMessage(),
                            StandardCharsets.UTF_8.name()) });
            builder.setParameters(queryParams);
            builder.setRedirectURL(genericErrorPage);
            builder.setStatusCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        } catch (UnsupportedEncodingException e) {
            if (log.isDebugEnabled()) {
                log.debug("Error while encoding query parameters.", e);
            }
        }
    } else {
        String redirectURL = request.getParameter(CASSSOConstants.SERVICE_PROVIDER_ARGUMENT);
        if (((CAS2ClientException) exception).getServiceTicketId() != null) {
            errorResponse = CASSSOUtil.buildFailureResponse(CASErrorConstants.INVALID_TICKET_CODE,
                    String.format(
                            CASResourceReader.getInstance().getLocalizedString(
                                    CASErrorConstants.INVALID_TICKET_MESSAGE, request.getLocale()),
                            ((CAS2ClientException) exception).getServiceTicketId()));
        } else {
            errorResponse = CASSSOUtil.buildFailureResponse(CASErrorConstants.INVALID_REQUEST_CODE,
                    CASResourceReader.getInstance().getLocalizedString(
                            CASErrorConstants.INVALID_REQUEST_MESSAGE, request.getLocale()));
        }
        builder.setBody(errorResponse);
        builder.setRedirectURL(redirectURL);
        builder.setStatusCode(HttpServletResponse.SC_BAD_REQUEST);
    }
    return builder;
}

From source file:uk.ac.cam.caret.sakai.rwiki.tool.RWikiServlet.java

public void execute(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (wac == null) {
        wac = WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
        if (wac == null) {
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Cannot get WebApplicationContext");
            return;
        }// w  w  w.ja v a 2s  . c o  m
    }
    log.debug("========================Page Start==========");
    request.setAttribute(Tool.NATIVE_URL, Tool.NATIVE_URL);

    String targetURL = persistState(request);

    String action = request.getParameter("action");
    if (!StringUtils.isEmpty(targetURL) && !StringUtils.equals(action, "search")
            && !StringUtils.equals(action, "full_search")) {
        response.sendRedirect(targetURL);
        return;
    }

    // Must be done on every request
    prePopulateRealm(request);

    addWikiStylesheet(request);

    request.setAttribute("footerScript", footerScript);
    if (headerScriptSource != null && headerScriptSource.length() > 0) {
        request.setAttribute("headerScriptSource", headerScriptSource);
    }

    RequestHelper helper = (RequestHelper) wac.getBean(RequestHelper.class.getName());

    HttpCommand command = helper.getCommandForRequest(request);

    // fix for IE6's poor cache capabilities
    String userAgent = request.getHeader("User-Agent");
    if (userAgent != null && userAgent.indexOf("MSIE 6") >= 0) {
        response.addHeader("Expires", "0");
        response.addHeader("Pragma", "cache");
        response.addHeader("Cache-Control", "private");
    }

    command.execute(dispatcher, request, response);

    request.removeAttribute(Tool.NATIVE_URL);
    log.debug("=====================Page End=============");
}

From source file:com.binarybirchtree.filters.IpFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
    // Do not block localhost.
    if (request.getRemoteAddr().equals("127.0.0.1")) {
        filterChain.doFilter(request, response);
        return;/*from www . j  av  a  2s. c  o  m*/
    }

    boolean allowed = true;

    // Refuse connections that circumvented Cloudflare.
    // Checking the latest IP from the X-Forwarded-For header on Heroku, since request.getRemoteAddr() seems to return an IP in Heroku's internal network.
    if (!ipIsInList(request.getRemoteAddr(), internalIps) || (getForwardedIp(request, 1) != null
            && !ipIsInList(getForwardedIp(request, 1), bypassCloudflareIps)
            && !ipIsInList(getForwardedIp(request, 1), cloudflareIps)))
        allowed = false;

    if (allowed) {
        // Check if the IP before Cloudflare is blacklisted.
        String proxiedIp = getForwardedIp(request, 2);

        if (proxiedIp != null) {
            for (String ip : blacklistIps) {
                SubnetUtils subnet = new SubnetUtils(ip);
                subnet.setInclusiveHostCount(true);
                if (!subnet.getInfo().isInRange(proxiedIp)) {
                    allowed = false;
                    break;
                }
            }
        }
    }

    // If the request failed one of the tests, send an error response and do not continue processing the request.
    if (!allowed) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return;
    }

    // If the request passed the tests, allow it to be processed normally.
    filterChain.doFilter(request, response);
}

From source file:com.servoy.extensions.plugins.rest_ws.RestWSPlugin.java

public Map<String, String> getRequiredPropertyNames() {
    Map<String, String> req = new HashMap<String, String>();
    req.put(CLIENT_POOL_SIZE_PROPERTY,//from w  w w .j a va2 s .c  o  m
            "Max number of clients used (this defines the number of concurrent requests and licences used), default = "
                    + CLIENT_POOL_SIZE_DEFAULT
                    + ", when running in developer this setting is ignored, pool size will always be 1");
    req.put(CLIENT_POOL_EXCHAUSTED_ACTION_PROPERTY, "The following values are supported for this property:\n" +
    //
            ACTION_BLOCK
            + " (default): requests will wait untill a client becomes available, when running in developer this value will be used\n"
            +
            //
            ACTION_FAIL + ": the request will fail. The API will generate a SERVICE_UNAVAILABLE response (HTTP "
            + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ")\n" +
            //
            ACTION_GROW
            + ": allows the pool to temporarily grow, by starting additional clients. These will be automatically removed when not required anymore.");
    req.put(AUTHORIZED_GROUPS_PROPERTY,
            "Only authenticated users in the listed groups (comma-separated) have access, when left empty unauthorised access is allowed");

    // RELOAD_SOLUTION_AFTER_REQUEST_PROPERTY is discouraged so we do not show it in the admin page plugin properties

    return req;
}

From source file:org.wso2.carbon.identity.sso.cas.request.CASIdentityRequestFactory.java

@Override
public HttpIdentityResponse.HttpIdentityResponseBuilder handleException(FrameworkClientException exception,
        HttpServletRequest request, HttpServletResponse response) {
    String errorResponse;// www  . j  a va2  s. co m
    HttpIdentityResponse.HttpIdentityResponseBuilder builder = new HttpIdentityResponse.HttpIdentityResponseBuilder();
    if (((CAS2ClientException) exception).getAcsUrl() != null) {
        try {
            Map<String, String[]> queryParams = new HashMap();
            String genericErrorPage = IdentityUtil
                    .getServerURL(CASConstants.CASSSOConstants.NOTIFICATION_ENDPOINT, false, false);
            queryParams.put(CASConstants.CASSSOConstants.STATUS,
                    new String[] { URLEncoder.encode(((CAS2ClientException) exception).getExceptionStatus(),
                            StandardCharsets.UTF_8.name()) });
            queryParams.put(CASConstants.CASSSOConstants.STATUS_MSG,
                    new String[] { URLEncoder.encode(((CAS2ClientException) exception).getExceptionMessage(),
                            StandardCharsets.UTF_8.name()) });
            builder.setParameters(queryParams);
            builder.setRedirectURL(genericErrorPage);
            builder.setStatusCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        } catch (UnsupportedEncodingException e) {
            if (log.isDebugEnabled()) {
                log.debug("Error while encoding query parameters.", e);
            }
        }
    } else {
        String redirectURL = request.getParameter(CASConstants.CASSSOConstants.SERVICE_PROVIDER_ARGUMENT);
        if (((CAS2ClientException) exception).getServiceTicketId() != null) {
            errorResponse = CASSSOUtil.buildFailureResponse(CASConstants.CASErrorConstants.INVALID_TICKET_CODE,
                    String.format(
                            CASResourceReader.getInstance().getLocalizedString(
                                    CASConstants.CASErrorConstants.INVALID_TICKET_MESSAGE, request.getLocale()),
                            ((CAS2ClientException) exception).getServiceTicketId()));
        } else {
            errorResponse = CASSSOUtil.buildFailureResponse(CASConstants.CASErrorConstants.INVALID_REQUEST_CODE,
                    CASResourceReader.getInstance().getLocalizedString(
                            CASConstants.CASErrorConstants.INVALID_REQUEST_MESSAGE, request.getLocale()));
        }
        builder.setBody(errorResponse);
        builder.setRedirectURL(redirectURL);
        builder.setStatusCode(HttpServletResponse.SC_BAD_REQUEST);
    }
    return builder;
}

From source file:org.opencastproject.inspection.impl.endpoints.MediaInspectionRestEndpoint.java

@GET
@Produces(MediaType.TEXT_XML)/*from   w ww .  j ava  2 s  . com*/
@Path("inspect")
@RestQuery(name = "inspect", description = "Analyze a given media file, returning a receipt to check on the status and outcome of the job", restParameters = {
        @RestParameter(description = "Location of the media file.", isRequired = false, name = "uri", type = RestParameter.Type.STRING) }, reponses = {
                @RestResponse(description = "XML encoded receipt is returned.", responseCode = HttpServletResponse.SC_NO_CONTENT),
                @RestResponse(description = "Service unavailabe or not currently present", responseCode = HttpServletResponse.SC_SERVICE_UNAVAILABLE),
                @RestResponse(description = "Problem retrieving media file or invalid media file or URL.", responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) }, returnDescription = "")
public Response inspectTrack(@QueryParam("uri") URI uri) {
    checkNotNull(service);
    try {
        Job job = service.inspect(uri);
        return Response.ok(new JaxbJob(job)).build();
    } catch (Exception e) {
        logger.info(e.getMessage());
        return Response.serverError().build();
    }
}

From source file:nl.ctrlaltdev.harbinger.filter.HttpEvidenceFilterTest.java

@Test
public void shouldRejectBadParameters() throws IOException, ServletException {
    request.setRemoteAddr("8.8.8.8");
    request.addParameter("name", new String[] { "' or '1'='1" });

    filter.doFilter(request, response, chain);

    assertEquals(5, collector.findByIp(new Evidence(request)).getDetections());
    // The request is aborted, so there isn't a complete request.
    assertEquals(0, collector.findByIp(new Evidence(request)).getNumberOfRequests());
    assertEquals(0, collector.findByIp(new Evidence(request)).getExceptions());

    assertEquals(HttpServletResponse.SC_SERVICE_UNAVAILABLE, response.getStatus());
}

From source file:nl.armatiek.xslweb.web.servlet.XSLWebServlet.java

@SuppressWarnings("unchecked")
@Override//  w w w  .  java  2s .  c  o  m
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    OutputStream respOs = resp.getOutputStream();
    WebApp webApp = null;
    try {
        webApp = (WebApp) req.getAttribute(Definitions.ATTRNAME_WEBAPP);
        if (webApp.isClosed()) {
            resp.resetBuffer();
            resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            resp.setContentType("text/html; charset=UTF-8");
            Writer w = new OutputStreamWriter(respOs, "UTF-8");
            w.write("<html><body><h1>Service temporarily unavailable</h1></body></html>");
            return;
        }
        executeRequest(webApp, req, resp, respOs);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        if (webApp != null && webApp.getDevelopmentMode()) {
            resp.setContentType("text/plain; charset=UTF-8");
            e.printStackTrace(new PrintStream(respOs));
        } else if (!resp.isCommitted()) {
            resp.resetBuffer();
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            resp.setContentType("text/html; charset=UTF-8");
            Writer w = new OutputStreamWriter(respOs, "UTF-8");
            w.write("<html><body><h1>Internal Server Error</h1></body></html>");
        }
    } finally {
        // Delete any registered temporary files:
        try {
            List<File> tempFiles = (List<File>) req.getAttribute(Definitions.ATTRNAME_TEMPFILES);
            if (tempFiles != null) {
                ListIterator<File> li = tempFiles.listIterator();
                while (li.hasNext()) {
                    File file;
                    if ((file = li.next()) != null) {
                        FileUtils.deleteQuietly(file);
                    }
                }
            }
        } catch (Exception se) {
            logger.error("Error deleting registered temporary files", se);
        }

        // Close any closeables:
        try {
            List<Closeable> closeables = (List<Closeable>) req.getAttribute("xslweb-closeables");
            if (closeables != null) {
                ListIterator<Closeable> li = closeables.listIterator(closeables.size());
                while (li.hasPrevious()) {
                    li.previous().close();
                }
            }
        } catch (Exception se) {
            logger.error("Could not close Closeable", se);
        }
    }
}

From source file:org.pentaho.test.platform.web.GetResourceIT.java

@Test
public void testNotSupportedExt() throws ServletException, IOException {
    when(request.getParameter(RESOURCE_PARAM)).thenReturn("not_supported.nsp");

    servlet.service(request, response);/*  www  .ja  v a  2s.c  om*/

    verify(response).setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    verify(servlet).error(matches(".*ERROR_0002.*"));
}