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.platform.web.servlet.GetResource.java

@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    // TODO perform any authorization here...
    // TODO support caching
    PentahoSystem.systemEntryPoint();/*w w  w  .j  av  a2 s . c om*/
    try {
        IPentahoSession session = getPentahoSession(request);
        String resource = request.getParameter("resource"); //$NON-NLS-1$

        if ((resource == null) || StringUtil.doesPathContainParentPathSegment(resource)) {
            error(Messages.getInstance().getErrorString("GetResource.ERROR_0001_RESOURCE_PARAMETER_MISSING")); //$NON-NLS-1$
            response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            return;
        }
        String resLower = resource.toLowerCase();

        String resourcePath;
        if (resLower.endsWith(".xsl")) { //$NON-NLS-1$
            resourcePath = "system/custom/xsl/" + resource; //$NON-NLS-1$
        } else if (resLower.endsWith(".mondrian.xml")) { //$NON-NLS-1$
            resourcePath = resource;
        } else if (resLower.endsWith(".jpg") || resLower.endsWith(".jpeg") || resLower.endsWith(".gif")
                || resLower.endsWith(".png") || resLower.endsWith(".bmp")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
            resourcePath = resource;
        } else if (resLower.endsWith(".jar")) { //$NON-NLS-1$
            resourcePath = resource;
        } else {
            error(Messages.getInstance().getErrorString("GetResource.ERROR_0002_INVALID_FILE", resource)); //$NON-NLS-1$
            response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            return;
        }

        IActionSequenceResource asqr = new ActionSequenceResource("", //$NON-NLS-1$
                IActionSequenceResource.SOLUTION_FILE_RESOURCE, "", //$NON-NLS-1$
                resourcePath);
        InputStream in = asqr.getInputStream(RepositoryFilePermission.READ, LocaleHelper.getLocale());
        if (in == null) {
            error(Messages.getInstance().getErrorString("GetResource.ERROR_0003_RESOURCE_MISSING", //$NON-NLS-1$
                    resourcePath));
            response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            return;
        }
        String mimeType = getServletContext().getMimeType(resourcePath);
        String resourceName = resourcePath;
        if (resourcePath.indexOf("/") != -1) { //$NON-NLS-1$
            resourceName = resourcePath.substring(resourcePath.lastIndexOf("/") + 1); //$NON-NLS-1$
        }
        response.setHeader("content-disposition", "attachment;filename=" + resourceName); //$NON-NLS-1$ //$NON-NLS-2$
        if ((null == mimeType) || (mimeType.length() <= 0)) {
            // Hard coded to PNG because BIRT does not give us a mime type at
            // all...
            response.setContentType("image/png"); //$NON-NLS-1$
        } else {
            response.setContentType(mimeType);
        }
        response.setCharacterEncoding(LocaleHelper.getSystemEncoding());
        response.setHeader("expires", "0"); //$NON-NLS-1$ //$NON-NLS-2$
        // Open the input and output streams
        OutputStream out = response.getOutputStream();
        try {
            // Copy the contents of the file to the output stream
            byte[] buf = new byte[1024];
            int count = 0;
            int totalBytes = 0;
            while ((count = in.read(buf)) >= 0) {
                out.write(buf, 0, count);
                totalBytes += count;
            }
            response.setContentLength(totalBytes);
        } finally {
            in.close();
            out.close();
        }
    } finally {
        PentahoSystem.systemExitPoint();
    }
}

From source file:org.wso2.carbon.tryit.TryitRequestProcessor.java

