Search in sources :

Example 1 with FieldNotAvailableException

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

the class MapFieldPersistenceProvider method populateValue.

@Override
public MetadataProviderResponse populateValue(PopulateValueRequest populateValueRequest, Serializable instance) {
    if (!canHandlePersistence(populateValueRequest, instance)) {
        return MetadataProviderResponse.NOT_HANDLED;
    }
    boolean dirty = false;
    try {
        Class<?> startingValueType = getStartingValueType(populateValueRequest);
        Class<?> valueType = getValueType(populateValueRequest, startingValueType);
        if (ValueAssignable.class.isAssignableFrom(valueType)) {
            boolean persistValue = false;
            ValueAssignable assignableValue;
            Object parent;
            try {
                parent = populateValueRequest.getFieldManager().getFieldValue(instance, populateValueRequest.getProperty().getName());
                if (parent instanceof List) {
                    parent = ((List) parent).get(0);
                }
                if (parent == null) {
                    parent = startingValueType.newInstance();
                    if (!startingValueType.equals(valueType)) {
                        setupJoinEntityParent(populateValueRequest, instance, parent);
                    }
                    populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), parent);
                    persistValue = true;
                }
                assignableValue = establishAssignableValue(populateValueRequest, parent);
            } catch (FieldNotAvailableException e) {
                throw new IllegalArgumentException(e);
            }
            dirty = persistValue || (assignableValue != null && ObjectUtils.notEqual(assignableValue.getValue(), populateValueRequest.getProperty().getValue()));
            if (dirty) {
                updateAssignableValue(populateValueRequest, instance, parent, valueType, persistValue, assignableValue);
            }
        } else {
            // handle the map value set itself
            if (MetadataProviderResponse.NOT_HANDLED == super.populateValue(populateValueRequest, instance)) {
                return MetadataProviderResponse.NOT_HANDLED;
            }
        }
    } catch (Exception e) {
        throw new PersistenceException(e);
    }
    populateValueRequest.getProperty().setIsDirty(dirty);
    return MetadataProviderResponse.HANDLED_BREAK;
}
Also used : ValueAssignable(org.broadleafcommerce.common.value.ValueAssignable) FieldNotAvailableException(org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException) PersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.PersistenceException) List(java.util.List) FieldNotAvailableException(org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException) PersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.PersistenceException)

Example 2 with FieldNotAvailableException

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

the class MapFieldPersistenceProvider method extractValue.

@Override
public MetadataProviderResponse extractValue(ExtractValueRequest extractValueRequest, Property property) throws PersistenceException {
    if (!canHandleExtraction(extractValueRequest, property)) {
        return MetadataProviderResponse.NOT_HANDLED;
    }
    checkValue: {
        if (extractValueRequest.getRequestedValue() != null) {
            Object requestedValue = extractValueRequest.getRequestedValue();
            if (!StringUtils.isEmpty(extractValueRequest.getMetadata().getToOneTargetProperty())) {
                try {
                    requestedValue = extractValueRequest.getFieldManager().getFieldValue(requestedValue, extractValueRequest.getMetadata().getToOneTargetProperty());
                } catch (IllegalAccessException e) {
                    throw ExceptionHelper.refineException(e);
                } catch (FieldNotAvailableException e) {
                    throw ExceptionHelper.refineException(e);
                }
            }
            if (requestedValue instanceof ValueAssignable) {
                ValueAssignable assignableValue = (ValueAssignable) requestedValue;
                String val = (String) assignableValue.getValue();
                property.setValue(val);
                property.setDisplayValue(extractValueRequest.getDisplayVal());
                break checkValue;
            }
        }
        if (MetadataProviderResponse.NOT_HANDLED == super.extractValue(extractValueRequest, property)) {
            return MetadataProviderResponse.NOT_HANDLED;
        }
    }
    return MetadataProviderResponse.HANDLED;
}
Also used : ValueAssignable(org.broadleafcommerce.common.value.ValueAssignable) FieldNotAvailableException(org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException)

Example 3 with FieldNotAvailableException

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

the class MediaFieldPersistenceProvider method populateValue.

