Search in sources :

Example 11 with FieldNotAvailableException

use of org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException in project BroadleafCommerce by BroadleafCommerce.

the class BasicFieldPersistenceProvider method extractValue.

@Override
public MetadataProviderResponse extractValue(ExtractValueRequest extractValueRequest, Property property) throws PersistenceException {
    if (!canHandleExtraction(extractValueRequest, property)) {
        return MetadataProviderResponse.NOT_HANDLED;
    }
    try {
        if (extractValueRequest.getRequestedValue() != null) {
            String val = null;
            if (extractValueRequest.getMetadata().getForeignKeyCollection()) {
                ((BasicFieldMetadata) property.getMetadata()).setFieldType(extractValueRequest.getMetadata().getFieldType());
            } else if (extractValueRequest.getMetadata().getFieldType().equals(SupportedFieldType.BOOLEAN) && extractValueRequest.getRequestedValue() instanceof Character) {
                val = (extractValueRequest.getRequestedValue().equals('Y')) ? "true" : "false";
            } else if (Date.class.isAssignableFrom(extractValueRequest.getRequestedValue().getClass())) {
                val = extractValueRequest.getDataFormatProvider().getSimpleDateFormatter().format((Date) extractValueRequest.getRequestedValue());
            } else if (Timestamp.class.isAssignableFrom(extractValueRequest.getRequestedValue().getClass())) {
                val = extractValueRequest.getDataFormatProvider().getSimpleDateFormatter().format(new Date(((Timestamp) extractValueRequest.getRequestedValue()).getTime()));
            } else if (Calendar.class.isAssignableFrom(extractValueRequest.getRequestedValue().getClass())) {
                val = extractValueRequest.getDataFormatProvider().getSimpleDateFormatter().format(((Calendar) extractValueRequest.getRequestedValue()).getTime());
            } else if (Double.class.isAssignableFrom(extractValueRequest.getRequestedValue().getClass())) {
                val = extractValueRequest.getDataFormatProvider().getDecimalFormatter().format(extractValueRequest.getRequestedValue());
            } else if (BigDecimal.class.isAssignableFrom(extractValueRequest.getRequestedValue().getClass())) {
                BigDecimal decimal = (BigDecimal) extractValueRequest.getRequestedValue();
                DecimalFormat format = extractValueRequest.getDataFormatProvider().getDecimalFormatter();
                // track all the decimal places in the scale of the BigDecimal - even if they're all zeros
                StringBuilder sb = new StringBuilder();
                sb.append("0");
                if (decimal.scale() > 0) {
                    sb.append(".");
                    for (int j = 0; j < decimal.scale(); j++) {
                        sb.append("0");
                    }
                }
                format.applyPattern(sb.toString());
                val = format.format(extractValueRequest.getRequestedValue());
            } else if (extractValueRequest.getMetadata().getForeignKeyClass() != null) {
                try {
                    val = extractValueRequest.getFieldManager().getFieldValue(extractValueRequest.getRequestedValue(), extractValueRequest.getMetadata().getForeignKeyProperty()).toString();
                    if (extensionManager != null) {
                        ExtensionResultHolder<Serializable> resultHolder = new ExtensionResultHolder<Serializable>();
                        ExtensionResultStatusType result = extensionManager.getProxy().transformForeignKey(extractValueRequest, property, resultHolder);
                        if (ExtensionResultStatusType.NOT_HANDLED != result && resultHolder.getResult() != null) {
                            val = String.valueOf(resultHolder.getResult());
                        }
                    }
                    // see if there's a name property and use it for the display value
                    String entityName = null;
                    if (extractValueRequest.getRequestedValue() instanceof AdminMainEntity) {
                        entityName = ((AdminMainEntity) extractValueRequest.getRequestedValue()).getMainEntityName();
                    }
                    Object temp = null;
                    if (!StringUtils.isEmpty(extractValueRequest.getMetadata().getForeignKeyDisplayValueProperty())) {
                        String nameProperty = extractValueRequest.getMetadata().getForeignKeyDisplayValueProperty();
                        try {
                            temp = extractValueRequest.getFieldManager().getFieldValue(extractValueRequest.getRequestedValue(), nameProperty);
                        } catch (FieldNotAvailableException e) {
                        // do nothing
                        }
                    }
                    if (temp == null && StringUtils.isEmpty(entityName)) {
                        try {
                            temp = extractValueRequest.getFieldManager().getFieldValue(extractValueRequest.getRequestedValue(), "name");
                        } catch (FieldNotAvailableException e) {
                        // do nothing
                        }
                    }
                    if (temp != null) {
                        extractValueRequest.setDisplayVal(temp.toString());
                    } else if (!StringUtils.isEmpty(entityName)) {
                        extractValueRequest.setDisplayVal(entityName);
                    }
                } catch (FieldNotAvailableException e) {
                    throw new IllegalArgumentException(e);
                }
            } else if (SupportedFieldType.ID == extractValueRequest.getMetadata().getFieldType()) {
                val = extractValueRequest.getRequestedValue().toString();
                if (extensionManager != null) {
                    ExtensionResultHolder<Serializable> resultHolder = new ExtensionResultHolder<Serializable>();
                    ExtensionResultStatusType result = extensionManager.getProxy().transformId(extractValueRequest, property, resultHolder);
                    if (ExtensionResultStatusType.NOT_HANDLED != result && resultHolder.getResult() != null) {
                        val = String.valueOf(resultHolder.getResult());
                    }
                }
            } else {
                val = extractValueRequest.getRequestedValue().toString();
            }
            property.setValue(val);
            property.setDisplayValue(extractValueRequest.getDisplayVal());
        }
    } catch (IllegalAccessException e) {
        throw new PersistenceException(e);
    }
    return MetadataProviderResponse.HANDLED;
}
Also used : Serializable(java.io.Serializable) Calendar(java.util.Calendar) DecimalFormat(java.text.DecimalFormat) ExtensionResultStatusType(org.broadleafcommerce.common.extension.ExtensionResultStatusType) Timestamp(java.sql.Timestamp) Date(java.util.Date) BigDecimal(java.math.BigDecimal) BasicFieldMetadata(org.broadleafcommerce.openadmin.dto.BasicFieldMetadata) FieldNotAvailableException(org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException) PersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.PersistenceException) ExtensionResultHolder(org.broadleafcommerce.common.extension.ExtensionResultHolder) AdminMainEntity(org.broadleafcommerce.common.admin.domain.AdminMainEntity)

