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:org.jboss.web.tomcat.security.FormAuthenticator.java

/**
 * Authenticate the user making this request, based on the specified
 * login configuration.  Return <code>true</code> if any specified
 * constraint has been satisfied, or <code>false</code> if we have
 * created a response challenge already.
 *
 * @param request Request we are processing
 * @param response Response we are creating
 * @param config    Login configuration describing how authentication
 *              should be performed/*from  w  w  w  .  ja v a2  s .co  m*/
 *
 * @exception IOException if an input/output error occurs
 */
public boolean authenticate(Request request, Response response, LoginConfig config) throws IOException {

    // References to objects we will need later
    Session session = null;

    // Have we already authenticated someone?
    Principal principal = request.getUserPrincipal();
    String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE);
    if (principal != null) {
        if (log.isDebugEnabled())
            log.debug("Already authenticated '" + principal.getName() + "'");
        // Associate the session with any existing SSO session
        if (ssoId != null)
            associate(ssoId, request.getSessionInternal(true));
        return (true);
    }

    // Is there an SSO session against which we can try to reauthenticate?
    if (ssoId != null) {
        if (log.isDebugEnabled())
            log.debug("SSO Id " + ssoId + " set; attempting " + "reauthentication");
        // Try to reauthenticate using data cached by SSO.  If this fails,
        // either the original SSO logon was of DIGEST or SSL (which
        // we can't reauthenticate ourselves because there is no
        // cached username and password), or the realm denied
        // the user's reauthentication for some reason.
        // In either case we have to prompt the user for a logon */
        if (reauthenticateFromSSO(ssoId, request))
            return true;
    }

    // Have we authenticated this user before but have caching disabled?
    if (!cache) {
        session = request.getSessionInternal(true);
        if (log.isDebugEnabled())
            log.debug("Checking for reauthenticate in session " + session);
        String username = (String) session.getNote(Constants.SESS_USERNAME_NOTE);
        String password = (String) session.getNote(Constants.SESS_PASSWORD_NOTE);
        if ((username != null) && (password != null)) {
            if (log.isDebugEnabled())
                log.debug("Reauthenticating username '" + username + "'");
            principal = context.getRealm().authenticate(username, password);
            if (principal != null) {
                session.setNote(Constants.FORM_PRINCIPAL_NOTE, principal);
                if (!matchRequest(request)) {
                    register(request, response, principal, Constants.FORM_METHOD, username, password);
                    return (true);
                }
            }
            if (log.isDebugEnabled())
                log.debug("Reauthentication failed, proceed normally");
        }
    }

    // Is this the re-submit of the original request URI after successful
    // authentication?  If so, forward the *original* request instead.
    if (matchRequest(request)) {
        session = request.getSessionInternal(true);
        if (log.isDebugEnabled())
            log.debug("Restore request from session '" + session.getId() + "'");
        principal = (Principal) session.getNote(Constants.FORM_PRINCIPAL_NOTE);
        register(request, response, principal, Constants.FORM_METHOD,
                (String) session.getNote(Constants.SESS_USERNAME_NOTE),
                (String) session.getNote(Constants.SESS_PASSWORD_NOTE));
        // If we're caching principals we no longer need the username
        // and password in the session, so remove them
        if (cache) {
            session.removeNote(Constants.SESS_USERNAME_NOTE);
            session.removeNote(Constants.SESS_PASSWORD_NOTE);
        }
        if (restoreRequest(request, session)) {
            if (log.isDebugEnabled())
                log.debug("Proceed to restored request");
            return (true);
        } else {
            if (log.isDebugEnabled())
                log.debug("Restore of original request failed");
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return (false);
        }
    }

    // Acquire references to objects we will need to evaluate
    MessageBytes uriMB = MessageBytes.newInstance();
    CharChunk uriCC = uriMB.getCharChunk();
    uriCC.setLimit(-1);
    String contextPath = request.getContextPath();
    String requestURI = request.getDecodedRequestURI();
    response.setContext(request.getContext());

    // Is this the action request from the login page?
    boolean loginAction = requestURI.startsWith(contextPath) && requestURI.endsWith(Constants.FORM_ACTION);

    // No -- Save this request and redirect to the form login page
    if (!loginAction) {
        session = request.getSessionInternal(true);
        if (log.isDebugEnabled())
            log.debug("Save request in session '" + session.getId() + "'");
        saveRequest(request, session);
        forwardToLoginPage(request, response, config);
        return (false);
    }

    // Yes -- Validate the specified credentials and redirect
    // to the error page if they are not correct
    Realm realm = context.getRealm();
    if (characterEncoding != null) {
        request.setCharacterEncoding(characterEncoding);
    }
    String username = request.getParameter(Constants.FORM_USERNAME);
    String password = request.getParameter(Constants.FORM_PASSWORD);
    if (log.isDebugEnabled())
        log.debug("Authenticating username '" + username + "'");
    principal = realm.authenticate(username, password);
    if (principal == null) {
        forwardToErrorPage(request, response, config);
        return (false);
    }

    if (log.isDebugEnabled())
        log.debug("Authentication of '" + username + "' was successful");

    if (session == null)
        session = request.getSessionInternal(false);
    if (session == null) {
        if (containerLog.isDebugEnabled())
            containerLog.debug("User took so long to log on the session expired");
        response.sendError(HttpServletResponse.SC_REQUEST_TIMEOUT,
                sm.getString("authenticator.sessionExpired"));
        return (false);
    }

    // Save the authenticated Principal in our session
    session.setNote(Constants.FORM_PRINCIPAL_NOTE, principal);

    // Save the username and password as well
    session.setNote(Constants.SESS_USERNAME_NOTE, username);
    session.setNote(Constants.SESS_PASSWORD_NOTE, password);

    // Redirect the user to the original request URI (which will cause
    // the original request to be restored)
    requestURI = savedRequestURL(session);
    if (log.isDebugEnabled())
        log.debug("Redirecting to original '" + requestURI + "'");
    if (requestURI == null)
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, sm.getString("authenticator.formlogin"));
    else
        response.sendRedirect(response.encodeRedirectURL(requestURI));
    return (false);

}

