Search in sources :

Example 6 with PersistenceException

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

the class EntityValidatorServiceImpl method validate.

@Override
public void validate(Entity submittedEntity, @Nullable Serializable instance, Map<String, FieldMetadata> propertiesMetadata, RecordHelper recordHelper, boolean validateUnsubmittedProperties) {
    Object idValue = null;
    if (instance != null) {
        String idField = (String) ((BasicPersistenceModule) recordHelper.getCompatibleModule(OperationType.BASIC)).getPersistenceManager().getDynamicEntityDao().getIdMetadata(instance.getClass()).get("name");
        try {
            idValue = recordHelper.getFieldManager().getFieldValue(instance, idField);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (FieldNotAvailableException e) {
            throw new RuntimeException(e);
        }
    }
    Entity entity;
    boolean isUpdateRequest;
    if (idValue == null) {
        // This is for an add, or if the instance variable is null (e.g. PageTemplateCustomPersistenceHandler)
        entity = submittedEntity;
        isUpdateRequest = false;
    } else {
        if (validateUnsubmittedProperties) {
            // This is for an update, as the submittedEntity instance will likely only contain the dirty properties
            entity = recordHelper.getRecord(propertiesMetadata, instance, null, null);
            // would be the confirmation field for a password validation
            for (Map.Entry<String, FieldMetadata> entry : propertiesMetadata.entrySet()) {
                if (entity.findProperty(entry.getKey()) == null) {
                    Property myProperty = submittedEntity.findProperty(entry.getKey());
                    if (myProperty != null) {
                        entity.addProperty(myProperty);
                    }
                } else if (submittedEntity.findProperty(entry.getKey()) != null) {
                    entity.findProperty(entry.getKey()).setValue(submittedEntity.findProperty(entry.getKey()).getValue());
                    entity.findProperty(entry.getKey()).setIsDirty(submittedEntity.findProperty(entry.getKey()).getIsDirty());
                }
            }
        } else {
            entity = submittedEntity;
        }
        isUpdateRequest = true;
    }
    List<String> types = getTypeHierarchy(entity);
    // validate each individual property according to their validation configuration
    for (Entry<String, FieldMetadata> metadataEntry : propertiesMetadata.entrySet()) {
        FieldMetadata metadata = metadataEntry.getValue();
        // Don't test this field if it was not inherited from our polymorphic type (or supertype)
        if (instance != null && (types.contains(metadata.getInheritedFromType()) || instance.getClass().getName().equals(metadata.getInheritedFromType()))) {
            Property property = entity.getPMap().get(metadataEntry.getKey());
            // and we don't need to validate them.
            if (!validateUnsubmittedProperties && property == null) {
                continue;
            }
            // for radio buttons, it's possible that the entity property was never populated in the first place from the POST
            // and so it will be null
            String propertyName = metadataEntry.getKey();
            String propertyValue = (property == null) ? null : property.getValue();
            if (metadata instanceof BasicFieldMetadata) {
                // First execute the global field validators
                if (CollectionUtils.isNotEmpty(globalEntityValidators)) {
                    for (GlobalPropertyValidator validator : globalEntityValidators) {
                        PropertyValidationResult result = validator.validate(entity, instance, propertiesMetadata, (BasicFieldMetadata) metadata, propertyName, propertyValue);
                        if (!result.isValid()) {
                            submittedEntity.addValidationError(propertyName, result.getErrorMessage());
                        }
                    }
                }
                // Now execute the validators configured for this particular field
                Map<String, List<Map<String, String>>> validations = ((BasicFieldMetadata) metadata).getValidationConfigurations();
                for (Map.Entry<String, List<Map<String, String>>> validation : validations.entrySet()) {
                    String validationImplementation = validation.getKey();
                    for (Map<String, String> configuration : validation.getValue()) {
                        PropertyValidator validator = null;
                        // attempt bean resolution to find the validator
                        if (applicationContext.containsBean(validationImplementation)) {
                            validator = applicationContext.getBean(validationImplementation, PropertyValidator.class);
                        }
                        // not a bean, attempt to instantiate the class
                        if (validator == null) {
                            try {
                                validator = (PropertyValidator) Class.forName(validationImplementation).newInstance();
                            } catch (Exception e) {
                            // do nothing
                            }
                        }
                        if (validator == null) {
                            throw new PersistenceException("Could not find validator: " + validationImplementation + " for property: " + propertyName);
                        }
                        PropertyValidationResult result = validator.validate(entity, instance, propertiesMetadata, configuration, (BasicFieldMetadata) metadata, propertyName, propertyValue);
                        if (!result.isValid()) {
                            for (String message : result.getErrorMessages()) {
                                submittedEntity.addValidationError(propertyName, message);
                            }
                        }
                    }
                }
            }
        }
    }
}
Also used : Entity(org.broadleafcommerce.openadmin.dto.Entity) FieldMetadata(org.broadleafcommerce.openadmin.dto.FieldMetadata) BasicFieldMetadata(org.broadleafcommerce.openadmin.dto.BasicFieldMetadata) BeansException(org.springframework.beans.BeansException) FieldNotAvailableException(org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException) PersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.PersistenceException) BasicPersistenceModule(org.broadleafcommerce.openadmin.server.service.persistence.module.BasicPersistenceModule) BasicFieldMetadata(org.broadleafcommerce.openadmin.dto.BasicFieldMetadata) FieldNotAvailableException(org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException) PersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.PersistenceException) ArrayList(java.util.ArrayList) List(java.util.List) Map(java.util.Map) Property(org.broadleafcommerce.openadmin.dto.Property)

