Search in sources :

Example 21 with DataWrapper

use of org.broadleafcommerce.openadmin.web.rulebuilder.dto.DataWrapper in project BroadleafCommerce by BroadleafCommerce.

the class RuleFieldExtractionUtility method convertSimpleRuleToJson.

/**
 * Converts a simple MVEL rule into its JSON representation suitable for adding to an {@link Entity} to pass to the
 * frontend.
 * @param translator
 * @param mapper
 * @param matchRule
 * @param jsonProp
 * @param fieldService
 * @return
 */
public Property convertSimpleRuleToJson(MVELToDataWrapperTranslator translator, ObjectMapper mapper, String matchRule, String jsonProp, String fieldService) {
    Entity[] matchCriteria = new Entity[1];
    Property[] properties = new Property[1];
    Property mvelProperty = new Property();
    mvelProperty.setName("matchRule");
    mvelProperty.setValue(matchRule == null ? "" : matchRule);
    properties[0] = mvelProperty;
    Entity criteria = new Entity();
    criteria.setProperties(properties);
    matchCriteria[0] = criteria;
    String json;
    try {
        DataWrapper orderWrapper = translator.createRuleData(matchCriteria, "matchRule", null, null, ruleBuilderFieldServiceFactory.createInstance(fieldService));
        json = mapper.writeValueAsString(orderWrapper);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    Property p = new Property();
    p.setName(jsonProp);
    p.setValue(json);
    return p;
}
Also used : DataWrapper(org.broadleafcommerce.openadmin.web.rulebuilder.dto.DataWrapper) Entity(org.broadleafcommerce.openadmin.dto.Entity) Property(org.broadleafcommerce.openadmin.dto.Property) IOException(java.io.IOException) MVELTranslationException(org.broadleafcommerce.openadmin.web.rulebuilder.MVELTranslationException)

Example 22 with DataWrapper

use of org.broadleafcommerce.openadmin.web.rulebuilder.dto.DataWrapper in project BroadleafCommerce by BroadleafCommerce.

the class RuleFieldPersistenceProvider method convertSimpleRuleToJson.

protected Property convertSimpleRuleToJson(MVELToDataWrapperTranslator translator, ObjectMapper mapper, SimpleRule simpleRule, String jsonProp, String fieldService) {
    String matchRule = simpleRule.getMatchRule();
    Entity[] matchCriteria = new Entity[1];
    Property[] properties = new Property[3];
    Property mvelProperty = new Property();
    mvelProperty.setName("matchRule");
    mvelProperty.setValue(matchRule == null ? "" : matchRule);
    properties[0] = mvelProperty;
    Entity criteria = new Entity();
    criteria.setProperties(properties);
    matchCriteria[0] = criteria;
    EntityManager em = PersistenceManagerFactory.getDefaultPersistenceManager().getDynamicEntityDao().getStandardEntityManager();
    Long id = getRuleId(simpleRule, em);
    Property idProperty = new Property();
    idProperty.setName("id");
    idProperty.setValue(String.valueOf(id));
    properties[1] = idProperty;
    Long containedId = getContainedRuleId(simpleRule, em);
    Property containedIdProperty = new Property();
    containedIdProperty.setName("containedId");
    containedIdProperty.setValue(String.valueOf(containedId));
    properties[2] = containedIdProperty;
    String json;
    try {
        DataWrapper orderWrapper = translator.createRuleData(matchCriteria, "matchRule", null, "id", "containedId", ruleBuilderFieldServiceFactory.createInstance(fieldService));
        json = mapper.writeValueAsString(orderWrapper);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    Property p = new Property();
    p.setName(jsonProp);
    p.setValue(json);
    return p;
}
Also used : DataWrapper(org.broadleafcommerce.openadmin.web.rulebuilder.dto.DataWrapper) Entity(org.broadleafcommerce.openadmin.dto.Entity) EntityManager(javax.persistence.EntityManager) Property(org.broadleafcommerce.openadmin.dto.Property) FieldNotAvailableException(org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException) MVELTranslationException(org.broadleafcommerce.openadmin.web.rulebuilder.MVELTranslationException) PersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.PersistenceException) ParentEntityPersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.ParentEntityPersistenceException)

