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:net.sf.j2ep.ProxyFilter.java

/**
 * Implementation of a reverse-proxy. All request go through here. This is
 * the main class where are handling starts.
 * //from  w  w  w .  java 2 s.  com
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {

    HttpServletResponse httpResponse = (HttpServletResponse) response;
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    //httpRequest.setCharacterEncoding("UTF-8");
    //httpResponse.setCharacterEncoding("UTF-8");
    Server server = (Server) httpRequest.getAttribute("proxyServer");
    if (server == null) {
        server = serverChain.evaluate(httpRequest);
    }

    if (server == null) {
        filterChain.doFilter(request, response);
    } else {
        String uri = server.getRule().process(getURI(httpRequest));
        String url = request.getScheme() + "://" + server.getDomainName() + server.getPath() + uri;
        log.debug("Connecting to " + url);

        ResponseHandler responseHandler = null;

        try {
            httpRequest = server.preExecute(httpRequest);
            responseHandler = executeRequest(httpRequest, url);
            httpResponse = server.postExecute(httpResponse);

            responseHandler.process(httpResponse);
        } catch (HttpException e) {
            log.error("Problem while connecting to server", e);
            httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            server.setConnectionExceptionRecieved(e);
        } catch (UnknownHostException e) {
            log.error("Could not connection to the host specified", e);
            httpResponse.setStatus(HttpServletResponse.SC_GATEWAY_TIMEOUT);
            server.setConnectionExceptionRecieved(e);
        } catch (IOException e) {
            log.error("Problem probably with the input being send, either with a Header or the Stream", e);
            httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (MethodNotAllowedException e) {
            log.error("Incoming method could not be handled", e);
            httpResponse.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            httpResponse.setHeader("Allow", e.getAllowedMethods());
        } finally {
            if (responseHandler != null) {
                responseHandler.close();
            }
        }
    }
}

From source file:org.openrepose.filters.authz.RequestAuthorizationHandler.java

@Override
public FilterDirector handleRequest(HttpServletRequest request, ReadableHttpServletResponse response) {
    final FilterDirector myDirector = new FilterDirectorImpl();
    myDirector.setFilterAction(FilterAction.RETURN);
    myDirector.setResponseStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    String message = "Failure in authorization component";

    final String tracingHeader = request.getHeader(CommonHttpHeader.TRACE_GUID.toString());
    final String authenticationToken = request.getHeader(CommonHttpHeader.AUTH_TOKEN.toString());

    try {/*from   w  ww .  j  a  va2s  .c  o m*/
        if (StringUtilities.isBlank(authenticationToken)) {
            // Reject if no token
            message = "Authentication token not found in X-Auth-Token header. Rejecting request.";
            LOG.debug(message);
            myDirector.setResponseStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
        } else if (adminRoleMatchIgnoringCase(request.getHeaders(OpenStackServiceHeader.ROLES.toString()))
                || isEndpointAuthorizedForToken(authenticationToken, tracingHeader)) {
            myDirector.setFilterAction(FilterAction.PASS);
        } else {
            message = "User token: " + authenticationToken
                    + ": The user's service catalog does not contain an endpoint that matches "
                    + "the endpoint configured in openstack-authorization.cfg.xml: \""
                    + configuredEndpoint.getHref() + "\".  User not authorized to access service.";
            LOG.info(message);
            myDirector.setResponseStatusCode(HttpServletResponse.SC_FORBIDDEN);
        }
    } catch (AuthServiceOverLimitException ex) {
        LOG.error(message);
        LOG.trace("", ex);
        myDirector.setResponseStatusCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); // (503)
        String retry = ex.getRetryAfter();
        if (retry == null) {
            Calendar retryCalendar = new GregorianCalendar();
            retryCalendar.add(Calendar.SECOND, 5);
            retry = new HttpDate(retryCalendar.getTime()).toRFC1123();
        }
        myDirector.responseHeaderManager().appendHeader(HttpHeaders.RETRY_AFTER, retry);
    } catch (AuthServiceException ex) {
        LOG.error(message);
        LOG.trace("", ex);
        if (ex.getCause() instanceof AkkaServiceClientException
                && ex.getCause().getCause() instanceof TimeoutException) {
            myDirector.setResponseStatusCode(HttpServletResponse.SC_GATEWAY_TIMEOUT);
        } else {
            myDirector.setResponseStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    } catch (Exception ex) {
        LOG.error(message);
        LOG.trace("", ex);
        myDirector.setResponseStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    if (delegating != null && myDirector.getFilterAction() != FilterAction.PASS) {
        myDirector.setFilterAction(FilterAction.PASS);
        for (Map.Entry<String, List<String>> mapHeaders : JavaDelegationManagerProxy
                .buildDelegationHeaders(myDirector.getResponseStatusCode(), CLIENT_AUTHORIZATION, message,
                        delegating.getQuality())
                .entrySet()) {
            List<String> value = mapHeaders.getValue();
            myDirector.requestHeaderManager().appendHeader(mapHeaders.getKey(),
                    value.toArray(new String[value.size()]));
        }
    }
    return myDirector;
}

From source file:org.jasig.portlet.emailpreview.controller.EmailAccountSummaryController.java

@ResourceMapping(value = "accountSummary")
public ModelAndView getAccountSummary(ResourceRequest req, ResourceResponse res,
        @RequestParam("pageStart") int start, @RequestParam("numberOfMessages") int max,
        @RequestParam(value = "inboxFolder", required = false) String folder) throws IOException {

    // Define view and generate model
    Map<String, Object> model = new HashMap<String, Object>();

    String username = req.getRemoteUser();
    try {//from  w ww  . jav  a 2  s . c om

        // Force a re-load from the data source if called for by the UI.
        boolean refresh = Boolean.valueOf(req.getParameter(FORCE_REFRESH_PARAMETER));

        // Or because of a change in settings.
        if (req.getPortletSession().getAttribute(FORCE_REFRESH_PARAMETER) != null) {
            // Doesn't matter what the value is;  this calls for a refresh...
            refresh = true;
            req.getPortletSession().removeAttribute(FORCE_REFRESH_PARAMETER);
        }

        PortletPreferences prefs = req.getPreferences();

        if ((folder == null) || (folder.equals(INBOX_NAME_UNDEFINED))) {
            folder = prefs.getValue(EmailAccountSummaryController.INBOX_NAME_PREFERENCE, INBOX_NAME_DEFAULT);
        }

        String prefFolder = prefs.getValue(EmailAccountSummaryController.INBOX_NAME_PREFERENCE,
                INBOX_NAME_DEFAULT);
        if ((!prefs.isReadOnly(INBOX_NAME_PREFERENCE)) && (!folder.equals(prefFolder))) {
            prefs.setValue(INBOX_NAME_PREFERENCE, folder);
            prefs.store();
        }

        // Get current user's account information
        AccountSummary accountSummary = getEmailAccountService(req).getAccountSummary(req, start, max, refresh,
                folder);

        // Check for AuthN failure...
        if (accountSummary.isValid()) {
            model.put(KEY_ACCOUNT_SUMMARY, accountSummary);
            model.put(KEY_INBOX_URL, accountSummary.getInboxUrl());
            if (accountSummary.getQuota() == null) {
                model.put(KEY_EMAIL_QUOTA_USAGE, "-1");
            } else {
                model.put(KEY_EMAIL_QUOTA_USAGE, accountSummary.getQuota().getUsageAsPercentage());
                model.put(KEY_EMAIL_QUOTA_LIMIT, accountSummary.getQuota().getLimitAsString());
            }
        } else {
            Throwable cause = accountSummary.getErrorCause();
            if (MailAuthenticationException.class.isAssignableFrom(cause.getClass())) {
                log.info("Authentication Failure (username='" + username + "') : " + cause.getMessage());
                res.setProperty(ResourceResponse.HTTP_STATUS_CODE,
                        Integer.toString(HttpServletResponse.SC_UNAUTHORIZED));
                model.put(KEY_ERROR, "Not authorized");
            } else {
                log.error("Unanticipated Error", cause);
                res.setProperty(ResourceResponse.HTTP_STATUS_CODE,
                        Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
                model.put(KEY_ERROR, "Unanticipated Error");
            }
        }

    } catch (MailTimeoutException ex) {
        log.error("Mail Service Timeout", ex);
        res.setProperty(ResourceResponse.HTTP_STATUS_CODE,
                Integer.toString(HttpServletResponse.SC_GATEWAY_TIMEOUT));
        model.put(KEY_ERROR, "Mail Service Timeout");
    } catch (Exception ex) {
        /* ********************************************************
        In the case of an unknown error we want to send the
        exception's message back to the portlet. This will
        let implementers write specific instructions for
        their service desks to follow for specific errors.
        ******************************************************** */
        log.error("Unanticipated Error", ex);
        res.setProperty(ResourceResponse.HTTP_STATUS_CODE,
                Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
        model.put(KEY_ERROR, "ex.getMessage()");
    }

    return new ModelAndView("json", model);

}

From source file:org.openrepose.filters.clientauth.common.AuthenticationHandler.java

private FilterDirector authenticate(HttpServletRequest request) {
    final FilterDirector filterDirector = new FilterDirectorImpl();
    filterDirector.setResponseStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
    filterDirector.setFilterAction(FilterAction.RETURN);
    int offset = getCacheOffset();

    final String tracingHeader = request.getHeader(CommonHttpHeader.TRACE_GUID.toString());
    final String authToken = request.getHeader(CommonHttpHeader.AUTH_TOKEN.toString());
    ExtractorResult<String> account = null;
    AuthToken token = null;/*from  w w w.  ja v a 2 s .c  o  m*/
    String contactId = null;

    if (tenanted) {
        account = extractAccountIdentification(request);
    }

    final boolean allow = allowAccount(account);

    String endpointsInBase64 = "";
    List<AuthGroup> groups = new ArrayList<AuthGroup>();
    try {
        if (!StringUtilities.isBlank(authToken) && allow) {
            token = checkToken(account, authToken);

            if (token == null) {
                token = validateToken(account, StringUriUtilities.encodeUri(authToken), tracingHeader);
                cacheUserInfo(token, offset);
            }
        }

        if (token != null) {
            groups = getAuthGroups(token, offset, tracingHeader);
            contactId = token.getContactId();

            //getting the encoded endpoints to pass into the header, if the endpoints config is not null
            if (endpointsConfiguration != null) {
                endpointsInBase64 = getEndpointsInBase64(token, tracingHeader);
            }
        }
    } catch (AuthServiceOverLimitException ex) {
        LOG.error(FAILURE_AUTH_N + REASON + ex.getMessage());
        LOG.trace("", ex);
        filterDirector.setResponseStatusCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); // (503)
        String retry = ex.getRetryAfter();
        if (retry == null) {
            Calendar retryCalendar = new GregorianCalendar();
            retryCalendar.add(Calendar.SECOND, 5);
            retry = new HttpDate(retryCalendar.getTime()).toRFC1123();
        }
        filterDirector.responseHeaderManager().appendHeader(HttpHeaders.RETRY_AFTER, retry);
        delegationMessage.set(FAILURE_AUTH_N);
    } catch (AuthServiceException ex) {
        LOG.error(FAILURE_AUTH_N + REASON + ex.getMessage());
        LOG.trace("", ex);
        if (ex.getCause() instanceof AkkaServiceClientException
                && ex.getCause().getCause() instanceof TimeoutException) {
            filterDirector.setResponseStatusCode(HttpServletResponse.SC_GATEWAY_TIMEOUT);
        } else {
            filterDirector.setResponseStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
        delegationMessage.set(FAILURE_AUTH_N);
    } catch (Exception ex) {
        LOG.error(FAILURE_AUTH_N, ex);
        filterDirector.setResponseStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        delegationMessage.set(FAILURE_AUTH_N + REASON + ex.getMessage());
    }

    setFilterDirectorValues(authToken, token, delegable, delegableQuality, delegationMessage.get(),
            filterDirector, account == null ? null : account.getResult(), groups, endpointsInBase64, contactId,
            sendAllTenantIds, sendTenantIdQuality);

    delegationMessage.remove();

    return filterDirector;
}

From source file:org.aludratest.cloud.selenium.impl.SeleniumHttpProxy.java

@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
    if (LOG.isTraceEnabled()) {
        // give a random ID for this request
        String id = Integer.toHexString((int) (Math.random() * Integer.MAX_VALUE));
        while (id.length() < 8) {
            id = "0" + id;
        }/*from ww w  . java  2 s  .  c  o  m*/
        LOG.trace("service() enter for " + resource + ", unique request code " + id);
        req.setAttribute("selenium.requestId", id);
    }

    // wait for update proxy if in progress
    synchronized (SeleniumHttpProxy.class) {
    }

    super.service(req, res);

    if (Boolean.TRUE.equals(req.getAttribute("selenium.connectFailed"))) {
        ((HttpServletResponse) res).sendError(HttpServletResponse.SC_GATEWAY_TIMEOUT);
    }
}

From source file:edu.slu.action.ObjectAction.java

/**
* Public API proxy to generate a new refresh token through Auth0.
* 
* @param authCode An authorization code generated by the Auth0 /authorize call.
* @return the Auth0 /oauth/token return's refresh_token value
*///from w ww.  j  av a2  s . co  m
public void generateNewRefreshToken() throws MalformedURLException, IOException, Exception {
    if (null != processRequestBody(request, false) && methodApproval(request, "token")) {
        System.out.println("Proxy generate a refresh token");
        JSONObject received = JSONObject.fromObject(content);
        JSONObject jsonReturn = new JSONObject();
        String authTokenURL = "https://cubap.auth0.com/oauth/token";
        JSONObject tokenRequestParams = new JSONObject();

        tokenRequestParams.element("grant_type", "authorization_code");
        tokenRequestParams.element("client_id", getRerumProperty("clientID"));
        tokenRequestParams.element("code", received.getString("authorization_code"));
        tokenRequestParams.element("client_secret", getRerumProperty("rerumSecret"));
        tokenRequestParams.element("redirect_uri", Constant.RERUM_BASE);
        try {
            URL auth0 = new URL(authTokenURL);
            HttpURLConnection connection = (HttpURLConnection) auth0.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(5 * 1000);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            connection.connect();
            DataOutputStream outStream = new DataOutputStream(connection.getOutputStream());
            //Pass in the user provided JSON for the body 
            outStream.writeBytes(tokenRequestParams.toString());
            outStream.flush();
            outStream.close();
            //Execute rerum server v1 request
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), "utf-8"));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                //Gather rerum server v1 response
                sb.append(line);
            }
            reader.close();
            connection.disconnect();
            jsonReturn = JSONObject.fromObject(sb.toString());
            out = response.getWriter();
            response.setStatus(HttpServletResponse.SC_OK);
            out.write(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(jsonReturn));
        } catch (java.net.SocketTimeoutException e) { //This specifically catches the timeout
            System.out.println("The Auth0 token endpoint is taking too long...");
            jsonReturn = new JSONObject(); //We were never going to get a response, so return an empty object.
            jsonReturn.element("error", "The Auth0 endpoint took too long");
            out = response.getWriter();
            response.setStatus(HttpServletResponse.SC_GATEWAY_TIMEOUT);
            out.write(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(jsonReturn));
        } catch (IOException ex) {
            Logger.getLogger(ObjectAction.class.getName()).log(Level.SEVERE, null, ex);
            jsonReturn = new JSONObject();
            jsonReturn.element("error", "Couldn't access output stream");
            jsonReturn.element("msg", ex.toString());
            out = response.getWriter();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.write(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(jsonReturn));
        }
    }
}

