Search in sources :

Example 6 with ValidationException

use of org.broadleafcommerce.openadmin.server.service.ValidationException 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;
}
Also used : AdminMainEntity(org.broadleafcommerce.common.admin.domain.AdminMainEntity) Entity(org.broadleafcommerce.openadmin.dto.Entity) Serializable(java.io.Serializable) FieldMetadata(org.broadleafcommerce.openadmin.dto.FieldMetadata) BasicFieldMetadata(org.broadleafcommerce.openadmin.dto.BasicFieldMetadata) ValidationException(org.broadleafcommerce.openadmin.server.service.ValidationException) FieldPersistenceProvider(org.broadleafcommerce.openadmin.server.service.persistence.module.provider.FieldPersistenceProvider) ArrayList(java.util.ArrayList) AddFilterPropertiesRequest(org.broadleafcommerce.openadmin.server.service.persistence.module.provider.request.AddFilterPropertiesRequest) Field(java.lang.reflect.Field) Property(org.broadleafcommerce.openadmin.dto.Property) MetadataProviderResponse(org.broadleafcommerce.openadmin.server.service.type.MetadataProviderResponse) FlushMode(org.hibernate.FlushMode) ParentEntityPersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.ParentEntityPersistenceException) PopulateValueRequest(org.broadleafcommerce.openadmin.server.service.persistence.module.provider.request.PopulateValueRequest) BasicFieldMetadata(org.broadleafcommerce.openadmin.dto.BasicFieldMetadata) PersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.PersistenceException) ParentEntityPersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.ParentEntityPersistenceException) PropertyValidationResult(org.broadleafcommerce.openadmin.server.service.persistence.validation.PropertyValidationResult) PopulateValueRequestValidator(org.broadleafcommerce.openadmin.server.service.persistence.validation.PopulateValueRequestValidator) Session(org.hibernate.Session)

Example 7 with ValidationException

use of org.broadleafcommerce.openadmin.server.service.ValidationException in project BroadleafCommerce by BroadleafCommerce.

the class AdminSecurityServiceRemote method securityCheck.

@Override
public void securityCheck(PersistencePackage persistencePackage, EntityOperationType operationType) throws ServiceException {
    Set<String> ceilingNames = new HashSet<String>();
    ceilingNames.add(persistencePackage.getSecurityCeilingEntityFullyQualifiedClassname());
    if (!ArrayUtils.isEmpty(persistencePackage.getSectionCrumbs())) {
        ceilingNames.addAll(CollectionUtils.transform(Arrays.asList(persistencePackage.getSectionCrumbs()), new Transformer() {

            @Override
            public Object transform(Object o) {
                return ((SectionCrumb) o).getSectionIdentifier();
            }
        }));
    }
    Entity entity = persistencePackage.getEntity();
    if (persistencePackage.getPersistencePerspectiveItems().containsKey(PersistencePerspectiveItemType.ADORNEDTARGETLIST)) {
        if (persistencePackage.getEntity() != null) {
            for (Property property : persistencePackage.getProperties()) {
                if (property.getName() != null && property.getName().endsWith(".id") && property.getValue() == null) {
                    entity.addGlobalValidationError("adornedTargetRequired");
                    throw new ValidationException(entity);
                }
            }
        }
    }
    GlobalValidationResult globalValidationResult = null;
    if (operationType.equals(EntityOperationType.UPDATE)) {
        globalValidationResult = rowLevelSecurityService.validateUpdateRequest(getPersistentAdminUser(), entity, persistencePackage);
    } else if (operationType.equals(EntityOperationType.REMOVE)) {
        globalValidationResult = rowLevelSecurityService.validateRemoveRequest(getPersistentAdminUser(), entity, persistencePackage);
    } else if (operationType.equals(EntityOperationType.ADD)) {
        globalValidationResult = rowLevelSecurityService.validateAddRequest(getPersistentAdminUser(), entity, persistencePackage);
    }
    if (globalValidationResult != null) {
        if (!globalValidationResult.isValid()) {
            if (StringUtils.isEmpty(globalValidationResult.getErrorMessage())) {
                entity.addGlobalValidationError("rowLevelSecurityFailed");
            } else {
                entity.addGlobalValidationErrors(globalValidationResult.getErrorMessages());
            }
            throw new ValidationException(entity, "Row level security check failed for " + operationType);
        }
    }
    securityCheck(ceilingNames.toArray(new String[ceilingNames.size()]), operationType);
}
Also used : SectionCrumb(org.broadleafcommerce.openadmin.dto.SectionCrumb) Entity(org.broadleafcommerce.openadmin.dto.Entity) Transformer(org.springframework.cglib.core.Transformer) ValidationException(org.broadleafcommerce.openadmin.server.service.ValidationException) GlobalValidationResult(org.broadleafcommerce.openadmin.server.service.persistence.validation.GlobalValidationResult) Property(org.broadleafcommerce.openadmin.dto.Property) HashSet(java.util.HashSet)

Example 8 with ValidationException

use of org.broadleafcommerce.openadmin.server.service.ValidationException in project BroadleafCommerce by BroadleafCommerce.

the class PageTemplateCustomPersistenceHandler method addOrUpdate.