Example 12 with FieldNotAvailableException

use of org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException in project BroadleafCommerce by BroadleafCommerce.

the class MaxGreaterThanMinValidator method validate.

@Override
public PropertyValidationResult validate(Entity entity, Serializable instance, Map<String, FieldMetadata> entityFieldMetadata, Map<String, String> validationConfiguration, BasicFieldMetadata propertyMetadata, String propertyName, String value) {
    String otherField = validationConfiguration.get("otherField");
    FieldManager fm = getFieldManager(propertyMetadata);
    boolean valid = true;
    String message = "";
    BigDecimal min = new BigDecimal(0);
    BigDecimal max = min;
    if (StringUtils.isBlank(value) || StringUtils.isBlank(otherField)) {
        return new PropertyValidationResult(true);
    }
    try {
        Object minObj = fm.getFieldValue(instance, otherField);
        if (minObj != null) {
            min = new BigDecimal(minObj.toString());
        }
        max = new BigDecimal(fm.getFieldValue(instance, propertyName).toString());
    } catch (IllegalAccessException | FieldNotAvailableException e) {
        valid = false;
        message = e.getMessage();
    }
    if (valid && max != null && min != null && max.compareTo(min) < 0) {
        valid = false;
        message = "minGreaterThanMax";
    }
    return new PropertyValidationResult(valid, message);
}
Also used : FieldManager(org.broadleafcommerce.openadmin.server.service.persistence.module.FieldManager) FieldNotAvailableException(org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException) BigDecimal(java.math.BigDecimal)

Example 13 with FieldNotAvailableException

use of org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException 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)

Example 14 with FieldNotAvailableException

use of org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException in project BroadleafCommerce by BroadleafCommerce.

the class BasicFieldTypeValidator method validate.

