Search in sources :

Example 1 with MetadataProviderResponse

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

the class Metadata method overrideMetadata.

public Map<String, FieldMetadata> overrideMetadata(Class<?>[] entities, PropertyBuilder propertyBuilder, String prefix, Boolean isParentExcluded, String ceilingEntityFullyQualifiedClassname, String configurationKey, DynamicEntityDao dynamicEntityDao) {
    Boolean classAnnotatedPopulateManyToOneFields = null;
    // go in reverse order since I want the lowest subclass override to come last to guarantee that it takes effect
    for (int i = entities.length - 1; i >= 0; i--) {
        AdminPresentationClass adminPresentationClass = AnnotationUtils.findAnnotation(entities[i], AdminPresentationClass.class);
        if (adminPresentationClass != null && adminPresentationClass.populateToOneFields() != PopulateToOneFieldsEnum.NOT_SPECIFIED) {
            classAnnotatedPopulateManyToOneFields = adminPresentationClass.populateToOneFields() == PopulateToOneFieldsEnum.TRUE;
            break;
        }
    }
    Map<String, FieldMetadata> mergedProperties = propertyBuilder.execute(classAnnotatedPopulateManyToOneFields);
    for (int i = entities.length - 1; i >= 0; i--) {
        boolean handled = false;
        for (FieldMetadataProvider fieldMetadataProvider : fieldMetadataProviders) {
            MetadataProviderResponse response = fieldMetadataProvider.overrideViaAnnotation(new OverrideViaAnnotationRequest(entities[i], isParentExcluded, dynamicEntityDao, prefix), mergedProperties);
            if (MetadataProviderResponse.NOT_HANDLED != response) {
                handled = true;
            }
            if (MetadataProviderResponse.HANDLED_BREAK == response) {
                break;
            }
        }
        if (!handled) {
            defaultFieldMetadataProvider.overrideViaAnnotation(new OverrideViaAnnotationRequest(entities[i], isParentExcluded, dynamicEntityDao, prefix), mergedProperties);
        }
    }
    ((DefaultFieldMetadataProvider) defaultFieldMetadataProvider).overrideExclusionsFromXml(new OverrideViaXmlRequest(configurationKey, ceilingEntityFullyQualifiedClassname, prefix, isParentExcluded, dynamicEntityDao), mergedProperties);
    boolean handled = false;
    for (FieldMetadataProvider fieldMetadataProvider : fieldMetadataProviders) {
        MetadataProviderResponse response = fieldMetadataProvider.overrideViaXml(new OverrideViaXmlRequest(configurationKey, ceilingEntityFullyQualifiedClassname, prefix, isParentExcluded, dynamicEntityDao), mergedProperties);
        if (MetadataProviderResponse.NOT_HANDLED != response) {
            handled = true;
        }
        if (MetadataProviderResponse.HANDLED_BREAK == response) {
            break;
        }
    }
    if (!handled) {
        defaultFieldMetadataProvider.overrideViaXml(new OverrideViaXmlRequest(configurationKey, ceilingEntityFullyQualifiedClassname, prefix, isParentExcluded, dynamicEntityDao), mergedProperties);
    }
    return mergedProperties;
}
Also used : AdminPresentationClass(org.broadleafcommerce.common.presentation.AdminPresentationClass) DefaultFieldMetadataProvider(org.broadleafcommerce.openadmin.server.dao.provider.metadata.DefaultFieldMetadataProvider) DefaultFieldMetadataProvider(org.broadleafcommerce.openadmin.server.dao.provider.metadata.DefaultFieldMetadataProvider) FieldMetadataProvider(org.broadleafcommerce.openadmin.server.dao.provider.metadata.FieldMetadataProvider) FieldMetadata(org.broadleafcommerce.openadmin.dto.FieldMetadata) OverrideViaXmlRequest(org.broadleafcommerce.openadmin.server.dao.provider.metadata.request.OverrideViaXmlRequest) MetadataProviderResponse(org.broadleafcommerce.openadmin.server.service.type.MetadataProviderResponse) OverrideViaAnnotationRequest(org.broadleafcommerce.openadmin.server.dao.provider.metadata.request.OverrideViaAnnotationRequest)

Example 2 with MetadataProviderResponse

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

the class DynamicEntityDaoImpl method getMergedProperties.

