Search in sources :

Example 16 with ForeignKey

use of org.broadleafcommerce.openadmin.dto.ForeignKey in project BroadleafCommerce by BroadleafCommerce.

the class MapStructurePersistenceModule method update.

@Override
public Entity update(PersistencePackage persistencePackage) throws ServiceException {
    String[] customCriteria = persistencePackage.getCustomCriteria();
    if (customCriteria != null && customCriteria.length > 0) {
        LOG.warn("custom persistence handlers and custom criteria not supported for update types other than BASIC");
    }
    PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
    Entity entity = persistencePackage.getEntity();
    MapStructure mapStructure = (MapStructure) persistencePerspective.getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.MAPSTRUCTURE);
    if (!mapStructure.getMutable()) {
        throw new SecurityServiceException("Field not mutable");
    }
    try {
        Map<String, FieldMetadata> ceilingMergedProperties = getSimpleMergedProperties(entity.getType()[0], persistencePerspective);
        String mapKey = entity.findProperty(mapStructure.getKeyPropertyName()).getValue();
        if (ceilingMergedProperties.containsKey(mapStructure.getMapProperty() + FieldManager.MAPFIELDSEPARATOR + mapKey)) {
            throw new ServiceException("\"" + mapKey + "\" is a reserved property name.");
        }
        Serializable instance = persistenceManager.getDynamicEntityDao().retrieve(Class.forName(entity.getType()[0]), Long.valueOf(entity.findProperty("symbolicId").getValue()));
        Assert.isTrue(instance != null, "Entity not found");
        FieldManager fieldManager = getFieldManager();
        Map map = (Map) fieldManager.getFieldValue(instance, mapStructure.getMapProperty());
        PersistentClass persistentClass = persistenceManager.getDynamicEntityDao().getPersistentClass(mapStructure.getValueClassName());
        Map<String, FieldMetadata> valueUnfilteredMergedProperties;
        if (persistentClass == null) {
            valueUnfilteredMergedProperties = persistenceManager.getDynamicEntityDao().getPropertiesForPrimitiveClass(((SimpleValueMapStructure) mapStructure).getValuePropertyName(), ((SimpleValueMapStructure) mapStructure).getValuePropertyFriendlyName(), Class.forName(mapStructure.getValueClassName()), Class.forName(entity.getType()[0]), MergedPropertyType.MAPSTRUCTUREVALUE);
        } else {
            String valueClassName = mapStructure.getValueClassName();
            Class<?>[] mapEntities = persistenceManager.getPolymorphicEntities(valueClassName);
            valueUnfilteredMergedProperties = persistenceManager.getDynamicEntityDao().getMergedProperties(valueClassName, mapEntities, null, new String[] {}, new ForeignKey[] {}, MergedPropertyType.MAPSTRUCTUREVALUE, persistencePerspective.getPopulateToOneFields(), persistencePerspective.getIncludeFields(), persistencePerspective.getExcludeFields(), persistencePerspective.getConfigurationKey(), "");
        }
        Map<String, FieldMetadata> valueMergedProperties = filterOutCollectionMetadata(valueUnfilteredMergedProperties);
        if (StringUtils.isEmpty(mapKey)) {
            entity.addValidationError(mapStructure.getKeyPropertyName(), RequiredPropertyValidator.ERROR_MESSAGE);
            LOG.debug("No key property passed in for map, failing validation");
        }
        populate: {
            if (persistentClass != null) {
                Serializable valueInstance = (Serializable) map.get(entity.findProperty("priorKey").getValue());
                if (valueInstance == null) {
                    valueInstance = procureSandBoxMapValue(mapStructure, entity);
                    if (valueInstance == null) {
                        break populate;
                    }
                }
                if (map.get(mapKey) != null && !map.get(mapKey).equals(valueInstance)) {
                    entity.addValidationError(mapStructure.getKeyPropertyName(), "keyExistsValidationError");
                }
                if (StringUtils.isNotBlank(mapStructure.getMapKeyValueProperty())) {
                    Property p = entity.findProperty("key");
                    Property newP = new Property();
                    newP.setName(mapStructure.getMapKeyValueProperty());
                    newP.setValue(p.getValue());
                    newP.setIsDirty(p.getIsDirty());
                    entity.addProperty(newP);
                }
                // allow validation on other properties in order to show key validation errors along with all the other properties
                // validation errors
                valueInstance = createPopulatedInstance(valueInstance, entity, valueMergedProperties, false);
                if (StringUtils.isNotEmpty(mapKey) && !entity.isValidationFailure()) {
                    if (!entity.findProperty("priorKey").getValue().equals(mapKey)) {
                        map.remove(entity.findProperty("priorKey").getValue());
                    }
                    /*
                         * TODO this map manipulation code currently assumes the key value is a String. This should be widened to accept
                         * additional types of primitive objects.
                         */
                    map.put(entity.findProperty(mapStructure.getKeyPropertyName()).getValue(), valueInstance);
                }
            } else {
                if (StringUtils.isNotEmpty(mapKey) && !entity.isValidationFailure()) {
                    map.put(entity.findProperty(mapStructure.getKeyPropertyName()).getValue(), entity.findProperty(((SimpleValueMapStructure) mapStructure).getValuePropertyName()).getValue());
                }
            }
        }
        instance = persistenceManager.getDynamicEntityDao().merge(instance);
        Entity[] responses = getMapRecords(instance, mapStructure, ceilingMergedProperties, valueMergedProperties, entity.findProperty("symbolicId"), null);
        for (Entity response : responses) {
            if (response.findProperty(mapStructure.getKeyPropertyName()).getValue().equals(persistencePackage.getEntity().findProperty(mapStructure.getKeyPropertyName()).getValue())) {
                return response;
            }
        }
        // could be empty if reverting a sandbox item that has experienced a deletion. make sure to at least return an empty instance of Entity.
        return ArrayUtils.isEmpty(responses) ? new Entity() : responses[0];
    } catch (Exception e) {
        throw new ServiceException("Problem updating entity : " + e.getMessage(), e);
    }
}
Also used : Entity(org.broadleafcommerce.openadmin.dto.Entity) SecurityServiceException(org.broadleafcommerce.common.exception.SecurityServiceException) Serializable(java.io.Serializable) FieldMetadata(org.broadleafcommerce.openadmin.dto.FieldMetadata) BasicFieldMetadata(org.broadleafcommerce.openadmin.dto.BasicFieldMetadata) ForeignKey(org.broadleafcommerce.openadmin.dto.ForeignKey) ParseException(java.text.ParseException) ServiceException(org.broadleafcommerce.common.exception.ServiceException) InvocationTargetException(java.lang.reflect.InvocationTargetException) SecurityServiceException(org.broadleafcommerce.common.exception.SecurityServiceException) MapStructure(org.broadleafcommerce.openadmin.dto.MapStructure) SimpleValueMapStructure(org.broadleafcommerce.openadmin.dto.SimpleValueMapStructure) PersistencePerspective(org.broadleafcommerce.openadmin.dto.PersistencePerspective) ServiceException(org.broadleafcommerce.common.exception.ServiceException) SecurityServiceException(org.broadleafcommerce.common.exception.SecurityServiceException) PersistentClass(org.hibernate.mapping.PersistentClass) Map(java.util.Map) Property(org.broadleafcommerce.openadmin.dto.Property) SimpleValueMapStructure(org.broadleafcommerce.openadmin.dto.SimpleValueMapStructure) PersistentClass(org.hibernate.mapping.PersistentClass)

