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.jahia.bundles.extender.jahiamodules.JspServletWrapper.java

@Override
public void service(final ServletRequest req, final ServletResponse res) throws ServletException, IOException {
    String jspPath = getJspFilePath(req);
    if (jspPath != null) {
        req.setAttribute(Constants.JSP_FILE, jspPath);
    }/*  ww w .  j  a va2 s.  c om*/

    Object currentLocaleResolver = req.getAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE);
    req.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, new LocaleResolver() {

        @Override
        public Locale resolveLocale(HttpServletRequest request) {
            HttpSession session = request.getSession();
            if (session != null) {
                Locale currentLocale = (Locale) session.getAttribute(org.jahia.api.Constants.SESSION_LOCALE);
                if (currentLocale != null) {
                    return currentLocale;
                }
            }
            return request.getLocale();
        }

        @Override
        public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
        }
    });

    // Prepare attributes for subsequent includes
    String p = (String) req.getAttribute("javax.servlet.include.servlet_path")
            + (String) req.getAttribute("javax.servlet.include.path_info");
    req.setAttribute("javax.servlet.include.path_info", null);
    req.setAttribute("javax.servlet.include.servlet_path", p);

    try {
        ContextClassLoaderUtils.doWithClassLoader(urlClassLoader, new Callable<Void>() {
            public Void call() throws Exception {
                jspServlet.service(req, res);
                return null;
            }
        });
    } catch (Exception e) {
        throw new ServletException("Error during servlet servicing", e);
    }
    req.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, currentLocaleResolver);
}

From source file:org.etudes.jforum.util.legacy.clickstream.ClickstreamFilter.java

/**
 * Processes the given request and/or response.
 * /*from w ww.  ja  va 2s. c o  m*/
 * @param request The request
 * @param response The response
 * @param chain The processing chain
 * @throws IOException If an error occurs
 * @throws ServletException If an error occurs
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    // Ensure that filter is only applied once per request.
    if (request.getAttribute(FILTER_APPLIED) == null) {
        request.setAttribute(FILTER_APPLIED, Boolean.TRUE);

        String bot = BotChecker.isBot((HttpServletRequest) request);

        if (bot != null && log.isInfoEnabled()) {
            log.info("Found a bot: " + bot);
        }

        request.setAttribute(ConfigKeys.IS_BOT, new Boolean(bot != null));
    }

    // Pass the request on
    chain.doFilter(request, response);
}

From source file:org.apache.tapestry.jsp.URLRetriever.java

/**
 *  Invokes the servlet to retrieve the URL.  The URL is inserted
 *  into the output (as with//ww  w . j av a 2s . com
 *  {@link RequestDispatcher#include(javax.servlet.ServletRequest, javax.servlet.ServletResponse)}). 
 * 
 *
 **/

public void insertURL(String servletPath) throws JspException {
    if (LOG.isDebugEnabled())
        LOG.debug("Obtaining Tapestry URL for service " + _serviceName + " at " + servletPath);

    ServletRequest request = _pageContext.getRequest();

    RequestDispatcher dispatcher = request.getRequestDispatcher(servletPath);

    if (dispatcher == null)
        throw new JspException(Tapestry.format("URLRetriever.unable-to-find-dispatcher", servletPath));

    request.setAttribute(Tapestry.TAG_SUPPORT_SERVICE_ATTRIBUTE, _serviceName);
    request.setAttribute(Tapestry.TAG_SUPPORT_PARAMETERS_ATTRIBUTE, _serviceParameters);
    request.setAttribute(Tapestry.TAG_SUPPORT_SERVLET_PATH_ATTRIBUTE, servletPath);

    try {
        _pageContext.getOut().flush();

        dispatcher.include(request, _pageContext.getResponse());
    } catch (IOException ex) {
        throw new JspException(Tapestry.format("URLRetriever.io-exception", servletPath, ex.getMessage()));
    } catch (ServletException ex) {
        throw new JspException(Tapestry.format("URLRetriever.servlet-exception", servletPath, ex.getMessage()));
    } finally {
        request.removeAttribute(Tapestry.TAG_SUPPORT_SERVICE_ATTRIBUTE);
        request.removeAttribute(Tapestry.TAG_SUPPORT_PARAMETERS_ATTRIBUTE);
        request.removeAttribute(Tapestry.TAG_SUPPORT_SERVLET_PATH_ATTRIBUTE);
    }

}