Example 7 with PersistenceException

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

the class HTMLFieldPersistenceProvider method populateValue.

@Override
public MetadataProviderResponse populateValue(PopulateValueRequest populateValueRequest, Serializable instance) throws PersistenceException {
    if (!canHandlePersistence(populateValueRequest, instance)) {
        return MetadataProviderResponse.NOT_HANDLED;
    }
    try {
        String requestedValue = populateValueRequest.getRequestedValue();
        String fixedValue = fixAssetPathsForStorage(requestedValue);
        boolean dirty;
        if (populateValueRequest.getProperty().getIsDirty()) {
            dirty = true;
        } else {
            dirty = checkDirtyState(populateValueRequest, instance, fixedValue);
        }
        populateValueRequest.getProperty().setIsDirty(dirty);
        populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), fixedValue);
    } catch (Exception e) {
        throw new PersistenceException(e);
    }
    return MetadataProviderResponse.HANDLED_BREAK;
}
Also used : PersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.PersistenceException) PersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.PersistenceException)

Example 8 with PersistenceException

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

the class BasicPersistenceModule method getRecords.

@Override
public Entity[] getRecords(Map<String, FieldMetadata> primaryUnfilteredMergedProperties, List<? extends Serializable> records, Map<String, FieldMetadata> alternateUnfilteredMergedProperties, String pathToTargetObject, String[] customCriteria) {
    Map<String, FieldMetadata> primaryMergedProperties = filterOutCollectionMetadata(primaryUnfilteredMergedProperties);
    Map<String, FieldMetadata> alternateMergedProperties = filterOutCollectionMetadata(alternateUnfilteredMergedProperties);
    Entity[] entities = new Entity[records.size()];
    int j = 0;
    for (Serializable recordEntity : records) {
        Serializable entity;
        if (pathToTargetObject != null) {
            try {
                entity = (Serializable) getFieldManager().getFieldValue(recordEntity, pathToTargetObject);
            } catch (Exception e) {
                throw new PersistenceException(e);
            }
        } else {
            entity = recordEntity;
        }
        Entity entityItem = new Entity();
        entityItem.setType(new String[] { entity.getClass().getName() });
        entities[j] = entityItem;
        List<Property> props = new ArrayList<Property>(primaryMergedProperties.size());
        extractPropertiesFromPersistentEntity(primaryMergedProperties, entity, props, customCriteria);
        if (alternateMergedProperties != null) {
            extractPropertiesFromPersistentEntity(alternateMergedProperties, recordEntity, props, customCriteria);
        }
        // Try to add the "main name" property. Log a debug message if we can't
        try {
            Property p = new Property();
            p.setName(MAIN_ENTITY_NAME_PROPERTY);
            String mainEntityName = (String) MethodUtils.invokeMethod(entity, "getMainEntityName");
            p.setValue(mainEntityName);
            props.add(p);
        } catch (Exception e) {
            LOG.debug(String.format("Could not execute the getMainEntityName() method for [%s]", entity.getClass().getName()), e);
        }
        // Try to add the alternate id property if available
        if (alternateMergedProperties != null) {
            for (Entry<String, FieldMetadata> entry : alternateMergedProperties.entrySet()) {
                if (entry.getValue() instanceof BasicFieldMetadata) {
                    if (((BasicFieldMetadata) entry.getValue()).getFieldType() == SupportedFieldType.ID) {
                        Map<String, FieldMetadata> alternateOnEntity = new HashMap<String, FieldMetadata>();
                        alternateOnEntity.put(entry.getKey(), entry.getValue());
                        List<Property> props2 = new ArrayList<Property>();
                        extractPropertiesFromPersistentEntity(alternateOnEntity, recordEntity, props2, customCriteria);
                        List<Property> filtered = new ArrayList<Property>();
                        for (Property prop : props2) {
                            if (!prop.getName().startsWith("__")) {
                                filtered.add(prop);
                            }
                        }
                        if (filtered.size() == 1 && !filtered.get(0).getName().contains(".")) {
                            Property alternateIdProp = filtered.get(0);
                            alternateIdProp.setName(ALTERNATE_ID_PROPERTY);
                            props.add(alternateIdProp);
                        }
                    }
                }
            }
        }
        Property[] properties = new Property[props.size()];
        properties = props.toArray(properties);
        entityItem.setProperties(properties);
        j++;
    }
    return entities;
}
Also used : AdminMainEntity(org.broadleafcommerce.common.admin.domain.AdminMainEntity) Entity(org.broadleafcommerce.openadmin.dto.Entity) Serializable(java.io.Serializable) FieldMetadata(org.broadleafcommerce.openadmin.dto.FieldMetadata) BasicFieldMetadata(org.broadleafcommerce.openadmin.dto.BasicFieldMetadata) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ServiceException(org.broadleafcommerce.common.exception.ServiceException) InvocationTargetException(java.lang.reflect.InvocationTargetException) PersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.PersistenceException) CriteriaConversionException(org.broadleafcommerce.openadmin.server.service.persistence.module.criteria.CriteriaConversionException) BeansException(org.springframework.beans.BeansException) ValidationException(org.broadleafcommerce.openadmin.server.service.ValidationException) ParentEntityPersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.ParentEntityPersistenceException) SecurityServiceException(org.broadleafcommerce.common.exception.SecurityServiceException) BasicFieldMetadata(org.broadleafcommerce.openadmin.dto.BasicFieldMetadata) PersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.PersistenceException) ParentEntityPersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.ParentEntityPersistenceException) Property(org.broadleafcommerce.openadmin.dto.Property)