public void process(CarbonHttpRequest request, CarbonHttpResponse response,
        ConfigurationContext configurationContext) throws Exception {
    OutputStream outputStream = response.getOutputStream();
    String requestURL = request.getRequestURL() + "?" + request.getQueryString();
    String serviceParameter = request.getParameter(WSDL2FormGenerator.SERVICE_QUERY_PARAM);
    String endpointParameter = request.getParameter(WSDL2FormGenerator.ENDPOINT_QUERY_PARAM);
    String operationParameter = request.getParameter(WSDL2FormGenerator.OPERATION_PARAM);

    response.addHeader(HTTP.CONTENT_TYPE, "text/html; charset=utf-8");

    try {//ww w. j  a  va  2s  . co m
        Result result = new StreamResult(outputStream);
        String str = WSDL2FormGenerator.getInstance().getInternalTryit(result, configurationContext, requestURL,
                serviceParameter, operationParameter, endpointParameter, true);
        if (!str.equals(WSDL2FormGenerator.SUCCESS)) {
            response.setRedirect(str);
        }
    } catch (CarbonException e) {
        log.error(e);
        if (e.getMessage().equals(WSDL2FormGenerator.SERVICE_INACTIVE)) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            outputStream.write(("<h4>Requested Service is inactive. Cannot generate stubs.</h4>").getBytes());
            outputStream.flush();
        } else if (e.getMessage().equals(WSDL2FormGenerator.SERVICE_NOT_FOUND)) {
            response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            outputStream.write(("<h4>Service cannot be found. Cannot display <em>Stub</em>.</h4>").getBytes());
            outputStream.flush();
        } else {
            response.setError(HttpServletResponse.SC_NOT_FOUND);
            outputStream.write(("<h4>" + e.getMessage() + "</h4>").getBytes());
            outputStream.flush();
        }
    }
}

From source file:org.nuxeo.ecm.core.management.statuses.StatusServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    StringBuilder response = new StringBuilder();
    String requestedInfo = req.getParameter(PARAM);
    if (requestedInfo.equals(PARAM_STARTED)) {
        getStartedInfo(response);/* w ww. j a va 2 s  .c om*/
    } else if (requestedInfo.equals(PARAM_SUMMARY)) {
        String givenKey = req.getParameter(PARAM_SUMMARY_KEY);
        if (getRuntimeService().getProperty(PARAM_STATUS_KEY).equals(givenKey)) {
            getSummaryInfo(response);
        } else {
            resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
        }
    } else if (requestedInfo.equals(PARAM_RELOAD)) {
        if (isStarted()) {
            response.append("reload();");
        } else {
            resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        }
    }
    sendResponse(resp, response.toString());
}

From source file:com.cloudera.oryx.als.serving.web.EstimateForAnonymousServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    CharSequence pathInfo = request.getPathInfo();
    if (pathInfo == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No path");
        return;//from w w w . j av  a 2 s.  c o m
    }
    Iterator<String> pathComponents = SLASH.split(pathInfo).iterator();
    String toItemID;
    Pair<String[], float[]> itemIDsAndValue;
    try {
        toItemID = pathComponents.next();
        itemIDsAndValue = RecommendToAnonymousServlet.parseItemValuePairs(pathComponents);
    } catch (NoSuchElementException nsee) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, nsee.toString());
        return;
    }

    if (itemIDsAndValue.getFirst().length == 0) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No items");
        return;
    }

    String[] itemIDs = itemIDsAndValue.getFirst();
    unescapeSlashHack(itemIDs);
    float[] values = itemIDsAndValue.getSecond();

    OryxRecommender recommender = getRecommender();
    try {
        float estimate = recommender.estimateForAnonymous(toItemID, itemIDs, values);
        Writer out = response.getWriter();
        out.write(Float.toString(estimate));
        out.write('\n');
    } catch (NotReadyException nre) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, nre.toString());
    } catch (NoSuchItemException nsie) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, nsie.toString());
    }
}

From source file:org.wso2.carbon.wsdl2form.StubRequestProcessor.java

