Example usage for javax.servlet.http HttpServletResponse SC_REQUEST_TIMEOUT

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

Introduction

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

Prototype

int SC_REQUEST_TIMEOUT

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

Click Source Link

Document

Status code (408) indicating that the client did not produce a request within the time that the server was prepared to wait.

Usage

From source file:jp.go.nict.langrid.servicesupervisor.invocationprocessor.executor.ServiceInvoker.java

/**
 * //from   www  . j  a v a 2 s  . c o  m
 * 
 */
public static int invoke(URL url, String userName, String password, Map<String, String> headers,
        InputStream input, HttpServletResponse output, OutputStream errorOut, int connectionTimeout,
        int soTimeout) throws IOException, SocketTimeoutException {
    HttpClient client = HttpClientUtil.createHttpClientWithHostConfig(url);
    SimpleHttpConnectionManager manager = new SimpleHttpConnectionManager(true);
    manager.getParams().setConnectionTimeout(connectionTimeout);
    manager.getParams().setSoTimeout(soTimeout);
    manager.getParams().setMaxConnectionsPerHost(client.getHostConfiguration(), 2);
    client.setHttpConnectionManager(manager);
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(0, false));

    PostMethod method = new PostMethod(url.getFile());
    method.setRequestEntity(new InputStreamRequestEntity(input));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        method.addRequestHeader(e.getKey(), e.getValue());
    }
    if (!headers.containsKey("Content-Type"))
        method.addRequestHeader("Content-Type", "text/xml; charset=utf-8");
    if (!headers.containsKey("Accept"))
        method.addRequestHeader("Accept", "application/soap+xml, application/dime, multipart/related, text/*");
    if (!headers.containsKey("SOAPAction"))
        method.addRequestHeader("SOAPAction", "\"\"");
    if (!headers.containsKey("User-Agent"))
        method.addRequestHeader("User-Agent", "Langrid Service Invoker/1.0");
    if (userName != null) {
        int port = url.getPort();
        if (port == -1) {
            port = url.getDefaultPort();
            if (port == -1) {
                port = 80;
            }
        }
        if (password == null) {
            password = "";
        }
        client.getState().setCredentials(new AuthScope(url.getHost(), port, null),
                new UsernamePasswordCredentials(userName, password));
        client.getParams().setAuthenticationPreemptive(true);
        method.setDoAuthentication(true);
    }

    try {
        int status;
        try {
            status = client.executeMethod(method);
        } catch (SocketTimeoutException e) {
            status = HttpServletResponse.SC_REQUEST_TIMEOUT;
        }
        output.setStatus(status);
        if (status == 200) {
            for (Header h : method.getResponseHeaders()) {
                String name = h.getName();
                if (name.startsWith("X-Langrid") || (!throughHeaders.contains(name.toLowerCase())))
                    continue;
                String value = h.getValue();
                output.addHeader(name, value);
            }
            OutputStream os = output.getOutputStream();
            StreamUtil.transfer(method.getResponseBodyAsStream(), os);
            os.flush();
        } else if (status == HttpServletResponse.SC_REQUEST_TIMEOUT) {
        } else {
            StreamUtil.transfer(method.getResponseBodyAsStream(), errorOut);
        }
        return status;
    } finally {
        manager.shutdown();
    }
}

From source file:byps.http.HActiveMessages.java

/**
 * This function is called when a new message arrives in onPost
 * @param header//from w  w  w  .j a v a2s.  com
 * @param rctxt
 * @param workerThread 
 * @throws BException
 */
public void addMessage(final BMessageHeader header, final HRequestContext rctxt, final Thread workerThread)
        throws BException {
    if (log.isDebugEnabled())
        log.debug("addMessage(" + header + ", rctxt=" + rctxt);

    HActiveMessage msg = getOrCreateActiveMessage(header.messageId);
    msg.setSessionid(header.sessionId);

    HAsyncErrorListener alsn = new HAsyncErrorListener() {

        @Override
        public void onTimeout(AsyncEvent arg0) throws IOException {

            HRequestContext rctxt = getAndRemoveRequestContext(header.messageId);
            if (rctxt == null)
                return;

            HttpServletResponse resp = (HttpServletResponse) arg0.getSuppliedResponse();

            boolean isLongPoll = (header.flags & BMessageHeader.FLAG_LONGPOLL) != 0;
            int status = isLongPoll ? HttpServletResponse.SC_NO_CONTENT
                    : HttpServletResponse.SC_REQUEST_TIMEOUT;
            resp.setStatus(status);

            resp.getOutputStream().close();

            if (log.isDebugEnabled())
                log.debug("AsyncErrorListener.onTimeout(" + arg0 + ") status=" + status);
        }

        @Override
        public void onError(AsyncEvent arg0) throws IOException {
            if (log.isDebugEnabled())
                log.debug("AsyncErrorListener.onError(" + arg0 + ")");
            getAndRemoveRequestContext(header.messageId);
        }
    };
    rctxt.addListener(alsn);

    msg.setRequestContext(rctxt, workerThread);
    if (log.isDebugEnabled())
        log.debug(")addMessage");
}

