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.servlet.OncePerRequestFilter.java

/**
 * This <code>doFilter</code> implementation stores a request attribute for
 * "already filtered", proceeding without filtering again if the
 * attribute is already there.//from   w ww . j av a  2s .  c o m
 *
 * @see #getAlreadyFilteredAttributeName
 * @see #shouldNotFilter
 * @see #doFilterInternal
 */
public final void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {

    String alreadyFilteredAttributeName = getAlreadyFilteredAttributeName();
    if (request.getAttribute(alreadyFilteredAttributeName) != null || shouldNotFilter(request)) {
        if (log.isTraceEnabled()) {
            log.trace("Filter already executed.  Proceeding without invoking this filter.");
        }
        // Proceed without invoking this filter...
        filterChain.doFilter(request, response);
    } else {
        // Do invoke this filter...
        if (log.isTraceEnabled()) {
            log.trace("Filter not yet executed.  Executing now.");
        }
        request.setAttribute(alreadyFilteredAttributeName, Boolean.TRUE);
        doFilterInternal(request, response, filterChain);
    }
}

From source file:com.jaspersoft.jasperserver.war.tags.BaseTagSupport.java

protected Map setRequestAttributes(Map attributes) {
    ServletRequest request = pageContext.getRequest();
    Set attributeNames = new HashSet();
    for (Enumeration it = request.getAttributeNames(); it.hasMoreElements();) {
        String attribute = (String) it.nextElement();
        attributeNames.add(attribute);//from  w ww . ja  v  a  2 s  .  com
    }

    Map restoreMap = new HashMap();
    for (Iterator it = attributes.entrySet().iterator(); it.hasNext();) {
        Map.Entry entry = (Map.Entry) it.next();
        String attribute = (String) entry.getKey();
        Object value = entry.getValue();

        Object restoreValue;
        if (attributeNames.contains(attribute)) {
            restoreValue = request.getAttribute(attribute);
        } else {
            restoreValue = NO_ATTRIBUTE;
        }
        restoreMap.put(attribute, restoreValue);

        request.setAttribute(attribute, value);
    }
    return restoreMap;
}

From source file:au.org.paperminer.main.UserFilter.java

/**
 * Changes the status of a user/*from www  . j a  va 2  s  .co  m*/
 * @param newStatus Status value to set
 * @param req
 * @param resp
 */
private void setStatus(int newStatus, ServletRequest req, ServletResponse resp) {
    m_logger.debug("set status");
    String id = req.getParameter("id");
    UserHelper helper = new UserHelper(id);
    if (helper.isKnownUser()) {
        m_logger.info("Upgrading status for user " + id);
        helper.set(UserHelper.STATUS, Integer.toString(newStatus));
        try {
            helper.update();
        } catch (PaperMinerException ex) {
            m_logger.error("Status update failed", ex);
            req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e105");
        }
        req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e111");
    }
}

From source file:org.apache.hadoop.hdfsproxy.AuthorizationFilter.java

/** {@inheritDoc} **/
@SuppressWarnings("unchecked")
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletResponse rsp = (HttpServletResponse) response;
    HttpServletRequest rqst = (HttpServletRequest) request;

    String userId = getUserId(request);
    String groups = getGroups(request);
    List<Path> allowedPaths = getAllowedPaths(request);

    UserGroupInformation ugi = UserGroupInformation.createRemoteUser(userId);

    String filePath = getPathFromRequest(rqst);

    if (filePath == null || !checkHdfsPath(filePath, allowedPaths)) {
        String msg = "User " + userId + " (" + groups + ") is not authorized to access path " + filePath;
        LOG.warn(msg);/*w w  w .ja  v a 2  s. c  o  m*/
        rsp.sendError(HttpServletResponse.SC_FORBIDDEN, msg);
        return;
    }
    request.setAttribute("authorized.ugi", ugi);

    chain.doFilter(request, response);
}

From source file:au.org.paperminer.main.UserFilter.java

/**
 * Creates a DB entry for a new user and loads their info into a session cookie.
 * The email is checked for basic syntax, and the trove key is validated by a Trove API call
 * before the DB record is created.//from  w  w  w .j av a 2  s. c  om
 * @param req
 * @param resp
 */
