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:com.github.jrialland.ajpclient.servlet.TestWrongHost.java

/**
 * tries to make a request to an unknown host, verifies that the request
 * fails (the library does not hangs) and that we have a 502 error
 * /*from   ww w . ja va 2s.com*/
 * @throws Exception
 */
@Test
public void testWrongTargetHost() throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("GET");
    request.setRequestURI("/dizzy.mp4");
    final MockHttpServletResponse response = new MockHttpServletResponse();

    final Future<Integer> statusFuture = Executors.newSingleThreadExecutor().submit(new Callable<Integer>() {
        @Override
        public Integer call() throws Exception {
            AjpServletProxy.forHost("unknownhost.inexistentdomain.com", 8415).forward(request, response);
            return response.getStatus();
        }
    });

    final long start = System.currentTimeMillis();

    // should finish in less that seconds
    final int status = statusFuture.get(10, TimeUnit.SECONDS);

    Assert.assertTrue(System.currentTimeMillis() - start < 8000);

    Assert.assertEquals(HttpServletResponse.SC_BAD_GATEWAY, status);
}

From source file:ee.ria.xroad.proxy.testsuite.testcases.ServerProxyHttpError.java

@Override
public AbstractHandler getServerProxyHandler() {
    return new AbstractHandler() {
        @Override/*from  w  w  w . j ava  2 s .c  o  m*/
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException {
            // Read all of the request.
            IOUtils.readLines(request.getInputStream());

            response.sendError(HttpServletResponse.SC_BAD_GATEWAY);
            baseRequest.setHandled(true);
        }
    };
}

From source file:org.piraso.web.base.PirasoResponseWrapperTest.java

@Test
public void testSendErrorWithReason() throws Exception {
    wrapper.sendError(HttpServletResponse.SC_BAD_GATEWAY, "test");
    assertEquals(HttpServletResponse.SC_BAD_GATEWAY, entry.getStatus());
    assertEquals("test", entry.getStatusReason());
}

From source file:com.pureinfo.tgirls.sns.servlet.SNSEntryServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("tgirls sns entry.");

    String taobaoUserId = null;/*from   w  w  w  .  j ava2s .c o m*/
    String taobaoUserName = null;

    String topSession = request.getParameter(APPConstants.REQ_PARAMETER_SESSION);
    String topParameters = request.getParameter(APPConstants.REQ_PARAMETER_PARAMETERS);
    String topSign = request.getParameter(APPConstants.REQ_PARAMETER_SIGN);

    TipBean tb = null;
    try {
        tb = TipUtil.beforeFetch(topSession, topParameters, topSign, APPConstants.SECRET);
        if (!tb.isOk()) {
            logger.error("top api failed." + tb.getErrMsg());

            throw new Exception("TOP API failed:" + tb.getErrMsg());
        }
        taobaoUserId = tb.getUserId() + "";
        taobaoUserName = tb.getUserNick();

        logger.debug("id:" + taobaoUserId);
        logger.debug("name:" + taobaoUserName);
        logger.debug("session:" + topSession);

        if ("0".equals(taobaoUserId) || StringUtils.isEmpty(taobaoUserId)
                || StringUtils.isEmpty(taobaoUserName)) {
            throw new Exception("parameter empty.");
        }
    } catch (Exception e) {
        logger.error("error when call top API.", e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "top system error." + e.getMessage());
        return;
    }

    HttpSession session = request.getSession(true);
    session.removeAttribute(ArkHelper.ATTR_LOGIN_USER);
    User loginUser = null;//(User) session.getAttribute(ArkHelper.ATTR_LOGIN_USER);
    //loginUser = CookieUtils.getLoginUser(request, response);

    if (loginUser != null && loginUser.getTaobaoID().equals(taobaoUserId)) {

        logger.debug("user " + taobaoUserId + " already logined.");

    } else {
        try {
            userMgr = (IUserMgr) ArkContentHelper.getContentMgrOf(User.class);
            if (!userMgr.isUserExists(taobaoUserId)) {
                loginUser = createUser(taobaoUserId, topSession);
                //ScriptWriteUtils.reBuildUserInfoScript(loginUser);
                try {
                    //ScriptWriteUtils.reBuildUserBuyPhotosScript(loginUser);
                    //ScriptWriteUtils.reBuildUserUploadPhotosScript(loginUser);
                } catch (Exception e) {
                    logger.error("error when rebuild buy and upload scripts.", e);
                }
            } else {
                loginUser = userMgr.getUserByTaobaoId(taobaoUserId);
            }
        } catch (PureException e) {
            logger.error("tgirls system error.", e);
            response.sendError(HttpServletResponse.SC_BAD_GATEWAY, "tgirls system error." + e.getMessage());
            return;
        } catch (NumberFormatException e) {
            logger.error("number format error.", e);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
            return;
        } catch (TaobaoApiException e) {
            logger.error("top system error.", e);
            response.sendError(HttpServletResponse.SC_BAD_GATEWAY, "top system error." + e.getMessage());
            return;
        }
    }

    if (loginUser == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "can not find current user.");
        return;
    }

    if (loginUser.getFunds() <= UserConstants.DISUSE_FUNDS
            || loginUser.getAssets() <= UserConstants.DISUSE_ASSETS) {
        response.sendRedirect(request.getContextPath() + "/disable.html");
        return;
    }

    updateUserHeadImg(loginUser, topSession);

    session.setAttribute(ArkHelper.ATTR_LOGIN_USER, loginUser);
    session.setAttribute(SessionConstants.TAOBAO_SESSION_ID, topSession);
    LocalContextHelper.setAttribute(SessionConstants.TAOBAO_SESSION_ID, topSession);

    addCookie(loginUser, request, response);

    //        System.out.println("========================");
    //        
    //        
    //       Cookie[] cs = request.getCookies();
    //        for (int i = 0; i < cs.length; i++) {
    //            Cookie c = cs[i];
    //            System.out.println("cookie[" + c.getName() + "]:" + c.getValue());
    //        }
    //        
    RequestDispatcher rd = request.getRequestDispatcher("/index.html");
    rd.forward(request, response);
    //response.sendRedirect(request.getContextPath());

    return;
}

