Example usage for javax.servlet.http HttpServletRequest removeAttribute

List of usage examples for javax.servlet.http HttpServletRequest removeAttribute

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest removeAttribute.

Prototype

public void removeAttribute(String name);

Source Link

Document

Removes an attribute from this request.

Usage

From source file:org.apache.struts.webapp.example2.SaveSubscriptionAction.java

/**
 * Process the specified HTTP request, and create the corresponding HTTP
 * response (or forward to another web component that will create it).
 * Return an <code>ActionForward</code> instance describing where and how
 * control should be forwarded, or <code>null</code> if the response has
 * already been completed./*w w w . j  a v a  2s  .com*/
 *
 * @param mapping The ActionMapping used to select this instance
 * @param form The optional ActionForm bean for this request (if any)
 * @param request The HTTP request we are processing
 * @param response The HTTP response we are creating
 *
 * @exception Exception if the application business logic throws
 *  an exception
 */
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    // Extract attributes and parameters we will need
    Locale locale = getLocale(request);
    MessageResources messages = getResources(request);
    HttpSession session = request.getSession();
    SubscriptionForm subform = (SubscriptionForm) form;
    String action = subform.getAction();
    if (action == null) {
        action = "?";
    }
    if (log.isDebugEnabled()) {
        log.debug("SaveSubscriptionAction:  Processing " + action + " action");
    }

    // Is there a currently logged on user?
    User user = (User) session.getAttribute(Constants.USER_KEY);
    if (user == null) {
        if (log.isTraceEnabled()) {
            log.trace(" User is not logged on in session " + session.getId());
        }
        return (mapping.findForward("logon"));
    }

    // Was this transaction cancelled?
    if (isCancelled(request)) {
        if (log.isTraceEnabled()) {
            log.trace(" Transaction '" + action + "' was cancelled");
        }
        session.removeAttribute(Constants.SUBSCRIPTION_KEY);
        return (mapping.findForward("success"));
    }

    // Is there a related Subscription object?
    Subscription subscription = (Subscription) session.getAttribute(Constants.SUBSCRIPTION_KEY);
    if ("Create".equals(action)) {
        if (log.isTraceEnabled()) {
            log.trace(" Creating subscription for mail server '" + subform.getHost() + "'");
        }
        subscription = user.createSubscription(subform.getHost());
    }
    if (subscription == null) {
        if (log.isTraceEnabled()) {
            log.trace(" Missing subscription for user '" + user.getUsername() + "'");
        }
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, messages.getMessage("error.noSubscription"));
        return (null);
    }

    // Was this transaction a Delete?
    if (action.equals("Delete")) {
        if (log.isTraceEnabled()) {
            log.trace(" Deleting mail server '" + subscription.getHost() + "' for user '" + user.getUsername()
                    + "'");
        }
        user.removeSubscription(subscription);
        session.removeAttribute(Constants.SUBSCRIPTION_KEY);
        try {
            UserDatabase database = (UserDatabase) servlet.getServletContext()
                    .getAttribute(Constants.DATABASE_KEY);
            database.save();
        } catch (Exception e) {
            log.error("Database save", e);
        }
        return (mapping.findForward("success"));
    }

    // All required validations were done by the form itself

    // Update the persistent subscription information
    if (log.isTraceEnabled()) {
        log.trace(" Populating database from form bean");
    }
    try {
        PropertyUtils.copyProperties(subscription, subform);
    } catch (InvocationTargetException e) {
        Throwable t = e.getTargetException();
        if (t == null)
            t = e;
        log.error("Subscription.populate", t);
        throw new ServletException("Subscription.populate", t);
    } catch (Throwable t) {
        log.error("Subscription.populate", t);
        throw new ServletException("Subscription.populate", t);
    }

    try {
        UserDatabase database = (UserDatabase) servlet.getServletContext().getAttribute(Constants.DATABASE_KEY);
        database.save();
    } catch (Exception e) {
        log.error("Database save", e);
    }

    // Remove the obsolete form bean and current subscription
    if (mapping.getAttribute() != null) {
        if ("request".equals(mapping.getScope()))
            request.removeAttribute(mapping.getAttribute());
        else
            session.removeAttribute(mapping.getAttribute());
    }
    session.removeAttribute(Constants.SUBSCRIPTION_KEY);

    // Forward control to the specified success URI
    if (log.isTraceEnabled()) {
        log.trace(" Forwarding to success page");
    }
    return (mapping.findForward("success"));

}

From source file:org.jahia.services.render.filter.cache.DefaultCacheKeyGenerator.java

/**
 * Get all cache attributes that need to be applied on this fragment and that will impact key generation. The
 * cache properties may come from the script properties file, or from the jmix:cache mixin (for cache.perUser
 * only).//from w  w w.  j  av  a 2s. c  om
 * <p/>
 * If the component is a list, the properties can also come from its hidden.load script properties.
 * <p/>
 * cache.perUser : is the cache entry specific for each user. Is set by j:perUser node property or cache.perUser
 * property in script properties
 * <p/>
 * cache.mainResource : is the cache entry dependant on the main resource. Is set by cache.mainResource property
 * in script properties, or automatically set if the component is bound.
 * <p/>
 * cache.requestParameters : list of request parameter that will impact the rendering of the resource. Is set
 * by cache.requestParameters property in script properties. ec,v,cacheinfo and moduleinfo are automatically added.
 * <p/>
 * cache.expiration : the expiration time of the cache entry. Can be set by the "expiration" request attribute,
 * j:expiration node property or the cache.expiration property in script properties.
 */
