Search in sources :

Example 1 with DataDTO

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

the class RuleFieldExtractionUtility method convertSimpleMatchRuleJsonToMvel.

/**
 * Converts the given {@link DataWrapper} into an MVEL expression
 * @param translator
 * @param entityKey
 * @param fieldService
 * @param dw
 * @return
 * @throws MVELTranslationException
 */
public String convertSimpleMatchRuleJsonToMvel(DataDTOToMVELTranslator translator, String entityKey, String fieldService, DataWrapper dw) throws MVELTranslationException {
    String mvel = null;
    // there can only be one DataDTO for an appliesTo* rule
    if (dw != null && dw.getData().size() == 1) {
        DataDTO dto = dw.getData().get(0);
        mvel = convertDTOToMvelString(translator, entityKey, dto, fieldService);
    }
    return mvel;
}
Also used : DataDTO(org.broadleafcommerce.openadmin.web.rulebuilder.dto.DataDTO)

Example 2 with DataDTO

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

the class RuleFieldPersistenceProvider method populateSimpleRule.

protected boolean populateSimpleRule(PopulateValueRequest populateValueRequest, Serializable instance) throws Exception {
    boolean dirty = false;
    String prop = populateValueRequest.getProperty().getName();
    if (prop.contains(FieldManager.MAPFIELDSEPARATOR)) {
        Field field = populateValueRequest.getFieldManager().getField(instance.getClass(), prop.substring(0, prop.indexOf(FieldManager.MAPFIELDSEPARATOR)));
        if (field.getAnnotation(OneToMany.class) == null) {
            throw new UnsupportedOperationException("RuleFieldPersistenceProvider is currently only compatible with map fields when modelled using @OneToMany");
        }
    }
    DataDTOToMVELTranslator translator = new DataDTOToMVELTranslator();
    // AntiSamy HTML encodes the rule JSON - pass the unHTMLEncoded version
    DataWrapper dw = ruleFieldExtractionUtility.convertJsonToDataWrapper(populateValueRequest.getProperty().getUnHtmlEncodedValue());
    if (dw == null || StringUtils.isEmpty(dw.getError())) {
        String mvel = ruleFieldExtractionUtility.convertSimpleMatchRuleJsonToMvel(translator, RuleIdentifier.ENTITY_KEY_MAP.get(populateValueRequest.getMetadata().getRuleIdentifier()), populateValueRequest.getMetadata().getRuleIdentifier(), dw);
        Class<?> valueType = getStartingValueType(populateValueRequest);
        // This is a simple String field (or String map field)
        if (String.class.isAssignableFrom(valueType)) {
            // first check if the property is null and the mvel is null
            if (instance != null && mvel == null) {
                Object value = populateValueRequest.getFieldManager().getFieldValue(instance, populateValueRequest.getProperty().getName());
                dirty = value != null;
            } else {
                dirty = checkDirtyState(populateValueRequest, instance, mvel);
            }
            populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), mvel);
        }
        if (SimpleRule.class.isAssignableFrom(valueType)) {
            boolean persist = false;
            SimpleRule rule;
            try {
                rule = (SimpleRule) populateValueRequest.getFieldManager().getFieldValue(instance, populateValueRequest.getProperty().getName());
                if (rule == null) {
                    rule = (SimpleRule) valueType.newInstance();
                    Field field = populateValueRequest.getFieldManager().getField(instance.getClass(), prop.substring(0, prop.indexOf(FieldManager.MAPFIELDSEPARATOR)));
                    OneToMany oneToMany = field.getAnnotation(OneToMany.class);
                    Object parent = extractParent(populateValueRequest, instance);
                    populateValueRequest.getFieldManager().setFieldValue(rule, oneToMany.mappedBy(), parent);
                    populateValueRequest.getFieldManager().setFieldValue(rule, populateValueRequest.getMetadata().getMapKeyValueProperty(), prop.substring(prop.indexOf(FieldManager.MAPFIELDSEPARATOR) + FieldManager.MAPFIELDSEPARATOR.length(), prop.length()));
                    persist = true;
                }
            } catch (FieldNotAvailableException e) {
                throw new IllegalArgumentException(e);
            }
            if (mvel == null) {
                // cause the rule to be deleted
                dirty = populateValueRequest.getFieldManager().getFieldValue(instance, populateValueRequest.getProperty().getName()) != null;
                if (dirty) {
                    if (!populateValueRequest.getProperty().getName().contains(FieldManager.MAPFIELDSEPARATOR)) {
                        populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), null);
                    } else {
                        // Since this class explicitly removes the simple rule - we must also preserve the id of the element
                        // as the CacheInvalidationProducer will need this in order to remove the member cache instance as well.
                        BroadleafRequestContext context = BroadleafRequestContext.getBroadleafRequestContext();
                        context.getAdditionalProperties().put("deletedSimpleRule", rule);
                        populateValueRequest.getPersistenceManager().getDynamicEntityDao().remove(rule);
                    }
                }
            } else if (rule != null) {
                dirty = !mvel.equals(rule.getMatchRule());
                if (!dirty && extensionManager != null) {
                    ExtensionResultHolder<Boolean> resultHolder = new ExtensionResultHolder<Boolean>();
                    ExtensionResultStatusType result = extensionManager.getProxy().establishDirtyState(rule, resultHolder);
                    if (ExtensionResultStatusType.NOT_HANDLED != result && resultHolder.getResult() != null) {
                        dirty = resultHolder.getResult();
                    }
                }
                if (dirty) {
                    updateSimpleRule(populateValueRequest, mvel, persist, rule);
                    EntityManager em = populateValueRequest.getPersistenceManager().getDynamicEntityDao().getStandardEntityManager();
                    Long id = getRuleId(rule, em);
                    Long containedId = getContainedRuleId(rule, em);
                    DataDTO dto = dw.getData().get(0);
                    if (persist && cascadeExtensionManager != null) {
                        ExtensionResultHolder resultHolder = new ExtensionResultHolder();
                        cascadeExtensionManager.getProxy().postCascadeAdd(rule, dto, resultHolder);
                    }
                    dto.setPk(id);
                    dto.setContainedPk(containedId);
                    ObjectMapper mapper = new ObjectMapper();
                    String json;
                    try {
                        json = mapper.writeValueAsString(dw);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    populateValueRequest.getProperty().setValue(json);
                }
            }
        }
    }
    return dirty;
}
Also used : BroadleafRequestContext(org.broadleafcommerce.common.web.BroadleafRequestContext) DataDTO(org.broadleafcommerce.openadmin.web.rulebuilder.dto.DataDTO) ExtensionResultStatusType(org.broadleafcommerce.common.extension.ExtensionResultStatusType) OneToMany(javax.persistence.OneToMany) DataDTOToMVELTranslator(org.broadleafcommerce.openadmin.web.rulebuilder.DataDTOToMVELTranslator) 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) Field(java.lang.reflect.Field) SimpleRule(org.broadleafcommerce.common.rule.SimpleRule) EntityManager(javax.persistence.EntityManager) FieldNotAvailableException(org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException) ExtensionResultHolder(org.broadleafcommerce.common.extension.ExtensionResultHolder) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 3 with DataDTO

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