From source file:org.infoscoop.admin.web.PreviewImpersonationFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    request.setAttribute(IS_PREVIEW, Boolean.TRUE);

    Subject previewUser = new Subject();

    List<String> principals = new ArrayList<String>();

    String uidParam = request.getParameter(ISPrincipal.UID_PRINCIPAL);
    if (uidParam != null) {
        principals.add(ISPrincipal.UID_PRINCIPAL);
        principals.add(uidParam);//from   w  ww  . ja va2  s. c om
        previewUser.getPrincipals().add(new ISPrincipal(ISPrincipal.UID_PRINCIPAL, uidParam));
    }
    for (PrincipalDef def : SessionCreateConfig.getInstance().getPrincipalDefs()) {
        String[] principalValues = request.getParameterValues(def.getType());
        if (principalValues != null) {
            for (int i = 0; i < principalValues.length; i++) {
                if (log.isInfoEnabled())
                    log.info("Set preview principal: PrincipalType=" + def.getType() + ", name="
                            + principalValues[i] + ".");

                principals.add(def.getType());
                principals.add(principalValues[i]);
                previewUser.getPrincipals().add(new ISPrincipal(def.getType(), principalValues[i]));
            }
        }
    }

    // Principal retrieved from AccountManager set AuthenticationService
    AuthenticationService service = AuthenticationService.getInstance();
    IAccountManager manager = null;
    if (service != null)
        manager = service.getAccountManager();
    if (manager != null) {
        for (PrincipalDef def : manager.getPrincipalDefs()) {
            String roleType = def.getType();
            String[] principalValues = request.getParameterValues(roleType);

            for (int i = 0; principalValues != null && i < principalValues.length; i++) {
                if (log.isInfoEnabled())
                    log.info("Set preview principal: PrincipalType=" + roleType + ", name=" + principalValues[i]
                            + ".");
                principals.add(def.getType());
                principals.add(principalValues[i]);
                previewUser.getPrincipals().add(new ISPrincipal(roleType, principalValues[i]));
            }
        }
    }

    request.setAttribute(PRINCIPAL_PARAMS, principals);

    SetPrincipalHttpServletRequest reqwrapper = new SetPrincipalHttpServletRequest((HttpServletRequest) request,
            previewUser);
    filterChain.doFilter(reqwrapper, response);
}

From source file:org.seasar.teeda.extension.filter.MultipartFormDataFilter.java

public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    if (request.getAttribute(DOFILTER_CALLED) != null) {
        chain.doFilter(request, response);
        return;//from w  w  w .j a va  2 s . c  o m
    }
    request.setAttribute(DOFILTER_CALLED, "true");

    if (!(response instanceof HttpServletResponse)) {
        chain.doFilter(request, response);
        return;
    }

    final HttpServletRequest httpRequest = (HttpServletRequest) request;
    if (!ServletFileUpload.isMultipartContent(httpRequest)) {
        chain.doFilter(request, response);
        return;
    }

    final HttpServletRequest multipartRequest = new MultipartFormDataRequestWrapper(httpRequest, maxSize,
            maxFileSize, thresholdSize, repositoryPath);
    chain.doFilter(multipartRequest, response);
}

From source file:eu.openanalytics.rpooli.web.BaseUriInjectionFilter.java

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    final HttpServletRequest req = (HttpServletRequest) request;
    final String baseUri = StringUtils.replace(req.getRequestURL().toString(), req.getRequestURI(),
            req.getContextPath());//from w  w  w . j a  v a 2 s .c o  m
    request.setAttribute("baseUri", baseUri);

    chain.doFilter(request, response);
}

From source file:org.osaf.cosmo.filters.UsernameRequestIntegrationFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    try {/*from   ww  w  .  j  av  a  2s .  c o m*/
        String principal = securityManager.getSecurityContext().getName();
        if (securityManager.getSecurityContext().getTicket() != null)
            principal = "ticket:" + principal;
        request.setAttribute(USERNAME_ATTRIBUTE_KEY, principal);
    } catch (CosmoSecurityException e) {
        request.setAttribute(USERNAME_ATTRIBUTE_KEY, "-");
    }

    chain.doFilter(request, response);
}

