use of org.broadleafcommerce.openadmin.dto.Entity 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.dto.Entity in project BroadleafCommerce by BroadleafCommerce.
the class ProductCustomPersistenceHandler method add.
@Override
public Entity add(PersistencePackage persistencePackage, DynamicEntityDao dynamicEntityDao, RecordHelper helper) throws ServiceException {
Entity entity = persistencePackage.getEntity();
try {
PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
Product adminInstance = (Product) Class.forName(entity.getType()[0]).newInstance();
Map<String, FieldMetadata> adminProperties = helper.getSimpleMergedProperties(Product.class.getName(), persistencePerspective);
if (adminInstance instanceof ProductBundle) {
removeBundleFieldRestrictions((ProductBundle) adminInstance, adminProperties, entity);
}
adminInstance = (Product) helper.createPopulatedInstance(adminInstance, entity, adminProperties, false);
adminInstance = dynamicEntityDao.merge(adminInstance);
// any Sku fields, and thus a Sku would not be created. Product still needs a default Sku so instantiate one
if (adminInstance.getDefaultSku() == null) {
Sku newSku = catalogService.createSku();
dynamicEntityDao.persist(newSku);
adminInstance.setDefaultSku(newSku);
adminInstance = dynamicEntityDao.merge(adminInstance);
}
// also set the default product for the Sku
adminInstance.getDefaultSku().setDefaultProduct(adminInstance);
dynamicEntityDao.merge(adminInstance.getDefaultSku());
// if this is a Pre-Add, skip the rest of the method
if (entity.isPreAdd()) {
return helper.getRecord(adminProperties, adminInstance, null, null);
}
boolean handled = false;
if (extensionManager != null) {
ExtensionResultStatusType result = extensionManager.getProxy().manageParentCategoryForAdd(persistencePackage, adminInstance);
handled = ExtensionResultStatusType.NOT_HANDLED != result;
}
if (!handled) {
setupXref(adminInstance);
}
return helper.getRecord(adminProperties, adminInstance, null, null);
} catch (Exception e) {
throw new ServiceException("Unable to add entity for " + entity.getType()[0], e);
}
}
use of org.broadleafcommerce.openadmin.dto.Entity in project BroadleafCommerce by BroadleafCommerce.
the class ProductOptionsCustomPersistenceHandler method update.
@Override
public Entity update(PersistencePackage persistencePackage, DynamicEntityDao dynamicEntityDao, RecordHelper helper) throws ServiceException {
Entity entity = persistencePackage.getEntity();
try {
PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
Map<String, FieldMetadata> adminProperties = helper.getSimpleMergedProperties(ProductOption.class.getName(), persistencePerspective);
Object primaryKey = helper.getPrimaryKey(entity, adminProperties);
ProductOption adminInstance = (ProductOption) dynamicEntityDao.retrieve(Class.forName(entity.getType()[0]), primaryKey);
adminInstance = (ProductOption) helper.createPopulatedInstance(adminInstance, entity, adminProperties, false);
// validate "Use in Sku generation"
if (needsAllowedValue(adminInstance)) {
String errorMessage = "Must add at least 1 Allowed Value when Product Option is used in Sku generation";
entity.addValidationError("useInSkuGeneration", errorMessage);
return entity;
}
adminInstance = (ProductOption) dynamicEntityDao.merge(adminInstance);
return helper.getRecord(adminProperties, adminInstance, null, null);
} catch (Exception e) {
throw new ServiceException("Unable to update entity for " + entity.getType()[0], e);
}
}
use of org.broadleafcommerce.openadmin.dto.Entity in project BroadleafCommerce by BroadleafCommerce.
the class SkuBundleItemCustomPersistenceHandler method fetch.
@Override
public DynamicResultSet fetch(PersistencePackage persistencePackage, CriteriaTransferObject cto, DynamicEntityDao dynamicEntityDao, RecordHelper helper) throws ServiceException {
String ceilingEntityFullyQualifiedClassname = persistencePackage.getCeilingEntityFullyQualifiedClassname();
try {
PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
ForeignKey foreignKey = (ForeignKey) persistencePerspective.getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.FOREIGNKEY);
// sort it
if (foreignKey != null && foreignKey.getSortField() != null) {
FilterAndSortCriteria sortCriteria = cto.get(foreignKey.getSortField());
sortCriteria.setSortAscending(foreignKey.getSortAscending());
}
// get the default properties from Inventory and its subclasses
Map<String, FieldMetadata> originalProps = helper.getSimpleMergedProperties(SkuBundleItem.class.getName(), persistencePerspective);
// Pull back the Inventory based on the criteria from the client
List<FilterMapping> filterMappings = helper.getFilterMappings(persistencePerspective, cto, ceilingEntityFullyQualifiedClassname, originalProps);
// attach the product option criteria
skuPersistenceHandler.applyProductOptionValueCriteria(filterMappings, cto, persistencePackage, "sku");
List<Serializable> records = helper.getPersistentRecords(persistencePackage.getCeilingEntityFullyQualifiedClassname(), filterMappings, cto.getFirstResult(), cto.getMaxResults());
// Convert Skus into the client-side Entity representation
Entity[] payload = helper.getRecords(originalProps, records);
int totalRecords = helper.getTotalRecords(persistencePackage.getCeilingEntityFullyQualifiedClassname(), filterMappings);
for (int i = 0; i < payload.length; i++) {
Entity entity = payload[i];
SkuBundleItem bundleItem = (SkuBundleItem) records.get(i);
Sku bundleSku = bundleItem.getSku();
entity.findProperty("sku").setDisplayValue(bundleSku.getName());
List<ProductOptionValue> productOptionValues = new ArrayList<>();
for (SkuProductOptionValueXref skuProductOptionValueXref : bundleSku.getProductOptionValueXrefs()) {
productOptionValues.add(skuProductOptionValueXref.getProductOptionValue());
}
Property optionsProperty = skuPersistenceHandler.getConsolidatedOptionProperty(productOptionValues);
entity.addProperty(optionsProperty);
}
return new DynamicResultSet(null, payload, totalRecords);
} catch (Exception e) {
throw new ServiceException("There was a problem fetching inventory. See server logs for more details", e);
}
}
use of org.broadleafcommerce.openadmin.dto.Entity in project BroadleafCommerce by BroadleafCommerce.
the class SkuCustomPersistenceHandler method validateUniqueProductOptionValueCombination.
/**
* Ensures that the given list of {@link ProductOptionValue} IDs is unique for the given {@link Product}.
*
* If sku browsing is enabled, then it is assumed that a single combination of {@link ProductOptionValue} IDs
* is not unique and more than one {@link Sku} could have the exact same combination of {@link ProductOptionValue} IDs.
* In this case, the following validation is skipped.
*
* @param product
* @param productOptionProperties
* @param currentSku - for update operations, this is the current Sku that is being updated; should be excluded from
* attempting validation
* @return <b>null</b> if successfully validation, the error entity otherwise
*/
protected Entity validateUniqueProductOptionValueCombination(Product product, List<Property> productOptionProperties, Sku currentSku) {
if (useSku) {
return null;
}
// do not attempt POV validation if no PO properties were passed in
if (CollectionUtils.isNotEmpty(productOptionProperties)) {
List<Long> productOptionValueIds = new ArrayList<>();
for (Property property : productOptionProperties) {
productOptionValueIds.add(Long.parseLong(property.getValue()));
}
boolean validated = true;
for (Sku sku : product.getAdditionalSkus()) {
if (currentSku == null || !sku.getId().equals(currentSku.getId())) {
List<Long> testList = new ArrayList<>();
for (ProductOptionValue optionValue : sku.getProductOptionValues()) {
testList.add(optionValue.getId());
}
if (CollectionUtils.isNotEmpty(testList) && productOptionValueIds.containsAll(testList) && productOptionValueIds.size() == testList.size()) {
validated = false;
break;
}
}
}
if (!validated) {
Entity errorEntity = new Entity();
for (Property productOptionProperty : productOptionProperties) {
errorEntity.addValidationError(productOptionProperty.getName(), "uniqueSkuError");
}
return errorEntity;
}
}
return null;
}
Aggregations