Example usage for org.springframework.web.context.request WebRequest setAttribute

List of usage examples for org.springframework.web.context.request WebRequest setAttribute

Introduction

In this page you can find the example usage for org.springframework.web.context.request WebRequest setAttribute.

Prototype

void setAttribute(String name, Object value, int scope);

Source Link

Document

Set the value for the scoped attribute of the given name, replacing an existing value (if any).

Usage

From source file:org.broadleafcommerce.common.web.BroadleafTimeZoneResolverImpl.java

@Override
public TimeZone resolveTimeZone(WebRequest request) {
    TimeZone timeZone = null;/*from   w w  w  .  jav  a  2  s. c om*/

    // First check for request attribute
    timeZone = (TimeZone) request.getAttribute(TIMEZONE_VAR, WebRequest.SCOPE_REQUEST);

    // Second, check for a request parameter
    if (timeZone == null && BLCRequestUtils.getURLorHeaderParameter(request, TIMEZONE_CODE_PARAM) != null) {
        String timeZoneCode = BLCRequestUtils.getURLorHeaderParameter(request, TIMEZONE_CODE_PARAM);
        timeZone = TimeZone.getTimeZone(timeZoneCode);

        if (LOG.isTraceEnabled()) {
            LOG.trace("Attempt to find TimeZone by param " + timeZoneCode + " resulted in " + timeZone);
        }
    }

    // Third, check the session 
    if (timeZone == null && BLCRequestUtils.isOKtoUseSession(request)) {
        //@TODO verify if we should take this from global session
        timeZone = (TimeZone) request.getAttribute(TIMEZONE_VAR, WebRequest.SCOPE_GLOBAL_SESSION);
        if (LOG.isTraceEnabled()) {
            LOG.trace("Attempt to find timezone from session resulted in " + timeZone);
        }
    }

    // Finally, use the default
    if (timeZone == null) {
        timeZone = TimeZone.getDefault();

        if (LOG.isTraceEnabled()) {
            LOG.trace("timezone set to default timezone " + timeZone);
        }
    }

    if (BLCRequestUtils.isOKtoUseSession(request)) {
        request.setAttribute(TIMEZONE_VAR, timeZone, WebRequest.SCOPE_GLOBAL_SESSION);
    }
    return timeZone;
}

From source file:org.broadleafcommerce.core.web.order.security.CartStateRequestProcessor.java

@Override
public void process(WebRequest request) {
    Customer customer = CustomerState.getCustomer();

    if (customer == null) {
        LOG.warn(/*from   ww w. j  a  v  a 2 s  .  c om*/
                "No customer was found on the current request, no cart will be added to the current request. Ensure that the"
                        + " blCustomerStateFilter occurs prior to the blCartStateFilter");
        return;
    }

    Order cart = getOverrideCart(request);

    if (cart == null && mergeCartNeeded(customer, request)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Merge cart required, calling mergeCart " + customer.getId());
        }
        cart = mergeCart(customer, request);
    } else if (cart == null) {
        cart = orderService.findCartForCustomer(customer);
    }

    if (cart == null) {
        cart = orderService.getNullOrder();
    } else {
        updateCartService.updateAndValidateCart(cart);
    }

    request.setAttribute(cartRequestAttributeName, cart, WebRequest.SCOPE_REQUEST);

    // Setup cart for content rule processing
    @SuppressWarnings("unchecked")
    Map<String, Object> ruleMap = (Map<String, Object>) request.getAttribute(BLC_RULE_MAP_PARAM,
            WebRequest.SCOPE_REQUEST);
    if (ruleMap == null) {
        ruleMap = new HashMap<String, Object>();
    }
    ruleMap.put("order", cart);

    // Leaving the following line in for backwards compatibility, but all rules should use order as the 
    // variable name.
    ruleMap.put("cart", cart);
    request.setAttribute(BLC_RULE_MAP_PARAM, ruleMap, WebRequest.SCOPE_REQUEST);

}

From source file:org.broadleafcommerce.core.web.order.security.CartStateRequestProcessor.java

/**
 * Looks up the anonymous customer and merges that cart with the cart from the given logged in <b>customer</b>. This
 * will also remove the customer from session after it has finished since it is no longer needed
 *//*from  w w w .ja v  a  2 s  .co m*/
