Example usage for javax.servlet.http HttpServletResponse SC_GATEWAY_TIMEOUT

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

Introduction

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

Prototype

int SC_GATEWAY_TIMEOUT

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

Click Source Link

Document

Status code (504) indicating that the server did not receive a timely response from the upstream server while acting as a gateway or proxy.

Usage

From source file:com.aol.webservice_base.util.http.HttpHelper.java

/**
 * Http client call./*from   www.ja  v  a2 s . c  o  m*/
 *
 * callers to this are responsible for ensuring connection is closed properly - httpHelper.releaseResponse() 
 *
 * @param requestMethod the request method
 * @param url the url
 * @param headers the headers
 * @param content the content
 * @return the http response
 * @throws HttpException the http exception
 */
protected HttpResponse httpClientCall(String requestMethod, String url, Map<String, String> headers,
        Object content) throws HttpException {
    HttpResponse response = null;
    if (!inited) {
        throw new Error("HttpHelper used when not initialized (call init) for " + url);
    }

    final String METHOD = "HttpHelper.httpClientCall()";
    HttpRequestBase httpRequest = null;
    boolean success = false;

    int iter = 0;
    int status;
    String statusMsg;
    do {
        try {
            long begin = System.currentTimeMillis();
            new URL(url);
            httpRequest = getHttpRequest(requestMethod, url, content);

            if (headers != null && headers.size() > 0) {
                for (Map.Entry<String, String> headerSet : headers.entrySet()) {
                    httpRequest.addHeader(headerSet.getKey(), headerSet.getValue());
                }
            }
            Header[] requestHeaders = httpRequest.getAllHeaders();
            for (int i = 0; i < requestHeaders.length; i++) {
                String name = requestHeaders[i].getName();
                String value = requestHeaders[i].getValue();
                if (logger.isDebugEnabled()) {
                    logger.debug("Request header " + name + " = [" + value + "]");
                }
            }

            // make the request
            //httpRequest.setFollowRedirects(false);
            response = httpClient.execute(httpRequest);
            status = response.getStatusLine().getStatusCode();
            statusMsg = response.getStatusLine().getReasonPhrase();
            if (logger.isDebugEnabled()) {
                logger.debug(METHOD + " status=" + status + " status desc: [" + statusMsg + "] url=[" + url
                        + "] took=" + (System.currentTimeMillis() - begin) + " ms");
            }
            if (status == 302 || status == 301) {
                Header loc = httpRequest.getFirstHeader("Location");
                if (loc != null) {
                    String origUrl = url;
                    url = loc.getValue();
                    if (!url.startsWith("http")) {
                        url = addHost(origUrl, url);
                    }
                    continue;
                }
            }
            if (status != 200 /* && status != 304 */) {
                throw new HttpException(status, statusMsg);
            }

            if (logger.isDebugEnabled()) {
                Header[] responseHeaders = response.getAllHeaders();
                for (int i = 0; i < responseHeaders.length; i++) {
                    String name = responseHeaders[i].getName();
                    String value = responseHeaders[i].getValue();
                    logger.debug("Response header " + name + " = [" + value + "]");
                }
            }

            success = true;
            return response;
        } catch (MalformedURLException e) {
            String msg = "target URL = [" + url + "] is invalid.";
            logger.error(msg);
            throw new HttpException(HttpServletResponse.SC_NOT_FOUND, msg);
        } catch (HttpException e) {
            logger.error("HttpException " + METHOD + " url=" + url + " exception=" + e.getMessage());
            throw e;
        } catch (java.net.SocketTimeoutException e) {
            logger.error("SocketTimeoutException " + METHOD + " url=" + url + " exception=" + e.getMessage());
            throw new HttpException(HttpServletResponse.SC_GATEWAY_TIMEOUT,
                    "Connection or Read timeout exception: " + e);
        } catch (Throwable t) {
            logger.error("HttpException " + METHOD + " url=" + url + " exception=" + t.getMessage());
            throw new HttpException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, t);
        } finally {
            // release the connection whenever we are not successful
            if ((!success) && (response != null)) {
                try {
                    releaseResponse(response);
                    response = null;
                } catch (IOException e) {
                    logger.error("HttpHelper - problem releasing connection", e);
                }
            }
        }
    } while (!success && (++iter <= this.followRedirectMax));

    throw new HttpException(status, statusMsg);
}