@Override
public Properties getAttributesForKey(RenderContext renderContext, Resource resource)
        throws RepositoryException {

    HttpServletRequest request = renderContext.getRequest();
    final Script script = resource.getScript(renderContext);
    final JCRNodeWrapper node = resource.safeLoadNode();
    boolean isBound = node.isNodeType(Constants.JAHIAMIX_BOUND_COMPONENT);
    boolean isList = node.isNodeType(Constants.JAHIAMIX_LIST);

    Properties properties = new Properties();

    if (script != null) {
        properties.putAll(script.getView().getDefaultProperties());
        properties.putAll(script.getView().getProperties());
    }

    if (isList) {
        Resource listLoader = new Resource(node, resource.getTemplateType(), "hidden.load",
                Resource.CONFIGURATION_INCLUDE);
        try {
            Script listScript = RenderService.getInstance().resolveScript(listLoader, renderContext);
            properties.putAll(listScript.getView().getProperties());
        } catch (TemplateNotFoundException e) {
            logger.error("Cannot find loader script for list " + node.getPath(), e);
        }
    }

    if (node.hasProperty(CacheUtils.NODE_PROPERTY_CACHE_PER_USER)) {
        properties.put(CacheUtils.FRAGMNENT_PROPERTY_CACHE_PER_USER,
                node.getProperty(CacheUtils.NODE_PROPERTY_CACHE_PER_USER).getString());
    }
    if (isBound) {
        // TODO check this, if the component is a bound component don't mean that it's always bound to the main resource
        properties.put("cache.mainResource", "true");
    }

    // update requestParameters if needed
    final StringBuilder updatedRequestParameters;
    final String requestParameters = properties.getProperty("cache.requestParameters");
    if (!StringUtils.isEmpty(requestParameters)) {
        updatedRequestParameters = new StringBuilder(requestParameters + ",ec,v");
    } else {
        updatedRequestParameters = new StringBuilder("ec,v");
    }
    if (SettingsBean.getInstance().isDevelopmentMode()) {
        updatedRequestParameters.append(",moduleinfo");
    }
    properties.put("cache.requestParameters", updatedRequestParameters.toString());

    // cache expiration lookup by order : request attribute -> node -> view -> -1 (forever in cache realm, 4 hours)
    String viewExpiration = properties.getProperty(CacheUtils.FRAGMNENT_PROPERTY_CACHE_EXPIRATION);
    final Object requestExpiration = request.getAttribute("expiration");
    if (requestExpiration != null) {
        // TODO BACKLOG-6561: we should avoid that, the day we remove AggregateCacheFilter, we can remove this one
        properties.put(CacheUtils.FRAGMNENT_PROPERTY_CACHE_EXPIRATION, requestExpiration);
    } else if (node.hasProperty("j:expiration")) {
        properties.put(CacheUtils.FRAGMNENT_PROPERTY_CACHE_EXPIRATION,
                node.getProperty("j:expiration").getString());
    } else if (viewExpiration != null) {
        properties.put(CacheUtils.FRAGMNENT_PROPERTY_CACHE_EXPIRATION, viewExpiration);
    } else {
        properties.put(CacheUtils.FRAGMNENT_PROPERTY_CACHE_EXPIRATION, "-1");
    }

    String propertiesScript = properties.getProperty("cache.propertiesScript");
    if (propertiesScript != null) {
        Resource propsResource = new Resource(node, resource.getTemplateType(), propertiesScript,
                Resource.CONFIGURATION_INCLUDE);
        try {
            Script propsScript = RenderService.getInstance().resolveScript(propsResource, renderContext);
            try {
                request.setAttribute("cacheProperties", properties);
                propsScript.execute(propsResource, renderContext);
            } catch (RenderException e) {
                logger.error("Cannot execute script", e);
            } finally {
                request.removeAttribute("cacheProperties");
            }
        } catch (TemplateNotFoundException e) {
            logger.error("Cannot find cache properties script " + propertiesScript + " for the node "
                    + node.getPath(), e);
        }
    }

    return properties;
}

From source file:org.sakaiproject.jsf.util.JsfTool.java

/**
 * Respond to requests./*from w  w  w .j ava  2 s  .c om*/
 * 
 * @param req
 *        The servlet request.
 * @param res
 *        The servlet response.
 * @throws ServletException.
 * @throws IOException.
 */