public Order mergeCart(Customer customer, WebRequest request) {
    Customer anonymousCustomer = customerStateRequestProcessor.getAnonymousCustomer(request);
    MergeCartResponse mergeCartResponse;
    try {
        Order cart = orderService.findCartForCustomer(anonymousCustomer);
        mergeCartResponse = mergeCartService.mergeCart(customer, cart);
    } catch (PricingException e) {
        throw new RuntimeException(e);
    } catch (RemoveFromCartException e) {
        throw new RuntimeException(e);
    }

    if (BLCRequestUtils.isOKtoUseSession(request)) {
        // The anonymous customer from session is no longer needed; it can be safely removed
        request.removeAttribute(CustomerStateRequestProcessor.getAnonymousCustomerSessionAttributeName(),
                WebRequest.SCOPE_GLOBAL_SESSION);
        request.removeAttribute(CustomerStateRequestProcessor.getAnonymousCustomerIdSessionAttributeName(),
                WebRequest.SCOPE_GLOBAL_SESSION);

        request.setAttribute(mergeCartResponseKey, mergeCartResponse, WebRequest.SCOPE_GLOBAL_SESSION);
    }
    return mergeCartResponse.getOrder();
}

From source file:org.broadleafcommerce.openadmin.web.filter.BroadleafAdminRequestProcessor.java

protected void prepareProfile(WebRequest request, BroadleafRequestContext brc) {
    AdminUser adminUser = adminRemoteSecurityService.getPersistentAdminUser();
    if (adminUser == null) {
        //clear any profile
        if (BLCRequestUtils.isOKtoUseSession(request)) {
            request.removeAttribute(PROFILE_REQ_PARAM, WebRequest.SCOPE_GLOBAL_SESSION);
        }// ww w  . j av a2s .c om
    } else {
        Site profile = null;
        if (StringUtils.isNotBlank(request.getParameter(PROFILE_REQ_PARAM))) {
            Long profileId = Long.parseLong(request.getParameter(PROFILE_REQ_PARAM));
            profile = siteService.retrievePersistentSiteById(profileId);
            if (profile == null) {
                throw new IllegalArgumentException(
                        String.format("Unable to find the requested profile: %s", profileId));
            }
        }

        if (profile == null) {
            Long previouslySetProfileId = null;
            if (BLCRequestUtils.isOKtoUseSession(request)) {
                previouslySetProfileId = (Long) request.getAttribute(PROFILE_REQ_PARAM,
                        WebRequest.SCOPE_GLOBAL_SESSION);
            }
            if (previouslySetProfileId != null) {
                profile = siteService.retrievePersistentSiteById(previouslySetProfileId);
            }
        }

        if (profile == null) {
            List<Site> profiles = new ArrayList<Site>();
            if (brc.getNonPersistentSite() != null) {
                Site currentSite = siteService.retrievePersistentSiteById(brc.getNonPersistentSite().getId());
                if (extensionManager != null) {
                    ExtensionResultHolder<Set<Site>> profilesResult = new ExtensionResultHolder<Set<Site>>();
                    extensionManager.getProxy().retrieveProfiles(currentSite, profilesResult);
                    if (!CollectionUtils.isEmpty(profilesResult.getResult())) {
                        profiles.addAll(profilesResult.getResult());
                    }
                }
            }
            if (profiles.size() == 1) {
                profile = profiles.get(0);
            }
        }

        if (profile != null) {
            if (BLCRequestUtils.isOKtoUseSession(request)) {
                request.setAttribute(PROFILE_REQ_PARAM, profile.getId(), WebRequest.SCOPE_GLOBAL_SESSION);
            }
            brc.setCurrentProfile(profile);
        }
    }
}

From source file:org.broadleafcommerce.openadmin.web.filter.BroadleafAdminRequestProcessor.java