Example 9 with PersistenceException

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

the class BasicPersistenceModule method createPopulatedInstance.

@Override
public Serializable createPopulatedInstance(Serializable instance, Entity entity, Map<String, FieldMetadata> unfilteredProperties, Boolean setId, Boolean validateUnsubmittedProperties) throws ValidationException {
    final Map<String, FieldMetadata> mergedProperties = filterOutCollectionMetadata(unfilteredProperties);
    FieldManager fieldManager = getFieldManager();
    boolean handled = false;
    for (FieldPersistenceProvider fieldPersistenceProvider : fieldPersistenceProviders) {
        MetadataProviderResponse response = fieldPersistenceProvider.filterProperties(new AddFilterPropertiesRequest(entity), unfilteredProperties);
        if (MetadataProviderResponse.NOT_HANDLED != response) {
            handled = true;
        }
        if (MetadataProviderResponse.HANDLED_BREAK == response) {
            break;
        }
    }
    if (!handled) {
        defaultFieldPersistenceProvider.filterProperties(new AddFilterPropertiesRequest(entity), unfilteredProperties);
    }
    // Order media field, map field and rule builder fields last, as they will have some validation components that depend on previous values
    Property[] sortedProperties = entity.getProperties();
    Arrays.sort(sortedProperties, new Comparator<Property>() {

        @Override
        public int compare(Property o1, Property o2) {
            BasicFieldMetadata mo1 = (BasicFieldMetadata) mergedProperties.get(o1.getName());
            BasicFieldMetadata mo2 = (BasicFieldMetadata) mergedProperties.get(o2.getName());
            boolean isLate1 = mo1 != null && mo1.getFieldType() != null && mo1.getName() != null && (SupportedFieldType.RULE_SIMPLE == mo1.getFieldType() || SupportedFieldType.RULE_WITH_QUANTITY == mo1.getFieldType() || SupportedFieldType.RULE_SIMPLE_TIME == mo1.getFieldType() || SupportedFieldType.MEDIA == mo1.getFieldType() || o1.getName().contains(FieldManager.MAPFIELDSEPARATOR));
            boolean isLate2 = mo2 != null && mo2.getFieldType() != null && mo2.getName() != null && (SupportedFieldType.RULE_SIMPLE == mo2.getFieldType() || SupportedFieldType.RULE_WITH_QUANTITY == mo2.getFieldType() || SupportedFieldType.RULE_SIMPLE_TIME == mo2.getFieldType() || SupportedFieldType.MEDIA == mo2.getFieldType() || o2.getName().contains(FieldManager.MAPFIELDSEPARATOR));
            if (isLate1 && !isLate2) {
                return 1;
            } else if (!isLate1 && isLate2) {
                return -1;
            }
            return 0;
        }
    });
    Session session = getPersistenceManager().getDynamicEntityDao().getStandardEntityManager().unwrap(Session.class);
    FlushMode originalFlushMode = session.getFlushMode();
    try {
        session.setFlushMode(FlushMode.MANUAL);
        RuntimeException entityPersistenceException = null;
        for (Property property : sortedProperties) {
            BasicFieldMetadata metadata = (BasicFieldMetadata) mergedProperties.get(property.getName());
            Class<?> returnType;
            if (!property.getName().contains(FieldManager.MAPFIELDSEPARATOR) && !property.getName().startsWith("__")) {
                Field field = fieldManager.getField(instance.getClass(), property.getName());
                if (field == null) {
                    LOG.debug("Unable to find a bean property for the reported property: " + StringUtil.sanitize(property.getName()) + ". Ignoring property.");
                    continue;
                }
                returnType = field.getType();
            } else {
                if (metadata == null) {
                    LOG.debug("Unable to find a metadata property for the reported property: " + StringUtil.sanitize(property.getName()) + ". Ignoring property.");
                    continue;
                }
                returnType = getMapFieldType(instance, fieldManager, property);
                if (returnType == null) {
                    returnType = getBasicBroadleafType(metadata.getFieldType());
                }
            }
            if (returnType == null) {
                throw new IllegalAccessException("Unable to determine the value type for the property (" + property.getName() + ")");
            }
            String value = property.getValue();
            if (metadata != null) {
                if (metadata.getFieldType().equals(SupportedFieldType.BOOLEAN)) {
                    if (value == null) {
                        value = "false";
                    }
                }
                if (attemptToPopulateValue(property, fieldManager, instance, setId, metadata, entity, value)) {
                    boolean isValid = true;
                    PopulateValueRequest request = new PopulateValueRequest(setId, fieldManager, property, metadata, returnType, value, persistenceManager, this, entity.isPreAdd());
                    handled = false;
                    if (value != null) {
                        for (PopulateValueRequestValidator validator : populateValidators) {
                            PropertyValidationResult validationResult = validator.validate(request, instance);
                            if (!validationResult.isValid()) {
                                entity.addValidationError(property.getName(), validationResult.getErrorMessage());
                                isValid = false;
                            }
                        }
                    }
                    if (isValid) {
                        try {
                            boolean isBreakDetected = false;
                            for (FieldPersistenceProvider fieldPersistenceProvider : fieldPersistenceProviders) {
                                if ((!isBreakDetected || fieldPersistenceProvider.alwaysRun()) && (value != null || fieldPersistenceProvider.canHandlePopulateNull())) {
                                    MetadataProviderResponse response = fieldPersistenceProvider.populateValue(request, instance);
                                    if (MetadataProviderResponse.NOT_HANDLED != response) {
                                        handled = true;
                                    }
                                    if (MetadataProviderResponse.HANDLED_BREAK == response) {
                                        isBreakDetected = true;
                                    }
                                }
                            }
                            if (!handled) {
                                if (value == null) {
                                    property.setIsDirty(true);
                                }
                                defaultFieldPersistenceProvider.populateValue(new PopulateValueRequest(setId, fieldManager, property, metadata, returnType, value, persistenceManager, this, entity.isPreAdd()), instance);
                                if (value == null) {
                                    fieldManager.setFieldValue(instance, property.getName(), null);
                                }
                            }
                        } catch (ParentEntityPersistenceException | javax.validation.ValidationException e) {
                            entityPersistenceException = e;
                            cleanupFailedPersistenceAttempt(instance);
                            break;
                        }
                    }
                }
            }
        }
        // Only check validation if not the initial add
        if (!entity.isPreAdd()) {
            validate(entity, instance, mergedProperties, validateUnsubmittedProperties);
        }
        // if validation failed, refresh the current instance so that none of the changes will be persisted
        if (entity.isValidationFailure()) {
            // only refresh the instance if it was managed to begin with
            if (persistenceManager.getDynamicEntityDao().getStandardEntityManager().contains(instance)) {
                persistenceManager.getDynamicEntityDao().refresh(instance);
            }
            // re-initialize the valid properties for the entity in order to deal with the potential of not
            // completely sending over all checkbox/radio fields
            List<Serializable> entityList = new ArrayList<Serializable>(1);
            entityList.add(instance);
            Entity invalid = getRecords(mergedProperties, entityList, null, null, null)[0];
            invalid.setPropertyValidationErrors(entity.getPropertyValidationErrors());
            invalid.overridePropertyValues(entity);
            String message = ValidationUtil.buildErrorMessage(invalid.getPropertyValidationErrors(), invalid.getGlobalValidationErrors());
            throw new ValidationException(invalid, message);
        } else if (entityPersistenceException != null) {
            throw ExceptionHelper.refineException(entityPersistenceException.getCause());
        } else {
            fieldManager.persistMiddleEntities();
        }
    } catch (IllegalAccessException e) {
        throw new PersistenceException(e);
    } catch (InstantiationException e) {
        throw new PersistenceException(e);
    } finally {
        session.setFlushMode(originalFlushMode);
    }
    return instance;
}
Also used : AdminMainEntity(org.broadleafcommerce.common.admin.domain.AdminMainEntity) Entity(org.broadleafcommerce.openadmin.dto.Entity) Serializable(java.io.Serializable) FieldMetadata(org.broadleafcommerce.openadmin.dto.FieldMetadata) BasicFieldMetadata(org.broadleafcommerce.openadmin.dto.BasicFieldMetadata) ValidationException(org.broadleafcommerce.openadmin.server.service.ValidationException) FieldPersistenceProvider(org.broadleafcommerce.openadmin.server.service.persistence.module.provider.FieldPersistenceProvider) ArrayList(java.util.ArrayList) AddFilterPropertiesRequest(org.broadleafcommerce.openadmin.server.service.persistence.module.provider.request.AddFilterPropertiesRequest) Field(java.lang.reflect.Field) Property(org.broadleafcommerce.openadmin.dto.Property) MetadataProviderResponse(org.broadleafcommerce.openadmin.server.service.type.MetadataProviderResponse) FlushMode(org.hibernate.FlushMode) ParentEntityPersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.ParentEntityPersistenceException) PopulateValueRequest(org.broadleafcommerce.openadmin.server.service.persistence.module.provider.request.PopulateValueRequest) BasicFieldMetadata(org.broadleafcommerce.openadmin.dto.BasicFieldMetadata) PersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.PersistenceException) ParentEntityPersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.ParentEntityPersistenceException) PropertyValidationResult(org.broadleafcommerce.openadmin.server.service.persistence.validation.PropertyValidationResult) PopulateValueRequestValidator(org.broadleafcommerce.openadmin.server.service.persistence.validation.PopulateValueRequestValidator) Session(org.hibernate.Session)

