Example usage for javax.servlet ServletRequest setAttribute

List of usage examples for javax.servlet ServletRequest setAttribute

Introduction

In this page you can find the example usage for javax.servlet ServletRequest setAttribute.

Prototype

public void setAttribute(String name, Object o);

Source Link

Document

Stores an attribute in this request.

Usage

From source file:org.jsecurity.web.session.DefaultWebSessionManager.java

protected Serializable retrieveSessionId(ServletRequest request, ServletResponse response) {
    WebAttribute<Serializable> cookieSessionIdAttribute = getSessionIdCookieAttribute();
    Serializable id = cookieSessionIdAttribute.retrieveValue(request, response);
    if (id != null) {
        request.setAttribute(JSecurityHttpServletRequest.REFERENCED_SESSION_ID_SOURCE,
                JSecurityHttpServletRequest.COOKIE_SESSION_ID_SOURCE);
    } else {/*from  ww  w . ja v a2  s  .co  m*/
        id = getSessionIdRequestParamAttribute().retrieveValue(request, response);
        if (id != null) {
            request.setAttribute(JSecurityHttpServletRequest.REFERENCED_SESSION_ID_SOURCE,
                    JSecurityHttpServletRequest.URL_SESSION_ID_SOURCE);
        }
    }
    return id;
}

From source file:org.onecmdb.web.acegi.AccessDeniedFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest)) {
        throw new ServletException("HttpServletRequest required");
    }/*  w  ww.j  a v  a 2  s.  com*/

    if (!(response instanceof HttpServletResponse)) {
        throw new ServletException("HttpServletResponse required");
    }

    try {
        request.setAttribute("ACCESS_DENIED", false);

        chain.doFilter(request, response);

        if (logger.isDebugEnabled()) {
            logger.debug("Chain processed normally");
        }
    } catch (AccessDeniedException ex) {
        handleException(request, response, chain, ex);
    } catch (ServletException ex) {

        Throwable rx = getRootCause(ex);
        if (rx instanceof AccessDeniedException) {
            handleException(request, response, chain, (AcegiSecurityException) rx);
        } else {
            throw ex;
        }
    } catch (IOException ex) {
        throw ex;
    }
}

From source file:org.jsecurity.web.session.DefaultWebSessionManager.java

protected Serializable start(ServletRequest request, ServletResponse response, InetAddress inetAddress) {
    Serializable sessionId = super.start(inetAddress);
    storeSessionId(sessionId, request, response);
    request.removeAttribute(JSecurityHttpServletRequest.REFERENCED_SESSION_ID_SOURCE);
    request.setAttribute(JSecurityHttpServletRequest.REFERENCED_SESSION_IS_NEW, Boolean.TRUE);
    return sessionId;
}

From source file:org.sakaiproject.kernel.webapp.filter.SakaiRequestFilter.java

/**
 * {@inheritDoc}// www .j a  va 2s  .  com
 *
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest hrequest = (HttpServletRequest) request;
    String requestedSessionID = hrequest.getRequestedSessionId();
    if (noSession) {
        request.setAttribute(SakaiServletRequest.NO_SESSION_USE, "true");
    }
    SakaiServletRequest wrequest = new SakaiServletRequest(request, response, userResolverService,
            sessionManagerService);
    SakaiServletResponse wresponse = new SakaiServletResponse(response);
    sessionManagerService.bindRequest(wrequest);
    try {
        begin();
        if (timeOn) {
            long start = System.currentTimeMillis();
            try {
                chain.doFilter(wrequest, wresponse);

            } finally {
                long end = System.currentTimeMillis();
                LOG.info("Request took " + hrequest.getMethod() + " " + hrequest.getPathInfo() + " "
                        + (end - start) + " ms");
            }
        } else {
            chain.doFilter(wrequest, wresponse);
        }
        try {
            if (jcrService.hasActiveSession()) {
                Session session = jcrService.getSession();
                session.save();
            }
        } catch (AccessDeniedException e) {
            throw new SecurityException(e.getMessage(), e);
        } catch (Exception e) {
            LOG.warn(e);
        }
        commit();
    } catch (SecurityException se) {
        se.printStackTrace();
        rollback();
        // catch any Security exceptions and send a 401
        wresponse.reset();
        wresponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, se.getMessage());
    } catch (UnauthorizedException ape) {
        rollback();
        // catch any Unauthorized exceptions and send a 401
        wresponse.reset();
        wresponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, ape.getMessage());
    } catch (PermissionDeniedException pde) {
        rollback();
        // catch any permission denied exceptions, and send a 403
        wresponse.reset();
        wresponse.sendError(HttpServletResponse.SC_FORBIDDEN, pde.getMessage());
    } catch (RuntimeException e) {
        rollback();
        throw e;
    } catch (IOException e) {
        rollback();
        throw e;
    } catch (ServletException e) {
        rollback();
        throw e;
    } catch (Throwable t) {
        rollback();
        throw new ServletException(t.getMessage(), t);
    } finally {
        wresponse.commitStatus(sessionManagerService);
        cacheManagerService.unbind(CacheScope.REQUEST);
    }
    if (debug) {
        HttpSession hsession = hrequest.getSession(false);
        if (hsession != null && !hsession.getId().equals(requestedSessionID)) {
            LOG.debug("New Session Created with ID " + hsession.getId());
        }
    }

}

From source file:org.apache.catalina.core.StandardHostValve.java

/**
 * Handle the HTTP status code (and corresponding message) generated
 * while processing the specified Request to produce the specified
 * Response.  Any exceptions that occur during generation of the error
 * report are logged and swallowed./*from  ww  w .ja v a2 s.co  m*/
 *
 * @param request The request being processed
 * @param response The response being generated
 */