protected Entity addOrUpdate(PersistencePackage persistencePackage, DynamicEntityDao dynamicEntityDao, RecordHelper helper) throws ServiceException {
    String ceilingEntityFullyQualifiedClassname = persistencePackage.getCeilingEntityFullyQualifiedClassname();
    try {
        String pageId = persistencePackage.getCustomCriteria()[1];
        if (StringUtils.isBlank(pageId)) {
            return persistencePackage.getEntity();
        }
        Page page = pageService.findPageById(Long.valueOf(pageId));
        Property[] properties = dynamicFieldUtil.buildDynamicPropertyList(getFieldGroups(page, null), PageTemplate.class);
        Map<String, FieldMetadata> md = new HashMap<String, FieldMetadata>();
        for (Property property : properties) {
            md.put(property.getName(), property.getMetadata());
        }
        boolean validated = helper.validate(persistencePackage.getEntity(), null, md);
        if (!validated) {
            throw new ValidationException(persistencePackage.getEntity(), "Page dynamic fields failed validation");
        }
        List<String> templateFieldNames = new ArrayList<String>(20);
        for (FieldGroup group : getFieldGroups(page, null)) {
            for (FieldDefinition def : group.getFieldDefinitions()) {
                templateFieldNames.add(def.getName());
            }
        }
        Map<String, String> dirtyFieldsOrigVals = new HashMap<String, String>();
        List<String> dirtyFields = new ArrayList<String>();
        Map<String, PageField> pageFieldMap = page.getPageFields();
        for (Property property : persistencePackage.getEntity().getProperties()) {
            if (property.getEnabled() && templateFieldNames.contains(property.getName())) {
                PageField pageField = pageFieldMap.get(property.getName());
                if (pageField != null) {
                    boolean isDirty = (pageField.getValue() == null && property.getValue() != null) || (pageField.getValue() != null && property.getValue() == null);
                    if (isDirty || (pageField.getValue() != null && property.getValue() != null && !pageField.getValue().trim().equals(property.getValue().trim()))) {
                        dirtyFields.add(property.getName());
                        dirtyFieldsOrigVals.put(property.getName(), pageField.getValue());
                        pageField.setValue(property.getValue());
                        pageField = dynamicEntityDao.merge(pageField);
                    }
                } else {
                    pageField = new PageFieldImpl();
                    pageField.setFieldKey(property.getName());
                    pageField.setValue(property.getValue());
                    pageField.setPage(page);
                    dynamicEntityDao.persist(pageField);
                    dirtyFields.add(property.getName());
                }
            }
        }
        List<String> removeItems = new ArrayList<String>();
        for (String key : pageFieldMap.keySet()) {
            if (persistencePackage.getEntity().findProperty(key) == null) {
                removeItems.add(key);
            }
        }
        if (removeItems.size() > 0) {
            for (String removeKey : removeItems) {
                pageFieldMap.remove(removeKey);
            }
        }
        Collections.sort(dirtyFields);
        Entity entity = fetchEntityBasedOnId(pageId, dirtyFields);
        for (Map.Entry<String, String> entry : dirtyFieldsOrigVals.entrySet()) {
            entity.getPMap().get(entry.getKey()).setOriginalValue(entry.getValue());
            entity.getPMap().get(entry.getKey()).setOriginalDisplayValue(entry.getValue());
        }
        return entity;
    } catch (ValidationException e) {
        throw e;
    } catch (Exception e) {
        throw new ServiceException("Unable to perform update for entity: " + ceilingEntityFullyQualifiedClassname, e);
    }
}
Also used : Entity(org.broadleafcommerce.openadmin.dto.Entity) AdminMainEntity(org.broadleafcommerce.common.admin.domain.AdminMainEntity) FieldMetadata(org.broadleafcommerce.openadmin.dto.FieldMetadata) ValidationException(org.broadleafcommerce.openadmin.server.service.ValidationException) HashMap(java.util.HashMap) FieldGroup(org.broadleafcommerce.cms.field.domain.FieldGroup) FieldDefinition(org.broadleafcommerce.cms.field.domain.FieldDefinition) ArrayList(java.util.ArrayList) Page(org.broadleafcommerce.cms.page.domain.Page) ServiceException(org.broadleafcommerce.common.exception.ServiceException) ValidationException(org.broadleafcommerce.openadmin.server.service.ValidationException) PageField(org.broadleafcommerce.cms.page.domain.PageField) ServiceException(org.broadleafcommerce.common.exception.ServiceException) Property(org.broadleafcommerce.openadmin.dto.Property) HashMap(java.util.HashMap) Map(java.util.Map) PageFieldImpl(org.broadleafcommerce.cms.page.domain.PageFieldImpl)

Aggregations

Entity (org.broadleafcommerce.openadmin.dto.Entity)8 ValidationException (org.broadleafcommerce.openadmin.server.service.ValidationException)8 ArrayList (java.util.ArrayList)5 HashMap (java.util.HashMap)4 AdminMainEntity (org.broadleafcommerce.common.admin.domain.AdminMainEntity)4 ServiceException (org.broadleafcommerce.common.exception.ServiceException)4 Property (org.broadleafcommerce.openadmin.dto.Property)4 List (java.util.List)3 Map (java.util.Map)3 FieldMetadata (org.broadleafcommerce.openadmin.dto.FieldMetadata)3 Serializable (java.io.Serializable)2 FieldDefinition (org.broadleafcommerce.cms.field.domain.FieldDefinition)2 FieldGroup (org.broadleafcommerce.cms.field.domain.FieldGroup)2 CriteriaTransferObject (org.broadleafcommerce.openadmin.dto.CriteriaTransferObject)2 PersistencePackage (org.broadleafcommerce.openadmin.dto.PersistencePackage)2 CustomPersistenceHandler (org.broadleafcommerce.openadmin.server.service.handler.CustomPersistenceHandler)2 PersistenceModule (org.broadleafcommerce.openadmin.server.service.persistence.module.PersistenceModule)2 RecordHelper (org.broadleafcommerce.openadmin.server.service.persistence.module.RecordHelper)2 Field (java.lang.reflect.Field)1 BigDecimal (java.math.BigDecimal)1