Example usage for javax.servlet.http HttpServletResponse SC_BAD_GATEWAY

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

Introduction

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

Prototype

int SC_BAD_GATEWAY

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

Click Source Link

Document

Status code (502) indicating that the HTTP server received an invalid response from a server it consulted when acting as a proxy or gateway.

Usage

From source file:opendap.threddsHandler.StaticCatalogDispatch.java

private void browseRemoteCatalog(Request oRequest, HttpServletResponse response, String query)
        throws IOException, SaxonApiException {

    String http = "http://";

    // Sanitize the incoming query.
    query = query.substring("browseCatalog=".length(), query.length());
    String remoteCatalog = Scrub.completeURL(query);

    if (!remoteCatalog.startsWith(http)) {
        log.error("Catalog Must be remote: " + Scrub.completeURL(remoteCatalog));
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Catalog Must be remote: " + remoteCatalog);
        return;//from  www  .  j a va 2  s . co m
    }

    // Build URL for remote system:

    String remoteHost = remoteCatalog.substring(0, remoteCatalog.indexOf('/', http.length()) + 1);
    String remoteRelativeURL = remoteCatalog.substring(0, remoteCatalog.lastIndexOf('/') + 1);

    log.debug("Remote Catalog: " + remoteCatalog);
    log.debug("Remote Catalog Host: " + remoteHost);
    log.debug("Remote Catalog RelativeURL: " + remoteRelativeURL);

    // Go get the target catalog:
    HttpClient httpClient = new HttpClient();
    GetMethod request = new GetMethod(remoteCatalog);
    int statusCode = httpClient.executeMethod(request);

    if (statusCode != HttpStatus.SC_OK) {
        log.error("Can't find catalog: " + remoteCatalog);
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "Can't find catalog: " + remoteCatalog);
        return;
    }
    InputStream catDocIs = null;

    try {
        catDocIs = request.getResponseBodyAsStream();
        catalogToHtmlTransformLock.lock();
        catalogToHtmlTransform.reloadTransformIfRequired();

        // Build the catalog document as an XdmNode.
        XdmNode catDoc = catalogToHtmlTransform.build(new StreamSource(catDocIs));

        catalogToHtmlTransform.setParameter("dapService", oRequest.getDapServiceLocalID());
        catalogToHtmlTransform.setParameter("docsService", oRequest.getDocsServiceLocalID());

        catalogToHtmlTransform.setParameter("remoteHost", remoteHost);
        catalogToHtmlTransform.setParameter("remoteRelativeURL", remoteRelativeURL);
        catalogToHtmlTransform.setParameter("remoteCatalog", remoteCatalog);

        // Set up the Http headers.
        response.setContentType("text/html");
        response.setHeader("Content-Description", "thredds_catalog");
        response.setStatus(HttpServletResponse.SC_OK);

        // Send the transformed documet.
        catalogToHtmlTransform.transform(catDoc, response.getOutputStream());

        log.debug("Used saxon to send THREDDS catalog (XML->XSLT(saxon)->HTML).");

    } catch (SaxonApiException sapie) {
        if (response.isCommitted()) {
            return;
        }
        // Set up the Http headers.
        response.setContentType("text/html");
        response.setHeader("Content-Description", "ERROR");
        response.setStatus(HttpServletResponse.SC_BAD_GATEWAY);

        // Responed with error.
        response.sendError(HttpServletResponse.SC_BAD_GATEWAY,
                "Remote resource does not appear to reference a THREDDS Catalog.");
    } finally {
        // Clean up the transform before releasing it.
        catalogToHtmlTransform.clearAllParameters();

        if (catDocIs != null) {
            try {
                catDocIs.close();
            } catch (IOException e) {
                log.error("Failed to close InputStream for " + remoteCatalog + " Error Message: "
                        + e.getMessage());
            }
        }
        catalogToHtmlTransformLock.unlock();
    }

}

From source file:org.apache.sling.servlethelpers.MockSlingHttpServletResponseTest.java

@Test
public void testSetStatus() throws Exception {
    assertEquals(HttpServletResponse.SC_OK, response.getStatus());

    response.setStatus(HttpServletResponse.SC_BAD_GATEWAY);
    assertEquals(HttpServletResponse.SC_BAD_GATEWAY, response.getStatus());

    response.reset();//from  w w  w.  j a v  a2 s. c  o  m
    assertEquals(HttpServletResponse.SC_OK, response.getStatus());
}

From source file:org.archive.wayback.resourcestore.locationdb.FileProxyServlet.java