From source file:org.apache.sling.launchpad.webapp.integrationtest.issues.SLING2082Test.java

public void testOptingServletPost() throws Exception {
    final String path = "/testing/HtmlResponseServlet";
    final GetMethod post = new GetMethod(HTTP_BASE_URL + path);
    runTest(post, HttpServletResponse.SC_GATEWAY_TIMEOUT);
}

From source file:org.eclipse.orion.server.cf.commands.GetSpaceCommand.java

@Override
protected ServerStatus _doIt() {
    try {/*from   w  ww.j  a v a  2  s . co m*/
        URI targetURI = URIUtil.toURI(getCloud().getUrl());

        /* get space */
        URI spacesURI = targetURI.resolve("/v2/spaces/" + this.spaceId);

        GetMethod getSpaceMethod = new GetMethod(spacesURI.toString());
        HttpUtil.configureHttpMethod(getSpaceMethod, getCloud());
        getSpaceMethod.setQueryString("inline-relations-depth=1"); //$NON-NLS-1$

        ServerStatus status = HttpUtil.executeMethod(getSpaceMethod);
        if (!status.isOK())
            return status;

        space = new Space().setCFJSON(status.getJsonData());
        JSONObject result = space.toJSON();

        return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result);
    } catch (ConnectTimeoutException e) {
        String msg = NLS.bind("An error occurred when performing operation {0}", commandName); //$NON-NLS-1$
        logger.error(msg, e);
        return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_GATEWAY_TIMEOUT, msg, e);
    } catch (Exception e) {
        String msg = NLS.bind("An error occurred when performing operation {0}", commandName); //$NON-NLS-1$
        logger.error(msg, e);
        return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
    }
}

From source file:org.eclipse.smarthome.ui.internal.proxy.BlockingProxyServlet.java

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

    URI uri = service.uriFromRequest(request);

    if (uri == null) {
        service.sendError(request, response);
    } else {/*  w ww  . j  a v  a 2s.  c o  m*/
        Request httpRequest = httpClient.newRequest(uri);

        service.maybeAppendAuthHeader(uri, httpRequest);

        InputStreamResponseListener listener = new InputStreamResponseListener();

        // do the client request
        try {
            httpRequest.send(listener);
            // wait for the response headers to arrive or the timeout to expire
            Response httpResponse = listener.get(TIMEOUT, TimeUnit.MILLISECONDS);

            // get response headers
            HttpFields headers = httpResponse.getHeaders();
            Iterator<HttpField> iterator = headers.iterator();

            // copy all headers
            while (iterator.hasNext()) {
                HttpField header = iterator.next();
                response.setHeader(header.getName(), header.getValue());
            }
        } catch (Exception e) {
            if (e instanceof TimeoutException) {
                logger.warn("Proxy servlet failed to stream content due to a timeout");
                response.sendError(HttpServletResponse.SC_GATEWAY_TIMEOUT);
            } else {
                logger.warn("Proxy servlet failed to stream content: {}", e.getMessage());
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
            }
            return;
        }
        // now copy/stream the body content
        try (InputStream responseContent = listener.getInputStream()) {
            IOUtils.copy(responseContent, response.getOutputStream());
        }
    }
}

From source file:org.j2free.servlet.ProxyServlet.java