protected void prepareCatalog(WebRequest request, BroadleafRequestContext brc) {
    AdminUser adminUser = adminRemoteSecurityService.getPersistentAdminUser();
    if (adminUser == null) {
        //clear any catalog
        if (BLCRequestUtils.isOKtoUseSession(request)) {
            request.removeAttribute(CATALOG_REQ_PARAM, WebRequest.SCOPE_GLOBAL_SESSION);
        }/*  w  w  w .j a v  a  2 s  .c  om*/
    } else {
        Catalog catalog = null;
        if (StringUtils.isNotBlank(request.getParameter(CATALOG_REQ_PARAM))) {
            Long catalogId = Long.parseLong(request.getParameter(CATALOG_REQ_PARAM));
            catalog = siteService.findCatalogById(catalogId);
            if (catalog == null) {
                throw new IllegalArgumentException(
                        String.format("Unable to find the requested catalog: %s", catalogId));
            }
        }

        if (catalog == null) {
            Long previouslySetCatalogId = null;
            if (BLCRequestUtils.isOKtoUseSession(request)) {
                previouslySetCatalogId = (Long) request.getAttribute(CATALOG_REQ_PARAM,
                        WebRequest.SCOPE_GLOBAL_SESSION);
            }
            if (previouslySetCatalogId != null) {
                catalog = siteService.findCatalogById(previouslySetCatalogId);
            }
        }

        if (catalog == null) {
            List<Catalog> catalogs = new ArrayList<Catalog>();
            if (brc.getNonPersistentSite() != null) {
                Site currentSite = siteService.retrievePersistentSiteById(brc.getNonPersistentSite().getId());
                if (extensionManager != null) {
                    ExtensionResultHolder<Set<Catalog>> catalogResult = new ExtensionResultHolder<Set<Catalog>>();
                    extensionManager.getProxy().retrieveCatalogs(currentSite, catalogResult);
                    if (!CollectionUtils.isEmpty(catalogResult.getResult())) {
                        catalogs.addAll(catalogResult.getResult());
                    }
                }
            }
            if (catalogs.size() == 1) {
                catalog = catalogs.get(0);
            }
        }

        if (catalog != null) {
            if (BLCRequestUtils.isOKtoUseSession(request)) {
                request.setAttribute(CATALOG_REQ_PARAM, catalog.getId(), WebRequest.SCOPE_GLOBAL_SESSION);
            }
            brc.setCurrentCatalog(catalog);
        }
    }
}

From source file:org.broadleafcommerce.openadmin.web.filter.BroadleafAdminRequestProcessor.java

protected void prepareSandBox(WebRequest request, BroadleafRequestContext brc) {
    AdminUser adminUser = adminRemoteSecurityService.getPersistentAdminUser();
    if (adminUser == null) {
        //clear any sandbox
        if (BLCRequestUtils.isOKtoUseSession(request)) {
            request.removeAttribute(BroadleafSandBoxResolver.SANDBOX_ID_VAR, WebRequest.SCOPE_GLOBAL_SESSION);
        }//from ww  w  .j  a  va  2 s  .  c om
    } else {
        SandBox sandBox = null;
        if (StringUtils.isNotBlank(request.getParameter(SANDBOX_REQ_PARAM))) {
            Long sandBoxId = Long.parseLong(request.getParameter(SANDBOX_REQ_PARAM));
            sandBox = sandBoxService.retrieveUserSandBoxForParent(adminUser.getId(), sandBoxId);
            if (sandBox == null) {
                SandBox approvalOrUserSandBox = sandBoxService.retrieveSandBoxManagementById(sandBoxId);
                if (approvalOrUserSandBox != null) {
                    if (approvalOrUserSandBox.getSandBoxType().equals(SandBoxType.USER)) {
                        sandBox = approvalOrUserSandBox;
                    } else {
                        sandBox = sandBoxService.createUserSandBox(adminUser.getId(), approvalOrUserSandBox);
                    }
                }
            }
        }

        if (sandBox == null) {
            Long previouslySetSandBoxId = null;
            if (BLCRequestUtils.isOKtoUseSession(request)) {
                previouslySetSandBoxId = (Long) request.getAttribute(BroadleafSandBoxResolver.SANDBOX_ID_VAR,
                        WebRequest.SCOPE_GLOBAL_SESSION);
            }
            if (previouslySetSandBoxId != null) {
                sandBox = sandBoxService.retrieveSandBoxManagementById(previouslySetSandBoxId);
            }
        }

        if (sandBox == null) {
            List<SandBox> defaultSandBoxes = sandBoxService.retrieveSandBoxesByType(SandBoxType.DEFAULT);
            if (defaultSandBoxes.size() > 1) {
                throw new IllegalStateException("Only one sandbox should be configured as default");
            }

            SandBox defaultSandBox;
            if (defaultSandBoxes.size() == 1) {
                defaultSandBox = defaultSandBoxes.get(0);
            } else {
                defaultSandBox = sandBoxService.createDefaultSandBox();
            }

            sandBox = sandBoxService.retrieveUserSandBoxForParent(adminUser.getId(), defaultSandBox.getId());
            if (sandBox == null) {
                sandBox = sandBoxService.createUserSandBox(adminUser.getId(), defaultSandBox);
            }
        }

        // If the user just changed sandboxes, we want to update the database record.
        Long previouslySetSandBoxId = null;
        if (BLCRequestUtils.isOKtoUseSession(request)) {
            previouslySetSandBoxId = (Long) request.getAttribute(BroadleafSandBoxResolver.SANDBOX_ID_VAR,
                    WebRequest.SCOPE_GLOBAL_SESSION);
        }
        if (previouslySetSandBoxId != null && !sandBox.getId().equals(previouslySetSandBoxId)) {
            adminUser.setLastUsedSandBoxId(sandBox.getId());
            adminUser = adminSecurityService.saveAdminUser(adminUser);
        }

        if (BLCRequestUtils.isOKtoUseSession(request)) {
            request.setAttribute(BroadleafSandBoxResolver.SANDBOX_ID_VAR, sandBox.getId(),
                    WebRequest.SCOPE_GLOBAL_SESSION);
        }
        brc.setSandBox(sandBox);
        brc.setDeployBehavior(deployBehaviorUtil.isProductionSandBoxMode() ? DeployBehavior.CLONE_PARENT
                : DeployBehavior.OVERWRITE_PARENT);
        brc.getAdditionalProperties().put("adminUser", adminUser);
    }
}

