Search in sources :

Example 6 with MetadataProviderResponse

use of org.broadleafcommerce.openadmin.server.service.type.MetadataProviderResponse 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 7 with MetadataProviderResponse

use of org.broadleafcommerce.openadmin.server.service.type.MetadataProviderResponse in project BroadleafCommerce by BroadleafCommerce.

the class Metadata method getFieldMetadataForTargetClass.

public Map<String, FieldMetadata> getFieldMetadataForTargetClass(Class<?> parentClass, Class<?> targetClass, DynamicEntityDao dynamicEntityDao, String prefix) {
    Map<String, FieldMetadata> metadata = new HashMap<>();
    Field[] fields = dynamicEntityDao.getAllFields(targetClass);
    for (Field field : fields) {
        boolean foundOneOrMoreHandlers = false;
        for (FieldMetadataProvider fieldMetadataProvider : fieldMetadataProviders) {
            MetadataProviderResponse response = fieldMetadataProvider.addMetadata(new AddFieldMetadataRequest(field, parentClass, targetClass, dynamicEntityDao, prefix), metadata);
            if (MetadataProviderResponse.NOT_HANDLED != response) {
                foundOneOrMoreHandlers = true;
            }
            if (MetadataProviderResponse.HANDLED_BREAK == response) {
                break;
            }
        }
        if (!foundOneOrMoreHandlers) {
            defaultFieldMetadataProvider.addMetadata(new AddFieldMetadataRequest(field, parentClass, targetClass, dynamicEntityDao, prefix), metadata);
        }
    }
    return metadata;
}
Also used : Field(java.lang.reflect.Field) DefaultFieldMetadataProvider(org.broadleafcommerce.openadmin.server.dao.provider.metadata.DefaultFieldMetadataProvider) FieldMetadataProvider(org.broadleafcommerce.openadmin.server.dao.provider.metadata.FieldMetadataProvider) FieldMetadata(org.broadleafcommerce.openadmin.dto.FieldMetadata) HashMap(java.util.HashMap) MetadataProviderResponse(org.broadleafcommerce.openadmin.server.service.type.MetadataProviderResponse) AddFieldMetadataRequest(org.broadleafcommerce.openadmin.server.dao.provider.metadata.request.AddFieldMetadataRequest)

Example 8 with MetadataProviderResponse

use of org.broadleafcommerce.openadmin.server.service.type.MetadataProviderResponse in project BroadleafCommerce by BroadleafCommerce.

the class Metadata method getFieldMetadata.

public FieldMetadata getFieldMetadata(String prefix, final String propertyName, final List<Property> componentProperties, final SupportedFieldType type, final SupportedFieldType secondaryType, final Type entityType, Class<?> targetClass, final FieldMetadata presentationAttribute, final MergedPropertyType mergedPropertyType, final DynamicEntityDao dynamicEntityDao) {
    if (presentationAttribute.getTargetClass() == null) {
        presentationAttribute.setTargetClass(targetClass.getName());
        presentationAttribute.setFieldName(propertyName);
    }
    presentationAttribute.setInheritedFromType(targetClass.getName());
    presentationAttribute.setAvailableToTypes(new String[] { targetClass.getName() });
    boolean handled = false;
    for (FieldMetadataProvider fieldMetadataProvider : fieldMetadataProviders) {
        MetadataProviderResponse response = fieldMetadataProvider.addMetadataFromMappingData(new AddMetadataFromMappingDataRequest(componentProperties, type, secondaryType, entityType, propertyName, mergedPropertyType, dynamicEntityDao), presentationAttribute);
        if (MetadataProviderResponse.NOT_HANDLED != response) {
            handled = true;
        }
        if (MetadataProviderResponse.HANDLED_BREAK == response) {
            break;
        }
    }
    if (!handled) {
        defaultFieldMetadataProvider.addMetadataFromMappingData(new AddMetadataFromMappingDataRequest(componentProperties, type, secondaryType, entityType, propertyName, mergedPropertyType, dynamicEntityDao), presentationAttribute);
    }
    return presentationAttribute;
}
Also used : DefaultFieldMetadataProvider(org.broadleafcommerce.openadmin.server.dao.provider.metadata.DefaultFieldMetadataProvider) FieldMetadataProvider(org.broadleafcommerce.openadmin.server.dao.provider.metadata.FieldMetadataProvider) AddMetadataFromMappingDataRequest(org.broadleafcommerce.openadmin.server.dao.provider.metadata.request.AddMetadataFromMappingDataRequest) MetadataProviderResponse(org.broadleafcommerce.openadmin.server.service.type.MetadataProviderResponse)

Example 9 with MetadataProviderResponse

use of org.broadleafcommerce.openadmin.server.service.type.MetadataProviderResponse in project BroadleafCommerce by BroadleafCommerce.

the class DynamicEntityDaoImpl method buildProperties.