Example 17 with ForeignKey

use of org.broadleafcommerce.openadmin.dto.ForeignKey in project BroadleafCommerce by BroadleafCommerce.

the class CollectionFieldMetadataProvider method buildCollectionMetadata.

protected void buildCollectionMetadata(Class<?> parentClass, Class<?> targetClass, Map<String, FieldMetadata> attributes, FieldInfo field, FieldMetadataOverride collectionMetadata, String prefix) {
    BasicCollectionMetadata serverMetadata = (BasicCollectionMetadata) attributes.get(field.getName());
    Class<?> resolvedClass = parentClass == null ? targetClass : parentClass;
    BasicCollectionMetadata metadata;
    if (serverMetadata != null) {
        metadata = serverMetadata;
    } else {
        metadata = new BasicCollectionMetadata();
    }
    metadata.setTargetClass(targetClass.getName());
    metadata.setFieldName(field.getName());
    if (collectionMetadata.getReadOnly() != null) {
        metadata.setMutable(!collectionMetadata.getReadOnly());
    }
    if (collectionMetadata.getAddMethodType() != null) {
        metadata.setAddMethodType(collectionMetadata.getAddMethodType());
    }
    if (collectionMetadata.getShowIfProperty() != null) {
        metadata.setShowIfProperty(collectionMetadata.getShowIfProperty());
    }
    if (collectionMetadata.getShowIfFieldEquals() != null) {
        metadata.setShowIfFieldEquals(collectionMetadata.getShowIfFieldEquals());
    }
    org.broadleafcommerce.openadmin.dto.OperationTypes dtoOperationTypes = new org.broadleafcommerce.openadmin.dto.OperationTypes(OperationType.BASIC, OperationType.BASIC, OperationType.BASIC, OperationType.BASIC, OperationType.BASIC);
    if (collectionMetadata.getAddType() != null) {
        dtoOperationTypes.setAddType(collectionMetadata.getAddType());
    }
    if (collectionMetadata.getRemoveType() != null) {
        dtoOperationTypes.setRemoveType(collectionMetadata.getRemoveType());
    }
    if (collectionMetadata.getFetchType() != null) {
        dtoOperationTypes.setFetchType(collectionMetadata.getFetchType());
    }
    if (collectionMetadata.getInspectType() != null) {
        dtoOperationTypes.setInspectType(collectionMetadata.getInspectType());
    }
    if (collectionMetadata.getUpdateType() != null) {
        dtoOperationTypes.setUpdateType(collectionMetadata.getUpdateType());
    }
    if (AddMethodType.LOOKUP == metadata.getAddMethodType() || AddMethodType.SELECTIZE_LOOKUP == metadata.getAddMethodType()) {
        dtoOperationTypes.setRemoveType(OperationType.NONDESTRUCTIVEREMOVE);
    }
    // don't allow additional non-persistent properties or additional foreign keys for an advanced collection datasource - they don't make sense in this context
    PersistencePerspective persistencePerspective;
    if (serverMetadata != null) {
        persistencePerspective = metadata.getPersistencePerspective();
        persistencePerspective.setOperationTypes(dtoOperationTypes);
    } else {
        persistencePerspective = new PersistencePerspective(dtoOperationTypes, new String[] {}, new ForeignKey[] {});
        metadata.setPersistencePerspective(persistencePerspective);
    }
    String foreignKeyName = null;
    if (serverMetadata != null) {
        foreignKeyName = ((ForeignKey) serverMetadata.getPersistencePerspective().getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.FOREIGNKEY)).getManyToField();
    }
    if (!StringUtils.isEmpty(collectionMetadata.getManyToField())) {
        foreignKeyName = collectionMetadata.getManyToField();
    }
    if (foreignKeyName == null && !StringUtils.isEmpty(field.getOneToManyMappedBy())) {
        foreignKeyName = field.getOneToManyMappedBy();
    }
    if (foreignKeyName == null && !StringUtils.isEmpty(field.getManyToManyMappedBy())) {
        foreignKeyName = field.getManyToManyMappedBy();
    }
    if (StringUtils.isEmpty(foreignKeyName)) {
        throw new IllegalArgumentException("Unable to infer a ManyToOne field name for the @AdminPresentationCollection annotated field(" + field.getName() + "). If not using the mappedBy property of @OneToMany or @ManyToMany, please make sure to explicitly define the manyToField property");
    }
    String sortProperty = null;
    if (serverMetadata != null) {
        sortProperty = ((ForeignKey) serverMetadata.getPersistencePerspective().getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.FOREIGNKEY)).getSortField();
    }
    if (!StringUtils.isEmpty(collectionMetadata.getSortProperty())) {
        sortProperty = collectionMetadata.getSortProperty();
    }
    Boolean isAscending = true;
    if (serverMetadata != null) {
        isAscending = ((ForeignKey) serverMetadata.getPersistencePerspective().getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.FOREIGNKEY)).getSortAscending();
    }
    if (collectionMetadata.isSortAscending() != null) {
        isAscending = collectionMetadata.isSortAscending();
    }
    if (serverMetadata != null) {
        ForeignKey foreignKey = (ForeignKey) metadata.getPersistencePerspective().getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.FOREIGNKEY);
        foreignKey.setManyToField(foreignKeyName);
        foreignKey.setForeignKeyClass(resolvedClass.getName());
        foreignKey.setMutable(metadata.isMutable());
        foreignKey.setOriginatingField(prefix + field.getName());
        foreignKey.setSortField(sortProperty);
        foreignKey.setSortAscending(isAscending);
    } else {
        ForeignKey foreignKey = new ForeignKey(foreignKeyName, resolvedClass.getName(), null, ForeignKeyRestrictionType.ID_EQ);
        foreignKey.setMutable(metadata.isMutable());
        foreignKey.setOriginatingField(prefix + field.getName());
        foreignKey.setSortField(sortProperty);
        foreignKey.setSortAscending(isAscending);
        persistencePerspective.addPersistencePerspectiveItem(PersistencePerspectiveItemType.FOREIGNKEY, foreignKey);
    }
    String ceiling = null;
    checkCeiling: {
        if (field.getGenericType() instanceof ParameterizedType) {
            try {
                ParameterizedType pt = (ParameterizedType) field.getGenericType();
                java.lang.reflect.Type collectionType = pt.getActualTypeArguments()[0];
                String ceilingEntityName = ((Class<?>) collectionType).getName();
                ceiling = entityConfiguration.lookupEntityClass(ceilingEntityName).getName();
                break checkCeiling;
            } catch (NoSuchBeanDefinitionException e) {
            // We weren't successful at looking at entity configuration to find the type of this collection.
            // We will continue and attempt to find it via the Hibernate annotations
            }
        }
        if (!StringUtils.isEmpty(field.getOneToManyTargetEntity()) && !void.class.getName().equals(field.getOneToManyTargetEntity())) {
            ceiling = field.getOneToManyTargetEntity();
            break checkCeiling;
        }
        if (!StringUtils.isEmpty(field.getManyToManyTargetEntity()) && !void.class.getName().equals(field.getManyToManyTargetEntity())) {
            ceiling = field.getManyToManyTargetEntity();
            break checkCeiling;
        }
    }
    if (!StringUtils.isEmpty(ceiling)) {
        metadata.setCollectionCeilingEntity(ceiling);
    }
    if (collectionMetadata.getExcluded() != null) {
        if (LOG.isDebugEnabled()) {
            if (collectionMetadata.getExcluded()) {
                LOG.debug("buildCollectionMetadata:Excluding " + field.getName() + " because it was explicitly declared in config");
            } else {
                LOG.debug("buildCollectionMetadata:Showing " + field.getName() + " because it was explicitly declared in config");
            }
        }
        metadata.setExcluded(collectionMetadata.getExcluded());
    }
    if (collectionMetadata.getLazyFetch() != null) {
        metadata.setLazyFetch(collectionMetadata.getLazyFetch());
    }
    if (collectionMetadata.getManualFetch() != null) {
        metadata.setManualFetch(collectionMetadata.getManualFetch());
    }
    if (collectionMetadata.getFriendlyName() != null) {
        metadata.setFriendlyName(collectionMetadata.getFriendlyName());
    }
    if (collectionMetadata.getAddFriendlyName() != null) {
        metadata.setAddFriendlyName(collectionMetadata.getAddFriendlyName());
    }
    if (collectionMetadata.getSecurityLevel() != null) {
        metadata.setSecurityLevel(collectionMetadata.getSecurityLevel());
    }
    if (collectionMetadata.getOrder() != null) {
        metadata.setOrder(collectionMetadata.getOrder());
    }
    if (collectionMetadata.getTab() != null) {
        metadata.setTab(collectionMetadata.getTab());
    }
    if (collectionMetadata.getTabOrder() != null) {
        metadata.setTabOrder(collectionMetadata.getTabOrder());
    }
    if (collectionMetadata.getGroup() != null) {
        metadata.setGroup(collectionMetadata.getGroup());
    }
    if (collectionMetadata.getSortProperty() != null) {
        metadata.setSortProperty(collectionMetadata.getSortProperty());
    }
    if (collectionMetadata.getCustomCriteria() != null) {
        metadata.setCustomCriteria(collectionMetadata.getCustomCriteria());
    }
    if (collectionMetadata.getUseServerSideInspectionCache() != null) {
        persistencePerspective.setUseServerSideInspectionCache(collectionMetadata.getUseServerSideInspectionCache());
    }
    if (collectionMetadata.getCurrencyCodeField() != null) {
        metadata.setCurrencyCodeField(collectionMetadata.getCurrencyCodeField());
    }
    if (collectionMetadata.getSelectizeVisibleField() != null) {
        metadata.setSelectizeVisibleField(collectionMetadata.getSelectizeVisibleField());
    }
    attributes.put(field.getName(), metadata);
}
Also used : ForeignKey(org.broadleafcommerce.openadmin.dto.ForeignKey) ParameterizedType(java.lang.reflect.ParameterizedType) PersistencePerspective(org.broadleafcommerce.openadmin.dto.PersistencePerspective) AdminPresentationOperationTypes(org.broadleafcommerce.common.presentation.AdminPresentationOperationTypes) BasicCollectionMetadata(org.broadleafcommerce.openadmin.dto.BasicCollectionMetadata) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException)

