use of org.broadleafcommerce.openadmin.dto.FieldMetadata 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;
}
use of org.broadleafcommerce.openadmin.dto.FieldMetadata in project BroadleafCommerce by BroadleafCommerce.
the class BasicPersistenceModule method filterOutCollectionMetadata.
protected Map<String, FieldMetadata> filterOutCollectionMetadata(Map<String, FieldMetadata> metadata) {
if (metadata == null) {
return null;
}
Map<String, FieldMetadata> newMap = new HashMap<String, FieldMetadata>();
for (Map.Entry<String, FieldMetadata> entry : metadata.entrySet()) {
String fieldName = entry.getKey();
FieldMetadata md = entry.getValue();
// can appropriate handle filtration and population
if (entry.getValue() instanceof BasicFieldMetadata) {
newMap.put(fieldName, md);
} else if (md.getAdditionalMetadata().containsKey(AdvancedCollectionFieldMetadataProvider.FOREIGN_KEY_ADDITIONAL_METADATA_KEY)) {
newMap.put(fieldName, (BasicFieldMetadata) md.getAdditionalMetadata().get(AdvancedCollectionFieldMetadataProvider.FOREIGN_KEY_ADDITIONAL_METADATA_KEY));
}
}
return newMap;
}
use of org.broadleafcommerce.openadmin.dto.FieldMetadata in project BroadleafCommerce by BroadleafCommerce.
the class BasicPersistenceModule method getMergedProperties.
public Map<String, FieldMetadata> getMergedProperties(PersistencePackage persistencePackage, CriteriaTransferObject cto) throws ServiceException {
PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
String ceilingEntityFullyQualifiedClassname = persistencePackage.getCeilingEntityFullyQualifiedClassname();
if (StringUtils.isEmpty(persistencePackage.getFetchTypeFullyQualifiedClassname())) {
persistencePackage.setFetchTypeFullyQualifiedClassname(ceilingEntityFullyQualifiedClassname);
}
try {
Class<?>[] entities = persistenceManager.getDynamicEntityDao().getAllPolymorphicEntitiesFromCeiling(Class.forName(ceilingEntityFullyQualifiedClassname));
Map<String, FieldMetadata> mergedProperties = persistenceManager.getDynamicEntityDao().getMergedProperties(ceilingEntityFullyQualifiedClassname, entities, (ForeignKey) persistencePerspective.getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.FOREIGNKEY), persistencePerspective.getAdditionalNonPersistentProperties(), persistencePerspective.getAdditionalForeignKeys(), MergedPropertyType.PRIMARY, persistencePerspective.getPopulateToOneFields(), persistencePerspective.getIncludeFields(), persistencePerspective.getExcludeFields(), persistencePerspective.getConfigurationKey(), "");
return mergedProperties;
} catch (Exception e) {
throw new ServiceException("Unable to fetch results for " + ceilingEntityFullyQualifiedClassname, e);
}
}
use of org.broadleafcommerce.openadmin.dto.FieldMetadata in project BroadleafCommerce by BroadleafCommerce.
the class BasicPersistenceModule method update.
protected EntityResult update(PersistencePackage persistencePackage, Object primaryKey, boolean includeRealEntity) throws ServiceException {
EntityResult entityResult = new EntityResult();
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> mergedProperties = persistenceManager.getDynamicEntityDao().getMergedProperties(persistencePackage.getCeilingEntityFullyQualifiedClassname(), entities, foreignKey, persistencePerspective.getAdditionalNonPersistentProperties(), persistencePerspective.getAdditionalForeignKeys(), MergedPropertyType.PRIMARY, persistencePerspective.getPopulateToOneFields(), persistencePerspective.getIncludeFields(), persistencePerspective.getExcludeFields(), persistencePerspective.getConfigurationKey(), "");
if (primaryKey == null) {
primaryKey = getPrimaryKey(entity, mergedProperties);
}
Serializable instance = persistenceManager.getDynamicEntityDao().retrieve(Class.forName(entity.getType()[0]), primaryKey);
Assert.isTrue(instance != null, "Entity not found");
if (!entity.isValidationFailure()) {
// Re-Balance the list if it is a Foreign Key toMany collection with a sort field property
if (foreignKey != null && foreignKey.getSortField() != null && entity.findProperty(foreignKey.getSortField()) != null && entity.findProperty(foreignKey.getSortField()).getValue() != null) {
ExtensionResultHolder<Serializable> result = new ExtensionResultHolder<Serializable>();
extensionManager.getProxy().rebalanceForUpdate(this, persistencePackage, instance, mergedProperties, primaryKey, result);
instance = result.getResult();
} else {
instance = createPopulatedInstance(instance, entity, mergedProperties, false, persistencePackage.isValidateUnsubmittedProperties());
}
instance = persistenceManager.getDynamicEntityDao().merge(instance);
if (includeRealEntity) {
entityResult.setEntityBackingObject(instance);
}
List<Serializable> entityList = new ArrayList<Serializable>(1);
entityList.add(instance);
entity = getRecords(mergedProperties, entityList, null, null, null)[0];
entityResult.setEntity(entity);
return entityResult;
} else {
entityResult.setEntity(entity);
return entityResult;
}
} catch (Exception e) {
throw new ServiceException("Problem updating entity : " + e.getMessage(), e);
}
}
use of org.broadleafcommerce.openadmin.dto.FieldMetadata in project BroadleafCommerce by BroadleafCommerce.
the class MapStructurePersistenceModule method add.
@Override
public Entity add(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 add 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 (StringUtils.isEmpty(mapKey)) {
entity.addValidationError(mapStructure.getKeyPropertyName(), RequiredPropertyValidator.ERROR_MESSAGE);
LOG.debug("No key property passed in for map, failing validation");
}
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());
if (map.containsKey(mapKey)) {
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);
}
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 (persistentClass != null) {
Serializable valueInstance = (Serializable) Class.forName(mapStructure.getValueClassName()).newInstance();
valueInstance = createPopulatedInstance(valueInstance, entity, valueMergedProperties, false);
if (valueInstance instanceof ValueAssignable) {
// This is likely a OneToMany map (see productAttributes) whose map key is actually the name field from
// the mapped entity.
((ValueAssignable) valueInstance).setName(entity.findProperty(mapStructure.getKeyPropertyName()).getValue());
}
if (mapStructure.getManyToField() != null) {
// Need to fulfill a bi-directional association back to the parent entity
fieldManager.setFieldValue(valueInstance, mapStructure.getManyToField(), instance);
}
valueInstance = persistenceManager.getDynamicEntityDao().persist(valueInstance);
/*
* 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(mapKey, valueInstance);
} else {
String propertyName = ((SimpleValueMapStructure) mapStructure).getValuePropertyName();
String value = entity.findProperty(propertyName).getValue();
Object convertedPrimitive = convertPrimitiveBasedOnType(propertyName, value, valueMergedProperties);
map.put(mapKey, convertedPrimitive);
}
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;
}
}
return responses[0];
} catch (Exception e) {
throw new ServiceException("Problem updating entity : " + e.getMessage(), e);
}
}
Aggregations