@Override
public Map<String, FieldMetadata> getMergedProperties(String ceilingEntityFullyQualifiedClassname, Class<?>[] entities, ForeignKey foreignField, String[] additionalNonPersistentProperties, ForeignKey[] additionalForeignFields, MergedPropertyType mergedPropertyType, Boolean populateManyToOneFields, String[] includeFields, String[] excludeFields, String configurationKey, String prefix) {
    Map<String, FieldMetadata> mergedProperties = getMergedPropertiesRecursively(ceilingEntityFullyQualifiedClassname, entities, foreignField, additionalNonPersistentProperties, additionalForeignFields, mergedPropertyType, populateManyToOneFields, includeFields, excludeFields, configurationKey, new ArrayList<Class<?>>(), prefix, false, "");
    final List<String> removeKeys = new ArrayList<>();
    for (final String key : mergedProperties.keySet()) {
        if (mergedProperties.get(key).getExcluded() != null && mergedProperties.get(key).getExcluded()) {
            removeKeys.add(key);
        }
    }
    for (String removeKey : removeKeys) {
        mergedProperties.remove(removeKey);
    }
    // Allow field metadata providers to contribute additional fields here. These latestage handlers take place
    // after any cached lookups occur, and are ideal for adding in dynamic properties that are not globally cacheable
    // like properties gleaned from reflection typically are.
    Set<String> keys = new HashSet<>(mergedProperties.keySet());
    for (Class<?> targetClass : entities) {
        for (String key : keys) {
            LateStageAddMetadataRequest amr = new LateStageAddMetadataRequest(key, null, targetClass, this, "");
            boolean foundOneOrMoreHandlers = false;
            for (FieldMetadataProvider fieldMetadataProvider : fieldMetadataProviders) {
                MetadataProviderResponse response = fieldMetadataProvider.lateStageAddMetadata(amr, mergedProperties);
                if (MetadataProviderResponse.NOT_HANDLED != response) {
                    foundOneOrMoreHandlers = true;
                }
                if (MetadataProviderResponse.HANDLED_BREAK == response) {
                    break;
                }
            }
            if (!foundOneOrMoreHandlers) {
                defaultFieldMetadataProvider.lateStageAddMetadata(amr, mergedProperties);
            }
        }
    }
    return mergedProperties;
}
Also used : LateStageAddMetadataRequest(org.broadleafcommerce.openadmin.server.dao.provider.metadata.request.LateStageAddMetadataRequest) FieldMetadata(org.broadleafcommerce.openadmin.dto.FieldMetadata) BasicFieldMetadata(org.broadleafcommerce.openadmin.dto.BasicFieldMetadata) MetadataProviderResponse(org.broadleafcommerce.openadmin.server.service.type.MetadataProviderResponse) ArrayList(java.util.ArrayList) FieldMetadataProvider(org.broadleafcommerce.openadmin.server.dao.provider.metadata.FieldMetadataProvider) PersistentClass(org.hibernate.mapping.PersistentClass) AdminPresentationClass(org.broadleafcommerce.common.presentation.AdminPresentationClass) HashSet(java.util.HashSet)

Example 3 with MetadataProviderResponse

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

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

the class BasicPersistenceModule method getFilterMappings.

@Override
public List<FilterMapping> getFilterMappings(PersistencePerspective persistencePerspective, CriteriaTransferObject cto, String ceilingEntityFullyQualifiedClassname, Map<String, FieldMetadata> mergedUnfilteredProperties, RestrictionFactory customRestrictionFactory) {
    Map<String, FieldMetadata> mergedProperties = filterOutCollectionMetadata(mergedUnfilteredProperties);
    List<FilterMapping> filterMappings = new ArrayList<FilterMapping>();
    for (String propertyId : cto.getCriteriaMap().keySet()) {
        if (mergedProperties.containsKey(propertyId)) {
            boolean handled = false;
            for (FieldPersistenceProvider fieldPersistenceProvider : fieldPersistenceProviders) {
                MetadataProviderResponse response = fieldPersistenceProvider.addSearchMapping(new AddSearchMappingRequest(persistencePerspective, cto, ceilingEntityFullyQualifiedClassname, mergedProperties, propertyId, getFieldManager(), this, this, customRestrictionFactory == null ? restrictionFactory : customRestrictionFactory), filterMappings);
                if (MetadataProviderResponse.NOT_HANDLED != response) {
                    handled = true;
                }
                if (MetadataProviderResponse.HANDLED_BREAK == response) {
                    break;
                }
            }
            if (!handled) {
                defaultFieldPersistenceProvider.addSearchMapping(new AddSearchMappingRequest(persistencePerspective, cto, ceilingEntityFullyQualifiedClassname, mergedProperties, propertyId, getFieldManager(), this, this, customRestrictionFactory == null ? restrictionFactory : customRestrictionFactory), filterMappings);
            }
        }
    }
    return filterMappings;
}
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) FieldPersistenceProvider(org.broadleafcommerce.openadmin.server.service.persistence.module.provider.FieldPersistenceProvider) FilterMapping(org.broadleafcommerce.openadmin.server.service.persistence.module.criteria.FilterMapping) AddSearchMappingRequest(org.broadleafcommerce.openadmin.server.service.persistence.module.provider.request.AddSearchMappingRequest)

Example 5 with MetadataProviderResponse

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

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