From source file:com.funambol.transport.http.server.Sync4jServlet.java

/**
 * Processes the request/* ww  w .ja  va2  s . c  o  m*/
 * @param httpRequest the request
 * @param httpResponse the response
 * @throws javax.servlet.ServletException if an error occurs
 * @throws java.io.IOException if an error occurs
 */
@Override
public void doPost(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse)
        throws ServletException, IOException {

    if (log.isInfoEnabled()) {
        log.info("Handling incoming request");
    }

    String requestURL = getRequestURL(httpRequest);
    String sessionId = getSessionId(httpRequest);
    String requestedSessionId = httpRequest.getRequestedSessionId();
    if (log.isInfoEnabled()) {
        log.info("Request URL: " + requestURL);
        log.info("Requested sessionId: " + requestedSessionId);
    }

    if (log.isTraceEnabled()) {
        showHeaders(httpRequest);
    }

    httpResponse.setHeader(HEADER_X_FUNAMBOL_DS_SERVER, getServerHeader());

    if (httpRequest.getSession().isNew()) {
        httpRequest.getSession().setMaxInactiveInterval(sessionTimeout);
        if (requestedSessionId != null && !requestedSessionId.equals("")) {
            if (!sessionId.equalsIgnoreCase(requestedSessionId)) {
                //
                // The client requires a session that maybe is already expired...
                // returing a 408
                //
                if (log.isInfoEnabled()) {
                    log.info("Session '" + requestedSessionId + "' not found");
                }
                httpResponse.setStatus(HttpServletResponse.SC_REQUEST_TIMEOUT);
                return;
            }
        }
    }

    long requestTime = System.currentTimeMillis();

    //
    // Setting the header 'Set-Cookie' in order to avoid the session tracking
    // using cookies.
    //
    // The web container adds a cookie JSESSIONID in order to
    // track the session, and to do that, it adds (transparently) in the response
    // header:
    // Set-Cookie: JSESSIONID=xxxxxxxxxx
    // In order not to use the cookie, the header "Set-Cookie" is set to an empty value
    // In this way, the session tracking is based on the jsessionid parameter
    // specified in the url (url rewriting).
    // The cookie is dangerous because a client could use:
    // http://xxxxxx:yyy/funambol/ds
    // but with a jsessionid specified as cookie. In this way, the server
    // search a previous session with the same id. And if a previous session
    // was interrupted and not expired, the server reuses this one and this
    // can cause an exception because the client sends the msg 1 and maybe
    // the previous session was in the mapping state.
    //
    // Unfortunatelly on Nokia S60 3Ed feature pack 1, the JAM is not able to
    // handle the response from the server if it contains an empty header Set-Cookie.
    // This means that to make the JAM working, we must avoid:
    //     httpResponse.setHeader("Set-Cookie", "");
    // and add a dummy cookie.
    // In order to do this in a generic way, we avoid empty Set-Cookie if in
    // the request is specified x-funambol-force-cookies header with value
    // 1 or yes or true
    //
    String x_funambol_force_cookies = httpRequest.getHeader(HEADER_X_FUNAMBOL_FORCE_COOKIES);
    if (!getBooleanValue(x_funambol_force_cookies)) {
        httpResponse.setHeader("Set-Cookie", "");
    } else {
        //
        // Setting a dummy cookie
        //
        Cookie cookie = new Cookie("funambol-dummy-cookie", "");
        httpResponse.addCookie(cookie);
    }

    final String contentType = httpRequest.getContentType().split(";")[0];

    final String contentEncoding = (String) httpRequest.getHeader(HEADER_CONTENT_ENCODING);
    final String sizeThreshold = (String) httpRequest.getHeader(HEADER_SIZE_THRESHOLD);

    String acceptEncoding = (String) httpRequest.getHeader(HEADER_ACCEPT_ENCODING);

    if (!enableCompression) {
        //
        // In this way it's like the client doesn't support any encoding
        //
        if (acceptEncoding != null && acceptEncoding.length() != 0) {
            if (log.isTraceEnabled()) {
                log.trace("Forcing no compression (enable-compression is set to false)");
            }
            acceptEncoding = null;
        }
    }

    Map params = getRequestParameters(httpRequest);
    Map headers = getRequestHeaders(httpRequest);

    byte[] requestData = null;
    try {
        requestData = getRequestContent(httpRequest, contentEncoding, requestTime, sessionId);

        if (requestData == null || requestData.length == 0) {
            handleError(httpRequest, httpResponse,
                    "Received empty content. Returning a BAD REQUEST code to the client.", null);
            return;
        }
    } catch (Exception e) {
        handleError(httpRequest, httpResponse, "Error reading the request", e);
        return;
    }

    //
    // If the session id is not specified in the URL, a new remote object
    // will be created. Otherwise the session id specifies which remote
    // object shall handles the request.
    //
    SyncHolder holder = null;

    try {
        holder = createHolder(httpRequest.getSession());

    } catch (Exception e) {
        handleError(httpRequest, httpResponse, "Error creating SyncBean", e);
        return;
    }

    String remoteAddress = httpRequest.getRemoteAddr();
    //
    // We put the remote address in the header map so that we can pass it to
    // the adapted.
    //
    headers.put(HEADER_X_FUNAMBOL_CLIENT_REMOTE_ADDRESS, remoteAddress);

    SyncResponse resp = null;
    try {
        if (com.funambol.framework.core.Constants.MIMETYPE_SYNCMLDS_WBXML.equals(contentType)) {
            resp = holder.processWBXMLMessage(requestURL, requestData, params, headers);
        } else if (com.funambol.framework.core.Constants.MIMETYPE_SYNCMLDS_XML.equals(contentType)) {
            resp = holder.processXMLMessage(requestURL, requestData, params, headers);
        } else {
            throw new ProtocolException("Mime type " + contentType + " not supported or unknown");
        }
    } catch (Exception e) {
        log.error("Error processing the request", e);

        Throwable cause = e.getCause();

        if ((cause != null) && ((cause instanceof ProtocolException) || (cause instanceof Sync4jException))) {

            handleError(httpRequest, httpResponse, "Protocol error", cause);
            return;
        } else {
            throw new ServletException(e);
        }
    }

    httpResponse.setContentType(contentType);
    setResponseContent(httpResponse, acceptEncoding, sizeThreshold, resp, requestTime, sessionId);

    if (log.isInfoEnabled()) {
        log.info("Request processed.");
    }

    //
    // If the message completed the SyncML communication, the session
    // must be closed and discarded.
    //
    if (resp.isCompleted()) {
        httpRequest.setAttribute(ATTRIBUTE_LAST_REQUEST, "true");
        closeSession(httpRequest.getSession());
    }

}