From source file:org.openo.auth.service.impl.TokenServiceImpl.java

/**
 * Get the Json Service instance according the service registered in the
 * <tt>auth_service.properties</tt> file.
 * <br/>/*from   ww w  .  j a  v a 2 s .  c o  m*/
 * 
 * @return jsonService : An instance of <tt>JsonService</tt> class.
 * @since
 */
private IJsonService getJsonService() {

    IJsonService jsonService = JsonFactory.getInstance().getJsonService();

    if (null == jsonService) {
        LOGGER.error("Exception Caught while connecting client ... ");
        throw new AuthException(HttpServletResponse.SC_REQUEST_TIMEOUT, ErrorCode.AUTH_LOAD_FAILED);
    }
    return jsonService;
}

From source file:org.piraso.server.spring.web.PirasoServletTest.java

@Test
public void testStoptimeout() throws Exception {
    servlet.setStopTimeout(100l);//  w  w w.ja va 2  s. c o  m

    request.addParameter("service", "stop");
    request.addParameter("preferences", mapper.writeValueAsString(new Preferences()));

    ResponseLoggerService service = mock(ResponseLoggerService.class);

    doReturn(true).when(service).isAlive();
    doReturn(service).when(registry).getLogger(Matchers.<User>any());

    servlet.handleRequest(request, response);

    assertEquals(HttpServletResponse.SC_REQUEST_TIMEOUT, response.getStatus());
}

From source file:org.openo.auth.service.impl.UserServiceImpl.java

/**
 * Perform Create user Operation./*from  w w  w. jav a 2s  . com*/
 * <br/>
 * 
 * @param request : HttpServletRequest Object
 * @param response : HttpServletResponse Object
 * @return response for the create user operation.
 * @since
 */
public Response createUser(HttpServletRequest request, HttpServletResponse response) {

    Response res = null;

    try {

        String authToken = request.getHeader(Constant.TOKEN_AUTH);

        LOGGER.info("authToken = " + authToken);
        if (null != accessDelegate) {
            Response accessResponse = accessDelegate.validateRights(request, response, Constant.CS_USERSERVICE,
                    Constant.OPERATION_CREATEUSER);

            if (accessResponse.getStatus() / 200 != 1) {
                LOGGER.info("access blocked by aut service, check policy and rights json");
                return accessResponse;
            }
        }

        UserDetailsUI userInfo = CommonUtil.getInstance().getUserInfo(request);

        LOGGER.info("userInfo UserName= " + userInfo.getUserName());

        CheckUserInfoRule.checkInfo(userInfo);

        KeyStoneConfiguration keyConf = KeyStoneConfigInitializer.getKeystoneConfiguration();

        String json = getJsonService().createUserJson(userInfo, keyConf);

        LOGGER.info("User json = " + json);

        ClientResponse resp = UserServiceClient.getInstance().createUser(json, authToken);

        int status = resp.getStatus();

        String respBody = resp.getBody();

        /* assign the role to the user */
        if (1 == status / 200 && null != roleDelegate) {

            LOGGER.info("User Created, assigning roles to user now.");

            status = roleDelegate.updateRolesToUser(userInfo.getRoles(), authToken,
                    getUserIdFromNewUser(respBody), Boolean.TRUE);
            respBody = getJsonService().responseForCreateUser(resp.getBody(), userInfo.getRoles());

        }
        response.setStatus(status);

        res = Response.status(status).entity(respBody).build();

    } catch (AuthException e) {
        LOGGER.error("Auth Exception ... " + e);
        throw e;
    } catch (Exception e) {
        LOGGER.error("Exception Caught while connecting client ... " + e);
        throw new AuthException(HttpServletResponse.SC_REQUEST_TIMEOUT, ErrorCode.FAILURE_INFORMATION);
    }
    return res;
}

From source file:org.openo.drivermgr.service.impl.DriverMgrServiceImpl.java

/**
 * get the driver info from the driver managerment.
 * <br/>/*from   w  w  w .jav a  2 s.co  m*/
 * 
 * @param request
 * @param response
 * @param serviceUrl
 * @param systemId
 * @return
 * @throws IOException
 * @throws JsonMappingException
 * @throws JsonGenerationException
 * @since  
 */
public String getDriverDetails(HttpServletRequest request, HttpServletResponse response, String serviceUrl,
        String systemId) {
    ObjectMapper mapper = new ObjectMapper();
    try {
        if (null == serviceUrl && null == systemId) {
            return mapper.writeValueAsString(getDriverDetails(request, response));
        } else {
            if (StringUtils.isBlank(systemId)) {
                throw new DriverManagerException(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                        ErrorCode.INVALID_PARAMETERS);
            }

            String driverUrl = getDriverDetail(request, response, serviceUrl, getSystemID(systemId));
            return mapper.writeValueAsString(new DriverUrl(driverUrl));

        }
    } catch (IOException e) {
        LOGGER.error("IO Exception Occuered", e);
        throw new DriverManagerException(HttpServletResponse.SC_REQUEST_TIMEOUT, ErrorCode.COMMUNICATION_ERROR);
    }
}