From source file:com.thoughtworks.go.agent.UrlBasedArtifactsRepositoryTest.java

@Test
public void shouldRetryUponUploadFailure() throws IOException {
    String data = "Some text whose checksum can be asserted";
    final String md5 = CachedDigestUtils.md5Hex(data);
    FileUtils.writeStringToFile(tempFile, data);
    Properties properties = new Properties();
    properties.setProperty("dest/path/file.txt", md5);

    when(httpService.upload(eq("http://baseurl/artifacts/dest/path?attempt=1&buildId=build42"),
            eq(tempFile.length()), any(File.class), eq(properties)))
                    .thenReturn(HttpServletResponse.SC_BAD_GATEWAY);
    when(httpService.upload(eq("http://baseurl/artifacts/dest/path?attempt=2&buildId=build42"),
            eq(tempFile.length()), any(File.class), eq(properties)))
                    .thenReturn(HttpServletResponse.SC_BAD_GATEWAY);
    when(httpService.upload(eq("http://baseurl/artifacts/dest/path?attempt=3&buildId=build42"),
            eq(tempFile.length()), any(File.class), eq(properties))).thenReturn(HttpServletResponse.SC_OK);
    artifactsRepository.upload(console, tempFile, "dest/path", "build42");
}

From source file:com.thoughtworks.go.agent.UrlBasedArtifactsRepositoryTest.java

