use of org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException in project BroadleafCommerce by BroadleafCommerce.
the class AfterStartDateValidator method validate.
@Override
public PropertyValidationResult validate(Entity entity, Serializable instance, Map<String, FieldMetadata> entityFieldMetadata, Map<String, String> validationConfiguration, BasicFieldMetadata propertyMetadata, String propertyName, String value) {
String otherField = validationConfiguration.get("otherField");
FieldManager fm = getFieldManager(propertyMetadata);
boolean valid = true;
String message = "";
Date startDate = null;
Date endDate = null;
if (StringUtils.isBlank(value) || StringUtils.isBlank(otherField)) {
return new PropertyValidationResult(true);
}
try {
startDate = (Date) fm.getFieldValue(instance, otherField);
endDate = (Date) fm.getFieldValue(instance, propertyName);
} catch (IllegalAccessException | FieldNotAvailableException e) {
valid = false;
message = e.getMessage();
}
if (valid && endDate != null && startDate != null && endDate.before(startDate)) {
valid = false;
message = END_DATE_BEFORE_START;
}
return new PropertyValidationResult(valid, message);
}
use of org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException 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);
}
}
}
}
}
}
}
}
use of org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException in project BroadleafCommerce by BroadleafCommerce.
the class MediaFieldPersistenceProvider method extractValue.
@Override
public MetadataProviderResponse extractValue(ExtractValueRequest extractValueRequest, Property property) throws PersistenceException {
if (!canHandleExtraction(extractValueRequest, property)) {
return MetadataProviderResponse.NOT_HANDLED;
}
if (extractValueRequest.getRequestedValue() != null) {
Object requestedValue = extractValueRequest.getRequestedValue();
if (!StringUtils.isEmpty(extractValueRequest.getMetadata().getToOneTargetProperty())) {
try {
requestedValue = extractValueRequest.getFieldManager().getFieldValue(requestedValue, extractValueRequest.getMetadata().getToOneTargetProperty());
} catch (IllegalAccessException e) {
throw ExceptionHelper.refineException(e);
} catch (FieldNotAvailableException e) {
throw ExceptionHelper.refineException(e);
}
}
if (requestedValue instanceof Media) {
Media media = (Media) requestedValue;
String jsonString = convertMediaToJson(media);
if (extensionManager != null) {
ExtensionResultHolder<Long> resultHolder = new ExtensionResultHolder<Long>();
ExtensionResultStatusType result = extensionManager.getProxy().transformId(media, resultHolder);
if (ExtensionResultStatusType.NOT_HANDLED != result && resultHolder.getResult() != null) {
Class<?> type;
if (media.isUnwrappableAs(Media.class)) {
type = media.unwrap(Media.class).getClass();
} else {
type = media.getClass();
}
Media converted = mediaBuilderService.convertJsonToMedia(jsonString, type);
converted.setId(resultHolder.getResult());
jsonString = convertMediaToJson(converted);
}
}
property.setValue(jsonString);
property.setUnHtmlEncodedValue(jsonString);
property.setDisplayValue(extractValueRequest.getDisplayVal());
return MetadataProviderResponse.HANDLED_BREAK;
} else {
throw new UnsupportedOperationException("MEDIA type is currently only supported on fields of type Media");
}
}
return MetadataProviderResponse.HANDLED;
}
use of org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException in project BroadleafCommerce by BroadleafCommerce.
the class MediaFieldPersistenceProvider method extractParent.
protected Object extractParent(PopulateValueRequest populateValueRequest, Serializable instance) throws IllegalAccessException, FieldNotAvailableException {
Object parent = instance;
String parentName = populateValueRequest.getProperty().getName();
if (parentName.contains(".")) {
parent = populateValueRequest.getFieldManager().getFieldValue(instance, parentName.substring(0, parentName.lastIndexOf(".")));
}
if (!populateValueRequest.getPersistenceManager().getDynamicEntityDao().getStandardEntityManager().contains(parent)) {
try {
populateValueRequest.getPersistenceManager().getDynamicEntityDao().persist(parent);
} catch (Exception e) {
throw new ParentEntityPersistenceException("Unable to Persist the parent entity during rule builder field population", e);
}
}
return parent;
}
use of org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException in project BroadleafCommerce by BroadleafCommerce.
the class BasicFieldPersistenceProvider method populateValue.
@Override
public MetadataProviderResponse populateValue(PopulateValueRequest populateValueRequest, Serializable instance) {
if (!canHandlePersistence(populateValueRequest, instance)) {
return MetadataProviderResponse.NOT_HANDLED;
}
boolean dirty = false;
try {
Property prop = populateValueRequest.getProperty();
Object origInstanceValue = populateValueRequest.getFieldManager().getFieldValue(instance, prop.getName());
switch(populateValueRequest.getMetadata().getFieldType()) {
case BOOLEAN:
boolean v = Boolean.valueOf(populateValueRequest.getRequestedValue());
prop.setOriginalValue(String.valueOf(origInstanceValue));
prop.setOriginalDisplayValue(prop.getOriginalValue());
try {
dirty = checkDirtyState(populateValueRequest, instance, v);
populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), v);
} catch (IllegalArgumentException e) {
boolean isChar = populateValueRequest.getRequestedValue().toCharArray().length > 1 ? false : true;
char c;
if (isChar) {
c = populateValueRequest.getRequestedValue().toCharArray()[0];
} else {
c = Boolean.valueOf(populateValueRequest.getRequestedValue()) ? 'Y' : 'N';
}
dirty = checkDirtyState(populateValueRequest, instance, c);
populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), c);
}
break;
case DATE:
Date date = (Date) populateValueRequest.getFieldManager().getFieldValue(instance, populateValueRequest.getProperty().getName());
String oldValue = null;
if (date != null) {
oldValue = populateValueRequest.getDataFormatProvider().getSimpleDateFormatter().format(date);
}
prop.setOriginalValue(oldValue);
prop.setOriginalDisplayValue(prop.getOriginalValue());
dirty = !StringUtils.equals(oldValue, populateValueRequest.getRequestedValue());
populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), populateValueRequest.getDataFormatProvider().getSimpleDateFormatter().parse(populateValueRequest.getRequestedValue()));
break;
case DECIMAL:
if (origInstanceValue != null) {
prop.setOriginalValue(String.valueOf(origInstanceValue));
prop.setOriginalDisplayValue(prop.getOriginalValue());
}
if (BigDecimal.class.isAssignableFrom(populateValueRequest.getReturnType())) {
DecimalFormat format = populateValueRequest.getDataFormatProvider().getDecimalFormatter();
format.setParseBigDecimal(true);
BigDecimal val = (BigDecimal) format.parse(populateValueRequest.getRequestedValue());
dirty = checkDirtyState(populateValueRequest, instance, val);
populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), val);
format.setParseBigDecimal(false);
} else {
Double val = populateValueRequest.getDataFormatProvider().getDecimalFormatter().parse(populateValueRequest.getRequestedValue()).doubleValue();
dirty = checkDirtyState(populateValueRequest, instance, val);
populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), val);
}
break;
case MONEY:
if (origInstanceValue != null) {
prop.setOriginalValue(String.valueOf(origInstanceValue));
prop.setOriginalDisplayValue(prop.getOriginalValue());
}
if (BigDecimal.class.isAssignableFrom(populateValueRequest.getReturnType())) {
DecimalFormat format = populateValueRequest.getDataFormatProvider().getDecimalFormatter();
format.setParseBigDecimal(true);
BigDecimal val = (BigDecimal) format.parse(populateValueRequest.getRequestedValue());
dirty = checkDirtyState(populateValueRequest, instance, val);
populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), val);
format.setParseBigDecimal(true);
} else if (Double.class.isAssignableFrom(populateValueRequest.getReturnType())) {
Double val = populateValueRequest.getDataFormatProvider().getDecimalFormatter().parse(populateValueRequest.getRequestedValue()).doubleValue();
dirty = checkDirtyState(populateValueRequest, instance, val);
LOG.warn("The requested Money field is of type double and could result in a loss of precision." + " Broadleaf recommends that the type of all Money fields be 'BigDecimal' in order to avoid" + " this loss of precision that could occur.");
populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), val);
} else {
DecimalFormat format = populateValueRequest.getDataFormatProvider().getDecimalFormatter();
format.setParseBigDecimal(true);
BigDecimal val = (BigDecimal) format.parse(populateValueRequest.getRequestedValue());
dirty = checkDirtyState(populateValueRequest, instance, val);
populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), new Money(val));
format.setParseBigDecimal(false);
}
break;
case INTEGER:
if (origInstanceValue != null) {
prop.setOriginalValue(String.valueOf(origInstanceValue));
prop.setOriginalDisplayValue(prop.getOriginalValue());
}
if (int.class.isAssignableFrom(populateValueRequest.getReturnType()) || Integer.class.isAssignableFrom(populateValueRequest.getReturnType())) {
dirty = checkDirtyState(populateValueRequest, instance, Integer.valueOf(populateValueRequest.getRequestedValue()));
populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), Integer.valueOf(populateValueRequest.getRequestedValue()));
} else if (byte.class.isAssignableFrom(populateValueRequest.getReturnType()) || Byte.class.isAssignableFrom(populateValueRequest.getReturnType())) {
dirty = checkDirtyState(populateValueRequest, instance, Byte.valueOf(populateValueRequest.getRequestedValue()));
populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), Byte.valueOf(populateValueRequest.getRequestedValue()));
} else if (short.class.isAssignableFrom(populateValueRequest.getReturnType()) || Short.class.isAssignableFrom(populateValueRequest.getReturnType())) {
dirty = checkDirtyState(populateValueRequest, instance, Short.valueOf(populateValueRequest.getRequestedValue()));
populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), Short.valueOf(populateValueRequest.getRequestedValue()));
} else if (long.class.isAssignableFrom(populateValueRequest.getReturnType()) || Long.class.isAssignableFrom(populateValueRequest.getReturnType())) {
dirty = checkDirtyState(populateValueRequest, instance, Long.valueOf(populateValueRequest.getRequestedValue()));
populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), Long.valueOf(populateValueRequest.getRequestedValue()));
}
break;
case CODE:
// **NOTE** We want to fall through in this case, do not break.
setNonDisplayableValues(populateValueRequest);
case STRING:
case HTML_BASIC:
case HTML:
case EMAIL:
if (origInstanceValue != null) {
prop.setOriginalValue(String.valueOf(origInstanceValue));
prop.setOriginalDisplayValue(prop.getOriginalValue());
}
dirty = checkDirtyState(populateValueRequest, instance, populateValueRequest.getRequestedValue());
populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), populateValueRequest.getRequestedValue());
break;
case FOREIGN_KEY:
{
if (origInstanceValue != null) {
prop.setOriginalValue(String.valueOf(origInstanceValue));
}
Serializable foreignInstance;
if (StringUtils.isEmpty(populateValueRequest.getRequestedValue())) {
foreignInstance = null;
} else {
if (SupportedFieldType.INTEGER.toString().equals(populateValueRequest.getMetadata().getSecondaryType().toString())) {
foreignInstance = populateValueRequest.getPersistenceManager().getDynamicEntityDao().retrieve(Class.forName(populateValueRequest.getMetadata().getForeignKeyClass()), Long.valueOf(populateValueRequest.getRequestedValue()));
} else {
foreignInstance = populateValueRequest.getPersistenceManager().getDynamicEntityDao().retrieve(Class.forName(populateValueRequest.getMetadata().getForeignKeyClass()), populateValueRequest.getRequestedValue());
}
}
if (Collection.class.isAssignableFrom(populateValueRequest.getReturnType())) {
Collection collection;
try {
collection = (Collection) populateValueRequest.getFieldManager().getFieldValue(instance, populateValueRequest.getProperty().getName());
} catch (FieldNotAvailableException e) {
throw new IllegalArgumentException(e);
}
if (!collection.contains(foreignInstance)) {
collection.add(foreignInstance);
dirty = true;
}
} else if (Map.class.isAssignableFrom(populateValueRequest.getReturnType())) {
throw new IllegalArgumentException("Map structures are not supported for foreign key fields.");
} else {
dirty = checkDirtyState(populateValueRequest, instance, foreignInstance);
populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), foreignInstance);
}
break;
}
case ADDITIONAL_FOREIGN_KEY:
{
Serializable foreignInstance;
if (StringUtils.isEmpty(populateValueRequest.getRequestedValue())) {
foreignInstance = null;
} else {
if (SupportedFieldType.INTEGER.toString().equals(populateValueRequest.getMetadata().getSecondaryType().toString())) {
foreignInstance = populateValueRequest.getPersistenceManager().getDynamicEntityDao().retrieve(Class.forName(populateValueRequest.getMetadata().getForeignKeyClass()), Long.valueOf(populateValueRequest.getRequestedValue()));
} else {
foreignInstance = populateValueRequest.getPersistenceManager().getDynamicEntityDao().retrieve(Class.forName(populateValueRequest.getMetadata().getForeignKeyClass()), populateValueRequest.getRequestedValue());
}
}
// Best guess at grabbing the original display value
String fkProp = populateValueRequest.getMetadata().getForeignKeyDisplayValueProperty();
Object origDispVal = null;
if (origInstanceValue != null) {
if (AdminMainEntity.MAIN_ENTITY_NAME_PROPERTY.equals(fkProp)) {
if (origInstanceValue instanceof AdminMainEntity) {
origDispVal = ((AdminMainEntity) origInstanceValue).getMainEntityName();
}
} else {
origDispVal = populateValueRequest.getFieldManager().getFieldValue(origInstanceValue, fkProp);
}
}
if (origDispVal != null) {
prop.setOriginalDisplayValue(String.valueOf(origDispVal));
Session session = populateValueRequest.getPersistenceManager().getDynamicEntityDao().getStandardEntityManager().unwrap(Session.class);
String originalValueFromSession = String.valueOf(session.getIdentifier(origInstanceValue));
prop.setOriginalValue(originalValueFromSession);
}
if (Collection.class.isAssignableFrom(populateValueRequest.getReturnType())) {
Collection collection;
try {
collection = (Collection) populateValueRequest.getFieldManager().getFieldValue(instance, populateValueRequest.getProperty().getName());
} catch (FieldNotAvailableException e) {
throw new IllegalArgumentException(e);
}
if (!collection.contains(foreignInstance)) {
collection.add(foreignInstance);
dirty = true;
}
} else if (Map.class.isAssignableFrom(populateValueRequest.getReturnType())) {
throw new IllegalArgumentException("Map structures are not supported for foreign key fields.");
} else {
dirty = checkDirtyState(populateValueRequest, instance, foreignInstance);
populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), foreignInstance);
}
break;
}
case ID:
if (populateValueRequest.getSetId()) {
switch(populateValueRequest.getMetadata().getSecondaryType()) {
case INTEGER:
dirty = checkDirtyState(populateValueRequest, instance, Long.valueOf(populateValueRequest.getRequestedValue()));
populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), Long.valueOf(populateValueRequest.getRequestedValue()));
break;
case STRING:
dirty = checkDirtyState(populateValueRequest, instance, populateValueRequest.getRequestedValue());
populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), populateValueRequest.getRequestedValue());
break;
}
}
break;
}
} catch (Exception e) {
throw new PersistenceException(e);
}
populateValueRequest.getProperty().setIsDirty(dirty);
return MetadataProviderResponse.HANDLED;
}
Aggregations