@Override
public MetadataProviderResponse populateValue(PopulateValueRequest populateValueRequest, Serializable instance) throws PersistenceException {
    if (!canHandlePersistence(populateValueRequest, instance)) {
        return MetadataProviderResponse.NOT_HANDLED;
    }
    String prop = populateValueRequest.getProperty().getName();
    if (prop.contains(FieldManager.MAPFIELDSEPARATOR)) {
        Field field = populateValueRequest.getFieldManager().getField(instance.getClass(), prop.substring(0, prop.indexOf(FieldManager.MAPFIELDSEPARATOR)));
        if (field.getAnnotation(OneToMany.class) == null) {
            throw new UnsupportedOperationException("MediaFieldPersistenceProvider is currently only compatible with map fields when modelled using @OneToMany");
        }
    }
    MetadataProviderResponse response = MetadataProviderResponse.HANDLED;
    boolean dirty = false;
    try {
        setNonDisplayableValues(populateValueRequest);
        Class<?> valueType = getStartingValueType(populateValueRequest);
        if (Media.class.isAssignableFrom(valueType)) {
            Media newMedia = mediaBuilderService.convertJsonToMedia(populateValueRequest.getProperty().getUnHtmlEncodedValue(), valueType);
            boolean persist = false;
            boolean noPrimary = false;
            boolean update = false;
            Media media;
            Boolean cleared;
            try {
                checkExtension: {
                    if (extensionManager != null) {
                        ExtensionResultHolder<Tuple<Media, Boolean>> result = new ExtensionResultHolder<Tuple<Media, Boolean>>();
                        ExtensionResultStatusType statusType = extensionManager.getProxy().retrieveMedia(instance, populateValueRequest, result);
                        if (ExtensionResultStatusType.NOT_HANDLED != statusType) {
                            Tuple<Media, Boolean> tuple = result.getResult();
                            media = tuple.getFirst();
                            cleared = tuple.getSecond();
                            break checkExtension;
                        }
                    }
                    media = (Media) populateValueRequest.getFieldManager().getFieldValue(instance, populateValueRequest.getProperty().getName());
                    cleared = false;
                }
                if (newMedia == null) {
                    noPrimary = true;
                    dirty = true;
                    update = false;
                    if (!cleared && media != null) {
                        // remove entry in sku to media map
                        populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), null);
                        populateValueRequest.getPersistenceManager().getDynamicEntityDao().remove(media);
                    }
                } else if (media == null) {
                    media = (Media) valueType.newInstance();
                    mediaBuilderService.instantiateMediaFields(media);
                    Object parent = extractParent(populateValueRequest, instance);
                    populateValueRequest.getFieldManager().setFieldValue(media, populateValueRequest.getMetadata().getToOneParentProperty(), parent);
                    populateValueRequest.getFieldManager().setFieldValue(media, populateValueRequest.getMetadata().getMapKeyValueProperty(), prop.substring(prop.indexOf(FieldManager.MAPFIELDSEPARATOR) + FieldManager.MAPFIELDSEPARATOR.length(), prop.length()));
                    persist = true;
                }
            } catch (FieldNotAvailableException e) {
                throw new IllegalArgumentException(e);
            }
            if (media != null) {
                if (media instanceof Status && 'Y' == ((Status) media).getArchived()) {
                    persist = true;
                }
                populateValueRequest.getProperty().setOriginalValue(convertMediaToJson(media));
            }
            if (!noPrimary) {
                dirty = establishDirtyState(newMedia, media);
                update = dirty;
            }
            if (dirty) {
                if (update) {
                    updateMedia(populateValueRequest, newMedia, persist, media);
                }
                response = MetadataProviderResponse.HANDLED_BREAK;
            }
        } else {
            throw new UnsupportedOperationException("MediaFields only work with Media types.");
        }
    } catch (Exception e) {
        throw ExceptionHelper.refineException(PersistenceException.class, PersistenceException.class, e);
    }
    populateValueRequest.getProperty().setIsDirty(dirty);
    return response;
}
Also used : Status(org.broadleafcommerce.common.persistence.Status) MetadataProviderResponse(org.broadleafcommerce.openadmin.server.service.type.MetadataProviderResponse) Media(org.broadleafcommerce.common.media.domain.Media) ExtensionResultStatusType(org.broadleafcommerce.common.extension.ExtensionResultStatusType) OneToMany(javax.persistence.OneToMany) FieldNotAvailableException(org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ParentEntityPersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.ParentEntityPersistenceException) PersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.PersistenceException) Field(java.lang.reflect.Field) FieldNotAvailableException(org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException) ParentEntityPersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.ParentEntityPersistenceException) PersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.PersistenceException) Tuple(org.broadleafcommerce.common.util.Tuple) ExtensionResultHolder(org.broadleafcommerce.common.extension.ExtensionResultHolder)