From source file:gov.nih.nci.security.cgmm.authenticators.CaGridFormAuthenticator.java

/**
 * Authenticate the user making this request, based on the specified
 * login configuration.  Return <code>true</code> if any specified
 * constraint has been satisfied, or <code>false</code> if we have
 * created a response challenge already.
 *
 * @param request Request we are processing
 * @param response Response we are creating
 * @param config    Login configuration describing how authentication
 *              should be performed//from  ww  w.  jav  a2s. c  om
 *
 * @exception IOException if an input/output error occurs
 */
public boolean authenticate(Request request, Response response, LoginConfig config) throws IOException {

    // References to objects we will need later
    Session session = null;

    // Have we already authenticated someone?
    Principal principal = request.getUserPrincipal();
    String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE);
    if (principal != null) {
        if (log.isDebugEnabled())
            log.debug("Already authenticated '" + principal.getName() + "'");
        // Associate the session with any existing SSO session
        if (ssoId != null)
            associate(ssoId, request.getSessionInternal(true));
        return (true);
    }

    // Is there an SSO session against which we can try to reauthenticate?
    if (ssoId != null) {
        if (log.isDebugEnabled())
            log.debug("SSO Id " + ssoId + " set; attempting " + "reauthentication");
        // Try to reauthenticate using data cached by SSO.  If this fails,
        // either the original SSO logon was of DIGEST or SSL (which
        // we can't reauthenticate ourselves because there is no
        // cached username and password), or the realm denied
        // the user's reauthentication for some reason.
        // In either case we have to prompt the user for a logon */
        if (reauthenticateFromSSO(ssoId, request))
            return true;
    }

    // Have we authenticated this user before but have caching disabled?
    if (!cache) {
        session = request.getSessionInternal(true);
        if (log.isDebugEnabled())
            log.debug("Checking for reauthenticate in session " + session);
        String username = (String) session.getNote(Constants.SESS_USERNAME_NOTE);
        String password = (String) session.getNote(Constants.SESS_PASSWORD_NOTE);
        if ((username != null) && (password != null)) {
            if (log.isDebugEnabled())
                log.debug("Reauthenticating username '" + username + "'");
            principal = context.getRealm().authenticate(username, password);
            if (principal != null) {
                session.setNote(Constants.FORM_PRINCIPAL_NOTE, principal);
                if (!matchRequest(request)) {
                    register(request, response, principal, Constants.FORM_METHOD, username, password);
                    return (true);
                }
            }
            if (log.isDebugEnabled())
                log.debug("Reauthentication failed, proceed normally");
        }
    }

    // Is this the re-submit of the original request URI after successful
    // authentication?  If so, forward the *original* request instead.
    if (matchRequest(request)) {
        session = request.getSessionInternal(true);
        if (log.isDebugEnabled())
            log.debug("Restore request from session '" + session.getIdInternal() + "'");
        principal = (Principal) session.getNote(Constants.FORM_PRINCIPAL_NOTE);
        register(request, response, principal, Constants.FORM_METHOD,
                (String) session.getNote(Constants.SESS_USERNAME_NOTE),
                (String) session.getNote(Constants.SESS_PASSWORD_NOTE));
        // If we're caching principals we no longer need the username
        // and password in the session, so remove them
        if (cache) {
            session.removeNote(Constants.SESS_USERNAME_NOTE);
            session.removeNote(Constants.SESS_PASSWORD_NOTE);
        }
        if (restoreRequest(request, session)) {
            if (log.isDebugEnabled())
                log.debug("Proceed to restored request");
            return (true);
        } else {
            if (log.isDebugEnabled())
                log.debug("Restore of original request failed");
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return (false);
        }
    }

    // Acquire references to objects we will need to evaluate
    MessageBytes uriMB = MessageBytes.newInstance();
    CharChunk uriCC = uriMB.getCharChunk();
    uriCC.setLimit(-1);
    String contextPath = request.getContextPath();
    String requestURI = request.getDecodedRequestURI();
    response.setContext(request.getContext());

    // Is this the action request from the login page?
    boolean loginAction = requestURI.startsWith(contextPath) && requestURI.endsWith(Constants.FORM_ACTION);

    // No -- Save this request and redirect to the form login page
    if (!loginAction) {
        session = request.getSessionInternal(true);
        if (log.isDebugEnabled())
            log.debug("Save request in session '" + session.getIdInternal() + "'");
        try {
            saveRequest(request, session);
        } catch (IOException ioe) {
            log.debug("Request body too big to save during authentication");
            response.sendError(HttpServletResponse.SC_FORBIDDEN,
                    sm.getString("authenticator.requestBodyTooBig"));
            return (false);
        }

        //Make sure Authentication Source is available.          
        try {
            CGMMManager cgmmManager = new CGMMManagerImpl();
            request.setAttribute("AUTHENTICATION_SOURCE_MAP", cgmmManager.getAuthenticationServiceURLMap());
            if (log.isDebugEnabled())
                log.debug("Successfully retrieved Authentication Source Map from CGMM in session '"
                        + session.getIdInternal() + "'");
        } catch (CGMMConfigurationException e) {
            if (log.isDebugEnabled())
                log.debug("Unable to retrieve Authentication Source Map from CGMM in session '"
                        + session.getIdInternal() + "'");

        }

        forwardToLoginPage(request, response, config);
        return (false);
    }

    // Custom Authenticate for CGMM-caGrid-CSM.

    boolean isPerformDefaultFormAuthentication = false;
    String username = request.getParameter(Constants.FORM_USERNAME);
    String password = request.getParameter(Constants.FORM_PASSWORD);
    String authenticationServiceURL = request.getParameter("authenticationServiceURL");
    if (null == authenticationServiceURL) {
        // AuthenticationServiceURL is not available. 
        // Check if Default Form Authenticator functionality is requested.
        String performDefaultFormAuthentication = request.getParameter("performDefaultFormAuthentication");
        if (null == performDefaultFormAuthentication) {
            isPerformDefaultFormAuthentication = false;
        } else {
            if (performDefaultFormAuthentication.equalsIgnoreCase("YES")) {
                isPerformDefaultFormAuthentication = true;
                if (log.isDebugEnabled())
                    log.debug(
                            "CaGridFormAuthenticator: Default Form Authenticator functionality is requested.");
            }
        }
    } else {
        // Resume caGrid Authentication

    }

    // Authenticate caGrid User
    GlobusCredential gc;

    if (!isPerformDefaultFormAuthentication) {

        try {
            CGMMManager cgmmManager = new CGMMManagerImpl();
            principal = new GenericPrincipal(context.getRealm(), username, password);
            gc = cgmmManager.performGridLogin(username, password, authenticationServiceURL);
            if (log.isDebugEnabled())
                log.debug("CaGridFormAuthenticator: Successfully performed Grid Login ");
        } catch (CGMMConfigurationException e) {
            if (log.isDebugEnabled())
                log.debug("CGMMConfigurationException: " + e.getMessage());
            forwardToErrorPage(request, response, config);
            return (false);
        } catch (CGMMInputException e) {
            if (log.isDebugEnabled())
                log.debug("CGMMInputException: " + e.getMessage());
            forwardToErrorPage(request, response, config);
            return (false);
        } catch (CGMMGridDorianException e) {
            if (log.isDebugEnabled())
                log.debug("CGMMGridDorianException: " + e.getMessage());
            forwardToErrorPage(request, response, config);
            return (false);
        } catch (CGMMGridAuthenticationServiceException e) {
            if (log.isDebugEnabled())
                log.debug("CGMMGridAuthenticationServiceException: " + e.getMessage());
            forwardToErrorPage(request, response, config);
            return (false);
        } catch (CGMMAuthenticationURLException e) {
            if (log.isDebugEnabled())
                log.debug("CGMMAuthenticationURLException: " + e.getMessage());
            forwardToErrorPage(request, response, config);
            return (false);
        }

        if (gc == null) {
            if (log.isDebugEnabled())
                log.debug("Unable to obtain the Grid Credentials. Forwarding to error page.");
            forwardToErrorPage(request, response, config);
            return (false);
        } else {
            // Set the Grid ID as the Username for LoginModule(s).
            username = gc.getIdentity();
        }

    }

    // Yes -- Validate the specified credentials and redirect
    // to the error page if they are not correct
    Realm realm = context.getRealm();

    if (characterEncoding != null) {
        request.setCharacterEncoding(characterEncoding);
    }
    if (log.isDebugEnabled())
        log.debug("Authenticating username '" + username + "'");

    principal = realm.authenticate(username, password);
    if (principal == null) {
        forwardToErrorPage(request, response, config);
        return (false);
    }

    if (log.isDebugEnabled())
        log.debug("Authentication of '" + username + "' was successful");

    if (session == null)
        session = request.getSessionInternal(false);
    if (session == null) {
        if (containerLog.isDebugEnabled())
            containerLog.debug("User took so long to log on the session expired");
        response.sendError(HttpServletResponse.SC_REQUEST_TIMEOUT,
                sm.getString("authenticator.sessionExpired"));
        return (false);
    }

    // Save the authenticated Principal in our session
    session.setNote(Constants.FORM_PRINCIPAL_NOTE, principal);

    // Save the username and password as well
    session.setNote(Constants.SESS_USERNAME_NOTE, username);
    session.setNote(Constants.SESS_PASSWORD_NOTE, password);

    // Redirect the user to the original request URI (which will cause
    // the original request to be restored)
    requestURI = savedRequestURL(session);
    if (log.isDebugEnabled())
        log.debug("Redirecting to original '" + requestURI + "'");
    if (requestURI == null)
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, sm.getString("authenticator.formlogin"));
    else
        response.sendRedirect(response.encodeRedirectURL(requestURI));
    return (false);

}