From source file:org.jetbrains.webdemo.handlers.ServerHandler.java

private void forwardRequestToBackend(HttpServletRequest request, HttpServletResponse response,
        Map<String, String> postParameters) {
    final boolean hasoutbody = (request.getMethod().equals("POST"));

    try {/*from   w  w w. ja v  a 2s .co  m*/
        final URL url = new URL("http://" + ApplicationSettings.BACKEND_URL + "/"
                + (request.getQueryString() != null ? "?" + request.getQueryString() : ""));
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        final Enumeration<String> headers = request.getHeaderNames();
        while (headers.hasMoreElements()) {
            final String header = headers.nextElement();
            final Enumeration<String> values = request.getHeaders(header);
            while (values.hasMoreElements()) {
                final String value = values.nextElement();
                conn.addRequestProperty(header, value);
            }
        }

        conn.setConnectTimeout(15000);
        conn.setReadTimeout(15000);
        conn.setUseCaches(false);
        conn.setDoOutput(hasoutbody);

        if (postParameters != null && !postParameters.isEmpty()) {
            conn.setRequestMethod("POST");
            try (OutputStream requestBody = conn.getOutputStream()) {
                boolean first = true;
                for (Map.Entry<String, String> entry : postParameters.entrySet()) {
                    if (entry.getValue() == null)
                        continue;
                    if (first) {
                        first = false;
                    } else {
                        requestBody.write('&');
                    }
                    requestBody.write(URLEncoder.encode(entry.getKey(), "UTF8").getBytes());
                    requestBody.write('=');
                    requestBody.write(URLEncoder.encode(entry.getValue(), "UTF8").getBytes());
                }
            }
        } else {
            conn.setRequestMethod("GET");
        }

        StringBuilder responseBody = new StringBuilder();
        if (conn.getResponseCode() >= 400) {
            StringBuilder serverMessage = new StringBuilder();
            try (InputStream errorStream = conn.getErrorStream()) {
                if (errorStream != null) {
                    byte[] buffer = new byte[1024];
                    while (true) {
                        final int read = errorStream.read(buffer);
                        if (read <= 0)
                            break;
                        serverMessage.append(new String(buffer, 0, read));
                    }
                }
            }

            switch (conn.getResponseCode()) {
            case HttpServletResponse.SC_NOT_FOUND:
                responseBody.append("Kotlin compile server not found");
                break;
            case HttpServletResponse.SC_SERVICE_UNAVAILABLE:
                responseBody.append("Kotlin compile server is temporary overloaded");
                break;
            default:
                responseBody = serverMessage;
                break;
            }
        } else {
            try (InputStream inputStream = conn.getInputStream()) {
                if (inputStream != null) {
                    byte[] buffer = new byte[1024];
                    while (true) {
                        final int read = inputStream.read(buffer);
                        if (read <= 0)
                            break;
                        responseBody.append(new String(buffer, 0, read));
                    }
                }
            }
        }
        writeResponse(request, response, responseBody.toString(), conn.getResponseCode());
    } catch (SocketTimeoutException e) {
        writeResponse(request, response, "Compile server connection timeout",
                HttpServletResponse.SC_GATEWAY_TIMEOUT);
    } catch (Exception e) {
        ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer(e, "FORWARD_REQUEST_TO_BACKEND", "",
                "Can't forward request to Kotlin compile server");
        writeResponse(request, response, "Can't send your request to Kotlin compile server",
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:edu.slu.action.ObjectAction.java

/**
 * Public API proxy to generate a new access token through Auth0.
 * /*from www .ja  v  a  2s  .  com*/
 * @param refreshToken The refresh token given to the user on registration or generateNewRefreshToken
 * @return the Auth0 /oauth/token return's access_token property
 */
public void generateNewAccessToken() throws MalformedURLException, IOException, Exception {
    if (null != processRequestBody(request, false) && methodApproval(request, "token")) {
        System.out.println("Proxy generate an access token");
        JSONObject received = JSONObject.fromObject(content);
        JSONObject jsonReturn = new JSONObject();
        String authTokenURL = "https://cubap.auth0.com/oauth/token";
        JSONObject tokenRequestParams = new JSONObject();
        tokenRequestParams.element("grant_type", "refresh_token");
        tokenRequestParams.element("client_id", getRerumProperty("clientID"));
        tokenRequestParams.element("client_secret", getRerumProperty("rerumSecret"));
        tokenRequestParams.element("refresh_token", received.getString("refresh_token"));
        tokenRequestParams.element("redirect_uri", Constant.RERUM_BASE);
        try {
            URL auth0 = new URL(authTokenURL);
            HttpURLConnection connection = (HttpURLConnection) auth0.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(5 * 1000);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.connect();
            DataOutputStream outStream = new DataOutputStream(connection.getOutputStream());
            //Pass in the user provided JSON for the body 
            outStream.writeBytes(tokenRequestParams.toString());
            outStream.flush();
            outStream.close();
            //Execute rerum server v1 request
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), "utf-8"));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                //Gather rerum server v1 response
                sb.append(line);
            }
            reader.close();
            connection.disconnect();
            jsonReturn = JSONObject.fromObject(sb.toString());
            out = response.getWriter();
            response.setStatus(HttpServletResponse.SC_OK);
            out.write(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(jsonReturn));
        } catch (java.net.SocketTimeoutException e) { //This specifically catches the timeout
            System.out.println("The Auth0 token endpoint is taking too long...");
            jsonReturn = new JSONObject();
            jsonReturn.element("error", "The Auth0 endpoint took too long");
            out = response.getWriter();
            response.setStatus(HttpServletResponse.SC_GATEWAY_TIMEOUT);
            out.write(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(jsonReturn));
        } catch (IOException ex) {
            Logger.getLogger(ObjectAction.class.getName()).log(Level.SEVERE, null, ex);
            jsonReturn = new JSONObject();
            jsonReturn.element("error", "Couldn't access output stream");
            jsonReturn.element("msg", ex.toString());
            out = response.getWriter();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.write(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(jsonReturn));
        }
    }
}

