use of org.broadleafcommerce.openadmin.dto.BasicFieldMetadata in project BroadleafCommerce by BroadleafCommerce.
the class BasicPersistenceModule method extractPropertiesFromMetadata.
protected void extractPropertiesFromMetadata(Class<?>[] inheritanceLine, Map<String, FieldMetadata> mergedProperties, List<Property> properties, Boolean isHiddenOverride, MergedPropertyType type) {
for (Map.Entry<String, FieldMetadata> entry : mergedProperties.entrySet()) {
String property = entry.getKey();
Property prop = new Property();
FieldMetadata metadata = mergedProperties.get(property);
prop.setName(property);
Comparator<Property> comparator = new Comparator<Property>() {
@Override
public int compare(Property o1, Property o2) {
return o1.getName().compareTo(o2.getName());
}
};
Collections.sort(properties, comparator);
int pos = Collections.binarySearch(properties, prop, comparator);
if (pos >= 0 && MergedPropertyType.MAPSTRUCTUREKEY != type && MergedPropertyType.MAPSTRUCTUREVALUE != type) {
logWarn: {
if ((metadata instanceof BasicFieldMetadata) && SupportedFieldType.ID.equals(((BasicFieldMetadata) metadata).getFieldType())) {
// don't warn for id field collisions, but still ignore the colliding fields
break logWarn;
}
// LOG.warn("Detected a field name collision (" + metadata.getTargetClass() + "." + property + ") during inspection for the inheritance line starting with (" + inheritanceLine[0].getName() + "). Ignoring the additional field. This can occur most commonly when using the @AdminPresentationAdornedTargetCollection and the collection type and target class have field names in common. This situation should be avoided, as the system will strip the repeated fields, which can cause unpredictable behavior.");
}
continue;
}
properties.add(prop);
prop.setMetadata(metadata);
if (isHiddenOverride && prop.getMetadata() instanceof BasicFieldMetadata) {
// this only makes sense for non collection types
((BasicFieldMetadata) prop.getMetadata()).setVisibility(VisibilityEnum.HIDDEN_ALL);
}
}
}
use of org.broadleafcommerce.openadmin.dto.BasicFieldMetadata in project BroadleafCommerce by BroadleafCommerce.
the class BasicPersistenceModule method getRecords.
@Override
public Entity[] getRecords(Map<String, FieldMetadata> primaryUnfilteredMergedProperties, List<? extends Serializable> records, Map<String, FieldMetadata> alternateUnfilteredMergedProperties, String pathToTargetObject, String[] customCriteria) {
Map<String, FieldMetadata> primaryMergedProperties = filterOutCollectionMetadata(primaryUnfilteredMergedProperties);
Map<String, FieldMetadata> alternateMergedProperties = filterOutCollectionMetadata(alternateUnfilteredMergedProperties);
Entity[] entities = new Entity[records.size()];
int j = 0;
for (Serializable recordEntity : records) {
Serializable entity;
if (pathToTargetObject != null) {
try {
entity = (Serializable) getFieldManager().getFieldValue(recordEntity, pathToTargetObject);
} catch (Exception e) {
throw new PersistenceException(e);
}
} else {
entity = recordEntity;
}
Entity entityItem = new Entity();
entityItem.setType(new String[] { entity.getClass().getName() });
entities[j] = entityItem;
List<Property> props = new ArrayList<Property>(primaryMergedProperties.size());
extractPropertiesFromPersistentEntity(primaryMergedProperties, entity, props, customCriteria);
if (alternateMergedProperties != null) {
extractPropertiesFromPersistentEntity(alternateMergedProperties, recordEntity, props, customCriteria);
}
// Try to add the "main name" property. Log a debug message if we can't
try {
Property p = new Property();
p.setName(MAIN_ENTITY_NAME_PROPERTY);
String mainEntityName = (String) MethodUtils.invokeMethod(entity, "getMainEntityName");
p.setValue(mainEntityName);
props.add(p);
} catch (Exception e) {
LOG.debug(String.format("Could not execute the getMainEntityName() method for [%s]", entity.getClass().getName()), e);
}
// Try to add the alternate id property if available
if (alternateMergedProperties != null) {
for (Entry<String, FieldMetadata> entry : alternateMergedProperties.entrySet()) {
if (entry.getValue() instanceof BasicFieldMetadata) {
if (((BasicFieldMetadata) entry.getValue()).getFieldType() == SupportedFieldType.ID) {
Map<String, FieldMetadata> alternateOnEntity = new HashMap<String, FieldMetadata>();
alternateOnEntity.put(entry.getKey(), entry.getValue());
List<Property> props2 = new ArrayList<Property>();
extractPropertiesFromPersistentEntity(alternateOnEntity, recordEntity, props2, customCriteria);
List<Property> filtered = new ArrayList<Property>();
for (Property prop : props2) {
if (!prop.getName().startsWith("__")) {
filtered.add(prop);
}
}
if (filtered.size() == 1 && !filtered.get(0).getName().contains(".")) {
Property alternateIdProp = filtered.get(0);
alternateIdProp.setName(ALTERNATE_ID_PROPERTY);
props.add(alternateIdProp);
}
}
}
}
}
Property[] properties = new Property[props.size()];
properties = props.toArray(properties);
entityItem.setProperties(properties);
j++;
}
return entities;
}
use of org.broadleafcommerce.openadmin.dto.BasicFieldMetadata 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.BasicFieldMetadata 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.BasicFieldMetadata in project BroadleafCommerce by BroadleafCommerce.
the class PersistenceManagerImpl method processMergedProperties.
public Property[] processMergedProperties(Class<?>[] entities, Map<MergedPropertyType, Map<String, FieldMetadata>> mergedProperties) {
List<Property> propertiesList = new ArrayList<>();
for (PersistenceModule module : modules) {
module.extractProperties(entities, mergedProperties, propertiesList);
}
Property[] properties = new Property[propertiesList.size()];
properties = propertiesList.toArray(properties);
Arrays.sort(properties, new Comparator<Property>() {
@Override
public int compare(Property o1, Property o2) {
Integer tabOrder1 = o1.getMetadata().getTabOrder() == null ? 99999 : o1.getMetadata().getTabOrder();
Integer tabOrder2 = o2.getMetadata().getTabOrder() == null ? 99999 : o2.getMetadata().getTabOrder();
Integer groupOrder1 = null;
Integer groupOrder2 = null;
if (o1.getMetadata() instanceof BasicFieldMetadata) {
BasicFieldMetadata b1 = (BasicFieldMetadata) o1.getMetadata();
groupOrder1 = b1.getGroupOrder();
}
groupOrder1 = groupOrder1 == null ? 99999 : groupOrder1;
if (o2.getMetadata() instanceof BasicFieldMetadata) {
BasicFieldMetadata b2 = (BasicFieldMetadata) o2.getMetadata();
groupOrder2 = b2.getGroupOrder();
}
groupOrder2 = groupOrder2 == null ? 99999 : groupOrder2;
Integer fieldOrder1 = o1.getMetadata().getOrder() == null ? 99999 : o1.getMetadata().getOrder();
Integer fieldOrder2 = o2.getMetadata().getOrder() == null ? 99999 : o2.getMetadata().getOrder();
String friendlyName1 = o1.getMetadata().getFriendlyName() == null ? "zzzz" : o1.getMetadata().getFriendlyName();
String friendlyName2 = o2.getMetadata().getFriendlyName() == null ? "zzzz" : o2.getMetadata().getFriendlyName();
String name1 = o1.getName() == null ? "zzzzz" : o1.getName();
String name2 = o2.getName() == null ? "zzzzz" : o2.getName();
return new CompareToBuilder().append(tabOrder1, tabOrder2).append(groupOrder1, groupOrder2).append(fieldOrder1, fieldOrder2).append(friendlyName1, friendlyName2).append(name1, name2).toComparison();
}
});
return properties;
}
Aggregations