protected boolean addCategoryListToModel(
      List<Category> categoryList, Category rootCategory, String url, ModelMap model) {
    boolean categoryError = false;

    while (categoryList == null) {
      categoryError = true;

      int pos = url.indexOf("/");
      if (pos == -1) {
        categoryList = new ArrayList<Category>(1);
        categoryList.add(rootCategory);
      } else {
        url = url.substring(0, url.lastIndexOf("/"));
        List<Long> categoryIdList =
            catalogService.getChildCategoryURLMapByCategoryId(rootCategory.getId()).get(url);
        if (categoryIdList != null) {
          categoryList = new ArrayList<Category>(categoryIdList.size());
          for (Long id : categoryIdList) {
            categoryList.add(catalogService.findCategoryById(id));
          }
        }
      }
    }

    List<Category> siblingCategories = new ArrayList<Category>();
    Category currentCategory = (Category) categoryList.get(categoryList.size() - 1);
    siblingCategories = currentCategory.getAllChildCategories();

    model.addAttribute("breadcrumbCategories", categoryList);
    model.addAttribute("currentCategory", categoryList.get(categoryList.size() - 1));
    model.addAttribute("categoryError", categoryError);
    model.addAttribute("displayCategories", siblingCategories);

    return categoryError;
  }
  public Order setUpAnonymousCartWithGiftWrap() throws PricingException {
    Customer customer = customerService.saveCustomer(createNamedCustomer());

    Order order = cartService.createNewCartForCustomer(customer);

    Sku newSku = addTestSku("Small Plastic Crate", "Plastic Crate", "Crates");
    Sku newInactiveSku = addTestSku("Small Red Plastic Crate", "Plastic Crate", "Crates");
    Sku giftWrapSku = addTestSku("Gift Box", "Gift Box", "Gift Wraps");

    Product newProduct = newSku.getAllParentProducts().get(0);
    Category newCategory = newProduct.getDefaultCategory();

    List<OrderItem> addedItems = new ArrayList<OrderItem>();
    addedItems.add(
        orderService.addSkuToOrder(
            order.getId(), newSku.getId(), newProduct.getId(), newCategory.getId(), 2));
    addedItems.add(
        orderService.addSkuToOrder(
            order.getId(), newInactiveSku.getId(), newProduct.getId(), newCategory.getId(), 2));

    orderService.addGiftWrapItemToOrder(
        order, createGiftWrapOrderItemRequest(giftWrapSku, 1, addedItems));

    return order;
  }
  protected void addCategorySiteMapEntries(
      Category parentCategory,
      int currentDepth,
      CategorySiteMapGeneratorConfiguration categorySMGC,
      SiteMapBuilder siteMapBuilder) {
    // If we've reached beyond the ending depth, don't proceed
    if (currentDepth > categorySMGC.getEndingDepth()) {
      return;
    }

    // If we're at or past the starting depth, add this category to the site map
    if (currentDepth >= categorySMGC.getStartingDepth()) {
      constructSiteMapURL(categorySMGC, siteMapBuilder, parentCategory);
    }

    // Recurse on child categories in batches of size rowLimit
    int rowOffset = 0;
    List<Category> categories;
    do {
      categories =
          categoryDao.readActiveSubCategoriesByCategory(parentCategory, rowLimit, rowOffset);
      rowOffset += categories.size();
      for (Category category : categories) {
        if (StringUtils.isNotEmpty(category.getUrl())) {
          addCategorySiteMapEntries(category, currentDepth + 1, categorySMGC, siteMapBuilder);
        } else {
          LOG.debug("Skipping empty category URL: " + category.getId());
        }
      }
    } while (categories.size() == rowLimit);
  }
  public Order setUpNamedOrder() throws PricingException {
    Customer customer = customerService.saveCustomer(createNamedCustomer());

    Sku newSku = addTestSku("Small Cube Box", "Cube Box", "Boxes");

    Order order = orderService.createNamedOrderForCustomer("Boxes Named Order", customer);

    Product newProduct = newSku.getAllParentProducts().get(0);
    Category newCategory = newProduct.getDefaultCategory();

    orderService.addSkuToOrder(
        order.getId(), newSku.getId(), newProduct.getId(), newCategory.getId(), 2);

    return order;
  }
  public Order setUpExistingCart(Customer customer) throws PricingException {
    Sku newSku = addTestSku("Large Plastic Crate", "Plastic Crate", "Crates");
    Sku newOtherSku = addTestSku("Large Red Plastic Crate", "Plastic Crate", "Crates");

    Product newProduct = newSku.getAllParentProducts().get(0);
    Category newCategory = newProduct.getDefaultCategory();

    Order order = cartService.createNewCartForCustomer(customer);

    orderService.addSkuToOrder(
        order.getId(), newSku.getId(), newProduct.getId(), newCategory.getId(), 2);
    orderService.addSkuToOrder(
        order.getId(), newOtherSku.getId(), newProduct.getId(), newCategory.getId(), 2);

    return order;
  }
  private String showCatalog(ModelMap model, HttpServletRequest request, CatalogSort catalogSort) {
    addCategoryToModel(request, model);
    boolean productFound = addProductsToModel(request, model, catalogSort);

    String view = defaultCategoryView;
    if (productFound) {
      // TODO: Nice to have: product logic similar to category below
      view = defaultProductView;
    } else {
      Category currentCategory = (Category) model.get("currentCategory");
      if (currentCategory.getUrl() != null && !"".equals(currentCategory.getUrl())) {
        return "redirect:" + currentCategory.getUrl();
      } else if (currentCategory.getDisplayTemplate() != null
          && !"".equals(currentCategory.getUrl())) {
        view = categoryTemplatePrefix + currentCategory.getDisplayTemplate();
      } else {
        if ("true".equals(request.getParameter("ajax"))) {
          view = "catalog/categoryView/mainContentFragment";
        } else {
          view = defaultCategoryView;
        }
      }
    }

    if (catalogSort == null) {
      model.addAttribute("catalogSort", new CatalogSort());
    }

    List<Order> wishlists =
        cartService.findOrdersForCustomer(customerState.getCustomer(request), OrderStatus.NAMED);
    model.addAttribute("wishlists", wishlists);

    return view;
  }
  private void populateProducts(List<Product> productList, Category currentCategory) {

    for (FeaturedProduct featuredProduct : currentCategory.getFeaturedProducts()) {
      for (Product product : productList) {
        if ((product.equals(featuredProduct.getProduct()))) {
          product.setPromoMessage(featuredProduct.getPromotionMessage());
        }
      }
    }
  }
  public Order setUpExistingCartWithInactiveSkuAndInactiveBundle(Customer customer)
      throws PricingException {
    Sku newSku = addTestSku("Large Plastic Crate", "Plastic Crate", "Crates");
    Sku newInactiveSku = addTestSku("Large Red Plastic Crate", "Plastic Crate", "Crates", false);

    Product newProduct = newSku.getAllParentProducts().get(0);
    Category newCategory = newProduct.getDefaultCategory();

    Order order = cartService.createNewCartForCustomer(customer);

    orderService.addSkuToOrder(
        order.getId(), newSku.getId(), newProduct.getId(), newCategory.getId(), 2);
    orderService.addSkuToOrder(
        order.getId(), newInactiveSku.getId(), newProduct.getId(), newCategory.getId(), 2);

    orderService.addBundleItemToOrder(order, createBundleOrderItemRequest());
    orderService.addBundleItemToOrder(order, createBundleOrderItemRequestWithInactiveSku());

    return order;
  }
  protected void addCategoryToModel(HttpServletRequest request, ModelMap model) {
    Category rootCategory = null;
    if (getRootCategoryId() != null) {
      rootCategory = catalogService.findCategoryById(getRootCategoryId());
    } else if (getRootCategoryName() != null) {
      rootCategory = catalogService.findCategoryByName(getRootCategoryName());
    }

    if (rootCategory == null) {
      throw new IllegalStateException(
          "Catalog Controller configured incorrectly - rootId category not found: "
              + rootCategoryId);
    }

    String url =
        pathHelper.getRequestUri(request).substring(pathHelper.getContextPath(request).length());
    String categoryId = request.getParameter("categoryId");
    if (categoryId != null) {
      Category category = catalogService.findCategoryById(new Long(categoryId));
      if (category != null) {
        url = category.getUrl();
      }
    }

    List<Long> categoryIdList =
        catalogService.getChildCategoryURLMapByCategoryId(rootCategory.getId()).get(url);
    List<Category> categoryList = null;
    if (categoryIdList != null) {
      categoryList = new ArrayList<Category>(categoryIdList.size());
      for (Long id : categoryIdList) {
        categoryList.add(catalogService.findCategoryById(id));
      }
    }

    addCategoryListToModel(categoryList, rootCategory, url, model);
    model.addAttribute("rootCategory", rootCategory);
  }
  public Order setUpAnonymousCartWithBundleGiftWrapReferringToRootItems() throws PricingException {
    Customer customer = customerService.saveCustomer(createNamedCustomer());

    Order order = cartService.createNewCartForCustomer(customer);

    Sku newSku = addTestSku("Small Plastic Bowl", "Plastic Bowl", "Bowls");
    Sku newActiveSku = addTestSku("Small Red Plastic Bowl", "Plastic Bowl", "Bowls");

    Product newProduct = newSku.getAllParentProducts().get(0);
    Category newCategory = newProduct.getDefaultCategory();

    List<OrderItem> addedItems = new ArrayList<OrderItem>();
    addedItems.add(
        orderService.addSkuToOrder(
            order.getId(), newSku.getId(), newProduct.getId(), newCategory.getId(), 2));
    addedItems.add(
        orderService.addSkuToOrder(
            order.getId(), newActiveSku.getId(), newProduct.getId(), newCategory.getId(), 2));

    BundleOrderItem newBundle =
        (BundleOrderItem)
            orderService.addBundleItemToOrder(order, createBundleOrderItemRequestWithGiftWrap());
    GiftWrapOrderItem giftItem = null;
    for (DiscreteOrderItem addedItem : newBundle.getDiscreteOrderItems()) {
      if (addedItem instanceof GiftWrapOrderItem) {
        giftItem = (GiftWrapOrderItem) addedItem;
      }
    }
    for (OrderItem addedItem : addedItems) {
      addedItem.setGiftWrapOrderItem(giftItem);
    }
    giftItem.getWrappedItems().addAll(addedItems);
    order = orderService.save(order, false);

    return order;
  }
  public void test_categoryTag() throws JspException {
    categoryTag.setJspContext(pageContext);
    categoryTag.setVar("categoryVar");
    categoryTag.setCatalogService(catalogService);

    pageContext.setAttribute("categoryVar", category);
    EasyMock.expect(pageContext.getAttribute("categoryVar")).andReturn(category);

    categoryTag.setCategoryId(0L);
    EasyMock.expect(catalogService.findCategoryById(0L)).andReturn(category);

    super.replayAdditionalMockObjects(category);

    categoryTag.doTag();

    Category ret = (Category) pageContext.getAttribute("categoryVar");

    assert (category.equals(ret));

    super.verifyBaseMockObjects(category);
  }
  /*
   * This controller method is for demonstration purposes only. It contains a call to
   * catalogService.findActiveProductsByCategory, which may return a large list. A
   * more performant solution would be to utilize data paging techniques.
   */
  protected boolean validateProductAndAddToModel(Product product, ModelMap model) {
    Category currentCategory = (Category) model.get("currentCategory");
    Category rootCategory = (Category) model.get("rootCategory");
    int productPosition = 0;

    List<Product> productList =
        catalogService.findActiveProductsByCategory(currentCategory, SystemTime.asDate());
    if (productList != null) {
      populateProducts(productList, currentCategory);
      model.addAttribute("products", productList);
    }
    productPosition = findProductPositionInList(product, productList);
    if (productPosition == 0) {
      // look for product in its default category and override category from request URL
      currentCategory = product.getDefaultCategory();
      if (currentCategory.isActive()) {
        model.put("currentCategory", currentCategory);
        productList =
            catalogService.findActiveProductsByCategory(currentCategory, SystemTime.asDate());
        if (productList != null) {
          model.put("currentProducts", productList);
        }
        String url = currentCategory.getGeneratedUrl();

        // override category list settings using this products default
        List<Long> categoryIdList =
            catalogService.getChildCategoryURLMapByCategoryId(rootCategory.getId()).get(url);
        List<Category> categoryList = null;
        if (categoryIdList != null) {
          categoryList = new ArrayList<Category>(categoryIdList.size());
          for (Long id : categoryIdList) {
            categoryList.add(catalogService.findCategoryById(id));
          }
        }
        if (categoryList != null
            && !addCategoryListToModel(categoryList, rootCategory, url, model)) {
          productPosition = findProductPositionInList(product, productList);
        }
      }
    }

    if (productPosition != 0) {
      model.addAttribute("productError", false);
      model.addAttribute("currentProduct", product);
      model.addAttribute("productPosition", productPosition);
      if (productPosition != 1) {
        model.addAttribute("previousProduct", productList.get(productPosition - 2));
      }
      if (productPosition < productList.size()) {
        model.addAttribute("nextProduct", productList.get(productPosition));
      }
      model.addAttribute("totalProducts", productList.size());
    } else {
      model.addAttribute("productError", true);
    }

    WishlistRequest wishlistRequest = new WishlistRequest();
    wishlistRequest.setAddCategoryId(currentCategory.getId());
    wishlistRequest.setAddProductId(product.getId());
    wishlistRequest.setQuantity(1);
    wishlistRequest.setAddSkuId(((ProductSku) product).getSku().getId());
    model.addAttribute("wishlistRequest", wishlistRequest);

    return (productPosition != 0);
  }
 protected String generateUri(SiteMapBuilder siteMapBuilder, Category category) {
   return BroadleafFileUtils.appendUnixPaths(siteMapBuilder.getBaseUrl(), category.getUrl());
 }