/**
 *
 * @param request/*  w  w  w .  jav a 2 s  .c  o m*/
 * @param response
 * @throws ServletException
 * @throws IOException
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String pathInfo = request.getServletPath().replaceFirst("/proxy", "");

    if (pathInfo == null) {
        log.warn("Received request to proxy but pathInfo null!");
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    String[] path = pathInfo.split("/");
    if (path.length == 0) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    String fetchUrl = "http://" + path[1];
    log.debug("Proxying " + fetchUrl);

    /*
    URL url = new URL(fetchUrl);
    URLConnection cxn = url.openConnection();
    BufferedReader in = new BufferedReader(new InputStreamReader(cxn.getInputStream()));
            
    String buff = "";
            
    String line = null;
    while ((line = in.readLine()) != null) {
    buff += line;
    }
    in.close();
            
    // this packs it down by removing new lines and extra whitespace
    buff = buff.replaceAll("\n", " ").replaceAll("\\s{2,}", " ");
     */

    HttpCallTask task = new HttpCallTask(fetchUrl);
    Future<HttpCallResult> future = SimpleHttpService.submit(task);
    HttpCallResult result;

    try {
        result = future.get();
    } catch (InterruptedException ie) {
        response.setStatus(HttpServletResponse.SC_GATEWAY_TIMEOUT);
        return;
    } catch (ExecutionException ee) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    PrintWriter out = response.getWriter();
    out.print(result.getResponse());
    out.flush();
    out.close();
}

From source file:org.nuxeo.ecm.platform.ui.web.auth.NuxeoAuthenticationFilter.java

protected Principal doAuthenticate(CachableUserIdentificationInfo cachableUserIdent,
        HttpServletRequest httpRequest) {

    LoginContext loginContext;/*from   w  ww  .ja v  a2 s  .  co  m*/
    try {
        CallbackHandler handler = service.getCallbackHandler(cachableUserIdent.getUserInfo());
        loginContext = new LoginContext(securityDomain, handler);

        if (isLoginSynchronized()) {
            synchronized (NuxeoAuthenticationFilter.class) {
                loginContext.login();
            }
        } else {
            loginContext.login();
        }

        Principal principal = (Principal) loginContext.getSubject().getPrincipals().toArray()[0];
        cachableUserIdent.setPrincipal(principal);
        cachableUserIdent.setAlreadyAuthenticated(true);
        // re-set the userName since for some SSO based on token,
        // the userName is not known before login is completed
        cachableUserIdent.getUserInfo().setUserName(principal.getName());

        logAuthenticationAttempt(cachableUserIdent.getUserInfo(), true);
    } catch (LoginException e) {
        log.info("Login failed for " + cachableUserIdent.getUserInfo().getUserName());
        logAuthenticationAttempt(cachableUserIdent.getUserInfo(), false);
        Throwable cause = e.getCause();
        if (cause instanceof DirectoryException) {
            Throwable rootCause = ExceptionUtils.getRootCause(cause);
            if (rootCause instanceof NamingException
                    && rootCause.getMessage().contains("LDAP response read timed out")
                    || rootCause instanceof SocketException) {
                httpRequest.setAttribute(LOGIN_STATUS_CODE, HttpServletResponse.SC_GATEWAY_TIMEOUT);
            }
            return DIRECTORY_ERROR_PRINCIPAL;
        }
        return null;
    }

    // store login context for the time of the request
    // TODO logincontext is also stored in cachableUserIdent - it is really
    // needed to store it??
    httpRequest.setAttribute(LOGINCONTEXT_KEY, loginContext);

    // store user ident
    cachableUserIdent.setLoginContext(loginContext);
    boolean createSession = needSessionSaving(cachableUserIdent.getUserInfo());
    HttpSession session = httpRequest.getSession(createSession);
    if (session != null) {
        session.setAttribute(USERIDENT_KEY, cachableUserIdent);
    }

    service.onAuthenticatedSessionCreated(httpRequest, session, cachableUserIdent);

    return cachableUserIdent.getPrincipal();
}