From source file:com.newatlanta.appengine.datastore.CachingDatastoreService.java

@SuppressWarnings("unchecked")
private static void doWriteBehindTask(HttpServletRequest req, HttpServletResponse res) throws IOException {
    Object payload = null;//from w w  w. j a  v  a 2s .  c  o  m
    try {
        payload = deserialize(req);
        if (payload == null) {
            return;
        }
    } catch (Exception e) {
        log.warning(e.toString());
        return;
    }
    MemcacheService memcache = getMemcacheService();
    List<Key> keys;
    if (payload instanceof Key) {
        keys = new ArrayList<Key>();
        keys.add((Key) payload);
        // delete flag that prevents multiple tasks from being queued
        memcache.delete(keyToString((Key) payload));
    } else if (payload instanceof List) {
        keys = (List) payload;
    } else {
        log.warning(payload.getClass().getName());
        return;
    }
    Map<String, Entity> entityMap = (Map) memcache.getAll((List) keys);
    if ((entityMap != null) && !entityMap.isEmpty()) {
        try {
            if (getDatastoreService().put(entityMap.values()).size() != entityMap.size()) {
                log.info("failed to write all entities - retrying");
                res.sendError(HttpServletResponse.SC_PARTIAL_CONTENT);
            }
        } catch (DatastoreTimeoutException e) { // retry task
            log.info(e.getMessage());
            res.sendError(HttpServletResponse.SC_REQUEST_TIMEOUT);
        } catch (ConcurrentModificationException e) { // retry task
            log.info(e.getMessage());
            res.sendError(HttpServletResponse.SC_CONFLICT);
        } catch (Exception e) { // don't retry
            log.warning(e.toString());
        }
    }
}