protected void status(Request request, Response response) {

    // Do nothing on non-HTTP responses
    if (!(response instanceof HttpResponse))
        return;
    HttpResponse hresponse = (HttpResponse) response;
    if (!(response.getResponse() instanceof HttpServletResponse))
        return;
    int statusCode = hresponse.getStatus();

    // Handle a custom error page for this status code
    Context context = request.getContext();
    if (context == null)
        return;

    ErrorPage errorPage = context.findErrorPage(statusCode);
    if (errorPage != null) {
        response.setAppCommitted(false);
        ServletRequest sreq = request.getRequest();
        ServletResponse sresp = response.getResponse();
        sreq.setAttribute(Globals.STATUS_CODE_ATTR, new Integer(statusCode));
        String message = RequestUtil.filter(hresponse.getMessage());
        if (message == null)
            message = "";
        sreq.setAttribute(Globals.ERROR_MESSAGE_ATTR, message);
        sreq.setAttribute(ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR, errorPage.getLocation());
        sreq.setAttribute(ApplicationFilterFactory.DISPATCHER_TYPE_ATTR,
                new Integer(ApplicationFilterFactory.ERROR));

        Wrapper wrapper = request.getWrapper();
        if (wrapper != null)
            sreq.setAttribute(Globals.SERVLET_NAME_ATTR, wrapper.getName());
        if (sreq instanceof HttpServletRequest)
            sreq.setAttribute(Globals.EXCEPTION_PAGE_ATTR, ((HttpServletRequest) sreq).getRequestURI());
        if (custom(request, response, errorPage)) {
            try {
                sresp.flushBuffer();
            } catch (IOException e) {
                log("Exception Processing " + errorPage, e);
            }
        }
    }

}

From source file:org.springframework.security.web.FilterChainProxy.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    boolean clearContext = request.getAttribute(FILTER_APPLIED) == null;
    if (clearContext) {
        try {//w w w  .  ja  v a2s.  co m
            request.setAttribute(FILTER_APPLIED, Boolean.TRUE);
            doFilterInternal(request, response, chain);
        } finally {
            SecurityContextHolder.clearContext();
            request.removeAttribute(FILTER_APPLIED);
        }
    } else {
        doFilterInternal(request, response, chain);
    }
}

From source file:com.mirantis.cachemod.filter.CacheFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws ServletException, IOException {

    if (request.getAttribute(conf.getAlreadyFilteredKey()) != null || !isCacheable(request)) {

        /*/*from   w  ww.j a  v a  2 s  .  c o m*/
         *  This request is not Cacheable
         */

        chain.doFilter(request, response);
    } else {
        request.setAttribute(conf.getAlreadyFilteredKey(), Boolean.TRUE);

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        boolean fragmentRequest = isFragment(httpRequest);

        String key = conf.getCacheKeyProvider().createKey(httpRequest);

        CacheEntry cacheEntry = conf.getCacheProvider().getEntry(key);
        if (cacheEntry != null) {

            if (!fragmentRequest) {

                /*
                 * -1 of no in header
                 */
                long clientLastModified = httpRequest.getDateHeader("If-Modified-Since");

                /*
                 * Reply with SC_NOT_MODIFIED for client that has newest page 
                 */
                if ((clientLastModified != -1) && (clientLastModified >= cacheEntry.getLastModified())) {
                    ((HttpServletResponse) response).setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    return;
                }
            }

            writeCacheToResponse(cacheEntry, response, fragmentRequest);

        } else {
            cacheEntry = conf.getCacheProvider().instantiateEntry();

            CacheHttpServletResponse cacheResponse = new CacheHttpServletResponse(
                    (HttpServletResponse) response, cacheEntry, conf, fragmentRequest);
            chain.doFilter(request, cacheResponse);

            if (cacheResponse.getStatus() == HttpServletResponse.SC_OK) {
                cacheResponse.commit();
                if (conf.getUserDataProvider() != null) {
                    cacheEntry.setUserData(conf.getUserDataProvider().createUserData(httpRequest));
                }
                conf.getCacheProvider().putEntry(key, cacheEntry);
            }
        }
    }

}