Example 10 with PersistenceException

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

the class BasicFieldPersistenceProvider method populateValue.

@Override
public MetadataProviderResponse populateValue(PopulateValueRequest populateValueRequest, Serializable instance) {
    if (!canHandlePersistence(populateValueRequest, instance)) {
        return MetadataProviderResponse.NOT_HANDLED;
    }
    boolean dirty = false;
    try {
        Property prop = populateValueRequest.getProperty();
        Object origInstanceValue = populateValueRequest.getFieldManager().getFieldValue(instance, prop.getName());
        switch(populateValueRequest.getMetadata().getFieldType()) {
            case BOOLEAN:
                boolean v = Boolean.valueOf(populateValueRequest.getRequestedValue());
                prop.setOriginalValue(String.valueOf(origInstanceValue));
                prop.setOriginalDisplayValue(prop.getOriginalValue());
                try {
                    dirty = checkDirtyState(populateValueRequest, instance, v);
                    populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), v);
                } catch (IllegalArgumentException e) {
                    boolean isChar = populateValueRequest.getRequestedValue().toCharArray().length > 1 ? false : true;
                    char c;
                    if (isChar) {
                        c = populateValueRequest.getRequestedValue().toCharArray()[0];
                    } else {
                        c = Boolean.valueOf(populateValueRequest.getRequestedValue()) ? 'Y' : 'N';
                    }
                    dirty = checkDirtyState(populateValueRequest, instance, c);
                    populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), c);
                }
                break;
            case DATE:
                Date date = (Date) populateValueRequest.getFieldManager().getFieldValue(instance, populateValueRequest.getProperty().getName());
                String oldValue = null;
                if (date != null) {
                    oldValue = populateValueRequest.getDataFormatProvider().getSimpleDateFormatter().format(date);
                }
                prop.setOriginalValue(oldValue);
                prop.setOriginalDisplayValue(prop.getOriginalValue());
                dirty = !StringUtils.equals(oldValue, populateValueRequest.getRequestedValue());
                populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), populateValueRequest.getDataFormatProvider().getSimpleDateFormatter().parse(populateValueRequest.getRequestedValue()));
                break;
            case DECIMAL:
                if (origInstanceValue != null) {
                    prop.setOriginalValue(String.valueOf(origInstanceValue));
                    prop.setOriginalDisplayValue(prop.getOriginalValue());
                }
                if (BigDecimal.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                    DecimalFormat format = populateValueRequest.getDataFormatProvider().getDecimalFormatter();
                    format.setParseBigDecimal(true);
                    BigDecimal val = (BigDecimal) format.parse(populateValueRequest.getRequestedValue());
                    dirty = checkDirtyState(populateValueRequest, instance, val);
                    populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), val);
                    format.setParseBigDecimal(false);
                } else {
                    Double val = populateValueRequest.getDataFormatProvider().getDecimalFormatter().parse(populateValueRequest.getRequestedValue()).doubleValue();
                    dirty = checkDirtyState(populateValueRequest, instance, val);
                    populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), val);
                }
                break;
            case MONEY:
                if (origInstanceValue != null) {
                    prop.setOriginalValue(String.valueOf(origInstanceValue));
                    prop.setOriginalDisplayValue(prop.getOriginalValue());
                }
                if (BigDecimal.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                    DecimalFormat format = populateValueRequest.getDataFormatProvider().getDecimalFormatter();
                    format.setParseBigDecimal(true);
                    BigDecimal val = (BigDecimal) format.parse(populateValueRequest.getRequestedValue());
                    dirty = checkDirtyState(populateValueRequest, instance, val);
                    populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), val);
                    format.setParseBigDecimal(true);
                } else if (Double.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                    Double val = populateValueRequest.getDataFormatProvider().getDecimalFormatter().parse(populateValueRequest.getRequestedValue()).doubleValue();
                    dirty = checkDirtyState(populateValueRequest, instance, val);
                    LOG.warn("The requested Money field is of type double and could result in a loss of precision." + " Broadleaf recommends that the type of all Money fields be 'BigDecimal' in order to avoid" + " this loss of precision that could occur.");
                    populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), val);
                } else {
                    DecimalFormat format = populateValueRequest.getDataFormatProvider().getDecimalFormatter();
                    format.setParseBigDecimal(true);
                    BigDecimal val = (BigDecimal) format.parse(populateValueRequest.getRequestedValue());
                    dirty = checkDirtyState(populateValueRequest, instance, val);
                    populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), new Money(val));
                    format.setParseBigDecimal(false);
                }
                break;
            case INTEGER:
                if (origInstanceValue != null) {
                    prop.setOriginalValue(String.valueOf(origInstanceValue));
                    prop.setOriginalDisplayValue(prop.getOriginalValue());
                }
                if (int.class.isAssignableFrom(populateValueRequest.getReturnType()) || Integer.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                    dirty = checkDirtyState(populateValueRequest, instance, Integer.valueOf(populateValueRequest.getRequestedValue()));
                    populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), Integer.valueOf(populateValueRequest.getRequestedValue()));
                } else if (byte.class.isAssignableFrom(populateValueRequest.getReturnType()) || Byte.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                    dirty = checkDirtyState(populateValueRequest, instance, Byte.valueOf(populateValueRequest.getRequestedValue()));
                    populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), Byte.valueOf(populateValueRequest.getRequestedValue()));
                } else if (short.class.isAssignableFrom(populateValueRequest.getReturnType()) || Short.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                    dirty = checkDirtyState(populateValueRequest, instance, Short.valueOf(populateValueRequest.getRequestedValue()));
                    populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), Short.valueOf(populateValueRequest.getRequestedValue()));
                } else if (long.class.isAssignableFrom(populateValueRequest.getReturnType()) || Long.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                    dirty = checkDirtyState(populateValueRequest, instance, Long.valueOf(populateValueRequest.getRequestedValue()));
                    populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), Long.valueOf(populateValueRequest.getRequestedValue()));
                }
                break;
            case CODE:
                // **NOTE** We want to fall through in this case, do not break.
                setNonDisplayableValues(populateValueRequest);
            case STRING:
            case HTML_BASIC:
            case HTML:
            case EMAIL:
                if (origInstanceValue != null) {
                    prop.setOriginalValue(String.valueOf(origInstanceValue));
                    prop.setOriginalDisplayValue(prop.getOriginalValue());
                }
                dirty = checkDirtyState(populateValueRequest, instance, populateValueRequest.getRequestedValue());
                populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), populateValueRequest.getRequestedValue());
                break;
            case FOREIGN_KEY:
                {
                    if (origInstanceValue != null) {
                        prop.setOriginalValue(String.valueOf(origInstanceValue));
                    }
                    Serializable foreignInstance;
                    if (StringUtils.isEmpty(populateValueRequest.getRequestedValue())) {
                        foreignInstance = null;
                    } else {
                        if (SupportedFieldType.INTEGER.toString().equals(populateValueRequest.getMetadata().getSecondaryType().toString())) {
                            foreignInstance = populateValueRequest.getPersistenceManager().getDynamicEntityDao().retrieve(Class.forName(populateValueRequest.getMetadata().getForeignKeyClass()), Long.valueOf(populateValueRequest.getRequestedValue()));
                        } else {
                            foreignInstance = populateValueRequest.getPersistenceManager().getDynamicEntityDao().retrieve(Class.forName(populateValueRequest.getMetadata().getForeignKeyClass()), populateValueRequest.getRequestedValue());
                        }
                    }
                    if (Collection.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                        Collection collection;
                        try {
                            collection = (Collection) populateValueRequest.getFieldManager().getFieldValue(instance, populateValueRequest.getProperty().getName());
                        } catch (FieldNotAvailableException e) {
                            throw new IllegalArgumentException(e);
                        }
                        if (!collection.contains(foreignInstance)) {
                            collection.add(foreignInstance);
                            dirty = true;
                        }
                    } else if (Map.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                        throw new IllegalArgumentException("Map structures are not supported for foreign key fields.");
                    } else {
                        dirty = checkDirtyState(populateValueRequest, instance, foreignInstance);
                        populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), foreignInstance);
                    }
                    break;
                }
            case ADDITIONAL_FOREIGN_KEY:
                {
                    Serializable foreignInstance;
                    if (StringUtils.isEmpty(populateValueRequest.getRequestedValue())) {
                        foreignInstance = null;
                    } else {
                        if (SupportedFieldType.INTEGER.toString().equals(populateValueRequest.getMetadata().getSecondaryType().toString())) {
                            foreignInstance = populateValueRequest.getPersistenceManager().getDynamicEntityDao().retrieve(Class.forName(populateValueRequest.getMetadata().getForeignKeyClass()), Long.valueOf(populateValueRequest.getRequestedValue()));
                        } else {
                            foreignInstance = populateValueRequest.getPersistenceManager().getDynamicEntityDao().retrieve(Class.forName(populateValueRequest.getMetadata().getForeignKeyClass()), populateValueRequest.getRequestedValue());
                        }
                    }
                    // Best guess at grabbing the original display value
                    String fkProp = populateValueRequest.getMetadata().getForeignKeyDisplayValueProperty();
                    Object origDispVal = null;
                    if (origInstanceValue != null) {
                        if (AdminMainEntity.MAIN_ENTITY_NAME_PROPERTY.equals(fkProp)) {
                            if (origInstanceValue instanceof AdminMainEntity) {
                                origDispVal = ((AdminMainEntity) origInstanceValue).getMainEntityName();
                            }
                        } else {
                            origDispVal = populateValueRequest.getFieldManager().getFieldValue(origInstanceValue, fkProp);
                        }
                    }
                    if (origDispVal != null) {
                        prop.setOriginalDisplayValue(String.valueOf(origDispVal));
                        Session session = populateValueRequest.getPersistenceManager().getDynamicEntityDao().getStandardEntityManager().unwrap(Session.class);
                        String originalValueFromSession = String.valueOf(session.getIdentifier(origInstanceValue));
                        prop.setOriginalValue(originalValueFromSession);
                    }
                    if (Collection.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                        Collection collection;
                        try {
                            collection = (Collection) populateValueRequest.getFieldManager().getFieldValue(instance, populateValueRequest.getProperty().getName());
                        } catch (FieldNotAvailableException e) {
                            throw new IllegalArgumentException(e);
                        }
                        if (!collection.contains(foreignInstance)) {
                            collection.add(foreignInstance);
                            dirty = true;
                        }
                    } else if (Map.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                        throw new IllegalArgumentException("Map structures are not supported for foreign key fields.");
                    } else {
                        dirty = checkDirtyState(populateValueRequest, instance, foreignInstance);
                        populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), foreignInstance);
                    }
                    break;
                }
            case ID:
                if (populateValueRequest.getSetId()) {
                    switch(populateValueRequest.getMetadata().getSecondaryType()) {
                        case INTEGER:
                            dirty = checkDirtyState(populateValueRequest, instance, Long.valueOf(populateValueRequest.getRequestedValue()));
                            populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), Long.valueOf(populateValueRequest.getRequestedValue()));
                            break;
                        case STRING:
                            dirty = checkDirtyState(populateValueRequest, instance, populateValueRequest.getRequestedValue());
                            populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), populateValueRequest.getRequestedValue());
                            break;
                    }
                }
                break;
        }
    } catch (Exception e) {
        throw new PersistenceException(e);
    }
    populateValueRequest.getProperty().setIsDirty(dirty);
    return MetadataProviderResponse.HANDLED;
}
Also used : Serializable(java.io.Serializable) DecimalFormat(java.text.DecimalFormat) Date(java.util.Date) BigDecimal(java.math.BigDecimal) FieldNotAvailableException(org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException) PersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.PersistenceException) Money(org.broadleafcommerce.common.money.Money) FieldNotAvailableException(org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException) PersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.PersistenceException) Collection(java.util.Collection) Property(org.broadleafcommerce.openadmin.dto.Property) AdminMainEntity(org.broadleafcommerce.common.admin.domain.AdminMainEntity) Session(org.hibernate.Session)