From source file:com.easyshop.common.web.filter.SetCommonDataFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    ///*www  . j av a  2s. c o  m*/
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    if (request.getAttribute(Constants.CONTEXT_PATH) == null) {
        request.setAttribute(Constants.CONTEXT_PATH, httpServletRequest.getContextPath());
    }
    if (request.getAttribute(Constants.WEB_BASE) == null) {
        request.setAttribute(Constants.WEB_BASE, webBase);
    }

    //?
    String currentPageStr = request.getParameter(currentPageParamKey);
    if (StringUtils.isNotBlank(currentPageStr)) {
        try {
            Integer currentPage = Integer.valueOf(currentPageStr);
            PageContext.setCurrentPage(currentPage);
        } catch (NumberFormatException e) {
            //e.printStackTrace();
            LOGGER.warn(
                    "?'currentPage'?,???,?{}",
                    currentPageStr);
        }
    }

    String pageSizeStr = request.getParameter(pageSizeParamKey);
    if (StringUtils.isNotBlank(pageSizeStr)) {
        try {
            Integer pageSize = Integer.valueOf(pageSizeStr);
            PageContext.setPageSize(pageSize);
        } catch (NumberFormatException e) {
            //e.printStackTrace();
            LOGGER.warn(
                    "?'pageSize'?,???,?{}",
                    pageSizeStr);
        }
    }

    try {
        chain.doFilter(request, response);
    } finally {
        PageContext.clear();
    }
}

From source file:no.kantega.publishing.admin.content.InputScreenRenderer.java

public void renderNormalAttribute(JspWriter out, ServletRequest request,
        Map<String, List<ValidationError>> fieldErrors, Attribute attr) throws IOException {
    request.setAttribute("attribute", attr);
    request.setAttribute("fieldName", AttributeHelper.getInputFieldName(attr.getNameIncludingPath()));

    try {//  w  ww.  j  a  v a 2s.co m
        out.print("\n<div class=\"contentAttribute");

        if (fieldErrors.get(attr.getName()) != null) {
            out.print(" error");
        }

        if (attributeIsHiddenEmpty(attr)) {
            this.hiddenAttributes = true;
            out.print(" attributeHiddenEmpty");
        }

        out.print("\" id=\"" + AttributeHelper.getInputContainerName(attr.getNameIncludingPath())
                + "\" data-title=\"" + attr.getTitle() + "\">\n");

        out.print("<div class=\"heading\">" + attr.getTitle());
        if (attr.isMandatory()) {
            out.print("<span class=\"mandatory\">*</span>");
        }
        out.print("</div>");
        String helptext = attr.getHelpText();
        if (helptext != null && helptext.length() > 0) {
            out.print("<div class=\"ui-state-highlight\">" + helptext + "</div>\n");
        }
        String script = attr.getScript();
        if (script != null && script.length() > 0) {
            out.print("<script type=\"text/javascript\">\n" + script + "\n</script>\n");
        }
        if (attr.inheritsFromAncestors()) {
            String inheritText = LocaleLabels.getLabel("aksess.editcontent.inheritsfromancestors",
                    Aksess.getDefaultAdminLocale());
            out.print("<div class=\"ui-state-highlight\">" + inheritText + "</div>\n");
        }
        pageContext.include("/admin/publish/attributes/" + attr.getRenderer() + ".jsp");
        out.print("\n");
        out.print("</div>\n");
    } catch (Exception e) {
        out.print("</div>\n");
        log.error("", e);
        String errorMessage = LocaleLabels.getLabel("aksess.editcontent.exception",
                Aksess.getDefaultAdminLocale());
        out.print("<div class=\"errorText\">" + errorMessage + ":" + attr.getTitle() + "</div>\n");
    }
}

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

/**
 * GrfX?O?o?B//from   w ww . j ava  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(EVIDENCELOG_THRU_KEY) == null) {

        req.setAttribute(EVIDENCELOG_THRU_KEY, "true");

        evidenceLog("--------------------------------------------");

        // NGXgURI?o
        evidenceLog("RequestURI = " + ((HttpServletRequest) req).getRequestURI());

        // p??[^?o
        evidenceLog("Parameters = {");
        Map paramMap = ((HttpServletRequest) req).getParameterMap();
        Iterator iter = paramMap.keySet().iterator();
        while (iter.hasNext()) {
            String key = (String) iter.next();
            Object value = paramMap.get(key);
            if (value == null) {
                evidenceLog("  " + key + " = null");
            } else if (value.getClass().isArray()) {
                Object[] values = (Object[]) value;
                for (int i = 0; i < values.length; i++) {
                    String valueView = "null";
                    if (values[i] != null) {
                        valueView = values[i].toString();
                    }
                    evidenceLog("  " + key + "[" + i + "] = " + valueView);
                }
            } else {
                evidenceLog("  " + key + " = " + value.toString());
            }
        }
        evidenceLog("}");

        evidenceLog("--------------------------------------------");

    }

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