private void addUser(ServletRequest req, ServletResponse resp) {
    m_logger.info("adding user");
    String email = req.getParameter("em");
    String troveKey = req.getParameter("tk");
    String verify = req.getParameter("vfy");
    m_logger.info("AddUserFilter email:" + email + " key:" + troveKey + " verify=" + verify);

    UserHelper userHelper = new UserHelper(email, troveKey);
    try {
        if (userHelper.isKnownUser()) {
            m_logger.info("user " + email + " exists with id " + userHelper.get(UserHelper.ID));
            req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e100");
        } else {
            m_logger.info("Adding " + email + " (" + troveKey + ")");
            if (!isValidEmailAddress(email)) {
                req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e101");
            } else if (!isValidTroveKey(troveKey)) {
                req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e102");
            } else {
                userHelper.createUser(email, troveKey);
                CookieHelper.addCookie((HttpServletResponse) resp, userHelper);
                m_logger.debug("user ID=" + userHelper.get(UserHelper.ID) + " status="
                        + userHelper.get(UserHelper.STATUS));

                if ((verify != null) && verify.equals("y")) {
                    sendVerificationEmail(userHelper.get(UserHelper.ID), userHelper.get(UserHelper.EMAIL), req);
                }

                m_logger.info("Added " + email + " (" + troveKey + ") OK");
            }
        }
    } catch (PaperMinerException ex) {
        m_logger.error("unexpected error", ex);
    }
}

From source file:com.scooterframework.web.controller.ScooterRequestFilter.java

/**
 * Time the processing that is performed by all subsequent filters in the
 * current filter stack, including the ultimately invoked servlet.
 *
 * @param request The servlet request we are processing
 * @param chain The filter chain we are processing
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 *//*  ww  w.j  a  v a2  s  . c  o m*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    boolean staticContent = isStaticContentRequest((HttpServletRequest) request);

    if (encoding != null) {
        request.setCharacterEncoding(encoding);
        if (!staticContent) {
            response.setCharacterEncoding(encoding);
        }
    }

    // boolean skip = skippedRequestPath((HttpServletRequest)request);
    boolean skip = staticContent;

    long before = System.currentTimeMillis();

    if (!skip) {
        initializeActionContext((HttpServletRequest) request, (HttpServletResponse) response);
    } else {
        request.setAttribute(Constants.SKIP_PATH, "Y");
    }

    if (isAjaxRequest((HttpServletRequest) request)) {
        request.setAttribute(Constants.SITEMESH_FILTERAPPLIED, Boolean.TRUE);
    }

    String requestPathKeyWithQueryString = requestInfo(skip, (HttpServletRequest) request);
    log.debug("============>>\"" + requestPathKeyWithQueryString + "\"");

    try {
        chain.doFilter(request, response);
    } catch (Throwable ex) {
        log.error("Error from chain.doFilter: " + ex.getMessage(), ex);
    }

    long after = System.currentTimeMillis();

    if (EnvConfig.getInstance().allowRecordBenchmark()) {
        log.info("\"" + requestPathKeyWithQueryString + "\" takes: " + (after - before) + " ms");
        if (EnvConfig.getInstance().allowRecordBenchmarkInHeader()) {
            HttpServletResponseWrapper resw = new HttpServletResponseWrapper((HttpServletResponse) response);
            resw.addHeader("Exec-Time", (after - before) + " ms");
        }
    }

    clearCachedRequestData();
}

From source file:de.highbyte_le.weberknecht.security.filters.NameBasedLoginPageForwardFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (logger.isDebugEnabled())
        logger.debug("doFilter() - start");

    boolean forward = true;

    if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) {
        logger.error("servlet request is no HTTP servlet request");
    } else {/*from  w w w.  j  a v  a  2s.c  o  m*/
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpSession session = httpRequest.getSession();

        UserAuthentication userAuthentication = (UserAuthentication) session.getAttribute("user_auth");
        if (userAuthentication != null && userAuthentication.isAuthenticated()) //user is logged in
            forward = false;
        else if (!isUserServlet(httpRequest.getServletPath())) //servlet is not protected
            forward = false;
    }

    if (forward) {
        request.setAttribute("de.highbyte_le.weberknecht.login.status", "failed");

        logger.debug("doFilter() - forward to login page");
        RequestDispatcher rd = request.getRequestDispatcher(loginPage);
        rd.forward(request, response);
    } else {
        logger.debug("doFilter() - Continue with filter chain");
        chain.doFilter(request, response);
    }
}

