use of org.broadleafcommerce.openadmin.dto.BasicFieldMetadata in project BroadleafCommerce by BroadleafCommerce.
the class BasicPersistenceModule method remove.
@Override
public void remove(PersistencePackage persistencePackage) throws ServiceException {
Entity entity = persistencePackage.getEntity();
PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
ForeignKey foreignKey = (ForeignKey) persistencePerspective.getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.FOREIGNKEY);
if (foreignKey != null && !foreignKey.getMutable()) {
throw new SecurityServiceException("Entity not mutable");
}
try {
Class<?>[] entities = persistenceManager.getPolymorphicEntities(persistencePackage.getCeilingEntityFullyQualifiedClassname());
Map<String, FieldMetadata> mergedUnfilteredProperties = persistenceManager.getDynamicEntityDao().getMergedProperties(persistencePackage.getCeilingEntityFullyQualifiedClassname(), entities, foreignKey, persistencePerspective.getAdditionalNonPersistentProperties(), persistencePerspective.getAdditionalForeignKeys(), MergedPropertyType.PRIMARY, persistencePerspective.getPopulateToOneFields(), persistencePerspective.getIncludeFields(), persistencePerspective.getExcludeFields(), persistencePerspective.getConfigurationKey(), "");
Map<String, FieldMetadata> mergedProperties = filterOutCollectionMetadata(mergedUnfilteredProperties);
Object primaryKey = getPrimaryKey(entity, mergedProperties);
Serializable instance = persistenceManager.getDynamicEntityDao().retrieve(Class.forName(entity.getType()[0]), primaryKey);
Assert.isTrue(instance != null, "Entity not found");
switch(persistencePerspective.getOperationTypes().getRemoveType()) {
case NONDESTRUCTIVEREMOVE:
FieldManager fieldManager = getFieldManager();
FieldMetadata manyToFieldMetadata = mergedUnfilteredProperties.get(foreignKey.getManyToField());
Object foreignKeyValue = entity.getPMap().get(foreignKey.getManyToField()).getValue();
try {
foreignKeyValue = Long.valueOf((String) foreignKeyValue);
} catch (NumberFormatException e) {
LOG.warn("Foreign primary key is not of type Long, assuming String for remove lookup");
}
Serializable foreignInstance = persistenceManager.getDynamicEntityDao().retrieve(Class.forName(foreignKey.getForeignKeyClass()), foreignKeyValue);
Collection collection = (Collection) fieldManager.getFieldValue(foreignInstance, foreignKey.getOriginatingField());
collection.remove(instance);
// set the manyTo field to null so that subsequent lookups will not find it
if (manyToFieldMetadata instanceof BasicFieldMetadata) {
if (BooleanUtils.isTrue(((BasicFieldMetadata) manyToFieldMetadata).getRequired())) {
throw new ServiceException("Could not remove from the collection as the ManyToOne side is a" + " non-optional relationship. Consider changing 'optional=true' in the @ManyToOne annotation" + " or nullable=true within the @JoinColumn annotation");
}
// Since this is occuring on a remove persistence package, merge up-front (before making a change) for proper operation in the presence of the enterprise module
instance = persistenceManager.getDynamicEntityDao().merge(instance);
Field manyToField = fieldManager.getField(instance.getClass(), foreignKey.getManyToField());
Object manyToObject = manyToField.get(instance);
if (manyToObject != null && !(manyToObject instanceof Collection) && !(manyToObject instanceof Map)) {
manyToField.set(instance, null);
instance = persistenceManager.getDynamicEntityDao().merge(instance);
}
}
break;
case BASIC:
persistenceManager.getDynamicEntityDao().remove(instance);
break;
}
} catch (Exception e) {
throw new ServiceException("Problem removing entity : " + e.getMessage(), e);
}
}
use of org.broadleafcommerce.openadmin.dto.BasicFieldMetadata in project BroadleafCommerce by BroadleafCommerce.
the class MediaFieldPersistenceProvider method filterProperties.
@Override
public MetadataProviderResponse filterProperties(AddFilterPropertiesRequest addFilterPropertiesRequest, Map<String, FieldMetadata> properties) {
// BP: Basically copied this from RuleFieldPersistenceProvider
List<Property> propertyList = new ArrayList<Property>();
propertyList.addAll(Arrays.asList(addFilterPropertiesRequest.getEntity().getProperties()));
Iterator<Property> itr = propertyList.iterator();
List<Property> additionalProperties = new ArrayList<Property>();
while (itr.hasNext()) {
Property prop = itr.next();
if (prop.getName().endsWith("Json")) {
for (Map.Entry<String, FieldMetadata> entry : properties.entrySet()) {
if (prop.getName().startsWith(entry.getKey())) {
BasicFieldMetadata originalFM = (BasicFieldMetadata) entry.getValue();
if (originalFM.getFieldType() == SupportedFieldType.MEDIA) {
Property originalProp = addFilterPropertiesRequest.getEntity().findProperty(originalFM.getName());
if (originalProp == null) {
originalProp = new Property();
originalProp.setName(originalFM.getName());
additionalProperties.add(originalProp);
}
originalProp.setValue(prop.getValue());
originalProp.setRawValue(prop.getRawValue());
originalProp.setUnHtmlEncodedValue(prop.getUnHtmlEncodedValue());
itr.remove();
break;
}
}
}
}
}
propertyList.addAll(additionalProperties);
addFilterPropertiesRequest.getEntity().setProperties(propertyList.toArray(new Property[propertyList.size()]));
return MetadataProviderResponse.HANDLED;
}
use of org.broadleafcommerce.openadmin.dto.BasicFieldMetadata in project BroadleafCommerce by BroadleafCommerce.
the class BasicFieldPersistenceProvider method canHandlePersistence.
protected boolean canHandlePersistence(PopulateValueRequest populateValueRequest, Serializable instance) {
BasicFieldMetadata metadata = populateValueRequest.getMetadata();
Property property = populateValueRequest.getProperty();
// don't handle map fields here - we'll get them in a separate provider
boolean response = detectBasicType(metadata, property);
if (!response) {
// we'll allow this provider to handle money filter mapping for persistence
response = metadata.getFieldType() == SupportedFieldType.MONEY;
}
return response;
}
use of org.broadleafcommerce.openadmin.dto.BasicFieldMetadata in project BroadleafCommerce by BroadleafCommerce.
the class BasicFieldPersistenceProvider method addSearchMapping.
@Override
public MetadataProviderResponse addSearchMapping(AddSearchMappingRequest addSearchMappingRequest, List<FilterMapping> filterMappings) {
if (!canHandleSearchMapping(addSearchMappingRequest, filterMappings)) {
return MetadataProviderResponse.NOT_HANDLED;
}
Class clazz;
try {
clazz = Class.forName(addSearchMappingRequest.getMergedProperties().get(addSearchMappingRequest.getPropertyName()).getInheritedFromType());
} catch (ClassNotFoundException e) {
throw new PersistenceException(e);
}
Field field = addSearchMappingRequest.getFieldManager().getField(clazz, addSearchMappingRequest.getPropertyName());
Class<?> targetType = null;
if (field != null) {
targetType = field.getType();
}
BasicFieldMetadata metadata = (BasicFieldMetadata) addSearchMappingRequest.getMergedProperties().get(addSearchMappingRequest.getPropertyName());
FilterAndSortCriteria fasc = addSearchMappingRequest.getRequestedCto().get(addSearchMappingRequest.getPropertyName());
FilterMapping filterMapping = new FilterMapping().withInheritedFromClass(clazz).withFullPropertyName(addSearchMappingRequest.getPropertyName()).withFilterValues(fasc.getFilterValues()).withSortDirection(fasc.getSortDirection()).withOrder(fasc.getOrder()).withNullsLast(fasc.isNullsLast());
filterMappings.add(filterMapping);
if (fasc.hasSpecialFilterValue()) {
filterMapping.setDirectFilterValues(new EmptyFilterValues());
// Handle special values on a case by case basis
List<String> specialValues = fasc.getSpecialFilterValues();
if (specialValues.contains(FilterAndSortCriteria.IS_NULL_FILTER_VALUE)) {
filterMapping.setRestriction(new Restriction().withPredicateProvider(new IsNullPredicateProvider()));
}
if (specialValues.contains(FilterAndSortCriteria.IS_NOT_NULL_FILTER_VALUE)) {
filterMapping.setRestriction(new Restriction().withPredicateProvider(new IsNotNullPredicateProvider()));
}
} else {
if (fasc.getRestrictionType() != null) {
filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(fasc.getRestrictionType().getType(), addSearchMappingRequest.getPropertyName()));
} else {
switch(metadata.getFieldType()) {
case BOOLEAN:
if (targetType == null || targetType.equals(Boolean.class) || targetType.equals(boolean.class)) {
filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.BOOLEAN.getType(), addSearchMappingRequest.getPropertyName()));
} else {
filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.CHARACTER.getType(), addSearchMappingRequest.getPropertyName()));
}
break;
case DATE:
filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.DATE.getType(), addSearchMappingRequest.getPropertyName()));
break;
case DECIMAL:
case MONEY:
filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.DECIMAL.getType(), addSearchMappingRequest.getPropertyName()));
break;
case INTEGER:
filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.LONG.getType(), addSearchMappingRequest.getPropertyName()));
break;
case BROADLEAF_ENUMERATION:
filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.STRING_EQUAL.getType(), addSearchMappingRequest.getPropertyName()));
break;
default:
filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.STRING_LIKE.getType(), addSearchMappingRequest.getPropertyName()));
break;
case FOREIGN_KEY:
if (!addSearchMappingRequest.getRequestedCto().get(addSearchMappingRequest.getPropertyName()).getFilterValues().isEmpty()) {
ForeignKey foreignKey = (ForeignKey) addSearchMappingRequest.getPersistencePerspective().getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.FOREIGNKEY);
if (metadata.getForeignKeyCollection()) {
if (ForeignKeyRestrictionType.COLLECTION_SIZE_EQ.toString().equals(foreignKey.getRestrictionType().toString())) {
filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.COLLECTION_SIZE_EQUAL.getType(), addSearchMappingRequest.getPropertyName()));
filterMapping.setFieldPath(new FieldPath());
} else {
filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.LONG.getType(), addSearchMappingRequest.getPropertyName()));
filterMapping.setFieldPath(new FieldPath().withTargetProperty(addSearchMappingRequest.getPropertyName() + "." + metadata.getForeignKeyProperty()));
}
} else if (addSearchMappingRequest.getRequestedCto().get(addSearchMappingRequest.getPropertyName()).getFilterValues().get(0) == null || "null".equals(addSearchMappingRequest.getRequestedCto().get(addSearchMappingRequest.getPropertyName()).getFilterValues().get(0))) {
filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.IS_NULL_LONG.getType(), addSearchMappingRequest.getPropertyName()));
} else if (metadata.getSecondaryType() == SupportedFieldType.STRING) {
filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.STRING_EQUAL.getType(), addSearchMappingRequest.getPropertyName()));
filterMapping.setFieldPath(new FieldPath().withTargetProperty(addSearchMappingRequest.getPropertyName() + "." + metadata.getForeignKeyProperty()));
} else {
filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.LONG_EQUAL.getType(), addSearchMappingRequest.getPropertyName()));
filterMapping.setFieldPath(new FieldPath().withTargetProperty(addSearchMappingRequest.getPropertyName() + "." + metadata.getForeignKeyProperty()));
}
}
break;
case ADDITIONAL_FOREIGN_KEY:
int additionalForeignKeyIndexPosition = Arrays.binarySearch(addSearchMappingRequest.getPersistencePerspective().getAdditionalForeignKeys(), new ForeignKey(addSearchMappingRequest.getPropertyName(), null, null), new Comparator<ForeignKey>() {
@Override
public int compare(ForeignKey o1, ForeignKey o2) {
return o1.getManyToField().compareTo(o2.getManyToField());
}
});
ForeignKey foreignKey = null;
if (additionalForeignKeyIndexPosition >= 0) {
foreignKey = addSearchMappingRequest.getPersistencePerspective().getAdditionalForeignKeys()[additionalForeignKeyIndexPosition];
}
// default to just using a ForeignKeyRestrictionType.ID_EQ
if (metadata.getForeignKeyCollection()) {
if (ForeignKeyRestrictionType.COLLECTION_SIZE_EQ.toString().equals(foreignKey.getRestrictionType().toString())) {
filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.COLLECTION_SIZE_EQUAL.getType(), addSearchMappingRequest.getPropertyName()));
filterMapping.setFieldPath(new FieldPath());
} else {
filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.LONG.getType(), addSearchMappingRequest.getPropertyName()));
filterMapping.setFieldPath(new FieldPath().withTargetProperty(addSearchMappingRequest.getPropertyName() + "." + metadata.getForeignKeyProperty()));
}
} else if (CollectionUtils.isEmpty(addSearchMappingRequest.getRequestedCto().get(addSearchMappingRequest.getPropertyName()).getFilterValues()) || addSearchMappingRequest.getRequestedCto().get(addSearchMappingRequest.getPropertyName()).getFilterValues().get(0) == null || "null".equals(addSearchMappingRequest.getRequestedCto().get(addSearchMappingRequest.getPropertyName()).getFilterValues().get(0))) {
filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.IS_NULL_LONG.getType(), addSearchMappingRequest.getPropertyName()));
} else if (metadata.getSecondaryType() == SupportedFieldType.STRING) {
filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.STRING_EQUAL.getType(), addSearchMappingRequest.getPropertyName()));
filterMapping.setFieldPath(new FieldPath().withTargetProperty(addSearchMappingRequest.getPropertyName() + "." + metadata.getForeignKeyProperty()));
} else {
filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.LONG_EQUAL.getType(), addSearchMappingRequest.getPropertyName()));
filterMapping.setFieldPath(new FieldPath().withTargetProperty(addSearchMappingRequest.getPropertyName() + "." + metadata.getForeignKeyProperty()));
}
break;
case ID:
switch(metadata.getSecondaryType()) {
case INTEGER:
filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.LONG_EQUAL.getType(), addSearchMappingRequest.getPropertyName()));
break;
case STRING:
filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.STRING_EQUAL.getType(), addSearchMappingRequest.getPropertyName()));
break;
}
break;
}
}
}
return MetadataProviderResponse.HANDLED;
}
use of org.broadleafcommerce.openadmin.dto.BasicFieldMetadata in project BroadleafCommerce by BroadleafCommerce.
the class EntityValidatorServiceImpl method validate.
@Override
public void validate(Entity submittedEntity, @Nullable Serializable instance, Map<String, FieldMetadata> propertiesMetadata, RecordHelper recordHelper, boolean validateUnsubmittedProperties) {
Object idValue = null;
if (instance != null) {
String idField = (String) ((BasicPersistenceModule) recordHelper.getCompatibleModule(OperationType.BASIC)).getPersistenceManager().getDynamicEntityDao().getIdMetadata(instance.getClass()).get("name");
try {
idValue = recordHelper.getFieldManager().getFieldValue(instance, idField);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (FieldNotAvailableException e) {
throw new RuntimeException(e);
}
}
Entity entity;
boolean isUpdateRequest;
if (idValue == null) {
// This is for an add, or if the instance variable is null (e.g. PageTemplateCustomPersistenceHandler)
entity = submittedEntity;
isUpdateRequest = false;
} else {
if (validateUnsubmittedProperties) {
// This is for an update, as the submittedEntity instance will likely only contain the dirty properties
entity = recordHelper.getRecord(propertiesMetadata, instance, null, null);
// would be the confirmation field for a password validation
for (Map.Entry<String, FieldMetadata> entry : propertiesMetadata.entrySet()) {
if (entity.findProperty(entry.getKey()) == null) {
Property myProperty = submittedEntity.findProperty(entry.getKey());
if (myProperty != null) {
entity.addProperty(myProperty);
}
} else if (submittedEntity.findProperty(entry.getKey()) != null) {
entity.findProperty(entry.getKey()).setValue(submittedEntity.findProperty(entry.getKey()).getValue());
entity.findProperty(entry.getKey()).setIsDirty(submittedEntity.findProperty(entry.getKey()).getIsDirty());
}
}
} else {
entity = submittedEntity;
}
isUpdateRequest = true;
}
List<String> types = getTypeHierarchy(entity);
// validate each individual property according to their validation configuration
for (Entry<String, FieldMetadata> metadataEntry : propertiesMetadata.entrySet()) {
FieldMetadata metadata = metadataEntry.getValue();
// Don't test this field if it was not inherited from our polymorphic type (or supertype)
if (instance != null && (types.contains(metadata.getInheritedFromType()) || instance.getClass().getName().equals(metadata.getInheritedFromType()))) {
Property property = entity.getPMap().get(metadataEntry.getKey());
// and we don't need to validate them.
if (!validateUnsubmittedProperties && property == null) {
continue;
}
// for radio buttons, it's possible that the entity property was never populated in the first place from the POST
// and so it will be null
String propertyName = metadataEntry.getKey();
String propertyValue = (property == null) ? null : property.getValue();
if (metadata instanceof BasicFieldMetadata) {
// First execute the global field validators
if (CollectionUtils.isNotEmpty(globalEntityValidators)) {
for (GlobalPropertyValidator validator : globalEntityValidators) {
PropertyValidationResult result = validator.validate(entity, instance, propertiesMetadata, (BasicFieldMetadata) metadata, propertyName, propertyValue);
if (!result.isValid()) {
submittedEntity.addValidationError(propertyName, result.getErrorMessage());
}
}
}
// Now execute the validators configured for this particular field
Map<String, List<Map<String, String>>> validations = ((BasicFieldMetadata) metadata).getValidationConfigurations();
for (Map.Entry<String, List<Map<String, String>>> validation : validations.entrySet()) {
String validationImplementation = validation.getKey();
for (Map<String, String> configuration : validation.getValue()) {
PropertyValidator validator = null;
// attempt bean resolution to find the validator
if (applicationContext.containsBean(validationImplementation)) {
validator = applicationContext.getBean(validationImplementation, PropertyValidator.class);
}
// not a bean, attempt to instantiate the class
if (validator == null) {
try {
validator = (PropertyValidator) Class.forName(validationImplementation).newInstance();
} catch (Exception e) {
// do nothing
}
}
if (validator == null) {
throw new PersistenceException("Could not find validator: " + validationImplementation + " for property: " + propertyName);
}
PropertyValidationResult result = validator.validate(entity, instance, propertiesMetadata, configuration, (BasicFieldMetadata) metadata, propertyName, propertyValue);
if (!result.isValid()) {
for (String message : result.getErrorMessages()) {
submittedEntity.addValidationError(propertyName, message);
}
}
}
}
}
}
}
}
Aggregations