Example 18 with ForeignKey

use of org.broadleafcommerce.openadmin.dto.ForeignKey in project BroadleafCommerce by BroadleafCommerce.

the class MapFieldMetadataProvider method buildMapMetadata.

protected void buildMapMetadata(Class<?> parentClass, Class<?> targetClass, Map<String, FieldMetadata> attributes, FieldInfo field, FieldMetadataOverride map, DynamicEntityDao dynamicEntityDao, String prefix) {
    MapMetadata serverMetadata = (MapMetadata) attributes.get(field.getName());
    Class<?> resolvedClass = parentClass == null ? targetClass : parentClass;
    MapMetadata metadata;
    if (serverMetadata != null) {
        metadata = serverMetadata;
    } else {
        metadata = new MapMetadata();
    }
    if (map.getReadOnly() != null) {
        metadata.setMutable(!map.getReadOnly());
    }
    if (map.getShowIfProperty() != null) {
        metadata.setShowIfProperty(map.getShowIfProperty());
    }
    if (map.getShowIfFieldEquals() != null) {
        metadata.setShowIfFieldEquals(map.getShowIfFieldEquals());
    }
    metadata.setPrefix(prefix);
    metadata.setTargetClass(targetClass.getName());
    metadata.setFieldName(field.getName());
    org.broadleafcommerce.openadmin.dto.OperationTypes dtoOperationTypes = new org.broadleafcommerce.openadmin.dto.OperationTypes(OperationType.MAP, OperationType.MAP, OperationType.MAP, OperationType.MAP, OperationType.MAP);
    if (map.getAddType() != null) {
        dtoOperationTypes.setAddType(map.getAddType());
    }
    if (map.getRemoveType() != null) {
        dtoOperationTypes.setRemoveType(map.getRemoveType());
    }
    if (map.getFetchType() != null) {
        dtoOperationTypes.setFetchType(map.getFetchType());
    }
    if (map.getInspectType() != null) {
        dtoOperationTypes.setInspectType(map.getInspectType());
    }
    if (map.getUpdateType() != null) {
        dtoOperationTypes.setUpdateType(map.getUpdateType());
    }
    // don't allow additional non-persistent properties or additional foreign keys for an advanced collection datasource - they don't make sense in this context
    PersistencePerspective persistencePerspective;
    if (serverMetadata != null) {
        persistencePerspective = metadata.getPersistencePerspective();
        persistencePerspective.setOperationTypes(dtoOperationTypes);
    } else {
        persistencePerspective = new PersistencePerspective(dtoOperationTypes, new String[] {}, new ForeignKey[] {});
        metadata.setPersistencePerspective(persistencePerspective);
    }
    String parentObjectClass = resolvedClass.getName();
    Map idMetadata;
    if (parentClass != null) {
        idMetadata = dynamicEntityDao.getIdMetadata(parentClass);
    } else {
        idMetadata = dynamicEntityDao.getIdMetadata(targetClass);
    }
    String parentObjectIdField = (String) idMetadata.get("name");
    String keyClassName = null;
    if (serverMetadata != null) {
        keyClassName = ((MapStructure) metadata.getPersistencePerspective().getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.MAPSTRUCTURE)).getKeyClassName();
    }
    if (map.getKeyClass() != null && !void.class.getName().equals(map.getKeyClass())) {
        keyClassName = map.getKeyClass();
    }
    if (keyClassName == null) {
        java.lang.reflect.Type type = field.getGenericType();
        if (type instanceof ParameterizedType) {
            ParameterizedType pType = (ParameterizedType) type;
            Class<?> clazz = (Class<?>) pType.getActualTypeArguments()[0];
            if (!ArrayUtils.isEmpty(dynamicEntityDao.getAllPolymorphicEntitiesFromCeiling(clazz))) {
                throw new IllegalArgumentException("Key class for AdminPresentationMap was determined to be a JPA managed type. Only primitive types for the key type are currently supported.");
            }
            keyClassName = clazz.getName();
        }
    }
    if (keyClassName == null) {
        keyClassName = String.class.getName();
    }
    String keyPropertyName = "key";
    String mapKeyValueProperty = "";
    if (StringUtils.isNotBlank(field.getMapKey())) {
        mapKeyValueProperty = field.getMapKey();
    }
    if (StringUtils.isNotBlank(map.getMapKeyValueProperty())) {
        mapKeyValueProperty = map.getMapKeyValueProperty();
    }
    String keyPropertyFriendlyName = null;
    if (serverMetadata != null) {
        keyPropertyFriendlyName = ((MapStructure) serverMetadata.getPersistencePerspective().getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.MAPSTRUCTURE)).getKeyPropertyFriendlyName();
    }
    if (map.getKeyPropertyFriendlyName() != null) {
        keyPropertyFriendlyName = map.getKeyPropertyFriendlyName();
    }
    Boolean deleteEntityUponRemove = null;
    if (serverMetadata != null) {
        deleteEntityUponRemove = ((MapStructure) serverMetadata.getPersistencePerspective().getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.MAPSTRUCTURE)).getDeleteValueEntity();
    }
    if (map.isDeleteEntityUponRemove() != null) {
        deleteEntityUponRemove = map.isDeleteEntityUponRemove();
    }
    String valuePropertyName = "value";
    String valuePropertyFriendlyName = null;
    if (serverMetadata != null) {
        MapStructure structure = (MapStructure) serverMetadata.getPersistencePerspective().getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.MAPSTRUCTURE);
        if (structure instanceof SimpleValueMapStructure) {
            valuePropertyFriendlyName = ((SimpleValueMapStructure) structure).getValuePropertyFriendlyName();
        } else {
            valuePropertyFriendlyName = "";
        }
    }
    if (map.getValuePropertyFriendlyName() != null) {
        valuePropertyFriendlyName = map.getValuePropertyFriendlyName();
    }
    if (map.getMediaField() != null) {
        metadata.setMediaField(map.getMediaField());
    }
    if (map.getToOneTargetProperty() != null) {
        metadata.setToOneTargetProperty(map.getToOneTargetProperty());
    }
    if (map.getToOneParentProperty() != null) {
        metadata.setToOneParentProperty((map.getToOneParentProperty()));
    }
    if (map.getValueClass() != null && !void.class.getName().equals(map.getValueClass())) {
        metadata.setValueClassName(map.getValueClass());
    }
    if (metadata.getValueClassName() == null) {
        java.lang.reflect.Type type = field.getGenericType();
        if (type instanceof ParameterizedType) {
            ParameterizedType pType = (ParameterizedType) type;
            Class<?> clazz = (Class<?>) pType.getActualTypeArguments()[1];
            Class<?>[] entities = dynamicEntityDao.getAllPolymorphicEntitiesFromCeiling(clazz);
            if (!ArrayUtils.isEmpty(entities)) {
                metadata.setValueClassName(entities[entities.length - 1].getName());
            }
        }
    }
    if (metadata.getValueClassName() == null) {
        if (!StringUtils.isEmpty(field.getManyToManyTargetEntity())) {
            metadata.setValueClassName(field.getManyToManyTargetEntity());
        }
    }
    if (metadata.getValueClassName() == null) {
        metadata.setValueClassName(String.class.getName());
    }
    Boolean simpleValue = null;
    if (map.getSimpleValue() != null && map.getSimpleValue() != UnspecifiedBooleanType.UNSPECIFIED) {
        simpleValue = map.getSimpleValue() == UnspecifiedBooleanType.TRUE;
    }
    if (simpleValue == null) {
        java.lang.reflect.Type type = field.getGenericType();
        if (type instanceof ParameterizedType) {
            ParameterizedType pType = (ParameterizedType) type;
            Class<?> clazz = (Class<?>) pType.getActualTypeArguments()[1];
            Class<?>[] entities = dynamicEntityDao.getAllPolymorphicEntitiesFromCeiling(clazz);
            simpleValue = ArrayUtils.isEmpty(entities);
        }
    }
    if (simpleValue == null) {
        // ManyToMany manyToMany = field.getAnnotation(ManyToMany.class);
        if (!StringUtils.isEmpty(field.getManyToManyTargetEntity())) {
            simpleValue = false;
        }
    }
    if (simpleValue == null) {
        throw new IllegalArgumentException("Unable to infer if the value for the map is of a complex or simple type based on any parameterized type or ManyToMany annotation. Please explicitly set the isSimpleValue property.");
    }
    metadata.setSimpleValue(simpleValue);
    if (map.getKeys() != null) {
        metadata.setKeys(map.getKeys());
    }
    metadata.setMapKeyValueProperty(mapKeyValueProperty);
    if (map.getMapKeyOptionEntityClass() != null) {
        if (!void.class.getName().equals(map.getMapKeyOptionEntityClass())) {
            metadata.setMapKeyOptionEntityClass(map.getMapKeyOptionEntityClass());
        } else {
            metadata.setMapKeyOptionEntityClass("");
        }
    }
    if (map.getMapKeyOptionEntityDisplayField() != null) {
        metadata.setMapKeyOptionEntityDisplayField(map.getMapKeyOptionEntityDisplayField());
    }
    if (map.getMapKeyOptionEntityValueField() != null) {
        metadata.setMapKeyOptionEntityValueField(map.getMapKeyOptionEntityValueField());
    }
    if (map.getForceFreeFormKeys() != null) {
        if (!map.getForceFreeFormKeys() && ArrayUtils.isEmpty(metadata.getKeys()) && (StringUtils.isEmpty(metadata.getMapKeyOptionEntityClass()) || StringUtils.isEmpty(metadata.getMapKeyOptionEntityValueField()) || StringUtils.isEmpty(metadata.getMapKeyOptionEntityDisplayField()))) {
            throw new IllegalArgumentException("Could not ascertain method for generating key options for the annotated map (" + field.getName() + "). Must specify either an array of AdminPresentationMapKey values for the keys property, or utilize the mapOptionKeyClass, mapOptionKeyDisplayField and mapOptionKeyValueField properties. If you wish to allow free form entry for key values, then set forceFreeFormKeys on AdminPresentationMap.");
        }
    }
    MapStructure mapStructure;
    if (serverMetadata != null) {
        ForeignKey foreignKey = (ForeignKey) persistencePerspective.getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.FOREIGNKEY);
        foreignKey.setManyToField(parentObjectIdField);
        foreignKey.setForeignKeyClass(parentObjectClass);
        if (metadata.isSimpleValue()) {
            mapStructure = (SimpleValueMapStructure) persistencePerspective.getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.MAPSTRUCTURE);
            mapStructure.setKeyClassName(keyClassName);
            mapStructure.setKeyPropertyName(keyPropertyName);
            mapStructure.setKeyPropertyFriendlyName(keyPropertyFriendlyName);
            mapStructure.setValueClassName(metadata.getValueClassName());
            ((SimpleValueMapStructure) mapStructure).setValuePropertyName(valuePropertyName);
            ((SimpleValueMapStructure) mapStructure).setValuePropertyFriendlyName(valuePropertyFriendlyName);
            mapStructure.setMapProperty(prefix + field.getName());
            mapStructure.setMutable(metadata.isMutable());
        } else {
            mapStructure = (MapStructure) persistencePerspective.getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.MAPSTRUCTURE);
            mapStructure.setKeyClassName(keyClassName);
            mapStructure.setKeyPropertyName(keyPropertyName);
            mapStructure.setKeyPropertyFriendlyName(keyPropertyFriendlyName);
            mapStructure.setValueClassName(metadata.getValueClassName());
            mapStructure.setMapProperty(prefix + field.getName());
            mapStructure.setDeleteValueEntity(deleteEntityUponRemove);
            mapStructure.setMutable(metadata.isMutable());
        }
    } else {
        ForeignKey foreignKey = new ForeignKey(parentObjectIdField, parentObjectClass);
        persistencePerspective.addPersistencePerspectiveItem(PersistencePerspectiveItemType.FOREIGNKEY, foreignKey);
        if (metadata.isSimpleValue()) {
            mapStructure = new SimpleValueMapStructure(keyClassName, keyPropertyName, keyPropertyFriendlyName, metadata.getValueClassName(), valuePropertyName, valuePropertyFriendlyName, prefix + field.getName(), mapKeyValueProperty);
            mapStructure.setMutable(metadata.isMutable());
        } else {
            mapStructure = new MapStructure(keyClassName, keyPropertyName, keyPropertyFriendlyName, metadata.getValueClassName(), prefix + field.getName(), deleteEntityUponRemove, mapKeyValueProperty);
            mapStructure.setMutable(metadata.isMutable());
        }
        persistencePerspective.addPersistencePerspectiveItem(PersistencePerspectiveItemType.MAPSTRUCTURE, mapStructure);
    }
    if (!StringUtils.isEmpty(map.getManyToField())) {
        mapStructure.setManyToField(map.getManyToField());
    }
    if (mapStructure.getManyToField() == null) {
        // try to infer the value
        if (field.getManyToManyMappedBy() != null) {
            mapStructure.setManyToField(field.getManyToManyMappedBy());
        }
    }
    if (mapStructure.getManyToField() == null) {
        // try to infer the value
        if (field.getOneToManyMappedBy() != null) {
            mapStructure.setManyToField(field.getOneToManyMappedBy());
        }
    }
    if (map.getExcluded() != null) {
        if (LOG.isDebugEnabled()) {
            if (map.getExcluded()) {
                LOG.debug("buildMapMetadata:Excluding " + field.getName() + " because it was explicitly declared in config");
            } else {
                LOG.debug("buildMapMetadata:Showing " + field.getName() + " because it was explicitly declared in config");
            }
        }
        metadata.setExcluded(map.getExcluded());
    }
    if (map.getLazyFetch() != null) {
        metadata.setLazyFetch(map.getLazyFetch());
    }
    if (map.getManualFetch() != null) {
        metadata.setManualFetch(map.getManualFetch());
    }
    if (map.getFriendlyName() != null) {
        metadata.setFriendlyName(map.getFriendlyName());
    }
    if (map.getSecurityLevel() != null) {
        metadata.setSecurityLevel(map.getSecurityLevel());
    }
    if (map.getOrder() != null) {
        metadata.setOrder(map.getOrder());
    }
    if (map.getTab() != null) {
        metadata.setTab(map.getTab());
    }
    if (map.getTabOrder() != null) {
        metadata.setTabOrder(map.getTabOrder());
    }
    if (map.getGroup() != null) {
        metadata.setGroup(map.getGroup());
    }
    if (map.getCustomCriteria() != null) {
        metadata.setCustomCriteria(map.getCustomCriteria());
    }
    if (map.getUseServerSideInspectionCache() != null) {
        persistencePerspective.setUseServerSideInspectionCache(map.getUseServerSideInspectionCache());
    }
    if (map.getCurrencyCodeField() != null) {
        metadata.setCurrencyCodeField(map.getCurrencyCodeField());
    }
    if (map.getForceFreeFormKeys() != null) {
        metadata.setForceFreeFormKeys(map.getForceFreeFormKeys());
    }
    attributes.put(field.getName(), metadata);
}
Also used : ForeignKey(org.broadleafcommerce.openadmin.dto.ForeignKey) ParameterizedType(java.lang.reflect.ParameterizedType) MapStructure(org.broadleafcommerce.openadmin.dto.MapStructure) SimpleValueMapStructure(org.broadleafcommerce.openadmin.dto.SimpleValueMapStructure) PersistencePerspective(org.broadleafcommerce.openadmin.dto.PersistencePerspective) AdminPresentationOperationTypes(org.broadleafcommerce.common.presentation.AdminPresentationOperationTypes) MapMetadata(org.broadleafcommerce.openadmin.dto.MapMetadata) HashMap(java.util.HashMap) Map(java.util.Map) AdminPresentationMap(org.broadleafcommerce.common.presentation.AdminPresentationMap) SimpleValueMapStructure(org.broadleafcommerce.openadmin.dto.SimpleValueMapStructure)