protected void buildProperties(Class<?> targetClass, ForeignKey foreignField, ForeignKey[] additionalForeignFields, String[] additionalNonPersistentProperties, MergedPropertyType mergedPropertyType, Map<String, FieldMetadata> presentationAttributes, List<Property> componentProperties, Map<String, FieldMetadata> fields, List<String> propertyNames, List<Type> propertyTypes, String idProperty, Boolean populateManyToOneFields, String[] includeFields, String[] excludeFields, String configurationKey, String ceilingEntityFullyQualifiedClassname, List<Class<?>> parentClasses, String prefix, Boolean isParentExcluded, Boolean isComponentPrefix, String parentPrefix) {
    int j = 0;
    Comparator<String> propertyComparator = new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {
            // check for property name equality and for map field properties
            if (o1.equals(o2) || o1.startsWith(o2 + FieldManager.MAPFIELDSEPARATOR) || o2.startsWith(o1 + FieldManager.MAPFIELDSEPARATOR)) {
                return 0;
            }
            return o1.compareTo(o2);
        }
    };
    List<String> presentationKeyList = new ArrayList<>(presentationAttributes.keySet());
    Collections.sort(presentationKeyList);
    for (String propertyName : propertyNames) {
        final Type type = propertyTypes.get(j);
        boolean isPropertyForeignKey = testForeignProperty(foreignField, prefix, propertyName);
        int additionalForeignKeyIndexPosition = findAdditionalForeignKeyIndex(additionalForeignFields, prefix, propertyName);
        j++;
        Field myField = getFieldManager().getField(targetClass, propertyName);
        if (myField == null) {
            // try to get the field with the prefix - needed for advanced collections that appear in @Embedded classes
            myField = getFieldManager().getField(targetClass, prefix + propertyName);
        }
        if (!type.isAnyType() && !type.isCollectionType() || isPropertyForeignKey || additionalForeignKeyIndexPosition >= 0 || Collections.binarySearch(presentationKeyList, propertyName, propertyComparator) >= 0) {
            if (myField != null) {
                boolean handled = false;
                for (FieldMetadataProvider provider : fieldMetadataProviders) {
                    FieldMetadata presentationAttribute = presentationAttributes.get(propertyName);
                    if (presentationAttribute != null) {
                        setExcludedBasedOnShowIfProperty(presentationAttribute);
                    }
                    MetadataProviderResponse response = provider.addMetadataFromFieldType(new AddMetadataFromFieldTypeRequest(myField, targetClass, foreignField, additionalForeignFields, mergedPropertyType, componentProperties, idProperty, prefix, propertyName, type, isPropertyForeignKey, additionalForeignKeyIndexPosition, presentationAttributes, presentationAttribute, null, type.getReturnedClass(), this), fields);
                    if (MetadataProviderResponse.NOT_HANDLED != response) {
                        handled = true;
                    }
                    if (MetadataProviderResponse.HANDLED_BREAK == response) {
                        break;
                    }
                }
                if (!handled) {
                    buildBasicProperty(myField, targetClass, foreignField, additionalForeignFields, additionalNonPersistentProperties, mergedPropertyType, presentationAttributes, componentProperties, fields, idProperty, populateManyToOneFields, includeFields, excludeFields, configurationKey, ceilingEntityFullyQualifiedClassname, parentClasses, prefix, isParentExcluded, propertyName, type, isPropertyForeignKey, additionalForeignKeyIndexPosition, isComponentPrefix, parentPrefix);
                }
            }
        }
    }
}
Also used : FieldMetadata(org.broadleafcommerce.openadmin.dto.FieldMetadata) BasicFieldMetadata(org.broadleafcommerce.openadmin.dto.BasicFieldMetadata) MetadataProviderResponse(org.broadleafcommerce.openadmin.server.service.type.MetadataProviderResponse) ArrayList(java.util.ArrayList) Comparator(java.util.Comparator) Field(java.lang.reflect.Field) MergedPropertyType(org.broadleafcommerce.openadmin.dto.MergedPropertyType) PersistencePerspectiveItemType(org.broadleafcommerce.common.presentation.client.PersistencePerspectiveItemType) SupportedFieldType(org.broadleafcommerce.common.presentation.client.SupportedFieldType) ComponentType(org.hibernate.type.ComponentType) Type(org.hibernate.type.Type) FieldMetadataProvider(org.broadleafcommerce.openadmin.server.dao.provider.metadata.FieldMetadataProvider) AddMetadataFromFieldTypeRequest(org.broadleafcommerce.openadmin.server.dao.provider.metadata.request.AddMetadataFromFieldTypeRequest)

Example 10 with MetadataProviderResponse

use of org.broadleafcommerce.openadmin.server.service.type.MetadataProviderResponse in project BroadleafCommerce by BroadleafCommerce.

the class DynamicEntityDaoImpl method getSimpleMergedProperties.