From source file:org.egov.ptis.workflow.filter.ActionsBasedOnWorkFlowFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    Action action = null;/*ww  w.j a va 2s .c o m*/
    boolean authorized = true;
    // from action, for which actions restricted for properties under work
    // flow should be applied expecting parameter with name ENTITY_ID and
    // value is bill no of property
    if (request.getParameter("ENTITY_ID") != null) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        List authResList = new ArrayList();
        String billNo = httpRequest.getParameter("ENTITY_ID");
        action = getAction(httpRequest);
        authResList = getWorkFlowActionAuth(action.getUrl(), billNo);
        authorized = Boolean.valueOf(authResList.get(0).toString());
        if (!authorized) { // if authorization fails throwing
            // AuthorizationException
            request.setAttribute("AuthRuleErrMsgKey", authResList.get(1).toString());
            throw new AuthorizationException(authResList.get(1).toString());
        }
    }
    chain.doFilter(request, response);
}

From source file:org.dspace.app.webui.jsptag.LayoutTag.java

public int doEndTag() throws JspException {
    // Context objects
    ServletRequest request = pageContext.getRequest();
    HttpServletResponse response = (HttpServletResponse) pageContext.getResponse();
    ServletConfig config = pageContext.getServletConfig();

    // header file
    String header = templatePath + "header-default.jsp";

    // Choose default style unless one is specified
    if (style != null) {
        header = templatePath + "header-" + style.toLowerCase() + ".jsp";
    }//from   w  w  w .  j a  v a 2s.  c om

    if (sidebar != null) {
        request.setAttribute("dspace.layout.sidebar", sidebar);
    }

    // Now include the header
    try {
        // Set headers to prevent browser caching, if appropriate
        if ((noCache != null) && noCache.equalsIgnoreCase("true")) {
            response.addDateHeader("expires", 1);
            response.addHeader("Pragma", "no-cache");
            response.addHeader("Cache-control", "no-store");
        }

        // Ensure the HTTP header will declare that UTF-8 is used
        // in the response.
        response.setContentType("text/html; charset=UTF-8");

        RequestDispatcher rd = config.getServletContext().getRequestDispatcher(header);

        rd.include(request, response);

        //pageContext.getOut().write(getBodyContent().getString());
        getBodyContent().writeOut(pageContext.getOut());
    } catch (IOException ioe) {
        throw new JspException("Got IOException: " + ioe);
    } catch (ServletException se) {
        log.warn("Exception", se.getRootCause());
        throw new JspException("Got ServletException: " + se);
    }

    // Footer file to use
    String footer = templatePath + "footer-default.jsp";

    // Choose default flavour unless one is specified
    if (style != null) {
        footer = templatePath + "footer-" + style.toLowerCase() + ".jsp";
    }

    try {
        // Ensure body is included before footer
        pageContext.getOut().flush();

        RequestDispatcher rd = config.getServletContext().getRequestDispatcher(footer);

        rd.include(request, response);
    } catch (ServletException se) {
        throw new JspException("Got ServletException: " + se);
    } catch (IOException ioe) {
        throw new JspException("Got IOException: " + ioe);
    }

    style = null;
    title = null;
    sidebar = null;
    navbar = null;
    locbar = null;
    parentTitle = null;
    parentLink = null;
    noCache = null;
    feedData = null;
    return EVAL_PAGE;
}

From source file:org.dspace.app.webui.jsptag.LayoutTag.java