@Override
public PropertyValidationResult validate(PopulateValueRequest populateValueRequest, Serializable instance) {
    BroadleafRequestContext brc = BroadleafRequestContext.getBroadleafRequestContext();
    Locale locale = brc.getJavaLocale();
    DecimalFormat format = populateValueRequest.getDataFormatProvider().getDecimalFormatter();
    ParsePosition pp;
    switch(populateValueRequest.getMetadata().getFieldType()) {
        case INTEGER:
            try {
                if (int.class.isAssignableFrom(populateValueRequest.getReturnType()) || Integer.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                    Integer.parseInt(populateValueRequest.getRequestedValue());
                } else if (byte.class.isAssignableFrom(populateValueRequest.getReturnType()) || Byte.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                    Byte.parseByte(populateValueRequest.getRequestedValue());
                } else if (short.class.isAssignableFrom(populateValueRequest.getReturnType()) || Short.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                    Short.parseShort(populateValueRequest.getRequestedValue());
                } else if (long.class.isAssignableFrom(populateValueRequest.getReturnType()) || Long.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                    Long.parseLong(populateValueRequest.getRequestedValue());
                }
            } catch (NumberFormatException e) {
                return new PropertyValidationResult(false, "Field must be an valid number");
            }
            break;
        case DECIMAL:
            pp = new ParsePosition(0);
            if (BigDecimal.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                format.setParseBigDecimal(true);
                format.parse(populateValueRequest.getRequestedValue(), pp);
                format.setParseBigDecimal(false);
            } else {
                format.parse(populateValueRequest.getRequestedValue(), pp);
            }
            if (pp.getIndex() != populateValueRequest.getRequestedValue().length()) {
                return new PropertyValidationResult(false, "Field must be a valid decimal");
            }
            break;
        case MONEY:
            pp = new ParsePosition(0);
            try {
                if (Double.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                    format.parse(populateValueRequest.getRequestedValue(), pp);
                } else {
                    format.setParseBigDecimal(true);
                    format.parse(populateValueRequest.getRequestedValue(), pp);
                    format.setParseBigDecimal(false);
                }
                if (pp.getIndex() != populateValueRequest.getRequestedValue().length()) {
                    return new PropertyValidationResult(false, "Field must be a valid number");
                }
            } catch (NumberFormatException e) {
                return new PropertyValidationResult(false, "Field must be a valid number");
            }
            break;
        case DATE:
            try {
                populateValueRequest.getDataFormatProvider().getSimpleDateFormatter().parse(populateValueRequest.getRequestedValue());
            } catch (ParseException e) {
                return new PropertyValidationResult(false, "Field must be a date of the format: " + populateValueRequest.getDataFormatProvider().getSimpleDateFormatter().toPattern());
            }
            break;
        case FOREIGN_KEY:
        case ADDITIONAL_FOREIGN_KEY:
            if (Collection.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                Collection collection;
                try {
                    collection = (Collection) populateValueRequest.getFieldManager().getFieldValue(instance, populateValueRequest.getProperty().getName());
                } catch (FieldNotAvailableException e) {
                    return new PropertyValidationResult(false, "External entity cannot be added to the specified collection at " + populateValueRequest.getProperty().getName());
                } catch (IllegalAccessException e) {
                    return new PropertyValidationResult(false, "External entity cannot be added to the specified collection at " + populateValueRequest.getProperty().getName());
                }
            } else if (Map.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                return new PropertyValidationResult(false, "External entity cannot be added to a map at " + populateValueRequest.getProperty().getName());
            }
        case ID:
            if (populateValueRequest.getSetId()) {
                switch(populateValueRequest.getMetadata().getSecondaryType()) {
                    case INTEGER:
                        Long.valueOf(populateValueRequest.getRequestedValue());
                        break;
                    default:
                }
            }
        default:
            return new PropertyValidationResult(true);
    }
    return new PropertyValidationResult(true);
}
Also used : Locale(java.util.Locale) BroadleafRequestContext(org.broadleafcommerce.common.web.BroadleafRequestContext) DecimalFormat(java.text.DecimalFormat) FieldNotAvailableException(org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException) Collection(java.util.Collection) ParseException(java.text.ParseException) Map(java.util.Map) ParsePosition(java.text.ParsePosition)

Aggregations

FieldNotAvailableException (org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException)14 PersistenceException (org.broadleafcommerce.openadmin.server.service.persistence.PersistenceException)7 BigDecimal (java.math.BigDecimal)4 ExtensionResultHolder (org.broadleafcommerce.common.extension.ExtensionResultHolder)4 ExtensionResultStatusType (org.broadleafcommerce.common.extension.ExtensionResultStatusType)4 Serializable (java.io.Serializable)3 DecimalFormat (java.text.DecimalFormat)3 Date (java.util.Date)3 List (java.util.List)3 ParentEntityPersistenceException (org.broadleafcommerce.openadmin.server.service.persistence.ParentEntityPersistenceException)3 Field (java.lang.reflect.Field)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 Collection (java.util.Collection)2 Map (java.util.Map)2 EntityManager (javax.persistence.EntityManager)2 OneToMany (javax.persistence.OneToMany)2 AdminMainEntity (org.broadleafcommerce.common.admin.domain.AdminMainEntity)2 Media (org.broadleafcommerce.common.media.domain.Media)2 ValueAssignable (org.broadleafcommerce.common.value.ValueAssignable)2 BroadleafRequestContext (org.broadleafcommerce.common.web.BroadleafRequestContext)2