From source file:org.protorabbit.servlet.ProtoRabbitServlet.java

void processResourceRequest(String id, WebContext wc, HttpServletRequest req, HttpServletResponse resp,
        boolean canGzip) throws IOException {

    OutputStream out = resp.getOutputStream();
    int lastDot = id.lastIndexOf(".");
    int resourceType = Config.UNKNOWN;
    if (lastDot != -1) {
        String extension = id.substring(lastDot + 1, id.length());
        if ("css".equals(extension)) {
            resourceType = Config.STYLE;
        } else if ("js".equals(extension)) {
            resourceType = Config.SCRIPT;
        }/*from  ww  w . j  a  v a2  s.  c o m*/
        id = id.substring(0, lastDot);
    }

    String resourceId = id;
    String templateId = req.getParameter("tid");
    if (templateId != null) {
        resourceId = templateId + "_" + resourceId;
    }

    boolean shouldGzip = false;
    ITemplate t = null;
    if (templateId != null) {
        t = jcfg.getTemplate(templateId, wc);
        wc.setTemplateId(templateId);
    }

    ResourceManager crm = jcfg.getCombinedResourceManager();
    ICacheable cr = crm.getResource(resourceId, wc);
    boolean requiresUAHandling = false;
    boolean hasUATest = false;
    if (t != null) {
        if (resourceType == Config.SCRIPT) {
            hasUATest = t.hasUserAgentScriptDependencies(wc);
            if (hasUATest) {
                String uaTest = wc.getUAScriptTests().get(0);
                requiresUAHandling = wc.uaTest(uaTest);
            }
        } else if (resourceType == Config.STYLE) {
            hasUATest = t.hasUserAgentStyleDependencies(wc);
            if (hasUATest) {
                String uaTest = wc.getUAStyleTests().get(0);
                requiresUAHandling = wc.uaTest(uaTest);
            }
        }
    }
    // re-constitute the resource. This case will happen across server restarts
    // where a client may have a resource reference with a long cache time
    if ("protorabbit".equals(id)) {
        cr = crm.getResource("protorabbit", wc);
        if (cr == null) {
            StringBuffer buff = IOUtil.getClasspathResource(jcfg, Config.PROTORABBIT_CLIENT);
            if (buff != null) {
                String hash = IOUtil.generateHash(buff.toString());
                cr = new CacheableResource("text/javascript", jcfg.getMaxAge(), hash);
                jcfg.getCombinedResourceManager().putResource("protorabbit", cr);
                cr.setContent(buff);
            } else {
                getLogger().severe("Unable to find protorabbit client script");
            }
        }
    } else if ("episodes".equals(id)) {
        cr = crm.getResource("episodes", wc);
        if (cr == null) {
            StringBuffer buff = IOUtil.getClasspathResource(jcfg, Config.EPISODES_CLIENT);
            if (buff != null) {
                String hash = IOUtil.generateHash(buff.toString());
                cr = new CacheableResource("text/javascript", jcfg.getMaxAge(), hash);
                jcfg.getCombinedResourceManager().putResource("episodes", cr);
                cr.setContent(buff);
            } else {
                getLogger().severe("Unable to find episodes client script");
            }
        }

    } else if (cr == null && t != null && resourceId != null || requiresUAHandling
            || (cr != null && cr.getCacheContext().isExpired())) {
        getLogger().fine("Re-constituting " + id + " from  template " + templateId);

        IProperty property = null;
        if ("styles".equals(id)) {
            List<ResourceURI> styles = t.getAllStyles(wc);
            crm.processStyles(styles, wc, out);
            cr = crm.getResource(resourceId, wc);
        } else if ("scripts".equals(id)) {

            List<ResourceURI> scripts = t.getAllScripts(wc);
            crm.processScripts(scripts, wc, false, out);
            cr = crm.getResource(resourceId, wc);
        } else if ("messages".equals(id)) {
            if (json == null) {
                SerializationFactory factory = new SerializationFactory();
                json = factory.getInstance();
            }
            List<IProperty> deferredProperties = new ArrayList<IProperty>();
            t.getDeferProperties(deferredProperties, wc);
            JSONObject jo = (JSONObject) json.serialize(deferredProperties);
            String content = jo.toString();
            cr = new CacheableResource("application/json", jcfg.getResourceTimeout(), resourceId);
            cr.setContent(new StringBuffer(content));
            crm.putResource(resourceId, cr);
            // assume this is a request for a deferred resource that hasn't been created
        } else {
            if (t != null) {
                property = t.getPropertyById(id, wc);
            }
            if (property == null) {
                getLogger().severe("Unable to find property with id " + id
                        + ((t != null) ? " in template " + t.getId() : " with no template."));
                return;
            }
        }
        // now before we do the work set the cache header
        if (canGzip) {
            if ("scripts".equals(id) && t.gzipScripts(wc) != null && t.gzipScripts(wc) == true) {
                shouldGzip = true;
                resp.setHeader("Content-Type", "text/javascript");
            } else if ("styles".equals(id) && t.gzipStyles(wc) != null && t.gzipStyles(wc) == true) {
                shouldGzip = true;
                resp.setHeader("Content-Type", "text/css");
            } else if (property != null && t.gzipTemplate(wc) != null && t.gzipTemplate(wc) == true) {
                shouldGzip = true;
                resp.setHeader("Content-Type", "text/html");
            }
        }
        // gzip needs to be set before we do anything else given a call to the RequestDispatcher will
        // stop all further headers
        if (shouldGzip) {
            resp.setHeader("Content-Encoding", "gzip");
            resp.setHeader("Vary", "Accept-Encoding");
        }
        if (property != null) {
            StringBuffer buff = null;

            IncludeFile inc = jcfg.getIncludeFileContent(property.getKey(), wc);
            if (inc != null) {
                buff = inc.getContent();
                String hash = IOUtil.generateHash(buff.toString());
                if (property.getId() != null) {
                    resourceId = property.getId();
                } else {
                    resourceId = hash;
                }
                cr = new CacheableResource("text/html", inc.getTimeout(), hash);
                cr.setContent(buff);
                crm.putResource(templateId + "_" + resourceId, cr);
            }
        } else if ("styles".equals(id)) {
            if (cr == null) {
                cr = crm.getResource(resourceId, wc);
            }
        } else if ("scripts".equals(id)) {
            if (cr == null) {
                cr = crm.getResource(resourceId, wc);
            }
        } else if ("messages".equals(id)) {
            if (json == null) {
                SerializationFactory factory = new SerializationFactory();
                json = factory.getInstance();
            }
            List<IProperty> deferredProperties = new ArrayList<IProperty>();
            t.getDeferProperties(deferredProperties, wc);
            JSONObject jo = (JSONObject) json.serialize(deferredProperties);
            String content = jo.toString();
            cr = new CacheableResource("application/json", jcfg.getResourceTimeout(), resourceId);
            cr.setContent(new StringBuffer(content));
            crm.putResource(resourceId, cr);
            // assume this is a request for a deferred resource that hasn't been created
        }
    } else if (cr == null) {
        getLogger().severe("Could not find resource " + id + " with template " + templateId);
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    if (cr != null) {
        CacheContext cc = cr.getCacheContext();

        if (cc.isExpired() || cr.getContent() == null || cr.getStatus() == ICacheable.INITIALIZED) {
            cr.refresh(wc);
        }
        // wait for the resource to load
        int tries = 0;
        while ((cr.getStatus() != 200) && tries < maxTries) {

            try {
                Thread.sleep(tryTimeout);
            } catch (InterruptedException e) {
            }
            tries += 1;
        }
        if (cr.getStatus() != 200) {
            resp.sendError(HttpServletResponse.SC_REQUEST_TIMEOUT);
            return;
        }
        if (cr.getContentType() != null) {
            resp.setContentType(cr.getContentType());
        }

        String etag = cr.getContentHash();
        // get the If-None-Match header
        String ifNoneMatch = req.getHeader("If-None-Match");
        if (etag != null && ifNoneMatch != null && ifNoneMatch.equals(etag)) {

            resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        }
        long timeout = 0;
        if (t != null && t.getTimeout(wc) != null) {
            timeout = t.getTimeout(wc);
        }
        if (etag != null && t != null && timeout > 0 && !jcfg.profile()) {
            resp.setHeader("ETag", etag);
            resp.setHeader("Expires", cc.getExpires());
            resp.setHeader("Cache-Control", "public,max-age=" + cc.getMaxAge());
        }

        if (shouldGzip) {

            byte[] bytes = cr.getGZippedContent();
            cr.incrementGzipAccessCount();
            if (bytes != null) {
                ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
                IOUtil.writeBinaryResource(bis, out);
            }
        } else {
            cr.incrementAccessCount();
            out.write(cr.getContent().toString().getBytes());
        }

    }
    long now = (new Date()).getTime();
    if (now - lastCleanup > cleanupTimeout) {
        getLogger().info("Protorabbit cleaning up old Objects");
        jcfg.getCombinedResourceManager().cleanup(maxAge);
        lastCleanup = now;
    }
}

From source file:org.springframework.extensions.webscripts.connector.RemoteClient.java

/**
 * Service a remote URL and write the the result into an output stream.
 * If an InputStream is provided then a POST will be performed with the content
 * pushed to the url. Otherwise a standard GET will be performed.
 * /*from w w  w.  j ava  2  s .  com*/
 * @param url    The URL to open and retrieve data from
 * @param in     The optional InputStream - if set a POST or similar will be performed
 * @param out    The OutputStream to write result to
 * @param res    Optional HttpServletResponse - to which response headers will be copied - i.e. proxied
 * @param status The status object to apply the response code too
 * 
 * @return encoding specified by the source URL - may be null
 * 
 * @throws IOException
 */
private String service(URL url, InputStream in, OutputStream out, HttpServletRequest req,
        HttpServletResponse res, ResponseStatus status) throws IOException {
    final boolean trace = logger.isTraceEnabled();
    final boolean debug = logger.isDebugEnabled();
    if (debug) {
        logger.debug("Executing " + "(" + requestMethod + ") " + url.toString());
        if (in != null)
            logger.debug(" - InputStream supplied - will push...");
        if (out != null)
            logger.debug(" - OutputStream supplied - will stream response...");
        if (req != null && res != null)
            logger.debug(" - Full Proxy mode between servlet request and response...");
    }

    // aquire and configure the HttpClient
    HttpClient httpClient = createHttpClient(url);

    URL redirectURL = url;
    HttpResponse response;
    HttpRequestBase method = null;
    int retries = 0;
    // Only process redirects if we are not processing a 'push'
    int maxRetries = in == null ? this.maxRedirects : 1;
    try {
        do {
            // Release a previous method that we processed due to a redirect
            if (method != null) {
                method.reset();
                method = null;
            }

            switch (this.requestMethod) {
            default:
            case GET:
                method = new HttpGet(redirectURL.toString());
                break;
            case PUT:
                method = new HttpPut(redirectURL.toString());
                break;
            case POST:
                method = new HttpPost(redirectURL.toString());
                break;
            case DELETE:
                method = new HttpDelete(redirectURL.toString());
                break;
            case HEAD:
                method = new HttpHead(redirectURL.toString());
                break;
            case OPTIONS:
                method = new HttpOptions(redirectURL.toString());
                break;
            }

            // proxy over any headers from the request stream to proxied request
            if (req != null) {
                Enumeration<String> headers = req.getHeaderNames();
                while (headers.hasMoreElements()) {
                    String key = headers.nextElement();
                    if (key != null) {
                        key = key.toLowerCase();
                        if (!this.removeRequestHeaders.contains(key) && !this.requestProperties.containsKey(key)
                                && !this.requestHeaders.containsKey(key)) {
                            method.setHeader(key, req.getHeader(key));
                            if (trace)
                                logger.trace("Proxy request header: " + key + "=" + req.getHeader(key));
                        }
                    }
                }
            }

            // apply request properties, allows for the assignment and override of specific header properties
            // firstly pre-configured headers are applied and overridden/augmented by runtime request properties 
            final Map<String, String> headers = (Map<String, String>) this.requestHeaders.clone();
            headers.putAll(this.requestProperties);
            if (headers.size() != 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    String headerName = entry.getKey();
                    String headerValue = headers.get(headerName);
                    if (headerValue != null) {
                        method.setHeader(headerName, headerValue);
                    }
                    if (trace)
                        logger.trace("Set request header: " + headerName + "=" + headerValue);
                }
            }

            // Apply cookies
            if (this.cookies != null && !this.cookies.isEmpty()) {
                StringBuilder builder = new StringBuilder(128);
                for (Map.Entry<String, String> entry : this.cookies.entrySet()) {
                    if (builder.length() != 0) {
                        builder.append(';');
                    }
                    builder.append(entry.getKey());
                    builder.append('=');
                    builder.append(entry.getValue());
                }

                String cookieString = builder.toString();

                if (debug)
                    logger.debug("Setting Cookie header: " + cookieString);
                method.setHeader(HEADER_COOKIE, cookieString);
            }

            // HTTP basic auth support
            if (this.username != null && this.password != null) {
                String auth = this.username + ':' + this.password;
                method.addHeader("Authorization",
                        "Basic " + Base64.encodeBytes(auth.getBytes(), Base64.DONT_BREAK_LINES));
                if (debug)
                    logger.debug("Applied HTTP Basic Authorization for user: " + this.username);
            }

            // prepare the POST/PUT entity data if input supplied
            if (in != null) {
                method.setHeader(HEADER_CONTENT_TYPE, getRequestContentType());
                if (debug)
                    logger.debug("Set Content-Type=" + getRequestContentType());

                boolean urlencoded = getRequestContentType().startsWith(X_WWW_FORM_URLENCODED);
                if (!urlencoded) {
                    // apply content-length here if known (i.e. from proxied req)
                    // if this is not set, then the content will be buffered in memory
                    long contentLength = -1L;
                    if (req != null) {
                        String contentLengthStr = req.getHeader(HEADER_CONTENT_LENGTH);
                        if (contentLengthStr != null) {
                            try {
                                long actualContentLength = Long.parseLong(contentLengthStr);
                                if (actualContentLength > 0) {
                                    contentLength = actualContentLength;
                                }
                            } catch (NumberFormatException e) {
                                logger.warn("Can't parse 'Content-Length' header from '" + contentLengthStr
                                        + "'. The contentLength is set to -1");
                            }
                        }
                    }

                    if (debug)
                        logger.debug(requestMethod + " entity Content-Length=" + contentLength);

                    // remove the Content-Length header as the setEntity() method will perform this explicitly
                    method.removeHeaders(HEADER_CONTENT_LENGTH);

                    try {
                        // Apache doc for AbstractHttpEntity states:
                        // HttpClient must use chunk coding if the entity content length is unknown (== -1).
                        HttpEntity entity = new InputStreamEntity(in, contentLength);
                        ((HttpEntityEnclosingRequest) method)
                                .setEntity(contentLength == -1L || contentLength > 16384L ? entity
                                        : new BufferedHttpEntity(entity));
                        ((HttpEntityEnclosingRequest) method).setHeader(HTTP.EXPECT_DIRECTIVE,
                                HTTP.EXPECT_CONTINUE);
                    } catch (IOException e) {
                        // During the creation of the BufferedHttpEntity the underlying stream can be closed by the client,
                        // this happens if the request is discarded by the browser - we don't log this IOException as INFO
                        // as that would fill the logs with unhelpful noise - enable DEBUG logging to see these messages.
                        throw new RuntimeException(e.getMessage(), e);
                    }
                } else {
                    if (req != null) {
                        // apply any supplied request parameters
                        Map<String, String[]> postParams = req.getParameterMap();
                        if (postParams != null) {
                            List<NameValuePair> params = new ArrayList<NameValuePair>(postParams.size());
                            for (String key : postParams.keySet()) {
                                String[] values = postParams.get(key);
                                for (int i = 0; i < values.length; i++) {
                                    params.add(new BasicNameValuePair(key, values[i]));
                                }
                            }
                        }
                        // ensure that the Content-Length header is not directly proxied - as the underlying
                        // HttpClient will encode the body as appropriate - cannot assume same as the original client sent
                        method.removeHeaders(HEADER_CONTENT_LENGTH);
                    } else {
                        // Apache doc for AbstractHttpEntity states:
                        // HttpClient must use chunk coding if the entity content length is unknown (== -1).
                        HttpEntity entity = new InputStreamEntity(in, -1L);
                        ((HttpEntityEnclosingRequest) method).setEntity(entity);
                        ((HttpEntityEnclosingRequest) method).setHeader(HTTP.EXPECT_DIRECTIVE,
                                HTTP.EXPECT_CONTINUE);
                    }
                }
            }

            //////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // Execute the method to get the response
            response = httpClient.execute(method);

            redirectURL = processResponse(redirectURL, response);
        } while (redirectURL != null && ++retries < maxRetries);

        // record the status code for the internal response object
        int responseCode = response.getStatusLine().getStatusCode();
        if (responseCode >= HttpServletResponse.SC_INTERNAL_SERVER_ERROR && this.exceptionOnError) {
            buildProxiedServerError(response);
        } else if (responseCode == HttpServletResponse.SC_SERVICE_UNAVAILABLE) {
            // Occurs when server is down and likely an ELB response 
            throw new ConnectException(response.toString());
        }
        boolean allowResponseCommit = (responseCode != HttpServletResponse.SC_UNAUTHORIZED
                || commitResponseOnAuthenticationError);
        status.setCode(responseCode);
        if (debug)
            logger.debug("Response status code: " + responseCode);

        // walk over headers that are returned from the connection
        // if we have a servlet response, push the headers back to the existing response object
        // otherwise, store headers on status
        Header contentType = null;
        Header contentLength = null;
        for (Header header : response.getAllHeaders()) {
            // NOTE: Tomcat does not appear to be obeying the servlet spec here.
            //       If you call setHeader() the spec says it will "clear existing values" - i.e. not
            //       add additional values to existing headers - but for Server and Transfer-Encoding
            //       if we set them, then two values are received in the response...
            // In addition handle the fact that the key can be null.
            final String key = header.getName();
            if (key != null) {
                if (!key.equalsIgnoreCase(HEADER_SERVER) && !key.equalsIgnoreCase(HEADER_TRANSFER_ENCODING)) {
                    if (res != null && allowResponseCommit
                            && !this.removeResponseHeaders.contains(key.toLowerCase())) {
                        res.setHeader(key, header.getValue());
                    }

                    // store headers back onto status
                    status.setHeader(key, header.getValue());

                    if (trace)
                        logger.trace("Response header: " + key + "=" + header.getValue());
                }

                // grab a reference to the the content-type header here if we find it
                if (contentType == null && key.equalsIgnoreCase(HEADER_CONTENT_TYPE)) {
                    contentType = header;
                    // additional optional processing based on the Content-Type header
                    processContentType(url, res, contentType);
                }
                // grab a reference to the Content-Length header here if we find it
                else if (contentLength == null && key.equalsIgnoreCase(HEADER_CONTENT_LENGTH)) {
                    contentLength = header;
                }
            }
        }

        // locate response encoding from the headers
        String encoding = null;
        String ct = null;
        if (contentType != null) {
            ct = contentType.getValue();
            int csi = ct.indexOf(CHARSETEQUALS);
            if (csi != -1) {
                encoding = ct.substring(csi + CHARSETEQUALS.length());
                if ((csi = encoding.lastIndexOf(';')) != -1) {
                    encoding = encoding.substring(0, csi);
                }
                if (debug)
                    logger.debug("Response charset: " + encoding);
            }
        }
        if (debug)
            logger.debug("Response encoding: " + contentType);

        // generate container driven error message response for specific response codes
        if (res != null && responseCode == HttpServletResponse.SC_UNAUTHORIZED && allowResponseCommit) {
            res.sendError(responseCode, response.getStatusLine().getReasonPhrase());
        } else {
            // push status to existing response object if required
            if (res != null && allowResponseCommit) {
                res.setStatus(responseCode);
            }
            // perform the stream write from the response to the output
            int bufferSize = this.bufferSize;
            if (contentLength != null) {
                long length = Long.parseLong(contentLength.getValue());
                if (length < bufferSize) {
                    bufferSize = (int) length;
                }
            }
            copyResponseStreamOutput(url, res, out, response, ct, bufferSize);
        }

        // if we get here call was successful
        return encoding;
    } catch (ConnectTimeoutException | SocketTimeoutException timeErr) {
        // caught a socket timeout IO exception - apply internal error code
        logger.info("Exception calling (" + requestMethod + ") " + url.toString());
        status.setCode(HttpServletResponse.SC_REQUEST_TIMEOUT);
        status.setException(timeErr);
        status.setMessage(timeErr.getMessage());
        if (res != null) {
            //return a Request Timeout error
            res.setStatus(HttpServletResponse.SC_REQUEST_TIMEOUT, timeErr.getMessage());
        }

        throw timeErr;
    } catch (UnknownHostException | ConnectException hostErr) {
        // caught an unknown host IO exception 
        logger.info("Exception calling (" + requestMethod + ") " + url.toString());
        status.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        status.setException(hostErr);
        status.setMessage(hostErr.getMessage());
        if (res != null) {
            // return server error code
            res.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE, hostErr.getMessage());
        }

        throw hostErr;
    } catch (IOException ioErr) {
        // caught a general IO exception - apply generic error code so one gets returned
        logger.info("Exception calling (" + requestMethod + ") " + url.toString());
        status.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        status.setException(ioErr);
        status.setMessage(ioErr.getMessage());
        if (res != null) {
            res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ioErr.getMessage());
        }

        throw ioErr;
    } catch (RuntimeException e) {
        // caught an exception - apply generic error code so one gets returned
        logger.debug("Exception calling (" + requestMethod + ") " + url.toString());
        status.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        status.setException(e);
        status.setMessage(e.getMessage());
        if (res != null) {
            res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }

        throw e;
    } finally {
        // reset state values
        if (method != null) {
            method.releaseConnection();
        }
        setRequestContentType(null);
        this.requestMethod = HttpMethod.GET;
    }
}