Example 19 with ForeignKey

use of org.broadleafcommerce.openadmin.dto.ForeignKey in project BroadleafCommerce by BroadleafCommerce.

the class DynamicEntityDaoImpl method setOriginatingFieldForForeignKey.

/*
     * There may be multiple pathways to this foreign key which may have come from a cached source.
     * Since ForeignKey contains an originating field concept that is occurrence specific, we need
     * to make sure it is set appropriately here.
     *
     * A known use case is vendorPortal.embeddableMultitenantSite.adminUsers and
     * owningSite.embeddableMultitenantSite.adminUsers.
     */
protected void setOriginatingFieldForForeignKey(String propertyName, String key, FieldMetadata fieldMetadata) {
    ForeignKey foreignKey = (ForeignKey) ((BasicCollectionMetadata) fieldMetadata).getPersistencePerspective().getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.FOREIGNKEY);
    foreignKey.setOriginatingField(propertyName + '.' + key);
}
Also used : ForeignKey(org.broadleafcommerce.openadmin.dto.ForeignKey)

Example 20 with ForeignKey

use of org.broadleafcommerce.openadmin.dto.ForeignKey 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

ForeignKey (org.broadleafcommerce.openadmin.dto.ForeignKey)20 PersistencePerspective (org.broadleafcommerce.openadmin.dto.PersistencePerspective)14 BasicFieldMetadata (org.broadleafcommerce.openadmin.dto.BasicFieldMetadata)11 FieldMetadata (org.broadleafcommerce.openadmin.dto.FieldMetadata)11 Entity (org.broadleafcommerce.openadmin.dto.Entity)10 Serializable (java.io.Serializable)9 ServiceException (org.broadleafcommerce.common.exception.ServiceException)9 InvocationTargetException (java.lang.reflect.InvocationTargetException)8 SecurityServiceException (org.broadleafcommerce.common.exception.SecurityServiceException)8 AdminMainEntity (org.broadleafcommerce.common.admin.domain.AdminMainEntity)5 CriteriaTransferObject (org.broadleafcommerce.openadmin.dto.CriteriaTransferObject)5 MapStructure (org.broadleafcommerce.openadmin.dto.MapStructure)5 SimpleValueMapStructure (org.broadleafcommerce.openadmin.dto.SimpleValueMapStructure)5 ValidationException (org.broadleafcommerce.openadmin.server.service.ValidationException)5 PersistenceException (org.broadleafcommerce.openadmin.server.service.persistence.PersistenceException)5 FilterMapping (org.broadleafcommerce.openadmin.server.service.persistence.module.criteria.FilterMapping)5 Field (java.lang.reflect.Field)4 ParseException (java.text.ParseException)4 ArrayList (java.util.ArrayList)4 Map (java.util.Map)4