protected void dispatch(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    // NOTE: this is a simple path dispatching, taking the path as the view id = jsp file name for the view,
    //       with default used if no path and a path prefix as configured.
    // TODO: need to allow other sorts of dispatching, such as pulling out drill-down ids and making them
    //       available to the JSF

    // build up the target that will be dispatched to
    String target = req.getPathInfo();

    // see if we have a resource request - i.e. a path with an extension, and one that is not the JSF_EXT
    if (isResourceRequest(target)) {
        // get a dispatcher to the path
        RequestDispatcher resourceDispatcher = getServletContext().getRequestDispatcher(target);
        if (resourceDispatcher != null) {
            resourceDispatcher.forward(req, res);
            return;
        }
    }

    if ("Title".equals(req.getParameter("panel"))) {
        // This allows only one Title JSF for each tool
        target = "/title.jsf";
    }

    else {
        ToolSession session = SessionManager.getCurrentToolSession();

        if (target == null || "/".equals(target)) {
            target = computeDefaultTarget();

            // make sure it's a valid path
            if (!target.startsWith("/")) {
                target = "/" + target;
            }

            // now that we've messed with the URL, send a redirect to make it official
            res.sendRedirect(Web.returnUrl(req, target));
            return;
        }

        // see if we want to change the specifically requested view
        String newTarget = redirectRequestedTarget(target);

        // make sure it's a valid path
        if (!newTarget.startsWith("/")) {
            newTarget = "/" + newTarget;
        }

        if (!newTarget.equals(target)) {
            // now that we've messed with the URL, send a redirect to make it official
            res.sendRedirect(Web.returnUrl(req, newTarget));
            return;
        }
        target = newTarget;

        // store this
        if (m_defaultToLastView) {
            session.setAttribute(LAST_VIEW_VISITED, target);
        }
    }

    // add the configured folder root and extension (if missing)
    target = m_path + target;

    // add the default JSF extension (if we have no extension)
    int lastSlash = target.lastIndexOf("/");
    int lastDot = target.lastIndexOf(".");
    if (lastDot < 0 || lastDot < lastSlash) {
        target += JSF_EXT;
    }

    // set the information that can be removed from return URLs
    req.setAttribute(URL_PATH, m_path);
    req.setAttribute(URL_EXT, JSF_FACELETS_EXT);

    // set the sakai request object wrappers to provide the native, not Sakai set up, URL information
    // - this assures that the FacesServlet can dispatch to the proper view based on the path info
    req.setAttribute(Tool.NATIVE_URL, Tool.NATIVE_URL);

    // TODO: Should setting the HTTP headers be moved up to the portal level as well?
    res.setContentType("text/html; charset=UTF-8");
    res.addDateHeader("Expires", System.currentTimeMillis() - (1000L * 60L * 60L * 24L * 365L));
    res.addDateHeader("Last-Modified", System.currentTimeMillis());
    res.addHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0");
    res.addHeader("Pragma", "no-cache");

    // dispatch to the target
    M_log.debug("dispatching path: " + req.getPathInfo() + " to: " + target + " context: "
            + getServletContext().getServletContextName());
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(target);
    dispatcher.forward(req, res);

    // restore the request object
    req.removeAttribute(Tool.NATIVE_URL);
    req.removeAttribute(URL_PATH);
    req.removeAttribute(URL_EXT);
}

From source file:org.sakaiproject.jsf.util.HelperAwareJsfTool.java

protected void dispatch(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    // NOTE: this is a simple path dispatching, taking the path as the view id = jsp file name for the view,
    //       with default used if no path and a path prefix as configured.
    // TODO: need to allow other sorts of dispatching, such as pulling out drill-down ids and making them
    //       available to the JSF

    // build up the target that will be dispatched to
    String target = req.getPathInfo();

    // see if we have a helper request
    if (sendToHelper(req, res, target)) {
        return;//  www .  j a v a  2  s  . co m
    }

    // see if we have a resource request - i.e. a path with an extension, and one that is not the JSF_EXT
    if (isResourceRequest(target)) {
        // get a dispatcher to the path
        RequestDispatcher resourceDispatcher = getServletContext().getRequestDispatcher(target);
        if (resourceDispatcher != null) {
            resourceDispatcher.forward(req, res);
            return;
        }
    }

    if ("Title".equals(req.getParameter("panel"))) {
        // This allows only one Title JSF for each tool
        target = "/title.jsf";
    }

    else {
        ToolSession session = SessionManager.getCurrentToolSession();

        if (target == null || "/".equals(target) || target.length() == 0) {
            if (!m_defaultToLastView) {
                // make sure tool session is clean
                session.clearAttributes();
            }

            target = computeDefaultTarget();

            // make sure it's a valid path
            if (!target.startsWith("/")) {
                target = "/" + target;
            }

            // now that we've messed with the URL, send a redirect to make it official
            res.sendRedirect(Web.returnUrl(req, target));
            return;
        }

        // see if we want to change the specifically requested view
        String newTarget = redirectRequestedTarget(target);

        // make sure it's a valid path
        if (!newTarget.startsWith("/")) {
            newTarget = "/" + newTarget;
        }

        if (!newTarget.equals(target)) {
            // now that we've messed with the URL, send a redirect to make it official
            res.sendRedirect(Web.returnUrl(req, newTarget));
            return;
        }
        target = newTarget;

        // store this
        session.setAttribute(LAST_VIEW_VISITED, target);
    }

    // add the configured folder root and extension (if missing)
    target = m_path + target;

    // add the default JSF extension (if we have no extension)
    int lastSlash = target.lastIndexOf("/");
    int lastDot = target.lastIndexOf(".");
    if (lastDot < 0 || lastDot < lastSlash) {
        target += JSF_EXT;
    }

    // set the information that can be removed from return URLs
    req.setAttribute(URL_PATH, m_path);
    req.setAttribute(URL_EXT, JSF_FACELETS_EXT);

    // set the sakai request object wrappers to provide the native, not Sakai set up, URL information
    // - this assures that the FacesServlet can dispatch to the proper view based on the path info
    req.setAttribute(Tool.NATIVE_URL, Tool.NATIVE_URL);

    // TODO: Should setting the HTTP headers be moved up to the portal level as well?
    res.setContentType("text/html; charset=UTF-8");
    res.addDateHeader("Expires", System.currentTimeMillis() - (1000L * 60L * 60L * 24L * 365L));
    res.addDateHeader("Last-Modified", System.currentTimeMillis());
    res.addHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0");
    res.addHeader("Pragma", "no-cache");

    // dispatch to the target
    M_log.debug("dispatching path: " + req.getPathInfo() + " to: " + target + " context: "
            + getServletContext().getServletContextName());
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(target);
    dispatcher.forward(req, res);

    // restore the request object
    req.removeAttribute(Tool.NATIVE_URL);
    req.removeAttribute(URL_PATH);
    req.removeAttribute(URL_EXT);
}