public int doStartTag() throws JspException {
    ServletRequest request = pageContext.getRequest();

    // Sort out location bar
    if (locbar == null) {
        locbar = "auto";
    }//from   w  ww  .  ja  v a 2 s  . c o  m

    // These lists will contain titles and links to put in the location
    // bar
    List<String> parents = new ArrayList<String>();
    List<String> parentLinks = new ArrayList<String>();

    if (locbar.equalsIgnoreCase("off")) {
        // No location bar
        request.setAttribute("dspace.layout.locbar", Boolean.FALSE);
    } else {
        // We'll always add "DSpace Home" to the a location bar
        parents.add(ConfigurationManager.getProperty("dspace.name"));

        if (locbar.equalsIgnoreCase("nolink")) {
            parentLinks.add("");
        } else {
            parentLinks.add("/");
        }

        // Add other relevant components to the location bar
        if (locbar.equalsIgnoreCase("link")) {
            // "link" mode - next thing in location bar is taken from
            // parameters of tag, with a link
            if (parentTitle != null) {
                parents.add(parentTitle);
                parentLinks.add(parentLink);
            } else if (parentTitleKey != null) {
                parents.add(LocaleSupport.getLocalizedMessage(pageContext, parentTitleKey));
                parentLinks.add(parentLink);
            }

        } else if (locbar.equalsIgnoreCase("commLink")) {
            // "commLink" mode - show all parent communities
            Community[] comms = (Community[]) request.getAttribute("dspace.communities");

            if (comms != null) {
                for (int i = 0; i < comms.length; i++) {
                    parents.add(comms[i].getMetadata("name"));
                    parentLinks.add("/handle/" + comms[i].getHandle());
                }
            }
        } else if (locbar.equalsIgnoreCase("nolink")) {
            // "nolink" mode - next thing in location bar is taken from
            // parameters of tag, with no link
            if (parentTitle != null) {
                parents.add(parentTitle);
                parentLinks.add("");
            }
        } else {
            // Grab parents from the URL - these should have been picked up
            // by the HandleServlet
            Collection col = (Collection) request.getAttribute("dspace.collection");
            Community[] comms = (Community[]) request.getAttribute("dspace.communities");

            if (comms != null) {
                for (int i = 0; i < comms.length; i++) {
                    parents.add(comms[i].getMetadata("name"));
                    parentLinks.add("/handle/" + comms[i].getHandle());
                }

                if (col != null) {
                    parents.add(col.getMetadata("name"));
                    parentLinks.add("/handle/" + col.getHandle());
                }
            }
        }

        request.setAttribute("dspace.layout.locbar", Boolean.TRUE);
    }

    request.setAttribute("dspace.layout.parenttitles", parents);
    request.setAttribute("dspace.layout.parentlinks", parentLinks);

    // Navigation bar: "default" is default :)
    if (navbar == null) {
        navbar = "default";
    }

    if (navbar.equals("off")) {
        request.setAttribute("dspace.layout.navbar", "off");
    } else {
        request.setAttribute("dspace.layout.navbar", templatePath + "navbar-" + navbar + ".jsp");
    }

    // Set title
    if (title != null) {
        request.setAttribute("dspace.layout.title", title);
    } else if (titleKey != null) {
        request.setAttribute("dspace.layout.title", LocaleSupport.getLocalizedMessage(pageContext, titleKey));
    } else {
        request.setAttribute("dspace.layout.title", "NO TITLE");
    }

    // Set feedData if present
    if (feedData != null && !"NONE".equals(feedData)) {
        // set the links' reference - community or collection
        boolean commLinks = feedData.startsWith("comm:");
        boolean collLinks = feedData.startsWith("coll:");
        if (commLinks) {
            Community com = (Community) request.getAttribute("dspace.community");
            request.setAttribute("dspace.layout.feedref", com.getHandle());
        } else if (collLinks) {
            Collection col = (Collection) request.getAttribute("dspace.collection");
            request.setAttribute("dspace.layout.feedref", col.getHandle());
        } else //feed is across all of DSpace and not Community/Collection specific
        {
            request.setAttribute("dspace.layout.feedref", FeedServlet.SITE_FEED_KEY);
        }

        // build a list of link attributes for each link format
        String[] formats = feedData.substring(feedData.indexOf(':') + 1).split(",");
        List<String> linkParts = new ArrayList<String>();
        // each link has a mime-type, title, and format (used in href URL)
        for (int i = 0; i < formats.length; i++) {
            if ("rss_1.0".equals(formats[i])) {
                linkParts.add("rdf+xml");
            } else {
                linkParts.add("rss+xml");
            }

            if (commLinks) {
                linkParts.add("Items in Community");
            } else if (collLinks) {
                linkParts.add("Items in Collection");
            } else {
                linkParts.add("Items in " + ConfigurationManager.getProperty("dspace.name"));
            }

            linkParts.add(formats[i]);
        }
        request.setAttribute("dspace.layout.linkparts", linkParts);
    } else {
        request.setAttribute("dspace.layout.feedref", "NONE");
    }

    return EVAL_BODY_BUFFERED;
}