/**
  * This is the main entry point for retrieving an object from this cache.
  *
  * @see org.broadleafcommerce.common.cache.StatisticsService
  * @param responseClass the class representing the type of the cache item
  * @param cacheName the name of the cache - the ehcache region name
  * @param statisticsName the name to use for cache hit statistics
  * @param retrieval the block of code to execute if a cache miss is not found in this cache
  * @param params the appropriate params comprising a unique key for this cache item
  * @param <T> the type of the cache item
  * @return The object retrieved from the executiom of the PersistentRetrieval, or null if a cache
  *     miss was found in this cache
  */
 protected <T> T getCachedObject(
     Class<T> responseClass,
     String cacheName,
     String statisticsName,
     PersistentRetrieval<T> retrieval,
     String... params) {
   T nullResponse = getNullObject(responseClass);
   BroadleafRequestContext context = BroadleafRequestContext.getBroadleafRequestContext();
   String key = buildKey(params);
   T response = null;
   if (context.isProductionSandBox()) {
     response = getObjectFromCache(key, cacheName);
   }
   if (response == null) {
     response = retrieval.retrievePersistentObject();
     if (response == null) {
       response = nullResponse;
     }
     // only handle null, non-hits. Otherwise, let level 2 cache handle it
     if (context.isProductionSandBox() && response.equals(nullResponse)) {
       statisticsService.addCacheStat(statisticsName, false);
       getCache(cacheName).put(new Element(key, response));
       if (getLogger().isTraceEnabled()) {
         getLogger().trace("Caching [" + key + "] as null in the [" + cacheName + "] cache.");
       }
     }
   } else {
     statisticsService.addCacheStat(statisticsName, true);
   }
   if (response.equals(nullResponse)) {
     return null;
   }
   return response;
 }
  protected String getText(Arguments arguments, Element element, String attributeName) {
    Money price;

    try {
      price =
          (Money)
              StandardExpressionProcessor.processExpression(
                  arguments, element.getAttributeValue(attributeName));
    } catch (ClassCastException e) {
      Number value =
          (Number)
              StandardExpressionProcessor.processExpression(
                  arguments, element.getAttributeValue(attributeName));
      price = new Money(value.doubleValue());
    }

    if (price == null) {
      return "Not Available";
    }
    BroadleafRequestContext brc = BroadleafRequestContext.getBroadleafRequestContext();
    if (brc.getJavaLocale() != null) {
      NumberFormat format = NumberFormat.getCurrencyInstance(brc.getJavaLocale());
      if (price.getCurrency().getCurrencyCode().equals("AUD")) {
        return "☯ " + price.getAmount().toString();
      }
      format.setCurrency(price.getCurrency());
      return format.format(price.getAmount());
    } else {

      return "$ " + price.getAmount().toString();
    }
  }
 /**
  * Build the key representing this missed cache item. Will include sandbox information if
  * appropriate.
  *
  * @param params the appropriate params comprising a unique key for this cache item
  * @return the completed key
  */
 protected String buildKey(String... params) {
   BroadleafRequestContext context = BroadleafRequestContext.getBroadleafRequestContext();
   SandBox sandBox = context.getSandBox();
   String key = StringUtils.join(params, '_');
   if (sandBox != null) {
     key = sandBox.getId() + "_" + key;
   }
   return key;
 }
 protected java.util.Locale convertLocaleToJavaLocale() {
   if (locale == null || locale.getLocaleCode() == null) {
     return java.util.Locale.getDefault();
   } else {
     return BroadleafRequestContext.convertLocaleToJavaLocale(locale);
   }
 }
  @Override
  public PropertyValidationResult validate(
      Entity entity,
      Serializable instance,
      Map<String, FieldMetadata> entityFieldMetadata,
      Map<String, String> validationConfiguration,
      BasicFieldMetadata propertyMetadata,
      String propertyName,
      String value) {
    String errorMessage = "";

    String compareFieldName = lookupCompareFieldName(propertyName, validationConfiguration);
    String compareFieldValue = validationConfiguration.get("compareFieldValue");
    String compareFieldRegEx = validationConfiguration.get("compareFieldRegEx");
    Property compareFieldProperty = null;

    boolean valid = true;
    if (StringUtils.isEmpty(value)) {
      compareFieldProperty = entity.getPMap().get(compareFieldName);

      if (compareFieldProperty != null) {
        if (compareFieldValue != null) {
          valid = !compareFieldValue.equals(compareFieldProperty.getValue());
        } else if (compareFieldRegEx != null) {
          String expression = validationConfiguration.get("compareFieldRegEx");
          valid = !compareFieldProperty.getValue().matches(expression);
        }
      }
    }

    if (!valid) {
      BroadleafRequestContext context = BroadleafRequestContext.getBroadleafRequestContext();
      MessageSource messages = context.getMessageSource();

      FieldMetadata fmd = entityFieldMetadata.get(compareFieldName);
      String fieldName = messages.getMessage(fmd.getFriendlyName(), null, context.getJavaLocale());
      errorMessage =
          messages.getMessage(
              "requiredIfValidationFailure",
              new Object[] {fieldName, compareFieldProperty.getValue()},
              context.getJavaLocale());
    }

    return new PropertyValidationResult(valid, errorMessage);
  }
  @Override
  @Transactional("blTransactionManager")
  public Order createNamedOrderForCustomer(String name, Customer customer) {
    Order namedOrder = orderDao.create();
    namedOrder.setCustomer(customer);
    namedOrder.setName(name);
    namedOrder.setStatus(OrderStatus.NAMED);

    if (extensionManager != null) {
      extensionManager.getProxy().attachAdditionalDataToNewNamedCart(customer, namedOrder);
    }

    if (BroadleafRequestContext.getBroadleafRequestContext() != null) {
      namedOrder.setLocale(BroadleafRequestContext.getBroadleafRequestContext().getLocale());
    }

    return orderDao.save(namedOrder); // No need to price here
  }
  public String getLabel() {
    if (getTranslations() != null && BroadleafRequestContext.hasLocale()) {
      Locale locale = BroadleafRequestContext.getBroadleafRequestContext().getLocale();

      // Search for translation based on locale
      String localeCode = locale.getLocaleCode();
      if (localeCode != null) {
        ProductOptionTranslation translation = getTranslations().get(localeCode);
        if (translation != null && translation.getLabel() != null) {
          return translation.getLabel();
        }
      }

      // try just the language
      String languageCode = LocaleUtil.findLanguageCode(locale);
      if (languageCode != null && !localeCode.equals(languageCode)) {
        ProductOptionTranslation translation = getTranslations().get(languageCode);
        if (translation != null && translation.getLabel() != null) {
          return translation.getLabel();
        }
      }
    }
    return label;
  }
  @Override
  @SuppressWarnings("unchecked")
  protected Map<String, String> getModifiedAttributeValues(
      Arguments arguments, Element element, String attributeName) {
    Map<String, String> attrs = new HashMap<String, String>();

    BroadleafRequestContext blcContext = BroadleafRequestContext.getBroadleafRequestContext();
    HttpServletRequest request = blcContext.getRequest();

    String baseUrl = request.getRequestURL().toString();
    Map<String, String[]> params = new HashMap<String, String[]>(request.getParameterMap());

    String key = ProductSearchCriteria.SORT_STRING;
    String sortField = element.getAttributeValue(attributeName);

    List<String[]> sortedFields = new ArrayList<String[]>();

    String[] paramValues = params.get(key);
    if (paramValues != null && paramValues.length > 0) {
      String sortQueries = paramValues[0];
      for (String sortQuery : sortQueries.split(",")) {
        String[] sort = sortQuery.split(" ");
        if (sort.length == 2) {
          sortedFields.add(new String[] {sort[0], sort[1]});
        }
      }
    }

    boolean currentlySortingOnThisField = false;
    boolean currentlyAscendingOnThisField = false;

    for (String[] sortedField : sortedFields) {
      if (sortField.equals(sortedField[0])) {
        currentlySortingOnThisField = true;
        currentlyAscendingOnThisField = sortedField[1].equals("asc");
        sortedField[1] = currentlyAscendingOnThisField ? "desc" : "asc";
      }
    }

    String sortString = sortField;
    String classString = "";

    if (currentlySortingOnThisField) {
      classString += "active ";
      if (currentlyAscendingOnThisField) {
        sortString += " desc";
        classString += "asc ";
      } else {
        sortString += " asc";
        classString += "desc ";
      }
    } else {
      sortString += " asc";
      classString += "asc ";
      params.remove(ProductSearchCriteria.PAGE_NUMBER);
    }

    if (allowMultipleSorts) {
      StringBuilder sortSb = new StringBuilder();
      for (String[] sortedField : sortedFields) {
        sortSb.append(sortedField[0]).append(" ").append(sortedField[1]).append(",");
      }

      sortString = sortSb.toString();
      if (sortString.charAt(sortString.length() - 1) == ',') {
        sortString = sortString.substring(0, sortString.length() - 1);
      }
    }

    params.put(key, new String[] {sortString});

    String url = ProcessorUtils.getUrl(baseUrl, params);

    attrs.put("class", classString);
    attrs.put("href", url);
    return attrs;
  }