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.onecmdb.web.acegi.AccessDeniedFilter.java

private void handleException(ServletRequest request, ServletResponse response, FilterChain chain,
        AcegiSecurityException exception) throws IOException, ServletException {
    if (exception instanceof AccessDeniedException) {
        if (logger.isDebugEnabled()) {
            logger.debug("Access is denied; delegating to AccessDeniedHandler", exception);
        }//w  w  w .  ja  va2 s.c om

        request.setAttribute("ACCESS_DENIED", true);

        accessDeniedHandler.handle(request, response, (AccessDeniedException) exception);
    }
}

From source file:org.seasar.s2click.servlet.S2ClickServlet.java

/**
 * HOT deploy????Click Framework?????/*from  w ww. jav  a2 s .  c om*/
 */
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {

    String hotDeployInitStatus = (String) req.getAttribute(UrlPatternFilter.HOTDEPLOY_INIT_KEY);

    if (initialized == false && !"initialized".equals(hotDeployInitStatus)) {
        super.init();
        req.setAttribute(UrlPatternFilter.HOTDEPLOY_INIT_KEY, "initialized");

        if ("initialize".equals(hotDeployInitStatus)) {
            return;
        }
    }

    super.service(new S2ClickRequestWrapper((HttpServletRequest) req), res);
}

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

protected Session doGetSession(ServletRequest request, ServletResponse response) {

    Session session = null;/*from  w ww . j a v a2  s.  c  o  m*/
    Serializable sessionId = retrieveSessionId(request, response);

    if (sessionId != null) {
        request.setAttribute(JSecurityHttpServletRequest.REFERENCED_SESSION_ID, sessionId);
        session = super.retrieveSession(sessionId);
        if (isValidateRequestOrigin()) {
            if (log.isDebugEnabled()) {
                log.debug("Validating request origin against session origin");
            }
            validateSessionOrigin(request, session);
        }
        if (session != null) {
            request.setAttribute(JSecurityHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
        }
    } else {
        if (log.isTraceEnabled()) {
            log.trace("No JSecurity session id associated with the given "
                    + "HttpServletRequest.  A Session will not be returned.");
        }
    }

    return session;
}

From source file:org.b3log.solo.filter.PageCacheFilter.java

/**
 * Try to write response from cache./*from   w ww  . j  a  v a 2s. c om*/
 *
 * @param request the specified request
 * @param response the specified response
 * @param chain filter chain
 * @throws IOException io exception
 * @throws ServletException servlet exception
 */
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    final long startTimeMillis = System.currentTimeMillis();
    request.setAttribute(Keys.HttpRequest.START_TIME_MILLIS, startTimeMillis);

    final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    final String requestURI = httpServletRequest.getRequestURI();
    LOGGER.log(Level.FINER, "Request URI[{0}]", requestURI);

    if (StaticResources.isStatic(httpServletRequest)) {
        final String path = httpServletRequest.getServletPath() + httpServletRequest.getPathInfo();
        LOGGER.log(Level.FINEST, "Requests a static resource, forwards to servlet[path={0}]", path);
        request.getRequestDispatcher(path).forward(request, response);

        return;
    }

    if (!Latkes.isPageCacheEnabled()) {
        LOGGER.log(Level.FINEST, "Page cache is disabled");
        chain.doFilter(request, response);

        return;
    }

    final String skinDirName = (String) httpServletRequest.getAttribute(Keys.TEMAPLTE_DIR_NAME);
    if ("mobile".equals(skinDirName)) {
        // Mobile request, bypasses page caching
        chain.doFilter(request, response);

        return;
    }

    String pageCacheKey;
    final String queryString = httpServletRequest.getQueryString();
    pageCacheKey = (String) request.getAttribute(Keys.PAGE_CACHE_KEY);
    if (Strings.isEmptyOrNull(pageCacheKey)) {
        pageCacheKey = PageCaches.getPageCacheKey(requestURI, queryString);
        request.setAttribute(Keys.PAGE_CACHE_KEY, pageCacheKey);
    }

    final JSONObject cachedPageContentObject = PageCaches.get(pageCacheKey, httpServletRequest,
            (HttpServletResponse) response);

    if (null == cachedPageContentObject) {
        LOGGER.log(Level.FINER, "Page cache miss for request URI[{0}]", requestURI);
        chain.doFilter(request, response);

        return;
    }

    final String cachedType = cachedPageContentObject.optString(PageCaches.CACHED_TYPE);

    try {
        // If cached an article that has view password, dispatches the password form
        if (langPropsService.get(PageTypes.ARTICLE.getLangeLabel()).equals(cachedType)
                && cachedPageContentObject.has(PageCaches.CACHED_PWD)) {
            JSONObject article = new JSONObject();

            final String articleId = cachedPageContentObject.optString(PageCaches.CACHED_OID);

            article.put(Keys.OBJECT_ID, articleId);
            article.put(Article.ARTICLE_VIEW_PWD, cachedPageContentObject.optString(PageCaches.CACHED_PWD));

            if (articles.needViewPwd(httpServletRequest, article)) {
                article = articleRepository.get(articleId); // Loads the article entity

                final HttpServletResponse httpServletResponse = (HttpServletResponse) response;
                try {
                    httpServletResponse.sendRedirect(Latkes.getServePath() + "/console/article-pwd"
                            + articles.buildArticleViewPwdFormParameters(article));
                    return;
                } catch (final Exception e) {
                    httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
                    return;
                }
            }
        }
    } catch (final Exception e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        chain.doFilter(request, response);
    }

    try {
        LOGGER.log(Level.FINEST, "Writes resposne for page[pageCacheKey={0}] from cache", pageCacheKey);
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        final PrintWriter writer = response.getWriter();
        String cachedPageContent = cachedPageContentObject.getString(PageCaches.CACHED_CONTENT);
        final String topBarHTML = TopBars.getTopBarHTML((HttpServletRequest) request,
                (HttpServletResponse) response);
        cachedPageContent = cachedPageContent.replace(Common.TOP_BAR_REPLACEMENT_FLAG, topBarHTML);

        final String cachedTitle = cachedPageContentObject.getString(PageCaches.CACHED_TITLE);
        LOGGER.log(Level.FINEST, "Cached value[key={0}, type={1}, title={2}]",
                new Object[] { pageCacheKey, cachedType, cachedTitle });

        statistics.incBlogViewCount((HttpServletRequest) request, (HttpServletResponse) response);

        final long endimeMillis = System.currentTimeMillis();
        final String dateString = DateFormatUtils.format(endimeMillis, "yyyy/MM/dd HH:mm:ss");
        final String msg = String.format("<!-- Cached by B3log Solo(%1$d ms), %2$s -->",
                endimeMillis - startTimeMillis, dateString);
        LOGGER.finer(msg);
        cachedPageContent += Strings.LINE_SEPARATOR + msg;
        writer.write(cachedPageContent);
        writer.flush();
        writer.close();
    } catch (final JSONException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        chain.doFilter(request, response);
    } catch (final RepositoryException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        chain.doFilter(request, response);
    } catch (final ServiceException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        chain.doFilter(request, response);
    }
}

