@Test(
     groups = {"changeCustomerPassword"},
     dependsOnGroups = {"readCustomer"})
 @Transactional
 @Rollback(false)
 public void changeCustomerPasswords() {
   for (String userName : userNames) {
     Customer customer = customerService.readCustomerByUsername(userName);
     customer.setPassword(customer.getPassword() + "-Changed");
     customerService.saveCustomer(customer);
   }
 }
 @Test(
     groups = "createCustomers",
     dependsOnGroups = "createCustomerIdGeneration",
     dataProvider = "setupCustomers",
     dataProviderClass = CustomerDataProvider.class)
 @Rollback(false)
 public void createCustomer(Customer customerInfo) {
   Customer customer = customerService.createCustomerFromId(null);
   customer.setPassword(customerInfo.getPassword());
   customer.setUsername(customerInfo.getUsername());
   Long customerId = customer.getId();
   assert customerId != null;
   customer = customerService.saveCustomer(customer);
   assert customer.getId() == customerId;
   userIds.add(customer.getId());
   userNames.add(customer.getUsername());
 }
 @Test(
     groups = {"readCustomer"},
     dependsOnGroups = {"createCustomers"})
 public void readCustomersById() {
   for (Long userId : userIds) {
     Customer customer = customerService.readCustomerById(userId);
     assert customer.getId() == userId;
   }
 }
 /**
  * Implementors can subclass to change how anonymous customers are created.
  *
  * @param request
  * @return
  */
 public Customer resolveAnonymousCustomer(WebRequest request) {
   Customer customer;
   customer =
       (Customer)
           request.getAttribute(
               getAnonymousCustomerAttributeName(), WebRequest.SCOPE_GLOBAL_SESSION);
   if (customer == null) {
     customer = customerService.createNewCustomer();
     customer.setAnonymous(true);
     request.setAttribute(
         getAnonymousCustomerAttributeName(), customer, WebRequest.SCOPE_GLOBAL_SESSION);
   }
   return customer;
 }
 public String processUpdateAccount(
     HttpServletRequest request,
     Model model,
     UpdateAccountForm form,
     BindingResult result,
     RedirectAttributes redirectAttributes)
     throws ServiceException {
   updateAccountValidator.validate(form, result);
   if (result.hasErrors()) {
     return getUpdateAccountView();
   }
   Customer customer = CustomerState.getCustomer();
   customer.setEmailAddress(form.getEmailAddress());
   customer.setFirstName(form.getFirstName());
   customer.setLastName(form.getLastName());
   customerService.saveCustomer(customer);
   redirectAttributes.addFlashAttribute("successMessage", getAccountUpdatedMessage());
   return getAccountRedirectView();
 }
  public void validate(Object obj, Errors errors, boolean useEmailForUsername) {
    RegisterCustomerForm form = (RegisterCustomerForm) obj;

    Customer customerFromDb =
        customerService.readCustomerByUsername(form.getCustomer().getUsername());

    if (customerFromDb != null) {
      if (useEmailForUsername) {
        errors.rejectValue("customer.emailAddress", "emailAddress.used", null, null);
      } else {
        errors.rejectValue("customer.username", "username.used", null, null);
      }
    }

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "password.required");
    ValidationUtils.rejectIfEmptyOrWhitespace(
        errors, "passwordConfirm", "passwordConfirm.required");

    errors.pushNestedPath("customer");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "firstName.required");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "lastName.required");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "emailAddress", "emailAddress.required");
    errors.popNestedPath();

    if (!errors.hasErrors()) {

      if (!form.getPassword().matches(getValidatePasswordExpression())) {
        errors.rejectValue("password", "password.invalid", null, null);
      }

      if (!form.getPassword().equals(form.getPasswordConfirm())) {
        errors.rejectValue("password", "passwordConfirm.invalid", null, null);
      }

      if (!GenericValidator.isEmail(form.getCustomer().getEmailAddress())) {
        errors.rejectValue("customer.emailAddress", "emailAddress.invalid", null, null);
      }
    }
  }
  @Override
  public void process(WebRequest request) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    Customer customer = null;
    if ((authentication != null) && !(authentication instanceof AnonymousAuthenticationToken)) {
      String userName = authentication.getName();
      customer =
          (Customer) request.getAttribute(customerRequestAttributeName, WebRequest.SCOPE_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) {
        ApplicationEvent lastPublishedEvent =
            (ApplicationEvent)
                request.getAttribute(
                    LAST_PUBLISHED_EVENT_SESSION_ATTRIBUTED_NAME, WebRequest.SCOPE_REQUEST);
        if (authentication instanceof RememberMeAuthenticationToken) {
          // set transient property of customer
          customer.setCookied(true);
          boolean publishRememberMeEvent = true;
          if (lastPublishedEvent != null
              && lastPublishedEvent instanceof CustomerAuthenticatedFromCookieEvent) {
            CustomerAuthenticatedFromCookieEvent cookieEvent =
                (CustomerAuthenticatedFromCookieEvent) lastPublishedEvent;
            if (userName.equals(cookieEvent.getCustomer().getUsername())) {
              publishRememberMeEvent = false;
            }
          }
          if (publishRememberMeEvent) {
            CustomerAuthenticatedFromCookieEvent cookieEvent =
                new CustomerAuthenticatedFromCookieEvent(customer, this.getClass().getName());
            eventPublisher.publishEvent(cookieEvent);
            request.setAttribute(
                LAST_PUBLISHED_EVENT_SESSION_ATTRIBUTED_NAME,
                cookieEvent,
                WebRequest.SCOPE_REQUEST);
          }
        } else if (authentication instanceof UsernamePasswordAuthenticationToken) {
          customer.setLoggedIn(true);
          boolean publishLoggedInEvent = true;
          if (lastPublishedEvent != null && lastPublishedEvent instanceof CustomerLoggedInEvent) {
            CustomerLoggedInEvent loggedInEvent = (CustomerLoggedInEvent) lastPublishedEvent;
            if (userName.equals(loggedInEvent.getCustomer().getUsername())) {
              publishLoggedInEvent = false;
            }
          }
          if (publishLoggedInEvent) {
            CustomerLoggedInEvent loggedInEvent =
                new CustomerLoggedInEvent(customer, this.getClass().getName());
            eventPublisher.publishEvent(loggedInEvent);
            request.setAttribute(
                LAST_PUBLISHED_EVENT_SESSION_ATTRIBUTED_NAME,
                loggedInEvent,
                WebRequest.SCOPE_REQUEST);
          }
        } 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);
    }
    request.setAttribute(customerRequestAttributeName, customer, WebRequest.SCOPE_REQUEST);

    // Setup customer for content rule processing
    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);
  }