@Test
public void shouldPrintFailureMessageToConsoleWhenUploadFailed() throws IOException {
    String data = "Some text whose checksum can be asserted";
    final String md5 = CachedDigestUtils.md5Hex(data);
    FileUtils.writeStringToFile(tempFile, data);
    Properties properties = new Properties();
    properties.setProperty("dest/path/file.txt", md5);

    when(httpService.upload(eq("http://baseurl/artifacts/dest/path?attempt=1&buildId=build42"),
            eq(tempFile.length()), any(File.class), eq(properties)))
                    .thenReturn(HttpServletResponse.SC_BAD_GATEWAY);
    when(httpService.upload(eq("http://baseurl/artifacts/dest/path?attempt=2&buildId=build42"),
            eq(tempFile.length()), any(File.class), eq(properties)))
                    .thenReturn(HttpServletResponse.SC_BAD_GATEWAY);
    when(httpService.upload(eq("http://baseurl/artifacts/dest/path?attempt=3&buildId=build42"),
            eq(tempFile.length()), any(File.class), eq(properties)))
                    .thenReturn(HttpServletResponse.SC_BAD_GATEWAY);

    try {/*from   w  ww.  j a va  2  s.  co m*/
        artifactsRepository.upload(console, tempFile, "dest/path", "build42");
        fail("should have thrown request entity too large error");
    } catch (RuntimeException e) {
        assertThat(console.output(), printedUploadingFailure(tempFile));
    }
}

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 {/*from w w w.ja  v  a2 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:com.google.apphosting.vmruntime.jetty9.VmRuntimeJettyKitchenSinkTest.java

public void testShutDown() throws Exception {

    int code = fetchResponseCode(createUrl("/_ah/health"));
    assertEquals(HttpServletResponse.SC_OK, code);

    // Send a request to /_ah/stop to trigger lameduck.
    String[] lines = fetchUrl(createUrl("/_ah/stop"));
    assertEquals(1, lines.length);//from  w  w w .  ja  v a  2s .  co  m
    assertEquals("ok", lines[0].trim());

    code = fetchResponseCode(createUrl("/_ah/health"));
    assertEquals(HttpServletResponse.SC_BAD_GATEWAY, code);
}

From source file:jp.aegif.alfresco.online_webdav.WebDAVHelper.java

/**
 * Check that the destination path is on this server and is a valid WebDAV
 * path for this server//  www.  j av  a 2 s  . com
 * 
 * @param request The request made against the WebDAV server.
 * @param urlStr String
 * @exception WebDAVServerException
 */
public void checkDestinationURL(HttpServletRequest request, String urlStr) throws WebDAVServerException {
    try {
        // Parse the URL

        URL url = new URL(urlStr);

        // Check if the path is on this WebDAV server

        boolean localPath = true;

        if (url.getPort() != -1 && url.getPort() != request.getServerPort()) {
            // Debug

            if (logger.isDebugEnabled())
                logger.debug("Destination path, different server port");

            localPath = false;
        } else if (url.getHost().equalsIgnoreCase(request.getServerName()) == false
                && url.getHost().equals(request.getLocalAddr()) == false) {
            // The target host may contain a domain or be specified as a numeric IP address

            String targetHost = url.getHost();

            if (IPAddress.isNumericAddress(targetHost) == false) {
                String localHost = request.getServerName();

                int pos = targetHost.indexOf(".");
                if (pos != -1)
                    targetHost = targetHost.substring(0, pos);

                pos = localHost.indexOf(".");
                if (pos != -1)
                    localHost = localHost.substring(0, pos);

                // compare the host names

                if (targetHost.equalsIgnoreCase(localHost) == false)
                    localPath = false;
            } else {
                try {
                    // Check if the target IP address is a local address

                    InetAddress targetAddr = InetAddress.getByName(targetHost);
                    if (NetworkInterface.getByInetAddress(targetAddr) == null)
                        localPath = false;
                } catch (Exception ex) {
                    // DEBUG

                    if (logger.isDebugEnabled())
                        logger.debug("Failed to check target IP address, " + targetHost);

                    localPath = false;
                }
            }

            // Debug

            if (localPath == false && logger.isDebugEnabled()) {
                logger.debug("Destination path, different server name/address");
                logger.debug("  URL host=" + url.getHost() + ", ServerName=" + request.getServerName()
                        + ", localAddr=" + request.getLocalAddr());
            }
        } else if (!url.getPath().startsWith(getUrlPathPrefix(request))) {
            // Debug

            if (logger.isDebugEnabled())
                logger.debug("Destination path, different serlet path");

            localPath = false;
        }

        // If the URL does not refer to this WebDAV server throw an
        // exception

        if (localPath != true)
            throw new WebDAVServerException(HttpServletResponse.SC_BAD_GATEWAY);
    } catch (MalformedURLException ex) {
        // Debug

        if (logger.isDebugEnabled())
            logger.debug("Bad destination path, " + urlStr);

        throw new WebDAVServerException(HttpServletResponse.SC_BAD_GATEWAY);
    }
}

From source file:opendap.threddsHandler.StaticCatalogDispatch.java

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

    String http = "http://";

    // Sanitize the incoming query.
    query = Scrub.completeURL(query);/*from   w  ww.j av a  2  s . c  om*/
    log.debug("Processing query string: " + query);

    if (!query.startsWith("browseDataset=")) {
        log.error("Not a browseDataset request: " + Scrub.completeURL(query));
        throw new IOException("Not a browseDataset request!");
    }

    query = query.substring("browseDataset=".length(), query.length());

    String targetDataset = query.substring(0, query.indexOf('&'));

    String remoteCatalog = query.substring(query.indexOf('&') + 1, query.length());

    if (!remoteCatalog.startsWith(http)) {
        log.error("Catalog Must be remote: " + remoteCatalog);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Catalog Must be remote: " + remoteCatalog);
        return;
    }

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

    log.debug("targetDataset: " + targetDataset);
    log.debug("remoteCatalog: " + remoteCatalog);
    log.debug("remoteHost: " + remoteHost);

    // 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();
        datasetToHtmlTransformLock.lock();
        datasetToHtmlTransform.reloadTransformIfRequired();

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

        datasetToHtmlTransform.setParameter("docsService", oRequest.getDocsServiceLocalID());
        datasetToHtmlTransform.setParameter("targetDataset", targetDataset);
        datasetToHtmlTransform.setParameter("remoteCatalog", remoteCatalog);
        datasetToHtmlTransform.setParameter("remoteHost", remoteHost);

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

        // Send the transformed document.
        datasetToHtmlTransform.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 {
        datasetToHtmlTransform.clearAllParameters();

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

}