From source file:org.beanfuse.security.monitor.SecurityFilter.java

/**
 * /*from   w  w  w. ja  v a2s  .  c om*/
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = ((HttpServletRequest) request);
    String resource = resourceExtractor.extract(httpRequest);
    request.setAttribute("resourceName", resource);
    HttpSession session = httpRequest.getSession(true);
    if (null == monitor) {
        WebApplicationContext wac = WebApplicationContextUtils
                .getRequiredWebApplicationContext(session.getServletContext());
        monitor = (SecurityMonitor) wac.getBean("securityMonitor", SecurityMonitor.class);
    }
    // ??login??
    if (!freeResources.contains(resource) && !monitor.isPublicResource(resource)) {
        OnlineActivity info = monitor.getSessionController().getOnlineActivity(session.getId());
        if (info != null && null != httpRequest.getRemoteUser()
                && !info.getPrincipal().equals(httpRequest.getRemoteUser())) {
            info = null;
        }
        if (null == info) {
            Authentication auth = null;
            // remember me
            if (monitor.enableRememberMe()) {
                auth = monitor.getRememberMeService().autoLogin(httpRequest);
            }
            if (null == auth) {
                auth = new SsoAuthentication(httpRequest);
                auth.setDetails(monitor.getUserDetailsSource().buildDetails(httpRequest));
            }
            try {
                monitor.authenticate(auth);
            } catch (AuthenticationException e) {
                // URL
                session.setAttribute(PREVIOUS_URL,
                        httpRequest.getRequestURL() + "?" + httpRequest.getQueryString());
                redirectTo((HttpServletRequest) request, (HttpServletResponse) response, loginFailPath);
                return;
            }
        } else if (info.isExpired()) {
            monitor.logout(session);
            // URL
            session.setAttribute(PREVIOUS_URL,
                    httpRequest.getRequestURL() + "?" + httpRequest.getQueryString());
            redirectTo((HttpServletRequest) request, (HttpServletResponse) response, expiredPath);
            return;
        } else {
            info.refreshLastRequest();
            boolean pass = monitor.isAuthorized(info.getUserid(), resource);
            if (pass) {
                logger.debug("user {} access {} success", info.getPrincipal(), resource);
            } else {
                logger.info("user {} cannot access resource[{}]", info.getPrincipal(), resource);
                redirectTo((HttpServletRequest) request, (HttpServletResponse) response, noAuthorityPath);
                return;
            }
        }
    } else {
        logger.debug("free or public resource {} was accessed", resource);
    }
    chain.doFilter(request, response);
}