From source file:net.ontopia.topicmaps.webed.taglibs.form.FormTag.java

/**
 * Renders the input form element with it's content.
 *//*  ww  w.j  a v  a  2 s  .co m*/
@Override
public int doAfterBody() throws JspException {
    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();

    TagUtils.setCurrentFormTag(request, null);

    VelocityContext vc = TagUtils.getVelocityContext(pageContext);
    // attributes of the form element
    vc.put("name", NAME);
    String id = idattr;
    if (id == null)
        id = requestId;
    // Use requestId by default, to make sure there always is an id.
    vc.put("idattr", id);
    // -- class
    if (klass != null)
        vc.put("class", klass);

    validationRules = getFieldValidationRules();
    if (!validationRules.isEmpty()) {
        vc.put("performFieldValidation", Boolean.TRUE);
        vc.put("validationRules", validationRules);
        vc.put("onsubmit", "return validate('" + id + "');");
    } else
        vc.put("onsubmit", "return true;");

    vc.put("outputSubmitFunc", getOutputSubmitFunc());

    // reset the outputSubmitFunc variable
    setOutputSubmitFunc(false);

    // -- action
    String context_name = request.getContextPath();
    String default_action = context_name + "/" + Constants.PROCESS_SERVLET;
    vc.put("action", (action_uri != null) ? action_uri : default_action);
    ActionRegistryIF registry = TagUtils.getActionRegistry(pageContext);
    // -- target (only in the case of a multi framed web app)
    if (registry == null)
        throw new JspException(
                "No action registry available! Check actions.xml for errors; see log for details.");
    vc.put("target", target);
    // -- enctype
    if (enctype != null)
        vc.put("enctype", enctype);
    // -- nested
    if (nested != null)
        vc.put("nested", nested);

    if (lockVarname != null)
        vc.put(Constants.RP_LOCKVAR, lockVarname);

    NavigatorPageIF contextTag = FrameworkUtils.getContextTag(pageContext);

    // add hidden parameter value pairs to identify the request
    String topicmap_id = request.getParameter(Constants.RP_TOPICMAP_ID);
    if (topicmap_id == null && contextTag != null) {
        // if not set try to retrieve it from the nav context
        NavigatorApplicationIF navApp = contextTag.getNavigatorApplication();
        TopicMapIF tm = contextTag.getTopicMap();
        if (tm != null)
            topicmap_id = navApp.getTopicMapRefId(tm);
    }
    vc.put(Constants.RP_TOPICMAP_ID, topicmap_id);
    vc.put(Constants.RP_TOPIC_ID, request.getParameter(Constants.RP_TOPIC_ID));
    vc.put(Constants.RP_ASSOC_ID, request.getParameter(Constants.RP_ASSOC_ID));
    vc.put(Constants.RP_ACTIONGROUP, actiongroup);
    vc.put(Constants.RP_REQUEST_ID, requestId);

    // FIXME: Do we really need this line? Probably not, since each control
    // should now itself be responisible for determining whether it should be
    // readonly. Hence the individual control can overrule the form setting.
    // vc.put("readonly", TagUtils.isFormReadOnly(request));

    // content inside the form element
    BodyContent body = getBodyContent();
    vc.put("content", body.getString());

    // render JavaScript to set the input focus (if required)
    if (focus != null) {
        String focus_elem = focus;
        StringBuilder focus_ref = new StringBuilder("[");
        if (focus_elem.indexOf('[') > 0) {
            StringTokenizer st = new StringTokenizer(focus_elem, "[");
            if (st.countTokens() == 2) {
                focus_elem = st.nextToken();
                focus_ref.append(st.nextToken());
            }
        }
        vc.put("focus_elem", focus_elem);
        if (focus_ref.length() > 1)
            vc.put("focus_ref", focus_ref.toString());
        else
            vc.put("focus_ref", "");
    }

    // all variables are now set, proceed with outputting
    TagUtils.processWithVelocity(pageContext, TEMPLATE_FILE, getBodyContent().getEnclosingWriter(), vc);

    // clear read-only state
    request.removeAttribute(Constants.OKS_FORM_READONLY);

    return SKIP_BODY;
}

From source file:org.sakaiproject.portal.charon.SkinnableCharonPortal.java

