Search in sources :

Example 1 with AdminMainEntity

use of org.broadleafcommerce.common.admin.domain.AdminMainEntity in project BroadleafCommerce by BroadleafCommerce.

the class BasicPersistenceModule method extractPropertiesFromPersistentEntity.

protected void extractPropertiesFromPersistentEntity(Map<String, FieldMetadata> mergedProperties, Serializable entity, List<Property> props, String[] customCriteria) {
    FieldManager fieldManager = getFieldManager();
    try {
        if (entity instanceof AdminMainEntity) {
            // its display name.
            try {
                Property propertyItem = new Property();
                propertyItem.setName(AdminMainEntity.MAIN_ENTITY_NAME_PROPERTY);
                propertyItem.setValue(((AdminMainEntity) entity).getMainEntityName());
                props.add(propertyItem);
            } catch (Exception e) {
            // do nothing here except for not add the property. Exceptions could occur when there is a validation
            // issue and some properties/relationships that are used for gleaning the main entity name end up
            // not being set
            }
        }
        for (Entry<String, FieldMetadata> entry : mergedProperties.entrySet()) {
            String property = entry.getKey();
            BasicFieldMetadata metadata = (BasicFieldMetadata) entry.getValue();
            if (Class.forName(metadata.getInheritedFromType()).isAssignableFrom(entity.getClass()) || entity.getClass().isAssignableFrom(Class.forName(metadata.getInheritedFromType()))) {
                boolean proceed = true;
                if (property.contains(".")) {
                    StringTokenizer tokens = new StringTokenizer(property, ".");
                    Object testObject = entity;
                    while (tokens.hasMoreTokens()) {
                        String token = tokens.nextToken();
                        if (tokens.hasMoreTokens()) {
                            try {
                                testObject = fieldManager.getFieldValue(testObject, token);
                            } catch (FieldNotAvailableException e) {
                                proceed = false;
                                break;
                            }
                            if (testObject == null) {
                                Property propertyItem = new Property();
                                propertyItem.setName(property);
                                if (props.contains(propertyItem)) {
                                    proceed = false;
                                    break;
                                }
                                propertyItem.setValue(null);
                                props.add(propertyItem);
                                proceed = false;
                                break;
                            }
                        }
                    }
                }
                if (!proceed) {
                    continue;
                }
                boolean isFieldAccessible = true;
                Object value = null;
                try {
                    value = fieldManager.getFieldValue(entity, property);
                } catch (FieldNotAvailableException e) {
                    isFieldAccessible = false;
                }
                checkField: {
                    if (isFieldAccessible) {
                        Property propertyItem = new Property();
                        propertyItem.setName(property);
                        if (props.contains(propertyItem)) {
                            continue;
                        }
                        props.add(propertyItem);
                        String displayVal = propertyItem.getDisplayValue();
                        boolean handled = false;
                        for (FieldPersistenceProvider fieldPersistenceProvider : fieldPersistenceProviders) {
                            MetadataProviderResponse response = fieldPersistenceProvider.extractValue(new ExtractValueRequest(props, fieldManager, metadata, value, displayVal, persistenceManager, this, entity, customCriteria), propertyItem);
                            if (MetadataProviderResponse.NOT_HANDLED != response) {
                                handled = true;
                            }
                            if (MetadataProviderResponse.HANDLED_BREAK == response) {
                                break;
                            }
                        }
                        if (!handled) {
                            defaultFieldPersistenceProvider.extractValue(new ExtractValueRequest(props, fieldManager, metadata, value, displayVal, persistenceManager, this, entity, customCriteria), propertyItem);
                        }
                        break checkField;
                    }
                    // try a direct property acquisition via reflection
                    try {
                        String strVal = null;
                        Method method;
                        try {
                            // try a 'get' prefixed mutator first
                            String temp = "get" + property.substring(0, 1).toUpperCase() + property.substring(1, property.length());
                            method = entity.getClass().getMethod(temp, new Class[] {});
                        } catch (NoSuchMethodException e) {
                            method = entity.getClass().getMethod(property, new Class[] {});
                        }
                        value = method.invoke(entity, new String[] {});
                        Property propertyItem = new Property();
                        propertyItem.setName(property);
                        if (props.contains(propertyItem)) {
                            continue;
                        }
                        props.add(propertyItem);
                        if (value == null) {
                            strVal = null;
                        } else {
                            if (Date.class.isAssignableFrom(value.getClass())) {
                                strVal = getSimpleDateFormatter().format((Date) value);
                            } else if (Timestamp.class.isAssignableFrom(value.getClass())) {
                                strVal = getSimpleDateFormatter().format(new Date(((Timestamp) value).getTime()));
                            } else if (Calendar.class.isAssignableFrom(value.getClass())) {
                                strVal = getSimpleDateFormatter().format(((Calendar) value).getTime());
                            } else if (Double.class.isAssignableFrom(value.getClass())) {
                                strVal = getDecimalFormatter().format(value);
                            } else if (BigDecimal.class.isAssignableFrom(value.getClass())) {
                                strVal = getDecimalFormatter().format(value);
                            } else {
                                strVal = value.toString();
                            }
                        }
                        propertyItem.setValue(strVal);
                    } catch (NoSuchMethodException e) {
                        LOG.debug("Unable to find a specified property in the entity: " + StringUtil.sanitize(property));
                    // do nothing - this property is simply not in the bean
                    }
                }
            }
        }
    } catch (ClassNotFoundException e) {
        throw new PersistenceException(e);
    } catch (IllegalAccessException e) {
        throw new PersistenceException(e);
    } catch (InvocationTargetException e) {
        throw new PersistenceException(e);
    }
}
Also used : FieldMetadata(org.broadleafcommerce.openadmin.dto.FieldMetadata) BasicFieldMetadata(org.broadleafcommerce.openadmin.dto.BasicFieldMetadata) FieldPersistenceProvider(org.broadleafcommerce.openadmin.server.service.persistence.module.provider.FieldPersistenceProvider) Timestamp(java.sql.Timestamp) Property(org.broadleafcommerce.openadmin.dto.Property) AdminMainEntity(org.broadleafcommerce.common.admin.domain.AdminMainEntity) MetadataProviderResponse(org.broadleafcommerce.openadmin.server.service.type.MetadataProviderResponse) ExtractValueRequest(org.broadleafcommerce.openadmin.server.service.persistence.module.provider.request.ExtractValueRequest) Calendar(java.util.Calendar) Method(java.lang.reflect.Method) 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) Date(java.util.Date) InvocationTargetException(java.lang.reflect.InvocationTargetException) StringTokenizer(java.util.StringTokenizer) BasicFieldMetadata(org.broadleafcommerce.openadmin.dto.BasicFieldMetadata) PersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.PersistenceException) ParentEntityPersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.ParentEntityPersistenceException) CriteriaTransferObject(org.broadleafcommerce.openadmin.dto.CriteriaTransferObject)

