use of org.broadleafcommerce.openadmin.dto.FieldMetadata in project BroadleafCommerce by BroadleafCommerce.
the class BasicPersistenceModule method extractPropertiesFromPersistentEntity.
protected void extractPropertiesFromPersistentEntity(Map<String, FieldMetadata> mergedProperties, Serializable entity, List<Property> props, String[] customCriteria) {
FieldManager fieldManager = getFieldManager();
try {
if (entity instanceof AdminMainEntity) {
// its display name.
try {
Property propertyItem = new Property();
propertyItem.setName(AdminMainEntity.MAIN_ENTITY_NAME_PROPERTY);
propertyItem.setValue(((AdminMainEntity) entity).getMainEntityName());
props.add(propertyItem);
} catch (Exception e) {
// do nothing here except for not add the property. Exceptions could occur when there is a validation
// issue and some properties/relationships that are used for gleaning the main entity name end up
// not being set
}
}
for (Entry<String, FieldMetadata> entry : mergedProperties.entrySet()) {
String property = entry.getKey();
BasicFieldMetadata metadata = (BasicFieldMetadata) entry.getValue();
if (Class.forName(metadata.getInheritedFromType()).isAssignableFrom(entity.getClass()) || entity.getClass().isAssignableFrom(Class.forName(metadata.getInheritedFromType()))) {
boolean proceed = true;
if (property.contains(".")) {
StringTokenizer tokens = new StringTokenizer(property, ".");
Object testObject = entity;
while (tokens.hasMoreTokens()) {
String token = tokens.nextToken();
if (tokens.hasMoreTokens()) {
try {
testObject = fieldManager.getFieldValue(testObject, token);
} catch (FieldNotAvailableException e) {
proceed = false;
break;
}
if (testObject == null) {
Property propertyItem = new Property();
propertyItem.setName(property);
if (props.contains(propertyItem)) {
proceed = false;
break;
}
propertyItem.setValue(null);
props.add(propertyItem);
proceed = false;
break;
}
}
}
}
if (!proceed) {
continue;
}
boolean isFieldAccessible = true;
Object value = null;
try {
value = fieldManager.getFieldValue(entity, property);
} catch (FieldNotAvailableException e) {
isFieldAccessible = false;
}
checkField: {
if (isFieldAccessible) {
Property propertyItem = new Property();
propertyItem.setName(property);
if (props.contains(propertyItem)) {
continue;
}
props.add(propertyItem);
String displayVal = propertyItem.getDisplayValue();
boolean handled = false;
for (FieldPersistenceProvider fieldPersistenceProvider : fieldPersistenceProviders) {
MetadataProviderResponse response = fieldPersistenceProvider.extractValue(new ExtractValueRequest(props, fieldManager, metadata, value, displayVal, persistenceManager, this, entity, customCriteria), propertyItem);
if (MetadataProviderResponse.NOT_HANDLED != response) {
handled = true;
}
if (MetadataProviderResponse.HANDLED_BREAK == response) {
break;
}
}
if (!handled) {
defaultFieldPersistenceProvider.extractValue(new ExtractValueRequest(props, fieldManager, metadata, value, displayVal, persistenceManager, this, entity, customCriteria), propertyItem);
}
break checkField;
}
// try a direct property acquisition via reflection
try {
String strVal = null;
Method method;
try {
// try a 'get' prefixed mutator first
String temp = "get" + property.substring(0, 1).toUpperCase() + property.substring(1, property.length());
method = entity.getClass().getMethod(temp, new Class[] {});
} catch (NoSuchMethodException e) {
method = entity.getClass().getMethod(property, new Class[] {});
}
value = method.invoke(entity, new String[] {});
Property propertyItem = new Property();
propertyItem.setName(property);
if (props.contains(propertyItem)) {
continue;
}
props.add(propertyItem);
if (value == null) {
strVal = null;
} else {
if (Date.class.isAssignableFrom(value.getClass())) {
strVal = getSimpleDateFormatter().format((Date) value);
} else if (Timestamp.class.isAssignableFrom(value.getClass())) {
strVal = getSimpleDateFormatter().format(new Date(((Timestamp) value).getTime()));
} else if (Calendar.class.isAssignableFrom(value.getClass())) {
strVal = getSimpleDateFormatter().format(((Calendar) value).getTime());
} else if (Double.class.isAssignableFrom(value.getClass())) {
strVal = getDecimalFormatter().format(value);
} else if (BigDecimal.class.isAssignableFrom(value.getClass())) {
strVal = getDecimalFormatter().format(value);
} else {
strVal = value.toString();
}
}
propertyItem.setValue(strVal);
} catch (NoSuchMethodException e) {
LOG.debug("Unable to find a specified property in the entity: " + StringUtil.sanitize(property));
// do nothing - this property is simply not in the bean
}
}
}
}
} catch (ClassNotFoundException e) {
throw new PersistenceException(e);
} catch (IllegalAccessException e) {
throw new PersistenceException(e);
} catch (InvocationTargetException e) {
throw new PersistenceException(e);
}
}
use of org.broadleafcommerce.openadmin.dto.FieldMetadata in project BroadleafCommerce by BroadleafCommerce.
the class BasicPersistenceModule method getFilterMappings.
@Override
public List<FilterMapping> getFilterMappings(PersistencePerspective persistencePerspective, CriteriaTransferObject cto, String ceilingEntityFullyQualifiedClassname, Map<String, FieldMetadata> mergedUnfilteredProperties, RestrictionFactory customRestrictionFactory) {
Map<String, FieldMetadata> mergedProperties = filterOutCollectionMetadata(mergedUnfilteredProperties);
List<FilterMapping> filterMappings = new ArrayList<FilterMapping>();
for (String propertyId : cto.getCriteriaMap().keySet()) {
if (mergedProperties.containsKey(propertyId)) {
boolean handled = false;
for (FieldPersistenceProvider fieldPersistenceProvider : fieldPersistenceProviders) {
MetadataProviderResponse response = fieldPersistenceProvider.addSearchMapping(new AddSearchMappingRequest(persistencePerspective, cto, ceilingEntityFullyQualifiedClassname, mergedProperties, propertyId, getFieldManager(), this, this, customRestrictionFactory == null ? restrictionFactory : customRestrictionFactory), filterMappings);
if (MetadataProviderResponse.NOT_HANDLED != response) {
handled = true;
}
if (MetadataProviderResponse.HANDLED_BREAK == response) {
break;
}
}
if (!handled) {
defaultFieldPersistenceProvider.addSearchMapping(new AddSearchMappingRequest(persistencePerspective, cto, ceilingEntityFullyQualifiedClassname, mergedProperties, propertyId, getFieldManager(), this, this, customRestrictionFactory == null ? restrictionFactory : customRestrictionFactory), filterMappings);
}
}
}
return filterMappings;
}
use of org.broadleafcommerce.openadmin.dto.FieldMetadata 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.FieldMetadata 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.FieldMetadata in project BroadleafCommerce by BroadleafCommerce.
the class MapStructurePersistenceModule method fetch.
@Override
public DynamicResultSet fetch(PersistencePackage persistencePackage, CriteriaTransferObject cto) throws ServiceException {
Entity[] payload;
int totalRecords;
String ceilingEntityFullyQualifiedClassname = persistencePackage.getCeilingEntityFullyQualifiedClassname();
if (StringUtils.isEmpty(persistencePackage.getFetchTypeFullyQualifiedClassname())) {
persistencePackage.setFetchTypeFullyQualifiedClassname(ceilingEntityFullyQualifiedClassname);
}
try {
PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
Class<?>[] entities = persistenceManager.getPolymorphicEntities(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(), "");
MapStructure mapStructure = (MapStructure) persistencePerspective.getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.MAPSTRUCTURE);
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(ceilingEntityFullyQualifiedClassname), 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, false, new String[] {}, new String[] {}, null, "");
}
Map<String, FieldMetadata> valueMergedProperties = filterOutCollectionMetadata(valueUnfilteredMergedProperties);
List<FilterMapping> filterMappings = getFilterMappings(persistencePerspective, cto, persistencePackage.getFetchTypeFullyQualifiedClassname(), mergedProperties);
if (CollectionUtils.isNotEmpty(cto.getAdditionalFilterMappings())) {
filterMappings.addAll(cto.getAdditionalFilterMappings());
}
totalRecords = getTotalRecords(persistencePackage.getFetchTypeFullyQualifiedClassname(), filterMappings);
if (totalRecords > 1) {
throw new ServiceException("Queries to retrieve an entity containing a MapStructure must return only 1 entity. Your query returned (" + totalRecords + ") values.");
}
List<Serializable> records = getPersistentRecords(persistencePackage.getFetchTypeFullyQualifiedClassname(), filterMappings, cto.getFirstResult(), cto.getMaxResults());
Map<String, FieldMetadata> ceilingMergedProperties = getSimpleMergedProperties(ceilingEntityFullyQualifiedClassname, persistencePerspective);
payload = getMapRecords(records.get(0), mapStructure, ceilingMergedProperties, valueMergedProperties, null, persistencePackage.getCustomCriteria());
} catch (Exception e) {
throw new ServiceException("Unable to fetch results for " + ceilingEntityFullyQualifiedClassname, e);
}
DynamicResultSet results = new DynamicResultSet(null, payload, payload.length);
return results;
}
Aggregations