/**
 * Forward to the tool - but first setup JavaScript/CSS etc that the tool
 * will render//from w ww .j a  va  2  s  .  co m
 */
public void forwardTool(ActiveTool tool, HttpServletRequest req, HttpServletResponse res, Placement p,
        String skin, String toolContextPath, String toolPathInfo) throws ToolException {
    // SAK-29656 - Make sure the request URL and toolContextPath treat tilde encoding the same way
    //
    // Since we cannot easily change what the request object already knows as its URL,
    // we patch the toolContextPath to match the tilde encoding in the request URL.
    //
    // This is what we would see in Chrome and Firefox.  Firefox fails with Wicket
    // Chrome: forwardtool call http://localhost:8080/portal/site/~csev/tool/aaf64e38-00df-419a-b2ac-63cf2d7f99cf
    //    toolPathInfo null ctx /portal/site/~csev/tool/aaf64e38-00df-419a-b2ac-63cf2d7f99cf
    // Firefox: http://localhost:8080/portal/site/%7ecsev/tool/aaf64e38-00df-419a-b2ac-63cf2d7f99cf/
    //    toolPathInfo null ctx /portal/site/~csev/tool/aaf64e38-00df-419a-b2ac-63cf2d7f99cf

    String reqUrl = req.getRequestURL().toString();
    if (reqUrl.indexOf(toolContextPath) < 0) {
        M_log.debug("Mismatch between request url " + reqUrl + " and toolContextPath " + toolContextPath);
        if (toolContextPath.indexOf("/~") > 0 && reqUrl.indexOf("/~") < 1) {
            if (reqUrl.indexOf("/%7e") > 0) {
                toolContextPath = toolContextPath.replace("/~", "/%7e");
            } else {
                toolContextPath = toolContextPath.replace("/~", "/%7E");
            }
        }
    }
    M_log.debug("forwardtool call " + req.getRequestURL().toString() + " toolPathInfo " + toolPathInfo + " ctx "
            + toolContextPath);

    // if there is a stored request state, and path, extract that from the
    // session and reinstance it

    StringBuilder ctx = new StringBuilder(toolContextPath);
    toolPathInfo = fixPath(toolPathInfo, ctx);
    toolContextPath = ctx.toString();
    boolean needNative = false;

    // let the tool do the the work (forward)
    if (enableDirect) {
        StoredState ss = portalService.getStoredState();
        if (ss == null || !toolContextPath.equals(ss.getToolContextPath())) {
            setupForward(req, res, p, skin);
            req.setAttribute(ToolURL.MANAGER, new ToolURLManagerImpl(res));
            M_log.debug("tool forward 1 " + toolPathInfo + " context " + toolContextPath);
            needNative = (req.getAttribute(Tool.NATIVE_URL) != null);
            if (needNative)
                req.removeAttribute(Tool.NATIVE_URL);
            tool.forward(req, res, p, toolContextPath, toolPathInfo);
            if (needNative)
                req.setAttribute(Tool.NATIVE_URL, Tool.NATIVE_URL);
        } else {
            M_log.debug("Restoring StoredState [" + ss + "]");
            HttpServletRequest sreq = ss.getRequest(req);
            Placement splacement = ss.getPlacement();
            StringBuilder sctx = new StringBuilder(ss.getToolContextPath());
            String stoolPathInfo = fixPath(ss.getToolPathInfo(), sctx);
            String stoolContext = sctx.toString();

            ActiveTool stool = ActiveToolManager.getActiveTool(p.getToolId());
            String sskin = ss.getSkin();
            setupForward(sreq, res, splacement, sskin);
            req.setAttribute(ToolURL.MANAGER, new ToolURLManagerImpl(res));
            M_log.debug("tool forward 2 " + stoolPathInfo + " context " + stoolContext);
            needNative = (sreq.getAttribute(Tool.NATIVE_URL) != null);
            if (needNative)
                sreq.removeAttribute(Tool.NATIVE_URL);
            stool.forward(sreq, res, splacement, stoolContext, stoolPathInfo);
            if (needNative)
                sreq.setAttribute(Tool.NATIVE_URL, Tool.NATIVE_URL);
            // this is correct as we have checked the context path of the
            // tool
            portalService.setStoredState(null);
        }
    } else {
        setupForward(req, res, p, skin);
        req.setAttribute(ToolURL.MANAGER, new ToolURLManagerImpl(res));
        M_log.debug("tool forward 3 " + toolPathInfo + " context " + toolContextPath);
        needNative = (req.getAttribute(Tool.NATIVE_URL) != null);
        if (needNative)
            req.removeAttribute(Tool.NATIVE_URL);
        tool.forward(req, res, p, toolContextPath, toolPathInfo);
        if (needNative)
            req.setAttribute(Tool.NATIVE_URL, Tool.NATIVE_URL);
    }

}