Example 23 with DataWrapper

use of org.broadleafcommerce.openadmin.web.rulebuilder.dto.DataWrapper 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;
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) MVELTranslationException(org.broadleafcommerce.openadmin.web.rulebuilder.MVELTranslationException) BroadleafRequestContext(org.broadleafcommerce.common.web.BroadleafRequestContext) ArrayList(java.util.ArrayList) DataDTO(org.broadleafcommerce.openadmin.web.rulebuilder.dto.DataDTO) ExtensionResultStatusType(org.broadleafcommerce.common.extension.ExtensionResultStatusType) FieldNotAvailableException(org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException) MVELTranslationException(org.broadleafcommerce.openadmin.web.rulebuilder.MVELTranslationException) PersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.PersistenceException) ParentEntityPersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.ParentEntityPersistenceException) DataWrapper(org.broadleafcommerce.openadmin.web.rulebuilder.dto.DataWrapper) QuantityBasedRule(org.broadleafcommerce.common.rule.QuantityBasedRule) ExtensionResultHolder(org.broadleafcommerce.common.extension.ExtensionResultHolder) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Session(org.hibernate.Session)

Example 24 with DataWrapper

use of org.broadleafcommerce.openadmin.web.rulebuilder.dto.DataWrapper in project BroadleafCommerce by BroadleafCommerce.

the class RuleFieldValidator method validate.

@Override
public PropertyValidationResult validate(PopulateValueRequest populateValueRequest, Serializable instance) {
    if (canHandleValidation(populateValueRequest)) {
        DataDTOToMVELTranslator translator = new DataDTOToMVELTranslator();
        EntityManager em = populateValueRequest.getPersistenceManager().getDynamicEntityDao().getStandardEntityManager();
        if (SupportedFieldType.RULE_SIMPLE.equals(populateValueRequest.getMetadata().getFieldType()) || SupportedFieldType.RULE_SIMPLE_TIME.equals(populateValueRequest.getMetadata().getFieldType())) {
            // AntiSamy HTML encodes the rule JSON - pass the unHTMLEncoded version
            DataWrapper dw = ruleFieldExtractionUtility.convertJsonToDataWrapper(populateValueRequest.getProperty().getUnHtmlEncodedValue());
            if (dw != null && StringUtils.isNotEmpty(dw.getError())) {
                return new PropertyValidationResult(false, "Could not serialize JSON from rule builder: " + dw.getError());
            }
            if (dw == null || StringUtils.isEmpty(dw.getError())) {
                try {
                    String mvel = ruleFieldExtractionUtility.convertSimpleMatchRuleJsonToMvel(translator, RuleIdentifier.ENTITY_KEY_MAP.get(populateValueRequest.getMetadata().getRuleIdentifier()), populateValueRequest.getMetadata().getRuleIdentifier(), dw);
                } catch (MVELTranslationException e) {
                    return new PropertyValidationResult(false, getMvelParsingErrorMesage(dw, e));
                }
            }
        }
        if (SupportedFieldType.RULE_WITH_QUANTITY.equals(populateValueRequest.getMetadata().getFieldType())) {
            Collection<QuantityBasedRule> existingRules;
            try {
                existingRules = (Collection<QuantityBasedRule>) populateValueRequest.getFieldManager().getFieldValue(instance, populateValueRequest.getProperty().getName());
            } catch (FieldNotAvailableException e) {
                return new PropertyValidationResult(false, "Could not access rule field on Java object to set values");
            } catch (IllegalAccessException e) {
                return new PropertyValidationResult(false, "Could not access rule field on Java object to set values");
            }
            String entityKey = RuleIdentifier.ENTITY_KEY_MAP.get(populateValueRequest.getMetadata().getRuleIdentifier());
            String jsonPropertyValue = populateValueRequest.getProperty().getUnHtmlEncodedValue();
            String fieldService = populateValueRequest.getMetadata().getRuleIdentifier();
            if (!StringUtils.isEmpty(jsonPropertyValue)) {
                DataWrapper dw = ruleFieldExtractionUtility.convertJsonToDataWrapper(jsonPropertyValue);
                if (dw != null && StringUtils.isNotEmpty(dw.getError())) {
                    return new PropertyValidationResult(false, "Could not serialize JSON from rule builder: " + dw.getError());
                }
                if (dw != null && StringUtils.isEmpty(dw.getError())) {
                    for (DataDTO dto : dw.getData()) {
                        if (dto.getPk() != null) {
                            boolean foundIdToUpdate = false;
                            for (QuantityBasedRule quantityBasedRule : existingRules) {
                                Long sandBoxVersionId = sandBoxHelper.getSandBoxVersionId(quantityBasedRule.getClass(), dto.getPk());
                                if (sandBoxVersionId == null) {
                                    sandBoxVersionId = dto.getPk();
                                }
                                if (sandBoxVersionId.equals(quantityBasedRule.getId()) || sandBoxHelper.isRelatedToParentCatalogIds(quantityBasedRule, dto.getPk())) {
                                    foundIdToUpdate = true;
                                    try {
                                        String mvel = ruleFieldExtractionUtility.convertDTOToMvelString(translator, entityKey, dto, fieldService);
                                    } catch (MVELTranslationException e) {
                                        return new PropertyValidationResult(false, getMvelParsingErrorMesage(dw, e));
                                    }
                                }
                            }
                            if (!foundIdToUpdate) {
                                return new PropertyValidationResult(false, "Tried to update QuantityBasedRule with ID " + dto.getPk() + " but that rule does not exist");
                            }
                        } else {
                            // This is a new rule, just validate that it parses successfully
                            try {
                                ruleFieldExtractionUtility.convertDTOToMvelString(translator, entityKey, dto, fieldService);
                            } catch (MVELTranslationException e) {
                                return new PropertyValidationResult(false, getMvelParsingErrorMesage(dw, e));
                            }
                        }
                    }
                }
            }
        }
    }
    return new PropertyValidationResult(true);
}
Also used : MVELTranslationException(org.broadleafcommerce.openadmin.web.rulebuilder.MVELTranslationException) DataDTO(org.broadleafcommerce.openadmin.web.rulebuilder.dto.DataDTO) DataDTOToMVELTranslator(org.broadleafcommerce.openadmin.web.rulebuilder.DataDTOToMVELTranslator) DataWrapper(org.broadleafcommerce.openadmin.web.rulebuilder.dto.DataWrapper) EntityManager(javax.persistence.EntityManager) QuantityBasedRule(org.broadleafcommerce.common.rule.QuantityBasedRule) FieldNotAvailableException(org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException)