From source file:org.broadleafcommerce.profile.web.core.security.CustomerStateRequestProcessor.java

@Override
public void process(WebRequest request) {
    Customer customer = null;/*from  ww w. j  av  a 2 s.c o  m*/
    Long overrideId = null;
    if (BLCRequestUtils.isOKtoUseSession(request)) {
        overrideId = (Long) request.getAttribute(OVERRIDE_CUSTOMER_SESSION_ATTR_NAME,
                WebRequest.SCOPE_GLOBAL_SESSION);
    }
    if (overrideId != null) {
        customer = customerService.readCustomerById(overrideId);
        if (customer != null && !customer.isRegistered() && !customer.isLoggedIn() && !customer.isCookied()) {
            customer.setAnonymous(true);
        }
    } else {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if ((authentication != null) && !(authentication instanceof AnonymousAuthenticationToken)) {
            String userName = authentication.getName();
            customer = (Customer) BroadleafRequestCustomerResolverImpl.getRequestCustomerResolver()
                    .getCustomer(request);
            if (userName != null && (customer == null || !userName.equals(customer.getUsername()))) {
                // can only get here if the authenticated user does not match the user in session
                customer = customerService.readCustomerByUsername(userName);
                if (logger.isDebugEnabled() && customer != null) {
                    logger.debug("Customer found by username " + userName);
                }
            }
            if (customer != null) {
                String lastPublishedEventClass = (String) BLCRequestUtils.getSessionAttributeIfOk(request,
                        LAST_PUBLISHED_EVENT_CLASS_SESSION_ATTRIBUTE_NAME);
                String eventUsername = (String) BLCRequestUtils.getSessionAttributeIfOk(request,
                        LAST_PUBLISHED_EVENT_USERNAME_SESSION_ATTRIBUTE_NAME);

                if (authentication instanceof RememberMeAuthenticationToken) {
                    // set transient property of customer
                    customer.setCookied(true);
                    boolean publishRememberMeEvent = true;
                    if (CustomerAuthenticatedFromCookieEvent.class.getName().equals(lastPublishedEventClass)) {
                        if (userName.equals(eventUsername)) {
                            publishRememberMeEvent = false;
                        }
                    }
                    if (publishRememberMeEvent) {
                        CustomerAuthenticatedFromCookieEvent cookieEvent = new CustomerAuthenticatedFromCookieEvent(
                                customer, this.getClass().getName());
                        publishEvent(cookieEvent, request, CustomerAuthenticatedFromCookieEvent.class.getName(),
                                userName);
                    }
                } else if (authentication instanceof UsernamePasswordAuthenticationToken) {
                    customer.setLoggedIn(true);
                    boolean publishLoggedInEvent = true;
                    if (CustomerLoggedInEvent.class.getName().equals(lastPublishedEventClass)) {
                        if (userName.equals(eventUsername)) {
                            publishLoggedInEvent = false;
                        }
                    }
                    if (publishLoggedInEvent) {
                        CustomerLoggedInEvent loggedInEvent = new CustomerLoggedInEvent(customer,
                                this.getClass().getName());
                        publishEvent(loggedInEvent, request, CustomerLoggedInEvent.class.getName(), userName);
                    }
                } else {
                    customer = resolveAuthenticatedCustomer(authentication);
                }
            }
        }
    }

    if (customer == null) {
        // This is an anonymous customer.
        // TODO: Handle a custom cookie (different than remember me) that is just for anonymous users.  
        // This can be used to remember their cart from a previous visit.
        // Cookie logic probably needs to be configurable - with TCS as the exception.

        customer = resolveAnonymousCustomer(request);
    } else {
        //Does this customer need to have an anonymous customer's data merged into it?
        customer = mergeCustomerIfRequired(request, customer);
    }
    CustomerState.setCustomer(customer);

    // Setup customer for content rule processing
    @SuppressWarnings("unchecked")
    Map<String, Object> ruleMap = (Map<String, Object>) request.getAttribute(BLC_RULE_MAP_PARAM,
            WebRequest.SCOPE_REQUEST);
    if (ruleMap == null) {
        ruleMap = new HashMap<String, Object>();
    }
    ruleMap.put("customer", customer);
    request.setAttribute(BLC_RULE_MAP_PARAM, ruleMap, WebRequest.SCOPE_REQUEST);

}