public void process(CarbonHttpRequest request, CarbonHttpResponse response,
        ConfigurationContext configurationContext) throws Exception {

    OutputStream outputStream = response.getOutputStream();
    String requestURL = request.getRequestURL() + "?" + request.getQueryString();
    String serviceParameter = request.getParameter(WSDL2FormGenerator.SERVICE_QUERY_PARAM);
    String endpointParameter = request.getParameter(WSDL2FormGenerator.ENDPOINT_QUERY_PARAM);
    String languageParameter = request.getParameter(WSDL2FormGenerator.LANGUAGE_QUERY_PARAM);
    String localhostParameter = request.getParameter(WSDL2FormGenerator.LOCALHOST_QUERY_PARAM);
    String contentTypeParameter = request.getParameter(WSDL2FormGenerator.CONTENT_TYPE_QUERY_PARAM);

    try {//  w w w . j  a  v a  2  s .co m
        Result result = new StreamResult(outputStream);
        String contentType = WSDL2FormGenerator.getInstance().getJSStub(result, configurationContext,
                requestURL, serviceParameter, endpointParameter, languageParameter, localhostParameter,
                contentTypeParameter);
        response.addHeader(HTTP.CONTENT_TYPE, contentType);
    } catch (CarbonException e) {
        log.error("Cannot generate stub", e);
        response.addHeader(HTTP.CONTENT_TYPE, "text/html; charset=utf-8");
        if (e.getMessage().equals(WSDL2FormGenerator.SERVICE_INACTIVE)) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            outputStream.write(("<h4>Requested Service is inactive. Cannot generate stubs.</h4>").getBytes());
            outputStream.flush();
            return;
        } else if (e.getMessage().equals(WSDL2FormGenerator.SERVICE_NOT_FOUND)) {
            response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            outputStream.write(("<h4>Service cannot be found. Cannot display <em>Stub</em>.</h4>").getBytes());
            outputStream.flush();
            return;
        } else if (e.getMessage().equals(WSDL2FormGenerator.UNSUPPORTED_LANG)) {
            response.setError(HttpServletResponse.SC_NOT_FOUND);
            outputStream.write(("<h4>Unsupported lang parameter " + languageParameter + "</h4>").getBytes());
            outputStream.flush();
            return;
        } else {
            response.setError(HttpServletResponse.SC_NOT_FOUND);
            response.addHeader(HTTP.CONTENT_TYPE, "text/html; charset=utf-8");
            outputStream.write(("<h4>" + e.getMessage() + "</h4>").getBytes());
            outputStream.flush();
            return;
        }
    }
}

From source file:nl.strohalm.cyclos.http.RestFilter.java

@Override
protected void execute(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain chain) throws IOException, ServletException {
    // If Rest is disabled by configuration, always send a 404 error
    if (restDisabled) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;// w w  w .  j  av a 2  s .com
    }

    // Check if the application is online
    if (!applicationService.isOnline()) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return;
    }

    // Add no cache control
    response.setHeader("Cache-control", "no-cache, no-store, must-revalidate");

    // Check non-secure access when HTTP is enabled
    if (Boolean.TRUE.equals(getServletContext().getAttribute("cyclos.httpEnabled"))) {
        if (!"https".equalsIgnoreCase(request.getProtocol())) {
            response.sendError(HttpStatus.UPGRADE_REQUIRED.value(),
                    HttpStatus.UPGRADE_REQUIRED.getReasonPhrase());
            response.addHeader("Upgrade", "TLS/1.0, HTTP/1.1");
            response.addHeader("Connection", "Upgrade");
            return;
        }
    }

    // When logging REST parameters, we need to wrap the request with StringBodyRequest in order to have the body available
    final boolean logParameters = loggingHandler.isRestParametersLogEnabled();
    super.execute(logParameters ? new StringBodyRequest(request) : request, response, chain);
}

From source file:net.myrrix.web.servlets.EstimateForAnonymousServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    CharSequence pathInfo = request.getPathInfo();
    if (pathInfo == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No path");
        return;/*w w  w  .  ja  va  2 s . c o  m*/
    }
    Iterator<String> pathComponents = SLASH.split(pathInfo).iterator();
    long toItemID;
    Pair<long[], float[]> itemIDsAndValue;
    try {
        toItemID = Long.parseLong(pathComponents.next());
        itemIDsAndValue = RecommendToAnonymousServlet.parseItemValuePairs(pathComponents);
    } catch (NoSuchElementException nsee) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, nsee.toString());
        return;
    } catch (NumberFormatException nfe) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, nfe.toString());
        return;
    }

    if (itemIDsAndValue.getFirst().length == 0) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No items");
        return;
    }

    long[] itemIDs = itemIDsAndValue.getFirst();
    float[] values = itemIDsAndValue.getSecond();

    MyrrixRecommender recommender = getRecommender();
    try {
        float estimate = recommender.estimateForAnonymous(toItemID, itemIDs, values);
        Writer out = response.getWriter();
        out.write(Float.toString(estimate));
        out.write('\n');
    } catch (NotReadyException nre) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, nre.toString());
    } catch (NoSuchItemException nsie) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, nsie.toString());
    } catch (TasteException te) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, te.toString());
        getServletContext().log("Unexpected error in " + getClass().getSimpleName(), te);
    }
}