@Override
public Map<String, FieldMetadata> getSimpleMergedProperties(String entityName, PersistencePerspective persistencePerspective) {
    Class<?>[] entityClasses;
    try {
        entityClasses = getAllPolymorphicEntitiesFromCeiling(Class.forName(entityName));
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
    if (!ArrayUtils.isEmpty(entityClasses)) {
        return getMergedProperties(entityName, entityClasses, (ForeignKey) persistencePerspective.getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.FOREIGNKEY), persistencePerspective.getAdditionalNonPersistentProperties(), persistencePerspective.getAdditionalForeignKeys(), MergedPropertyType.PRIMARY, persistencePerspective.getPopulateToOneFields(), persistencePerspective.getIncludeFields(), persistencePerspective.getExcludeFields(), persistencePerspective.getConfigurationKey(), "");
    } else {
        Map<String, FieldMetadata> mergedProperties = new HashMap<>();
        Class<?> targetClass;
        try {
            targetClass = Class.forName(entityName);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        Map<String, FieldMetadata> attributesMap = metadata.getFieldMetadataForTargetClass(null, targetClass, this, "");
        for (String property : attributesMap.keySet()) {
            FieldMetadata presentationAttribute = attributesMap.get(property);
            if (!presentationAttribute.getExcluded()) {
                Field field = FieldManager.getSingleField(targetClass, property);
                if (!Modifier.isStatic(field.getModifiers())) {
                    boolean handled = false;
                    for (FieldMetadataProvider provider : fieldMetadataProviders) {
                        MetadataProviderResponse response = provider.addMetadataFromFieldType(new AddMetadataFromFieldTypeRequest(field, targetClass, null, new ForeignKey[] {}, MergedPropertyType.PRIMARY, null, null, "", property, null, false, 0, attributesMap, presentationAttribute, ((BasicFieldMetadata) presentationAttribute).getExplicitFieldType(), field.getType(), this), mergedProperties);
                        if (MetadataProviderResponse.NOT_HANDLED != response) {
                            handled = true;
                        }
                        if (MetadataProviderResponse.HANDLED_BREAK == response) {
                            break;
                        }
                    }
                    if (!handled) {
                        // this provider is not included in the provider list on purpose - it is designed to handle basic
                        // AdminPresentation fields, and those fields not admin presentation annotated at all
                        defaultFieldMetadataProvider.addMetadataFromFieldType(new AddMetadataFromFieldTypeRequest(field, targetClass, null, new ForeignKey[] {}, MergedPropertyType.PRIMARY, null, null, "", property, null, false, 0, attributesMap, presentationAttribute, ((BasicFieldMetadata) presentationAttribute).getExplicitFieldType(), field.getType(), this), mergedProperties);
                    }
                }
            }
        }
        return mergedProperties;
    }
}
Also used : FieldMetadata(org.broadleafcommerce.openadmin.dto.FieldMetadata) BasicFieldMetadata(org.broadleafcommerce.openadmin.dto.BasicFieldMetadata) HashMap(java.util.HashMap) MetadataProviderResponse(org.broadleafcommerce.openadmin.server.service.type.MetadataProviderResponse) ForeignKey(org.broadleafcommerce.openadmin.dto.ForeignKey) Field(java.lang.reflect.Field) FieldMetadataProvider(org.broadleafcommerce.openadmin.server.dao.provider.metadata.FieldMetadataProvider) BasicFieldMetadata(org.broadleafcommerce.openadmin.dto.BasicFieldMetadata) PersistentClass(org.hibernate.mapping.PersistentClass) AdminPresentationClass(org.broadleafcommerce.common.presentation.AdminPresentationClass) AddMetadataFromFieldTypeRequest(org.broadleafcommerce.openadmin.server.dao.provider.metadata.request.AddMetadataFromFieldTypeRequest)

Aggregations

MetadataProviderResponse (org.broadleafcommerce.openadmin.server.service.type.MetadataProviderResponse)10 FieldMetadata (org.broadleafcommerce.openadmin.dto.FieldMetadata)8 BasicFieldMetadata (org.broadleafcommerce.openadmin.dto.BasicFieldMetadata)6 FieldMetadataProvider (org.broadleafcommerce.openadmin.server.dao.provider.metadata.FieldMetadataProvider)6 Field (java.lang.reflect.Field)5 ArrayList (java.util.ArrayList)4 AdminPresentationClass (org.broadleafcommerce.common.presentation.AdminPresentationClass)3 DefaultFieldMetadataProvider (org.broadleafcommerce.openadmin.server.dao.provider.metadata.DefaultFieldMetadataProvider)3 ParentEntityPersistenceException (org.broadleafcommerce.openadmin.server.service.persistence.ParentEntityPersistenceException)3 PersistenceException (org.broadleafcommerce.openadmin.server.service.persistence.PersistenceException)3 FieldPersistenceProvider (org.broadleafcommerce.openadmin.server.service.persistence.module.provider.FieldPersistenceProvider)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 HashMap (java.util.HashMap)2 AdminMainEntity (org.broadleafcommerce.common.admin.domain.AdminMainEntity)2 Property (org.broadleafcommerce.openadmin.dto.Property)2 AddMetadataFromFieldTypeRequest (org.broadleafcommerce.openadmin.server.dao.provider.metadata.request.AddMetadataFromFieldTypeRequest)2 ValidationException (org.broadleafcommerce.openadmin.server.service.ValidationException)2 PersistentClass (org.hibernate.mapping.PersistentClass)2 Serializable (java.io.Serializable)1 Method (java.lang.reflect.Method)1