public boolean handleRequest(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
        throws IOException, ServletException {

    ResourceLocation location = parseRequest(httpRequest);
    if (location == null) {
        httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, "no/invalid name");
    } else {/*from  w  ww  . j a va  2 s  .c  o m*/

        String urls[] = locationDB.nameToUrls(location.getName());

        if (urls == null || urls.length == 0) {

            LOGGER.warning("No locations for " + location.getName());
            httpResponse.sendError(HttpServletResponse.SC_NOT_FOUND,
                    "Unable to locate(" + location.getName() + ")");
        } else {

            DataSource ds = null;
            for (String urlString : urls) {
                try {
                    ds = locationToDataSource(urlString, location.getOffset());
                    if (ds != null) {
                        break;
                    }
                } catch (IOException e) {
                    LOGGER.warning("failed proxy of " + urlString + " " + e.getLocalizedMessage());
                }
            }
            if (ds == null) {
                LOGGER.warning("No successful locations for " + location.getName());
                httpResponse.sendError(HttpServletResponse.SC_BAD_GATEWAY,
                        "failed proxy of (" + location.getName() + ")");

            } else {
                httpResponse.setStatus(HttpServletResponse.SC_OK);
                // BUGBUG: this will be broken for non compressed data...
                httpResponse.setContentType(ds.getContentType());
                httpResponse.setBufferSize(BUF_SIZE);
                ds.copyTo(httpResponse.getOutputStream());
            }
        }
    }
    return true;
}

From source file:org.opendatakit.aggregate.task.gae.servlet.WatchdogServlet.java

/**
 * Handler for HTTP Get request to run watchdog task
 *
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 *//* w  ww . j a v a2 s .c  om*/
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    CallingContext cc = ContextFactory.getCallingContext(this, req);
    cc.setAsDaemon(true);

    logger.info("Beginning servlet processing");
    WatchdogWorkerImpl worker = new WatchdogWorkerImpl();
    try {
        worker.checkTasks(cc);
        logger.info("ending successful servlet processing");
        resp.setStatus(HttpServletResponse.SC_ACCEPTED);
    } catch (ODKExternalServiceException e) {
        e.printStackTrace();
        logger.error(e.toString());
        resp.sendError(HttpServletResponse.SC_BAD_GATEWAY, e.toString());
        return;
    } catch (ODKFormNotFoundException e) {
        e.printStackTrace();
        logger.error(e.toString());
        odkIdNotFoundError(resp);
        return;
    } catch (ODKDatastoreException e) {
        e.printStackTrace();
        logger.error(e.toString());
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
        return;
    } catch (ODKIncompleteSubmissionData e) {
        e.printStackTrace();
        logger.error(e.toString());
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
        return;
    }
}

From source file:org.wso2.carbon.identity.oauth.endpoint.token.OAuth2TokenEndpoint.java

private Response handleSQLError() throws OAuthSystemException {
    OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_GATEWAY)
            .setError(OAuth2ErrorCodes.SERVER_ERROR).setErrorDescription("Service Unavailable Error.")
            .buildJSONMessage();/*ww  w.  j a v a 2  s. co  m*/

    return Response.status(response.getResponseStatus())
            .header(OAuthConstants.HTTP_RESP_HEADER_AUTHENTICATE, EndpointUtil.getRealmInfo())
            .entity(response.getBody()).build();
}

From source file:org.wso2.carbon.identity.oauth.endpoint.token.OAuth2TokenEndpointTest.java

@DataProvider(name = "testTokenErrorResponseDataProvider")
public Object[][] testTokenErrorResponseDataProvider() {
    ResponseHeader contentType = new ResponseHeader();
    contentType.setKey(OAuth.HeaderType.CONTENT_TYPE);
    contentType.setValue(OAuth.ContentType.URL_ENCODED);

    ResponseHeader[] headers1 = new ResponseHeader[] { contentType };
    ResponseHeader[] headers2 = new ResponseHeader[] { null };
    ResponseHeader[] headers3 = new ResponseHeader[0];

    // This object provides data to cover all the scenarios with token error response
    return new Object[][] {
            { OAuth2ErrorCodes.INVALID_CLIENT, null, HttpServletResponse.SC_UNAUTHORIZED,
                    OAuth2ErrorCodes.INVALID_CLIENT },
            { OAuth2ErrorCodes.SERVER_ERROR, null, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    OAuth2ErrorCodes.SERVER_ERROR },
            { SQL_ERROR, null, HttpServletResponse.SC_BAD_GATEWAY, OAuth2ErrorCodes.SERVER_ERROR },
            { TOKEN_ERROR, null, HttpServletResponse.SC_BAD_REQUEST, TOKEN_ERROR },
            { TOKEN_ERROR, headers1, HttpServletResponse.SC_BAD_REQUEST, TOKEN_ERROR },
            { TOKEN_ERROR, headers2, HttpServletResponse.SC_BAD_REQUEST, TOKEN_ERROR },
            { TOKEN_ERROR, headers3, HttpServletResponse.SC_BAD_REQUEST, TOKEN_ERROR }, };
}