From source file:jp.terasoluna.fw.web.thin.ExtensionFilter.java

/**
 * gq`FbN?s?B//from   w  w w  . j  a v a 2  s . c  o m
 *
 * @param req HTTPNGXg
 * @param res HTTPX|X
 * @param chain tB^`F?[
 * 
 * @throws IOException I/OG?[
 * @throws ServletException T?[ubgO
 * 
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    //NGXgtB^?B
    if (req.getAttribute(EXTENSION_THRU_KEY) == null) {

        //tB^?Zbg
        req.setAttribute(EXTENSION_THRU_KEY, "true");

        //NGXgpXgq`FbN?spXXg
        //v?????I
        String pathInfo = RequestUtil.getPathInfo(req);
        if (pathInfo != null && !restrictionEscapePaths.contains(pathInfo)) {

            //gq`FbN?s
            //NGXgpXgq?B
            String extension = StringUtil.getExtension(pathInfo);
            if (prohibitedExtensionList.contains(extension)) {

                if (log.isDebugEnabled()) {
                    log.debug("requestURI[" + pathInfo + "] has prohibited extension");
                }

                // HTTPG?[404
                ((HttpServletResponse) res).sendError(HttpServletResponse.SC_NOT_FOUND);
                return; // ?~?s
            }
        }
    }

    // tB^T?[ubg
    chain.doFilter(req, res);
}

From source file:com.redhat.rhn.frontend.struts.RhnUnpagedListAction.java

/**
 * Sets up the ListControl filter data//from   ww w  . j  a  va 2 s .c  o  m
 * @param lc ListControl to use
 * @param request ServletRequest
 * @param viewer user requesting the page
 */
public void filterList(ListControl lc, ServletRequest request, User viewer) {
    /*
     * Make sure we have a user. If not, something bad happened and we should
     * just bail out with an exception. Since this is probably the result of
     * a bad uid param, throw a BadParameterException.
     */
    if (viewer == null) {
        throw new BadParameterException("Null viewer");
    }

    String filterData = request.getParameter(RequestContext.FILTER_STRING);
    request.setAttribute("isFiltered", Boolean.valueOf(!StringUtils.isEmpty(filterData)));
    if (!StringUtils.isBlank(filterData)) {
        HttpServletRequest req = (HttpServletRequest) request;
        createSuccessMessage(req, "filter.clearfilter", req.getRequestURI());
    }

    lc.setFilterData(filterData);
}

From source file:jp.terasoluna.fw.web.thin.ServerBlockageControlFilter.java

/**
 * T?[o?`FbN?s?B/*from w w  w.j  a va  2  s.c om*/
 * 
 * @param req
 *            HTTPNGXg
 * @param res
 *            HTTPX|X
 * @param chain
 *            tB^`F?[
 * @throws IOException
 *             I/OG?[
 * @throws ServletException
 *             T?[ubgO
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *                                    javax.servlet.ServletResponse,
 *                                    javax.servlet.FilterChain)
 */
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    // NGXgtB^?B
    if (req.getAttribute(SERVER_BLOCKAGE_THRU_KEY) == null) {

        // tB^?Zbg
        req.setAttribute(SERVER_BLOCKAGE_THRU_KEY, "true");

        // T?[o?`FbN
        if (controller.isBlockaded(RequestUtil.getPathInfo(req))) {
            if (log.isDebugEnabled()) {
                log.debug("isBlockaded() failed.");
            }
            throw new ServerBlockageException();
        }
    }

    // tB^T?[ubg
    chain.doFilter(req, res);
}

From source file:org.ops4j.gaderian.servlet.GaderianFilter.java

/**
 * Passes the request to the filter chain, but then invokes {@link Registry#cleanupThread()}
 * &nbsp; (from a finally block).//w w  w . ja va  2 s .co m
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    try {
        // I believe the _registry will only be null in a couple of test situations.

        if (_registry != null)
            _registry.setupThread();

        request.setAttribute(REQUEST_KEY, _registry);

        chain.doFilter(request, response);
    } finally {
        cleanupThread();

        checkRegistryRebuild(request);
    }
}

From source file:com.ace.erp.filter.user.SysUserFilter.java

@Override
protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
    Subject subject = getSubject(request, response);
    if (subject == null) {
        return true;
    }/* www .  j a  va 2 s  .  co  m*/

    String username = (String) subject.getPrincipal();
    //? ?db
    User user = userService.getUserByName(username);
    //?session
    request.setAttribute(Constants.CURRENT_USER, user);
    //druid?
    //((HttpServletRequest)request).getSession().setAttribute(Constants.CURRENT_USERNAME, username);

    return true;
}