the class DataDTOToMVELTranslatorTest method testFulfillmentQualificationMVEL.

/**
 * Tests the creation of a Fulfillment Group Qualification MVEL expression from a DataDTO
 * @throws MVELTranslationException
 *
 * [{"pk":null,
 *  "quantity":null,
 *  "condition":"AND",
 *  "rules":[
 *      {"pk":null,
 *      "quantity":null,
 *      "condition":null,
 *      "rules":null,
 *      "id":"address.state.name",
 *      "operator":"EQUALS",
 *      "value":["Texas"]},
 *      {"pk":null,
 *      "quantity":null,
 *      "condition":null,
 *      "rules":null,
 *      "id":"retailShippingPrice",
 *      "operator":"BETWEEN_INCLUSIVE",
 *      "value":"[99,199]"}]
 *  }]
 */
public void testFulfillmentQualificationMVEL() throws MVELTranslationException {
    DataDTOToMVELTranslator translator = new DataDTOToMVELTranslator();
    DataDTO dataDTO = new DataDTO();
    dataDTO.setCondition(BLCOperator.AND.name());
    ExpressionDTO e1 = new ExpressionDTO();
    e1.setId("address.state.name");
    e1.setOperator(BLCOperator.EQUALS.name());
    e1.setValue("Texas");
    ExpressionDTO e2 = new ExpressionDTO();
    e2.setId("retailFulfillmentPrice");
    e2.setOperator(BLCOperator.BETWEEN_INCLUSIVE.name());
    e2.setValue("[99,199]");
    dataDTO.getRules().add(e1);
    dataDTO.getRules().add(e2);
    String translated = translator.createMVEL("fulfillmentGroup", dataDTO, fulfillmentGroupFieldService);
    String mvel = "fulfillmentGroup.?address.?state.?name==\"Texas\"&&(fulfillmentGroup.?retailFulfillmentPrice.getAmount()>=99&&fulfillmentGroup.?retailFulfillmentPrice.getAmount()<=199)";
    assert (mvel.equals(translated));
}
Also used : DataDTO(org.broadleafcommerce.openadmin.web.rulebuilder.dto.DataDTO) DataDTOToMVELTranslator(org.broadleafcommerce.openadmin.web.rulebuilder.DataDTOToMVELTranslator) ExpressionDTO(org.broadleafcommerce.openadmin.web.rulebuilder.dto.ExpressionDTO)