Aggregations

PersistenceException (org.broadleafcommerce.openadmin.server.service.persistence.PersistenceException)11 BasicFieldMetadata (org.broadleafcommerce.openadmin.dto.BasicFieldMetadata)6 Property (org.broadleafcommerce.openadmin.dto.Property)6 AdminMainEntity (org.broadleafcommerce.common.admin.domain.AdminMainEntity)5 FieldNotAvailableException (org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException)5 Serializable (java.io.Serializable)4 FieldMetadata (org.broadleafcommerce.openadmin.dto.FieldMetadata)4 ParentEntityPersistenceException (org.broadleafcommerce.openadmin.server.service.persistence.ParentEntityPersistenceException)4 Field (java.lang.reflect.Field)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)3 ArrayList (java.util.ArrayList)3 Date (java.util.Date)3 Entity (org.broadleafcommerce.openadmin.dto.Entity)3 ValidationException (org.broadleafcommerce.openadmin.server.service.ValidationException)3 MetadataProviderResponse (org.broadleafcommerce.openadmin.server.service.type.MetadataProviderResponse)3 BeansException (org.springframework.beans.BeansException)3 BigDecimal (java.math.BigDecimal)2 Timestamp (java.sql.Timestamp)2 DecimalFormat (java.text.DecimalFormat)2 Calendar (java.util.Calendar)2