From source file:org.apache.struts.webapp.example.SaveRegistrationAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    // Extract attributes and parameters we will need
    HttpSession session = request.getSession();
    RegistrationForm regform = (RegistrationForm) form;
    String action = regform.getAction();
    if (action == null) {
        action = "Create";
    }// w  ww .j  a v a 2s  . c o m

    UserDatabase database = (UserDatabase) servlet.getServletContext().getAttribute(Constants.DATABASE_KEY);

    if (log.isDebugEnabled()) {
        log.debug("SaveRegistrationAction:  Processing " + action + " action");
    }

    // Is there a currently logged on user (unless creating)?
    User user = (User) session.getAttribute(Constants.USER_KEY);
    if (!"Create".equals(action) && (user == null)) {
        if (log.isTraceEnabled()) {
            log.trace(" User is not logged on in session " + session.getId());
        }
        return (mapping.findForward("logon"));
    }

    // Was this transaction cancelled?
    if (isCancelled(request)) {
        if (log.isTraceEnabled()) {
            log.trace(" Transaction '" + action + "' was cancelled");
        }
        session.removeAttribute(Constants.SUBSCRIPTION_KEY);
        return (mapping.findForward("success"));
    }

    // Validate the transactional control token
    ActionMessages errors = new ActionMessages();
    if (log.isTraceEnabled()) {
        log.trace(" Checking transactional control token");
    }

    if (!isTokenValid(request)) {
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.transaction.token"));
    }

    resetToken(request);

    // Validate the request parameters specified by the user
    if (log.isTraceEnabled()) {
        log.trace(" Performing extra validations");
    }

    String value = null;
    value = regform.getUsername();
    if (("Create".equals(action)) && (database.findUser(value) != null)) {
        errors.add("username", new ActionMessage("error.username.unique", regform.getUsername()));
    }

    if ("Create".equals(action)) {
        value = regform.getPassword();
        if ((value == null) || (value.length() < 1)) {
            errors.add("password", new ActionMessage("error.password.required"));
        }

        value = regform.getPassword2();

        if ((value == null) || (value.length() < 1)) {
            errors.add("password2", new ActionMessage("error.password2.required"));
        }
    }

    // Report any errors we have discovered back to the original form
    if (!errors.isEmpty()) {
        this.saveErrors(request, errors);
        this.saveToken(request);
        return (mapping.getInputForward());
    }

    // Update the user's persistent profile information
    try {
        if ("Create".equals(action)) {
            user = database.createUser(regform.getUsername());
        }

        String oldPassword = user.getPassword();
        PropertyUtils.copyProperties(user, regform);
        if ((regform.getPassword() == null) || (regform.getPassword().length() < 1)) {

            user.setPassword(oldPassword);
        }

    } catch (InvocationTargetException e) {
        Throwable t = e.getTargetException();
        if (t == null) {
            t = e;
        }

        log.error("Registration.populate", t);
        throw new ServletException("Registration.populate", t);

    } catch (Throwable t) {
        log.error("Registration.populate", t);
        throw new ServletException("Subscription.populate", t);
    }

    try {
        database.save();
    } catch (Exception e) {
        log.error("Database save", e);
    }

    // Log the user in if appropriate
    if ("Create".equals(action)) {
        session.setAttribute(Constants.USER_KEY, user);
        if (log.isTraceEnabled()) {
            log.trace(" User '" + user.getUsername() + "' logged on in session " + session.getId());
        }
    }

    // Remove the obsolete form bean
    if (mapping.getAttribute() != null) {
        if ("request".equals(mapping.getScope()))
            request.removeAttribute(mapping.getAttribute());
        else
            session.removeAttribute(mapping.getAttribute());
    }

    // Forward control to the specified success URI
    if (log.isTraceEnabled()) {
        log.trace(" Forwarding to success page");
    }

    return (mapping.findForward("success"));

}

From source file:org.sakaiproject.spring.util.SpringTool.java

/**
 * Respond to requests.//  w  w  w . j a  v  a 2 s. co m
 *
 * @param req The servlet request.
 * @param res The servlet response.
 * @throws ServletException
 * @throws IOException
 */