Example 4 with DataDTO

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

the class DataDTOToMVELTranslatorTest method testOrderQualificationMVEL.

/**
 * Tests the creation of an Order Qualification MVEL expression from a DataDTO
 * @throws MVELTranslationException
 *
 * [{"pk":null,
 *  "quantity":null,
 *  "condition":"AND",
 *  "rules":[
 *      {"pk":null,
 *      "quantity":null,
 *      "condition":null,
 *      "rules":null,
 *      "id":"subTotal",
 *      "operator":"GREATER_OR_EQUAL",
 *      "value":"100"}]
 *  }]
 */
public void testOrderQualificationMVEL() throws MVELTranslationException {
    DataDTOToMVELTranslator translator = new DataDTOToMVELTranslator();
    DataDTO dataDTO = new DataDTO();
    dataDTO.setCondition(BLCOperator.AND.name());
    ExpressionDTO expressionDTO = new ExpressionDTO();
    expressionDTO.setId("subTotal");
    expressionDTO.setOperator(BLCOperator.GREATER_OR_EQUAL.name());
    expressionDTO.setValue("100");
    dataDTO.getRules().add(expressionDTO);
    String translated = translator.createMVEL("order", dataDTO, orderFieldService);
    String mvel = "order.?subTotal.getAmount()>=100";
    assert (mvel.equals(translated));
}
Also used : DataDTO(org.broadleafcommerce.openadmin.web.rulebuilder.dto.DataDTO) DataDTOToMVELTranslator(org.broadleafcommerce.openadmin.web.rulebuilder.DataDTOToMVELTranslator) ExpressionDTO(org.broadleafcommerce.openadmin.web.rulebuilder.dto.ExpressionDTO)

Example 5 with DataDTO

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

the class DataDTODeserializer method deserialize.