From source file:info.magnolia.cms.security.SecurityFilter.java

/**
 * Checks access from Listener / Authenticator / AccessLock.
 * @param req HttpServletRequest as received by the service method
 * @param res HttpServletResponse as received by the service method
 * @return boolean <code>true</code> if access to the resource is allowed
 * @throws IOException can be thrown when the servlet is unable to write to the response stream
 *//*from   w w  w  . ja v a2  s .  co m*/
protected boolean isAllowed(HttpServletRequest req, HttpServletResponse res) throws IOException {
    if (Lock.isSystemLocked()) {
        res.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return false;
    } else if (Authenticator.isAuthenticated(req)) {
        return true;
    } else if (SecureURI.isUnsecure(Path.getURI(req)))
        return true;
    else if (SecureURI.isProtected(Path.getURI(req))) {
        return authenticate(req, res);
    } else if (!Listener.isAllowed(req)) {
        res.sendError(HttpServletResponse.SC_FORBIDDEN);
        return false;
    }
    return true;
}

From source file:cn.leancloud.diamond.server.controller.ConfigController.java

public String getProbeModifyResult(HttpServletRequest request, HttpServletResponse response,
        String probeModify) {/*from www. ja  va  2  s  .com*/
    response.setHeader("Content-Type", "text/html;charset=UTF-8");
    final String address = getRemortIP(request);
    if (address == null) {
        // ?400
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return "400";
    }

    if (GlobalCounter.getCounter().decrementAndGet() >= 0) {
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return "503";
    }

    final List<ConfigKey> configKeyList = getConfigKeyList(probeModify);

    StringBuilder resultBuilder = new StringBuilder();
    for (ConfigKey key : configKeyList) {
        String md5 = this.configService.getContentMD5(key.getDataId(), key.getGroup());
        if (!StringUtils.equals(md5, key.getMd5())) {
            resultBuilder.append(key.getDataId()).append(Constants.WORD_SEPARATOR).append(key.getGroup())
                    .append(Constants.LINE_SEPARATOR);
        }
    }

    String returnHeader = resultBuilder.toString();
    try {
        returnHeader = URLEncoder.encode(resultBuilder.toString(), "UTF-8");
    } catch (Exception e) {
        // ignore
    }

    request.setAttribute("content", returnHeader);
    // ?
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setHeader("Cache-Control", "no-cache,no-store");
    return "200";
}

From source file:com.taobao.diamond.server.controller.ConfigController.java

public String getProbeModifyResult(HttpServletRequest request, HttpServletResponse response,
        String probeModify) {/*  www.j a v  a 2 s  . c o  m*/
    response.setHeader("Content-Type", "text/html;charset=GBK");
    final String address = getRemortIP(request);
    if (address == null) {
        // 400
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return "400";
    }

    if (GlobalCounter.getCounter().decrementAndGet() >= 0) {
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return "503";
    }

    final List<ConfigKey> configKeyList = getConfigKeyList(probeModify);

    StringBuilder resultBuilder = new StringBuilder();
    for (ConfigKey key : configKeyList) {
        String md5 = this.configService.getContentMD5(key.getDataId(), key.getGroup());
        if (!StringUtils.equals(md5, key.getMd5())) {
            resultBuilder.append(key.getDataId()).append(WORD_SEPARATOR).append(key.getGroup())
                    .append(LINE_SEPARATOR);
        }
    }

    String returnHeader = resultBuilder.toString();
    try {
        returnHeader = URLEncoder.encode(resultBuilder.toString(), "UTF-8");
    } catch (Exception e) {
        // ignore
    }

    request.setAttribute("content", returnHeader);
    // 
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setHeader("Cache-Control", "no-cache,no-store");
    return "200";
}