From source file:org.apache.catalina.core.StandardHostValve.java

/**
 * Handle the specified Throwable encountered while processing
 * the specified Request to produce the specified Response.  Any
 * exceptions that occur during generation of the exception report are
 * logged and swallowed./*from w ww.j av  a  2 s. c  om*/
 *
 * @param request The request being processed
 * @param response The response being generated
 * @param exception The exception that occurred (which possibly wraps
 *  a root cause exception
 */
protected void throwable(Request request, Response response, Throwable throwable) {
    Context context = request.getContext();
    if (context == null)
        return;

    Throwable realError = throwable;

    if (realError instanceof ServletException) {
        realError = ((ServletException) realError).getRootCause();
        if (realError == null) {
            realError = throwable;
        }
    }

    // If this is an aborted request from a client just log it and return
    if (realError instanceof ClientAbortException) {
        log.debug(sm.getString("standardHost.clientAbort",
                ((ClientAbortException) realError).getThrowable().getMessage()));
        return;
    }

    ErrorPage errorPage = findErrorPage(context, realError);

    if (errorPage != null) {
        response.setAppCommitted(false);
        ServletRequest sreq = request.getRequest();
        ServletResponse sresp = response.getResponse();
        sreq.setAttribute(ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR, errorPage.getLocation());
        sreq.setAttribute(ApplicationFilterFactory.DISPATCHER_TYPE_ATTR,
                new Integer(ApplicationFilterFactory.ERROR));
        sreq.setAttribute(Globals.STATUS_CODE_ATTR, new Integer(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
        sreq.setAttribute(Globals.ERROR_MESSAGE_ATTR, throwable.getMessage());
        sreq.setAttribute(Globals.EXCEPTION_ATTR, realError);
        Wrapper wrapper = request.getWrapper();
        if (wrapper != null)
            sreq.setAttribute(Globals.SERVLET_NAME_ATTR, wrapper.getName());
        if (sreq instanceof HttpServletRequest)
            sreq.setAttribute(Globals.EXCEPTION_PAGE_ATTR, ((HttpServletRequest) sreq).getRequestURI());
        sreq.setAttribute(Globals.EXCEPTION_TYPE_ATTR, realError.getClass());
        if (custom(request, response, errorPage)) {
            try {
                sresp.flushBuffer();
            } catch (IOException e) {
                log("Exception Processing " + errorPage, e);
            }
        }
    } else {
        // A custom error-page has not been defined for the exception
        // that was thrown during request processing. Check if an
        // error-page for error code 500 was specified and if so, 
        // send that page back as the response.
        ServletResponse sresp = (ServletResponse) response;
        if (sresp instanceof HttpServletResponse) {
            ((HttpServletResponse) sresp).setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            // The response is an error
            response.setError();

            status(request, response);
        }
    }

}

From source file:com.day.cq.wcm.foundation.forms.FormsHelper.java

/**
 * Sets the Sling POST serlvet's ":redirect" parameter dynamically during
 * the form POST execution, when//www  .jav a  2s. c o  m
 * {@link #setForwardPath(SlingHttpServletRequest, String)} is used.
 * 
 * @since 5.5
 * 
 * @param request
 *            the current request
 * @param redirect
 *            a redirect path/url
 */
public static void setForwardRedirect(final ServletRequest request, String redirect) {
    request.setAttribute(REQ_ATTR_REDIRECT, redirect);
}

From source file:edu.emory.cci.aiw.cvrg.eureka.servlet.filter.UserInfoFilter.java

@Override
public void doFilter(ServletRequest inRequest, ServletResponse inResponse, FilterChain inFilterChain)
        throws IOException, ServletException {
    HttpServletRequest servletRequest = (HttpServletRequest) inRequest;
    String remoteUser = servletRequest.getRemoteUser();
    boolean userIsActivated = false;
    if (!StringUtils.isEmpty(remoteUser)) {
        User user = (User) inRequest.getAttribute("user");
        if (user != null && user.isActive()) {
            userIsActivated = true;/*from   ww w  . j  a  va  2 s . co  m*/
        }
    }

    inRequest.setAttribute("userIsActivated", userIsActivated);
    inFilterChain.doFilter(inRequest, inResponse);
}