@Override
public DataDTO deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    ObjectMapper mapper = (ObjectMapper) jp.getCodec();
    ObjectNode root = (ObjectNode) mapper.readTree(jp);
    Iterator<Map.Entry<String, JsonNode>> elementsIterator = root.fields();
    DataDTO dataDTO = new DataDTO();
    ExpressionDTO expressionDTO = new ExpressionDTO();
    boolean isExpression = false;
    while (elementsIterator.hasNext()) {
        Map.Entry<String, JsonNode> element = elementsIterator.next();
        String name = element.getKey();
        if ("id".equals(name)) {
            expressionDTO.setId(getNullAwareText(element.getValue()));
            isExpression = true;
        }
        if ("operator".equals(name)) {
            expressionDTO.setOperator(getNullAwareText(element.getValue()));
            isExpression = true;
        }
        if ("value".equals(name)) {
            expressionDTO.setValue(getNullAwareText(element.getValue()));
            isExpression = true;
        }
        if ("pk".equals(name)) {
            if (getNullAwareText(element.getValue()) == null || StringUtils.isBlank(element.getValue().asText())) {
                dataDTO.setPk(null);
            } else {
                dataDTO.setPk(element.getValue().asLong());
            }
        }
        if ("previousPk".equals(name)) {
            if (getNullAwareText(element.getValue()) == null || StringUtils.isBlank(element.getValue().asText())) {
                dataDTO.setPreviousPk(null);
            } else {
                dataDTO.setPreviousPk(element.getValue().asLong());
            }
        }
        if ("containedPk".equals(name)) {
            if (getNullAwareText(element.getValue()) == null || StringUtils.isBlank(element.getValue().asText())) {
                dataDTO.setContainedPk(null);
            } else {
                dataDTO.setContainedPk(element.getValue().asLong());
            }
        }
        if ("previousContainedPk".equals(name)) {
            if (getNullAwareText(element.getValue()) == null || StringUtils.isBlank(element.getValue().asText())) {
                dataDTO.setPreviousContainedPk(null);
            } else {
                dataDTO.setPreviousContainedPk(element.getValue().asLong());
            }
        }
        if ("quantity".equals(name)) {
            if (getNullAwareText(element.getValue()) == null) {
                dataDTO.setQuantity(null);
            } else {
                dataDTO.setQuantity(element.getValue().asInt());
            }
        }
        if ("condition".equals(name)) {
            dataDTO.setCondition(getNullAwareText(element.getValue()));
        }
        if ("rules".equals(name)) {
            CollectionType dtoCollectionType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, DataDTO.class);
            dataDTO.setRules((ArrayList<DataDTO>) mapper.readValue(element.getValue().traverse(jp.getCodec()), dtoCollectionType));
        }
    }
    if (isExpression) {
        return expressionDTO;
    } else {
        return dataDTO;
    }
}
Also used : ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) CollectionType(com.fasterxml.jackson.databind.type.CollectionType) DataDTO(org.broadleafcommerce.openadmin.web.rulebuilder.dto.DataDTO) JsonNode(com.fasterxml.jackson.databind.JsonNode) Map(java.util.Map) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ExpressionDTO(org.broadleafcommerce.openadmin.web.rulebuilder.dto.ExpressionDTO)

Aggregations

DataDTO (org.broadleafcommerce.openadmin.web.rulebuilder.dto.DataDTO)14 ExpressionDTO (org.broadleafcommerce.openadmin.web.rulebuilder.dto.ExpressionDTO)8 DataDTOToMVELTranslator (org.broadleafcommerce.openadmin.web.rulebuilder.DataDTOToMVELTranslator)7 DataWrapper (org.broadleafcommerce.openadmin.web.rulebuilder.dto.DataWrapper)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 FieldNotAvailableException (org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException)3 MVELTranslationException (org.broadleafcommerce.openadmin.web.rulebuilder.MVELTranslationException)3 ArrayList (java.util.ArrayList)2 EntityManager (javax.persistence.EntityManager)2 ExtensionResultHolder (org.broadleafcommerce.common.extension.ExtensionResultHolder)2 ExtensionResultStatusType (org.broadleafcommerce.common.extension.ExtensionResultStatusType)2 QuantityBasedRule (org.broadleafcommerce.common.rule.QuantityBasedRule)2 BroadleafRequestContext (org.broadleafcommerce.common.web.BroadleafRequestContext)2 ParentEntityPersistenceException (org.broadleafcommerce.openadmin.server.service.persistence.ParentEntityPersistenceException)2 PersistenceException (org.broadleafcommerce.openadmin.server.service.persistence.PersistenceException)2 Group (org.broadleafcommerce.openadmin.web.rulebuilder.grouping.Group)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)1 CollectionType (com.fasterxml.jackson.databind.type.CollectionType)1 Field (java.lang.reflect.Field)1