Example 4 with FieldNotAvailableException

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

the class RuleFieldPersistenceProvider method populateSimpleRule.

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

Example 5 with FieldNotAvailableException

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

the class DefaultBasicPersistenceModuleExtensionHandler method rebalanceForUpdate.

@Override
public ExtensionResultStatusType rebalanceForUpdate(final BasicPersistenceModule basicPersistenceModule, PersistencePackage persistencePackage, Serializable instance, Map<String, FieldMetadata> mergedProperties, Object primaryKey, ExtensionResultHolder<Serializable> resultHolder) {
    try {
        Entity entity = persistencePackage.getEntity();
        PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
        ForeignKey foreignKey = (ForeignKey) persistencePerspective.getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.FOREIGNKEY);
        Integer requestedSequence = Integer.valueOf(entity.findProperty(foreignKey.getSortField()).getValue());
        Integer previousSequence = new BigDecimal(String.valueOf(basicPersistenceModule.getFieldManager().getFieldValue(instance, foreignKey.getSortField()))).intValue();
        final String idPropertyName = basicPersistenceModule.getIdPropertyName(mergedProperties);
        final Object pKey = primaryKey;
        instance = basicPersistenceModule.createPopulatedInstance(instance, entity, mergedProperties, false, persistencePackage.isValidateUnsubmittedProperties());
        if (!previousSequence.equals(requestedSequence)) {
            // Sequence has changed. Rebalance the list
            Serializable manyToField = (Serializable) basicPersistenceModule.getFieldManager().getFieldValue(instance, foreignKey.getManyToField());
            List<Serializable> records = (List<Serializable>) basicPersistenceModule.getFieldManager().getFieldValue(manyToField, foreignKey.getOriginatingField());
            Serializable myRecord = (Serializable) CollectionUtils.find(records, new TypedPredicate<Serializable>() {

                @Override
                public boolean eval(Serializable record) {
                    try {
                        return (pKey.equals(basicPersistenceModule.getFieldManager().getFieldValue(record, idPropertyName)));
                    } catch (IllegalAccessException e) {
                        return false;
                    } catch (FieldNotAvailableException e) {
                        return false;
                    }
                }
            });
            records.remove(myRecord);
            if (CollectionUtils.isEmpty(records)) {
                records.add(myRecord);
            } else {
                records.add(requestedSequence - 1, myRecord);
            }
            int index = 1;
            Class<?> type = basicPersistenceModule.getFieldManager().getField(myRecord.getClass(), foreignKey.getSortField()).getType();
            boolean isBigDecimal = BigDecimal.class.isAssignableFrom(type);
            for (Serializable record : records) {
                basicPersistenceModule.getFieldManager().setFieldValue(record, foreignKey.getSortField(), isBigDecimal ? new BigDecimal(index) : Long.valueOf(index));
                index++;
            }
        }
        resultHolder.setResult(instance);
    } catch (IllegalAccessException e) {
        throw ExceptionHelper.refineException(e);
    } catch (FieldNotAvailableException e) {
        throw ExceptionHelper.refineException(e);
    } catch (ValidationException e) {
        throw ExceptionHelper.refineException(e);
    } catch (InstantiationException e) {
        throw ExceptionHelper.refineException(e);
    }
    return ExtensionResultStatusType.HANDLED;
}
Also used : Entity(org.broadleafcommerce.openadmin.dto.Entity) Serializable(java.io.Serializable) ValidationException(org.broadleafcommerce.openadmin.server.service.ValidationException) ForeignKey(org.broadleafcommerce.openadmin.dto.ForeignKey) BigDecimal(java.math.BigDecimal) PersistencePerspective(org.broadleafcommerce.openadmin.dto.PersistencePerspective) FieldNotAvailableException(org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException) CriteriaTransferObject(org.broadleafcommerce.openadmin.dto.CriteriaTransferObject) List(java.util.List) TypedPredicate(org.broadleafcommerce.common.util.TypedPredicate)

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