Aggregations

DataWrapper (org.broadleafcommerce.openadmin.web.rulebuilder.dto.DataWrapper)24 Property (org.broadleafcommerce.openadmin.dto.Property)21 Entity (org.broadleafcommerce.openadmin.dto.Entity)16 MVELToDataWrapperTranslator (org.broadleafcommerce.openadmin.web.rulebuilder.MVELToDataWrapperTranslator)12 ExpressionDTO (org.broadleafcommerce.openadmin.web.rulebuilder.dto.ExpressionDTO)8 MVELTranslationException (org.broadleafcommerce.openadmin.web.rulebuilder.MVELTranslationException)6 FieldNotAvailableException (org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException)5 ArrayList (java.util.ArrayList)4 EntityManager (javax.persistence.EntityManager)4 BasicFieldMetadata (org.broadleafcommerce.openadmin.dto.BasicFieldMetadata)4 ParentEntityPersistenceException (org.broadleafcommerce.openadmin.server.service.persistence.ParentEntityPersistenceException)4 PersistenceException (org.broadleafcommerce.openadmin.server.service.persistence.PersistenceException)4 MediaField (org.broadleafcommerce.openadmin.web.form.component.MediaField)4 RuleBuilderField (org.broadleafcommerce.openadmin.web.form.component.RuleBuilderField)4 CodeField (org.broadleafcommerce.openadmin.web.form.entity.CodeField)4 ComboField (org.broadleafcommerce.openadmin.web.form.entity.ComboField)4 Field (org.broadleafcommerce.openadmin.web.form.entity.Field)4 QuantityBasedRule (org.broadleafcommerce.common.rule.QuantityBasedRule)3 DataDTO (org.broadleafcommerce.openadmin.web.rulebuilder.dto.DataDTO)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2