From source file:org.deegree.portal.owswatch.validator.AbstractValidator.java

/**
 * @param statusCode//w ww  . j  a v a  2 s.  com
 * @return instance of the validatorresponse with the error
 */
protected ValidatorResponse validateErrorHttpResponse(int statusCode) {

    String lastMessage = null;
    Status status = null;

    if (statusCode == HttpServletResponse.SC_REQUEST_TIMEOUT) {
        status = Status.RESULT_STATE_TIMEOUT;
        lastMessage = status.getStatusMessage();
    } else {
        status = Status.RESULT_STATE_PAGE_UNAVAILABLE;
        lastMessage = status.getStatusMessage();
    }

    return new ValidatorResponse(lastMessage, status);
}

From source file:org.piraso.server.spring.web.PirasoServlet.java

private void stopService(HttpServletResponse response, User user) throws IOException {
    ResponseLoggerService service = getRegistry().getLogger(user);

    if (service == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND,
                String.format("Service for user '%s' not found.", user.toString()));
        return;//  ww w.j ava  2 s  . c o m
    }

    if (!service.isAlive()) {
        response.sendError(HttpServletResponse.SC_CONFLICT,
                String.format("Service for user '%s' not active.", user.toString()));
        getRegistry().removeUser(user);

        return;
    }

    try {
        // gracefully stop the service
        service.stopAndWait(stopTimeout);

        if (service.isAlive()) {
            response.sendError(HttpServletResponse.SC_REQUEST_TIMEOUT,
                    String.format("Service for user '%s' stop timeout.", user.toString()));
        }
    } catch (InterruptedException ignored) {
    }
}

From source file:pt.webdetails.cpf.SimpleContentGenerator.java

private void handleError(final String methodName, Throwable e) throws IOException {

    logger.error(methodName + ": " + e.getMessage(), e);

    String msg = e.getLocalizedMessage();
    if (e instanceof QueryTimeoutException || e instanceof TimeoutException)
    //          ||
    //          (e instanceof RuntimeException &&
    //              StringUtils.containsIgnoreCase(e.getClass().getName(), "timeout"))) 
    {//from  w  w w. j  av a  2  s.  co m
        getResponse().sendError(HttpServletResponse.SC_REQUEST_TIMEOUT, msg);
    } else {// default to 500
        getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
    }
}

From source file:net.geant.edugain.filter.EduGAINFilter.java

private void fromHome(HttpServletRequest request, HttpServletResponse response) {
    String target = request.getParameter("TARGET");
    AuthenticationResponse eduGAINresponse = null;
    try {/*  ww w  . j a v a2s  . com*/
        eduGAINresponse = getSAMLResponse(request.getParameter("SAMLResponse").getBytes());
    } catch (Exception e) {
        e.printStackTrace();
        try {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unable to parse eduGAIN response");
            return;
        } catch (IOException e1) {
            this.log.error("Invalid eduGAIN response; unable to forward user to error page");
        }
    }

    if ((eduGAINresponse != null)
            && eduGAINresponse.getResult().equals(AuthenticationResponse.EDUGAIN_NAMESPACE_RESULT_ACCEPTED)) {
        try {
            Cookie lcook = getCookie(request, response, "statecook");
            HashMap attrs = validateCookie(lcook, "statecook");
            if ((attrs != null) && (attrs.containsKey("KEY"))) {
                String key = (String) attrs.get("KEY");
                HashMap<String, String> oldRequest = (HashMap<String, String>) this.loadRequest(key);
                String oldURL = reconstructRequest(oldRequest, response);

                attrs = parseAttrs(eduGAINresponse);

                request.getSession().setAttribute("SAMLResponse", eduGAINresponse.toSAML());
                attachCookies("lcook", attrs, response, false);
                attachCookies("statecook", null, response, true);
                //addAttributes(attrs,request.getSession());
                if (!(oldURL.equals("")) && (oldRequest != null) && !(response.isCommitted()))
                    response.sendRedirect(oldURL);
                else
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unable to load old request");

            } else
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Connection timed out");
        } catch (IOException ioe) {
            try {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "State cookie not found");
            } catch (IOException e) {
                this.log.error("State cookie not found");
                ioe.printStackTrace();
            }

        } catch (Exception e) {
            try {
                e.printStackTrace();
                response.sendError(HttpServletResponse.SC_REQUEST_TIMEOUT, "Process timed out");
            } catch (IOException e1) {
                this.log.error("Process timed out");
                e1.printStackTrace();
            }
        }

    } else
        try {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid authentication at home domain");
        } catch (IOException e) {
            this.log.error("Invalid authentication at home domain");
            e.printStackTrace();
        } catch (IllegalStateException ex) {
            this.log.error("Unable to forward user to error page");
            ex.printStackTrace();
        }

}