From source file:org.aludratest.cloud.selenium.impl.SeleniumHttpProxy.java

private void checkState() {
    // first of all, check if the resource is idle for too long. Regain it then.
    if (resource.getState() == ResourceState.IN_USE && resource.getIdleTime() > maxIdleTime) {
        // try to safely shutdown Selenium session
        LOG.info("Detected IDLE IN_USE resource (" + resource.getOriginalUrl() + "), trying to regain it.");
        resource.tryKillSession();//from  w ww.  j a  va  2  s  .co m
        resource.stopUsing();
        return;
    }

    // check state via our very own proxy - to get custom timeouts and direct feedback for lost connections.
    InputStream in = null;
    HttpGet request = null;
    CloseableHttpResponse response = null;
    try {
        URL uurl = new URL(accessUrl);
        URL checkUrl = new URL("http://127.0.0.1:" + uurl.getPort() + uurl.getPath() + "/wd/hub/status");
        LOG.debug("Checking health state for " + resource.getOriginalUrl() + " using "
                + checkUrl.toExternalForm());

        request = new HttpGet(checkUrl.toURI());
        response = healthCheckClient.execute(request);

        if (response.getStatusLine() != null
                && response.getStatusLine().getStatusCode() == HttpServletResponse.SC_GATEWAY_TIMEOUT) {
            LOG.debug(resource.getOriginalUrl() + " is DISCONNECTED (proxy timeout)");
            resource.setState(ResourceState.DISCONNECTED);
        } else if (response.getStatusLine() != null
                && response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) {
            LOG.debug(resource.getOriginalUrl() + " is DISCONNECTED (invalid HTTP status code "
                    + response.getStatusLine().getStatusCode() + ")");
            resource.setState(ResourceState.DISCONNECTED);
        } else if (response.getEntity() != null) {
            in = response.getEntity().getContent();
            ByteArrayOutputStream buf = new ByteArrayOutputStream();
            IOUtils.copy(in, buf);
            String statusStr = new String(buf.toByteArray(), "UTF-8");
            if (statusStr.contains("\"status\":0")) {
                if (resource.getState() == ResourceState.DISCONNECTED
                        || resource.getState() == ResourceState.CONNECTED) {
                    resource.setState(ResourceState.READY);
                    LOG.debug(resource.getOriginalUrl() + " is READY");
                }
            } else {
                LOG.debug(resource.getOriginalUrl() + " is DISCONNECTED (invalid response content: " + statusStr
                        + ")");
                resource.setState(ResourceState.DISCONNECTED);
            }
        } else {
            LOG.debug(resource.getOriginalUrl() + " is DISCONNECTED (invalid or no HTTP response)");
            resource.setState(ResourceState.DISCONNECTED);
        }
    } catch (IOException e) {
        LOG.debug(resource.getOriginalUrl() + " is DISCONNECTED due to IOException: " + e.getMessage());
        resource.setState(ResourceState.DISCONNECTED);
    } catch (URISyntaxException e) {
        LOG.debug(resource.getOriginalUrl() + " is DISCONNECTED due to URISyntaxException: " + e.getMessage());
        resource.setState(ResourceState.DISCONNECTED);
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(response);
    }
}