Example 2 with AdminMainEntity

use of org.broadleafcommerce.common.admin.domain.AdminMainEntity in project BroadleafCommerce by BroadleafCommerce.

the class AdminEntityServiceImpl method getForeignEntityName.

@Override
public String getForeignEntityName(String owningClass, String id) {
    if (owningClass == null || id == null) {
        return null;
    }
    DynamicEntityDao dynamicEntityDao = getDynamicEntityDao(owningClass);
    Class<?> clazz = dynamicEntityDao.getImplClass(owningClass);
    Object foreignEntity = dynamicEntityDao.find(clazz, toIdFieldType(id, clazz));
    if (foreignEntity instanceof AdminMainEntity) {
        return ((AdminMainEntity) foreignEntity).getMainEntityName();
    }
    return null;
}
Also used : CriteriaTransferObject(org.broadleafcommerce.openadmin.dto.CriteriaTransferObject) DynamicEntityDao(org.broadleafcommerce.openadmin.server.dao.DynamicEntityDao) AdminMainEntity(org.broadleafcommerce.common.admin.domain.AdminMainEntity)

Example 3 with AdminMainEntity

use of org.broadleafcommerce.common.admin.domain.AdminMainEntity in project BroadleafCommerce by BroadleafCommerce.

the class PageTemplateCustomPersistenceHandler method populateFKLookupValues.

/**
 * Some of the values in this entity might be foreign key lookups. In this case, we need to set the display
 * value appropriately
 *
 * @param dynamicEntityDao
 * @param entity
 * @throws ClassNotFoundException
 */
protected void populateFKLookupValues(DynamicEntityDao dynamicEntityDao, Entity entity) throws ClassNotFoundException {
    for (Property prop : entity.getProperties()) {
        if (StringUtils.isNotBlank(prop.getValue()) && StringUtils.isNotBlank(prop.getMetadata().getOwningClass())) {
            Class<?> clazz = Class.forName(prop.getMetadata().getOwningClass());
            Class<?>[] lookupClasses = dynamicEntityDao.getAllPolymorphicEntitiesFromCeiling(clazz);
            int i = 0;
            Object foreignEntity = null;
            while (foreignEntity == null && i < lookupClasses.length) {
                foreignEntity = dynamicEntityDao.find(lookupClasses[i++], Long.parseLong(prop.getValue()));
            }
            if (foreignEntity instanceof AdminMainEntity) {
                prop.setDisplayValue(((AdminMainEntity) foreignEntity).getMainEntityName());
            }
            prop.getMetadata().setOwningClass(null);
        }
    }
}
Also used : CriteriaTransferObject(org.broadleafcommerce.openadmin.dto.CriteriaTransferObject) Property(org.broadleafcommerce.openadmin.dto.Property) AdminMainEntity(org.broadleafcommerce.common.admin.domain.AdminMainEntity)

Example 4 with AdminMainEntity

use of org.broadleafcommerce.common.admin.domain.AdminMainEntity 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)

Example 5 with AdminMainEntity

use of org.broadleafcommerce.common.admin.domain.AdminMainEntity 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)

Aggregations

AdminMainEntity (org.broadleafcommerce.common.admin.domain.AdminMainEntity)5 Date (java.util.Date)3 CriteriaTransferObject (org.broadleafcommerce.openadmin.dto.CriteriaTransferObject)3 Property (org.broadleafcommerce.openadmin.dto.Property)3 PersistenceException (org.broadleafcommerce.openadmin.server.service.persistence.PersistenceException)3 Serializable (java.io.Serializable)2 BigDecimal (java.math.BigDecimal)2 Timestamp (java.sql.Timestamp)2 DecimalFormat (java.text.DecimalFormat)2 Calendar (java.util.Calendar)2 BasicFieldMetadata (org.broadleafcommerce.openadmin.dto.BasicFieldMetadata)2 FieldNotAvailableException (org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Method (java.lang.reflect.Method)1 Collection (java.util.Collection)1 StringTokenizer (java.util.StringTokenizer)1 SecurityServiceException (org.broadleafcommerce.common.exception.SecurityServiceException)1 ServiceException (org.broadleafcommerce.common.exception.ServiceException)1 ExtensionResultHolder (org.broadleafcommerce.common.extension.ExtensionResultHolder)1 ExtensionResultStatusType (org.broadleafcommerce.common.extension.ExtensionResultStatusType)1