protected void dispatch(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    // NOTE: this is a simple path dispatching, taking the path as the view id = jsp file name for the view,
    //       with default used if no path and a path prefix as configured.
    // TODO: need to allow other sorts of dispatching, such as pulling out drill-down ids and making them
    //       available to the JSF

    // build up the target that will be dispatched to
    String target = req.getPathInfo();

    // see if we have a helper request
    if (sendToHelper(req, res, target)) {
        return;
    }

    // see if we have a resource request - i.e. a path with an extension, and one that is not the JSF_EXT
    if (isResourceRequest(target)) {
        // get a dispatcher to the path
        RequestDispatcher resourceDispatcher = getServletContext().getRequestDispatcher(target);
        if (resourceDispatcher != null) {
            resourceDispatcher.forward(req, res);
            return;
        }
    }

    if ("Title".equals(req.getParameter("panel"))) {
        // This allows only one Title JSF for each tool
        target = "/title.osp";
    }

    else {
        ToolSession session = SessionManager.getCurrentToolSession();

        if (target == null || "/".equals(target)) {
            if (!m_defaultToLastView) {
                // make sure tool session is clean
                session.clearAttributes();
            }

            target = computeDefaultTarget();

            // make sure it's a valid path
            if (!target.startsWith("/")) {
                target = "/" + target;
            }

            // now that we've messed with the URL, send a redirect to make it official
            res.sendRedirect(Web.returnUrl(req, target));
            return;
        }

        // see if we want to change the specifically requested view
        String newTarget = redirectRequestedTarget(target);

        // make sure it's a valid path
        if (!newTarget.startsWith("/")) {
            newTarget = "/" + newTarget;
        }

        if (!newTarget.equals(target)) {
            // now that we've messed with the URL, send a redirect to make it official
            res.sendRedirect(Web.returnUrl(req, newTarget));
            return;
        }
        target = newTarget;

        // store this
        session.setAttribute(LAST_VIEW_VISITED, target);
    }

    // add the configured folder root and extension (if missing)
    target = m_path + target;

    // add the default JSF extension (if we have no extension)
    int lastSlash = target.lastIndexOf("/");
    int lastDot = target.lastIndexOf(".");
    if (lastDot < 0 || lastDot < lastSlash) {
        target += JSF_EXT;
    }

    // set the information that can be removed from return URLs
    req.setAttribute(URL_PATH, m_path);
    req.setAttribute(URL_EXT, ".jsp");

    // set the sakai request object wrappers to provide the native, not Sakai set up, URL information
    // - this assures that the FacesServlet can dispatch to the proper view based on the path info
    req.setAttribute(Tool.NATIVE_URL, Tool.NATIVE_URL);

    // TODO: Should setting the HTTP headers be moved up to the portal level as well?
    res.setContentType("text/html; charset=UTF-8");
    res.addDateHeader("Expires", System.currentTimeMillis() - (1000L * 60L * 60L * 24L * 365L));
    res.addDateHeader("Last-Modified", System.currentTimeMillis());
    res.addHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0");
    res.addHeader("Pragma", "no-cache");

    // dispatch to the target
    M_log.debug("dispatching path: " + req.getPathInfo() + " to: " + target + " context: "
            + getServletContext().getServletContextName());
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(target);
    dispatcher.forward(req, res);

    // restore the request object
    req.removeAttribute(Tool.NATIVE_URL);
    req.removeAttribute(URL_PATH);
    req.removeAttribute(URL_EXT);
}

From source file:org.apache.struts.webapp.example2.SaveRegistrationAction.java

/**
 * Process the specified HTTP request, and create the corresponding HTTP
 * response (or forward to another web component that will create it).
 * Return an <code>ActionForward</code> instance describing where and how
 * control should be forwarded, or <code>null</code> if the response has
 * already been completed.//from w ww.j  av  a 2s  .c  om
 *
 * @param mapping The ActionMapping used to select this instance
 * @param form The optional ActionForm bean for this request (if any)
 * @param request The HTTP request we are processing
 * @param response The HTTP response we are creating
 *
 * @exception Exception if the application business logic throws
 *  an exception
 */
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    // Extract attributes and parameters we will need
    Locale locale = getLocale(request);
    MessageResources messages = getResources(request);
    HttpSession session = request.getSession();
    RegistrationForm regform = (RegistrationForm) form;
    String action = regform.getAction();
    if (action == null) {
        action = "Create";
    }
    UserDatabase database = (UserDatabase) servlet.getServletContext().getAttribute(Constants.DATABASE_KEY);
    if (log.isDebugEnabled()) {
        log.debug("SaveRegistrationAction:  Processing " + action + " action");
    }

    // Is there a currently logged on user (unless creating)?
    User user = (User) session.getAttribute(Constants.USER_KEY);
    if (!"Create".equals(action) && (user == null)) {
        if (log.isTraceEnabled()) {
            log.trace(" User is not logged on in session " + session.getId());
        }
        return (mapping.findForward("logon"));
    }

    // Was this transaction cancelled?
    if (isCancelled(request)) {
        if (log.isTraceEnabled()) {
            log.trace(" Transaction '" + action + "' was cancelled");
        }
        session.removeAttribute(Constants.SUBSCRIPTION_KEY);
        return (mapping.findForward("failure"));
    }

    // Validate the transactional control token
    ActionErrors errors = new ActionErrors();
    if (log.isTraceEnabled()) {
        log.trace(" Checking transactional control token");
    }
    if (!isTokenValid(request)) {
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.transaction.token"));
    }
    resetToken(request);

    // Validate the request parameters specified by the user
    if (log.isTraceEnabled()) {
        log.trace(" Performing extra validations");
    }
    String value = null;
    value = regform.getUsername();
    if (("Create".equals(action)) && (database.findUser(value) != null)) {
        errors.add("username", new ActionError("error.username.unique", regform.getUsername()));
    }
    if ("Create".equals(action)) {
        value = regform.getPassword();
        if ((value == null) || (value.length() < 1)) {
            errors.add("password", new ActionError("error.password.required"));
        }
        value = regform.getPassword2();
        if ((value == null) || (value.length() < 1)) {
            errors.add("password2", new ActionError("error.password2.required"));
        }
    }

    // Report any errors we have discovered back to the original form
    if (!errors.isEmpty()) {
        saveErrors(request, errors);
        saveToken(request);
        return (mapping.getInputForward());
    }

    // Update the user's persistent profile information
    try {
        if ("Create".equals(action)) {
            user = database.createUser(regform.getUsername());
        }
        String oldPassword = user.getPassword();
        PropertyUtils.copyProperties(user, regform);
        if ((regform.getPassword() == null) || (regform.getPassword().length() < 1)) {
            user.setPassword(oldPassword);
        }
    } catch (InvocationTargetException e) {
        Throwable t = e.getTargetException();
        if (t == null) {
            t = e;
        }
        log.error("Registration.populate", t);
        throw new ServletException("Registration.populate", t);
    } catch (Throwable t) {
        log.error("Registration.populate", t);
        throw new ServletException("Subscription.populate", t);
    }

    try {
        database.save();
    } catch (Exception e) {
        log.error("Database save", e);
    }

    // Log the user in if appropriate
    if ("Create".equals(action)) {
        session.setAttribute(Constants.USER_KEY, user);
        if (log.isTraceEnabled()) {
            log.trace(" User '" + user.getUsername() + "' logged on in session " + session.getId());
        }
    }

    // Remove the obsolete form bean
    if (mapping.getAttribute() != null) {
        if ("request".equals(mapping.getScope()))
            request.removeAttribute(mapping.getAttribute());
        else
            session.removeAttribute(mapping.getAttribute());
    }

    // Forward control to the specified success URI
    if (log.isTraceEnabled()) {
        log.trace(" Forwarding to success page");
    }
    return (mapping.findForward("success"));

}