From source file:org.broadleafcommerce.profile.web.core.security.CustomerStateRequestProcessor.java

/**
 * Allows the merging of anonymous customer data and / or session data, to the logged in customer, if required. 
 * This is written to only require it to happen once.
 * @param request/*  w  w w.j av a 2 s . c  o m*/
 * @param customer
 * @return
 */
protected Customer mergeCustomerIfRequired(WebRequest request, Customer customer) {
    if (BLCRequestUtils.isOKtoUseSession(request)) {
        //Don't call this if it has already been called
        if (request.getAttribute(getAnonymousCustomerMergedSessionAttributeName(),
                WebRequest.SCOPE_GLOBAL_SESSION) == null) {
            //Set this so we don't do this every time.
            request.setAttribute(getAnonymousCustomerMergedSessionAttributeName(), Boolean.TRUE,
                    WebRequest.SCOPE_GLOBAL_SESSION);

            Customer anonymousCustomer = getAnonymousCustomer(request);
            customer = copyAnonymousCustomerInfoToCustomer(request, anonymousCustomer, customer);
        }
    }
    return customer;
}

From source file:org.broadleafcommerce.profile.web.core.security.CustomerStateRequestProcessor.java

/**
 * <p>Implementors can subclass to change how anonymous customers are created. Note that this method is intended to actually create the anonymous
 * customer if one does not exist. If you are looking to just get the current anonymous customer (if it exists) then instead use the
 * {@link #getAnonymousCustomer(WebRequest)} method.<p>
 * /*from ww  w . j  a va 2 s  .  co  m*/
 * <p>The intended behavior of this method is as follows:</p>
 * 
 * <ul>
 *  <li>Look for a {@link Customer} on the session</li>
 *  <ul>
 *      <li>If a customer is found in session, keep using the session-based customer</li>
 *      <li>If a customer is not found in session</li>
 *      <ul>
 *          <li>Look for a customer ID in session</li>
 *          <li>If a customer ID is found in session:</li>
 *          <ul><li>Look up the customer in the database</ul></li>
 *      </ul>
 *      <li>If no there is no customer ID in session (and thus no {@link Customer})</li>
 *      <ol>
 *          <li>Create a new customer</li>
 *          <li>Put the newly-created {@link Customer} in session</li>
 *      </ol>
 *  </ul>
 * </ul>
 * 
 * @param request
 * @return
 * @see {@link #getAnonymousCustomer(WebRequest)}
 * @see {@link #getAnonymousCustomerAttributeName()}
 * @see {@link #getAnonymousCustomerIdAttributeName()}
 */
public Customer resolveAnonymousCustomer(WebRequest request) {
    Customer customer;
    customer = getAnonymousCustomer(request);

    //If there is no Customer object in session, AND no customer id in session, create a new customer
    //and store the entire customer in session (don't persist to DB just yet)
    if (customer == null) {
        customer = customerService.createNewCustomer();
        if (BLCRequestUtils.isOKtoUseSession(request)) {
            request.setAttribute(getAnonymousCustomerSessionAttributeName(), customer,
                    WebRequest.SCOPE_GLOBAL_SESSION);
        }
    }
    customer.setAnonymous(true);

    return customer;
}

From source file:org.encuestame.oauth1.support.OAuth1RequestFlow.java

/**
 *
 * @param scope/*from   www  .j a va 2  s . co m*/
 * @param request
 * @param httpRequest
 * @return
 * @throws EnMeOAuthSecurityException
 */
public String buildOAuth1AuthorizeUrl(final String scope, final WebRequest request,
        final HttpServletRequest httpRequest) throws EnMeOAuthSecurityException {
    final OAuth1Token requestToken = this.getRequestToken(httpRequest);
    request.setAttribute(OAuthUtils.OAUTH_TOKEN_ATTRIBUTE, requestToken, WebRequest.SCOPE_SESSION);
    return this.buildRequestTokenUrl(httpRequest);
}