use of org.broadleafcommerce.common.rule.QuantityBasedRule in project BroadleafCommerce by BroadleafCommerce.
the class RuleFieldPersistenceProvider method findContainedRuleIfApplicable.
public static Object findContainedRuleIfApplicable(Object rule) {
Object response = null;
for (Field field : getAllFields(rule.getClass())) {
field.setAccessible(true);
Object test = null;
try {
test = field.get(rule);
} catch (IllegalAccessException e) {
throw ExceptionHelper.refineException(e);
}
if (test != null && (test instanceof SimpleRule || test instanceof QuantityBasedRule)) {
response = test;
break;
}
}
return response;
}
use of org.broadleafcommerce.common.rule.QuantityBasedRule in project BroadleafCommerce by BroadleafCommerce.
the class RuleFieldPersistenceProvider method convertQuantityBasedRuleToJson.
protected Property convertQuantityBasedRuleToJson(MVELToDataWrapperTranslator translator, ObjectMapper mapper, Collection<QuantityBasedRule> quantityBasedRules, String jsonProp, String fieldService) {
int k = 0;
Entity[] targetItemCriterias = new Entity[quantityBasedRules.size()];
for (QuantityBasedRule quantityBasedRule : quantityBasedRules) {
Property[] properties = new Property[4];
Property mvelProperty = new Property();
mvelProperty.setName("matchRule");
mvelProperty.setValue(quantityBasedRule.getMatchRule());
Property quantityProperty = new Property();
quantityProperty.setName("quantity");
quantityProperty.setValue(quantityBasedRule.getQuantity().toString());
Property idProperty = new Property();
idProperty.setName("id");
Long id = quantityBasedRule.getId();
id = transformId(id, quantityBasedRule);
idProperty.setValue(String.valueOf(id));
Object containedRule = findContainedRuleIfApplicable(quantityBasedRule);
Property containedIdProperty = new Property();
if (containedRule != null) {
containedIdProperty.setName("containedId");
EntityManager em = PersistenceManagerFactory.getDefaultPersistenceManager().getDynamicEntityDao().getStandardEntityManager();
Long containedId = (Long) em.unwrap(Session.class).getIdentifier(containedRule);
containedId = transformId(containedId, containedRule);
containedIdProperty.setValue(String.valueOf(containedId));
}
properties[0] = mvelProperty;
properties[1] = quantityProperty;
properties[2] = idProperty;
properties[3] = containedIdProperty;
Entity criteria = new Entity();
criteria.setProperties(properties);
targetItemCriterias[k] = criteria;
k++;
}
String json;
try {
DataWrapper oiWrapper = translator.createRuleData(targetItemCriterias, "matchRule", "quantity", "id", "containedId", ruleBuilderFieldServiceFactory.createInstance(fieldService));
json = mapper.writeValueAsString(oiWrapper);
} catch (Exception e) {
throw new RuntimeException(e);
}
Property p = new Property();
p.setName(jsonProp);
p.setValue(json);
return p;
}
use of org.broadleafcommerce.common.rule.QuantityBasedRule in project BroadleafCommerce by BroadleafCommerce.
the class RuleFieldPersistenceProvider method updateQuantityRule.
protected boolean updateQuantityRule(EntityManager em, DataDTOToMVELTranslator translator, String entityKey, String fieldService, String jsonPropertyValue, Collection<QuantityBasedRule> criteriaList, Class<?> memberType, Object parent, String mappedBy, Property property) {
boolean dirty = false;
if (!StringUtils.isEmpty(jsonPropertyValue)) {
// avoid lazy init exception on the criteria list for criteria created during an add
criteriaList.size();
DataWrapper dw = ruleFieldExtractionUtility.convertJsonToDataWrapper(jsonPropertyValue);
if (dw != null && StringUtils.isEmpty(dw.getError())) {
List<QuantityBasedRule> updatedRules = new ArrayList<QuantityBasedRule>();
for (DataDTO dto : dw.getData()) {
if (dto.getPk() != null && !CollectionUtils.isEmpty(criteriaList)) {
checkId: {
// Update Existing Criteria
for (QuantityBasedRule quantityBasedRule : criteriaList) {
// make compatible with enterprise module
boolean isParentRelated = sandBoxHelper.isRelatedToParentCatalogIds(quantityBasedRule, dto.getPk());
boolean isMatch = isParentRelated || dto.getPk().equals(quantityBasedRule.getId());
if (isMatch) {
String mvel;
// don't update if the data has not changed
if (!quantityBasedRule.getQuantity().equals(dto.getQuantity())) {
dirty = true;
}
try {
mvel = ruleFieldExtractionUtility.convertDTOToMvelString(translator, entityKey, dto, fieldService);
if (!quantityBasedRule.getMatchRule().equals(mvel)) {
dirty = true;
}
} catch (MVELTranslationException e) {
throw new RuntimeException(e);
}
if (!dirty && extensionManager != null) {
ExtensionResultHolder<Boolean> resultHolder = new ExtensionResultHolder<Boolean>();
ExtensionResultStatusType result = extensionManager.getProxy().establishDirtyState(quantityBasedRule, resultHolder);
if (ExtensionResultStatusType.NOT_HANDLED != result && resultHolder.getResult() != null) {
dirty = resultHolder.getResult();
}
}
if (dirty) {
// pre-merge (can result in a clone for enterprise)
quantityBasedRule = em.merge(quantityBasedRule);
// update the quantity based rule
quantityBasedRule.setQuantity(dto.getQuantity());
quantityBasedRule.setMatchRule(mvel);
quantityBasedRule = em.merge(quantityBasedRule);
}
updatedRules.add(quantityBasedRule);
break checkId;
}
}
throw new IllegalArgumentException("Unable to update the rule of type (" + memberType.getName() + ") because an update was requested for id (" + dto.getPk() + "), which does not exist.");
}
} else {
// Create a new Criteria
QuantityBasedRule quantityBasedRule;
try {
quantityBasedRule = (QuantityBasedRule) memberType.newInstance();
quantityBasedRule.setQuantity(dto.getQuantity());
quantityBasedRule.setMatchRule(ruleFieldExtractionUtility.convertDTOToMvelString(translator, entityKey, dto, fieldService));
if (StringUtils.isEmpty(quantityBasedRule.getMatchRule()) && !StringUtils.isEmpty(dw.getRawMvel())) {
quantityBasedRule.setMatchRule(dw.getRawMvel());
}
PropertyUtils.setNestedProperty(quantityBasedRule, mappedBy, parent);
} catch (Exception e) {
throw new RuntimeException(e);
}
em.persist(quantityBasedRule);
dto.setPk(quantityBasedRule.getId());
Object contained = findContainedRuleIfApplicable(quantityBasedRule);
if (contained != null) {
dto.setContainedPk((Long) em.unwrap(Session.class).getIdentifier(contained));
}
if (extensionManager != null) {
ExtensionResultHolder resultHolder = new ExtensionResultHolder();
extensionManager.getProxy().postAdd(quantityBasedRule, resultHolder);
if (resultHolder.getResult() != null) {
quantityBasedRule = (QuantityBasedRule) resultHolder.getResult();
}
}
if (cascadeExtensionManager != null) {
ExtensionResultHolder resultHolder = new ExtensionResultHolder();
cascadeExtensionManager.getProxy().postCascadeAdd(quantityBasedRule, dto, resultHolder);
if (resultHolder.getResult() != null) {
quantityBasedRule = (QuantityBasedRule) resultHolder.getResult();
}
}
updatedRules.add(quantityBasedRule);
dirty = true;
}
}
// if an item was not included in the comprehensive submit from the client, we can assume that the
// listing was deleted, so we remove it here.
Iterator<QuantityBasedRule> itr = criteriaList.iterator();
// Since this class explicitly removes the quantity based rule - we must also preserve the id of the element
// as the CacheInvalidationProducer will need this in order to remove each collection member cache instance as well.
BroadleafRequestContext context = BroadleafRequestContext.getBroadleafRequestContext();
context.getAdditionalProperties().put("deletedQuantityBasedRules", new HashSet<QuantityBasedRule>());
while (itr.hasNext()) {
checkForRemove: {
QuantityBasedRule original = itr.next();
for (QuantityBasedRule quantityBasedRule : updatedRules) {
Long id = sandBoxHelper.getOriginalId(quantityBasedRule);
boolean isMatch = original.getId().equals(id) || original.getId().equals(quantityBasedRule.getId());
if (isMatch) {
break checkForRemove;
}
}
((Set<QuantityBasedRule>) context.getAdditionalProperties().get("deletedQuantityBasedRules")).add(original);
em.remove(original);
itr.remove();
dirty = true;
}
}
ObjectMapper mapper = new ObjectMapper();
String json;
try {
json = mapper.writeValueAsString(dw);
} catch (Exception e) {
throw new RuntimeException(e);
}
property.setValue(json);
}
}
return dirty;
}
use of org.broadleafcommerce.common.rule.QuantityBasedRule in project BroadleafCommerce by BroadleafCommerce.
the class RuleFieldPersistenceProvider method extractQuantityRule.
protected void extractQuantityRule(ExtractValueRequest extractValueRequest, ObjectMapper mapper, MVELToDataWrapperTranslator translator) {
if (extractValueRequest.getRequestedValue() != null) {
if (extractValueRequest.getRequestedValue() instanceof Collection) {
// these quantity rules are in a list - this is a special, valid case for quantity rules
Property jsonProperty = convertQuantityBasedRuleToJson(translator, mapper, (Collection<QuantityBasedRule>) extractValueRequest.getRequestedValue(), extractValueRequest.getMetadata().getName() + "Json", extractValueRequest.getMetadata().getRuleIdentifier());
extractValueRequest.getProps().add(jsonProperty);
} else {
// TODO support a single quantity based rule
throw new UnsupportedOperationException("RULE_WITH_QUANTITY type is currently only supported" + "on collection fields. A single field with this type is not currently supported.");
}
}
}
use of org.broadleafcommerce.common.rule.QuantityBasedRule in project BroadleafCommerce by BroadleafCommerce.
the class RuleFieldPersistenceProvider method populateQuantityRule.
protected boolean populateQuantityRule(PopulateValueRequest populateValueRequest, Serializable instance) throws FieldNotAvailableException, IllegalAccessException {
String prop = populateValueRequest.getProperty().getName();
Field field = populateValueRequest.getFieldManager().getField(instance.getClass(), prop);
OneToMany oneToMany = field.getAnnotation(OneToMany.class);
if (oneToMany == null) {
throw new UnsupportedOperationException("RuleFieldPersistenceProvider is currently only compatible with collection fields when modelled using @OneToMany");
}
// currently, this only works with Collection fields
boolean dirty;
Class<?> valueType = getListFieldType(instance, populateValueRequest.getFieldManager(), populateValueRequest.getProperty(), populateValueRequest.getPersistenceManager());
if (valueType == null) {
throw new IllegalAccessException("Unable to determine the valueType for the rule field (" + populateValueRequest.getProperty().getName() + ")");
}
DataDTOToMVELTranslator translator = new DataDTOToMVELTranslator();
Collection<QuantityBasedRule> rules;
rules = (Collection<QuantityBasedRule>) populateValueRequest.getFieldManager().getFieldValue(instance, populateValueRequest.getProperty().getName());
Object parent = extractParent(populateValueRequest, instance);
// AntiSamy HTML encodes the rule JSON - pass the unHTMLEncoded version
EntityManager entityManager = populateValueRequest.getPersistenceManager().getDynamicEntityDao().getStandardEntityManager();
String fieldService = populateValueRequest.getMetadata().getRuleIdentifier();
String entityKey = RuleIdentifier.ENTITY_KEY_MAP.get(fieldService);
Property ruleProperty = populateValueRequest.getProperty();
String jsonPropertyValue = ruleProperty.getUnHtmlEncodedValue();
String mappedByEntity = oneToMany.mappedBy();
dirty = updateQuantityRule(entityManager, translator, entityKey, fieldService, jsonPropertyValue, rules, valueType, parent, mappedByEntity, ruleProperty);
return dirty;
}
Aggregations