From source file:org.sakaiproject.signup.tool.SignupServlet.java

protected void dispatch(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    ToolSession session = null;//  www .  j  a  v  a2  s.co m
    String target = req.getPathInfo();

    // see if we have a helper request
    if (sendToHelper(req, res, target)) {
        return;
    }

    // see if we have a resource request - i.e. a path with an extension,
    // and one that is not the JSF_EXT
    if (isResourceRequest(target)) {
        // get a dispatcher to the path
        RequestDispatcher resourceDispatcher = getServletContext().getRequestDispatcher(target);
        if (resourceDispatcher != null) {
            resourceDispatcher.forward(req, res);
            return;
        }
    }

    if ("Title".equals(req.getParameter("panel"))) {
        // This allows only one Title JSF for each tool
        target = "/title.jsf";
    }

    else {
        session = SessionManager.getCurrentToolSession();

        if (target == null || "/".equals(target) || target.length() == 0) {
            if (!m_defaultToLastView) {
                // make sure tool session is clean
                session.clearAttributes();
            }

            target = computeDefaultTarget();

            // make sure it's a valid path
            if (!target.startsWith("/")) {
                target = "/" + target;
            }

            // now that we've messed with the URL, send a redirect to make
            // it official
            res.sendRedirect(Web.returnUrl(req, target));
            return;
        }

        // see if we want to change the specifically requested view
        String newTarget = redirectRequestedTarget(target);

        // make sure it's a valid path
        if (!newTarget.startsWith("/")) {
            newTarget = "/" + newTarget;
        }

        if (!newTarget.equals(target)) {
            // now that we've messed with the URL, send a redirect to make
            // it official
            res.sendRedirect(Web.returnUrl(req, newTarget));
            return;
        }
        target = newTarget;

        // store this
        session.setAttribute(LAST_VIEW_VISITED, target);
    }

    // add the configured folder root and extension (if missing)
    target = m_path + target;

    // add the default JSF extension (if we have no extension)
    int lastSlash = target.lastIndexOf("/");
    int lastDot = target.lastIndexOf(".");
    if (lastDot < 0 || lastDot < lastSlash) {
        target += JSF_EXT;
    }

    // set the information that can be removed from return URLs
    req.setAttribute(URL_PATH, m_path);
    req.setAttribute(URL_EXT, ".jsp");

    // set the sakai request object wrappers to provide the native, not
    // Sakai set up, URL information
    // - this assures that the FacesServlet can dispatch to the proper view
    // based on the path info
    req.setAttribute(Tool.NATIVE_URL, Tool.NATIVE_URL);

    // TODO: Should setting the HTTP headers be moved up to the portal level
    // as well?
    res.setContentType("text/html; charset=UTF-8");
    res.addDateHeader("Expires", System.currentTimeMillis() - (1000L * 60L * 60L * 24L * 365L));
    res.addDateHeader("Last-Modified", System.currentTimeMillis());
    res.addHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0");
    res.addHeader("Pragma", "no-cache");

    if (session != null && ("true").equals(session.getAttribute("SENT_TO_FILEPICKER_HELPER"))) {
        AttachmentHandler bean = (AttachmentHandler) lookupBeanFromExternalServlet("AttachmentHandler", req,
                res);
        bean.setAttachmentItems();
        session.removeAttribute("SENT_TO_FILEPICKER_HELPER");
    }

    // dispatch to the target
    M_log.debug("dispatching path: " + req.getPathInfo() + " to: " + target + " context: "
            + getServletContext().getServletContextName());
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(target);
    dispatcher.forward(req, res);

    // restore the request object
    req.removeAttribute(Tool.NATIVE_URL);
    req.removeAttribute(URL_PATH);
    req.removeAttribute(URL_EXT);

    // see if we have a helper request
    if (!sendToHelper(req, res, "")) {
        ToolSession toolSession = SessionManager.getCurrentToolSession();
        if (("true").equals(toolSession.getAttribute("SENT_TO_FILEPICKER_HELPER"))) {
            AttachmentHandler bean = (AttachmentHandler) lookupBeanFromExternalServlet("AttachmentHandler", req,
                    res);
            bean.setAttachmentItems();
            toolSession.removeAttribute("SENT_TO_FILEPICKER_HELPER");
        }
    }
}