Search in sources :

Example 1 with ValidationException

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

the class AdminUserCustomPersistenceHandler method remove.

@Override
public void remove(PersistencePackage persistencePackage, DynamicEntityDao dynamicEntityDao, RecordHelper helper) throws ServiceException {
    Entity entity = persistencePackage.getEntity();
    String idValue = entity.findProperty("id").getValue();
    String userLoginToRemove = entity.findProperty("login") == null ? null : entity.findProperty("login").getValue();
    AdminUser persistentAdminUser = adminRemoteSecurityService.getPersistentAdminUser();
    if (persistentAdminUser != null && persistentAdminUser.getLogin() != null && userLoginToRemove != null) {
        if (persistentAdminUser.getLogin().equals(userLoginToRemove)) {
            throw new ValidationException(entity, "admin.cantDeleteCurrentUserError");
        }
    }
    if (idValue != null) {
        Long id = Long.parseLong(idValue);
        AdminUser adminInstance = adminSecurityService.readAdminUserById(id);
        // Check if Status was Weaved in
        if (Status.class.isAssignableFrom(adminInstance.getClass())) {
            ((Status) adminInstance).setArchived('Y');
            adminSecurityService.saveAdminUser(adminInstance);
            return;
        }
    }
    OperationType removeType = persistencePackage.getPersistencePerspective().getOperationTypes().getRemoveType();
    helper.getCompatibleModule(removeType).remove(persistencePackage);
}
Also used : Status(org.broadleafcommerce.common.persistence.Status) Entity(org.broadleafcommerce.openadmin.dto.Entity) ValidationException(org.broadleafcommerce.openadmin.server.service.ValidationException) AdminUser(org.broadleafcommerce.openadmin.server.security.domain.AdminUser) EntityOperationType(org.broadleafcommerce.openadmin.server.security.remote.EntityOperationType) OperationType(org.broadleafcommerce.common.presentation.client.OperationType)

Example 2 with ValidationException

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

the class DefaultBasicPersistenceModuleExtensionHandler method rebalanceForUpdate.

@Override
public ExtensionResultStatusType rebalanceForUpdate(final BasicPersistenceModule basicPersistenceModule, PersistencePackage persistencePackage, Serializable instance, Map<String, FieldMetadata> mergedProperties, Object primaryKey, ExtensionResultHolder<Serializable> resultHolder) {
    try {
        Entity entity = persistencePackage.getEntity();
        PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
        ForeignKey foreignKey = (ForeignKey) persistencePerspective.getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.FOREIGNKEY);
        Integer requestedSequence = Integer.valueOf(entity.findProperty(foreignKey.getSortField()).getValue());
        Integer previousSequence = new BigDecimal(String.valueOf(basicPersistenceModule.getFieldManager().getFieldValue(instance, foreignKey.getSortField()))).intValue();
        final String idPropertyName = basicPersistenceModule.getIdPropertyName(mergedProperties);
        final Object pKey = primaryKey;
        instance = basicPersistenceModule.createPopulatedInstance(instance, entity, mergedProperties, false, persistencePackage.isValidateUnsubmittedProperties());
        if (!previousSequence.equals(requestedSequence)) {
            // Sequence has changed. Rebalance the list
            Serializable manyToField = (Serializable) basicPersistenceModule.getFieldManager().getFieldValue(instance, foreignKey.getManyToField());
            List<Serializable> records = (List<Serializable>) basicPersistenceModule.getFieldManager().getFieldValue(manyToField, foreignKey.getOriginatingField());
            Serializable myRecord = (Serializable) CollectionUtils.find(records, new TypedPredicate<Serializable>() {

                @Override
                public boolean eval(Serializable record) {
                    try {
                        return (pKey.equals(basicPersistenceModule.getFieldManager().getFieldValue(record, idPropertyName)));
                    } catch (IllegalAccessException e) {
                        return false;
                    } catch (FieldNotAvailableException e) {
                        return false;
                    }
                }
            });
            records.remove(myRecord);
            if (CollectionUtils.isEmpty(records)) {
                records.add(myRecord);
            } else {
                records.add(requestedSequence - 1, myRecord);
            }
            int index = 1;
            Class<?> type = basicPersistenceModule.getFieldManager().getField(myRecord.getClass(), foreignKey.getSortField()).getType();
            boolean isBigDecimal = BigDecimal.class.isAssignableFrom(type);
            for (Serializable record : records) {
                basicPersistenceModule.getFieldManager().setFieldValue(record, foreignKey.getSortField(), isBigDecimal ? new BigDecimal(index) : Long.valueOf(index));
                index++;
            }
        }
        resultHolder.setResult(instance);
    } catch (IllegalAccessException e) {
        throw ExceptionHelper.refineException(e);
    } catch (FieldNotAvailableException e) {
        throw ExceptionHelper.refineException(e);
    } catch (ValidationException e) {
        throw ExceptionHelper.refineException(e);
    } catch (InstantiationException e) {
        throw ExceptionHelper.refineException(e);
    }
    return ExtensionResultStatusType.HANDLED;
}
Also used : Entity(org.broadleafcommerce.openadmin.dto.Entity) Serializable(java.io.Serializable) ValidationException(org.broadleafcommerce.openadmin.server.service.ValidationException) ForeignKey(org.broadleafcommerce.openadmin.dto.ForeignKey) BigDecimal(java.math.BigDecimal) PersistencePerspective(org.broadleafcommerce.openadmin.dto.PersistencePerspective) FieldNotAvailableException(org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException) CriteriaTransferObject(org.broadleafcommerce.openadmin.dto.CriteriaTransferObject) List(java.util.List) TypedPredicate(org.broadleafcommerce.common.util.TypedPredicate)

Example 3 with ValidationException

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

the class StructuredContentTypeCustomPersistenceHandler method addOrUpdate.

protected Entity addOrUpdate(PersistencePackage persistencePackage, DynamicEntityDao dynamicEntityDao, RecordHelper helper) throws ServiceException {
    String ceilingEntityFullyQualifiedClassname = persistencePackage.getCeilingEntityFullyQualifiedClassname();
    try {
        String structuredContentId = persistencePackage.getCustomCriteria()[1];
        StructuredContent structuredContent = structuredContentService.findStructuredContentById(Long.valueOf(structuredContentId));
        Property[] properties = dynamicFieldUtil.buildDynamicPropertyList(structuredContent.getStructuredContentType().getStructuredContentFieldTemplate().getFieldGroups(), StructuredContentType.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(), "Structured Content dynamic fields failed validation");
        }
        List<String> templateFieldNames = new ArrayList<String>(20);
        for (FieldGroup group : structuredContent.getStructuredContentType().getStructuredContentFieldTemplate().getFieldGroups()) {
            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, StructuredContentFieldXref> structuredContentFieldMap = structuredContent.getStructuredContentFieldXrefs();
        for (Property property : persistencePackage.getEntity().getProperties()) {
            if (property.getEnabled() && templateFieldNames.contains(property.getName())) {
                StructuredContentFieldXref scXref = structuredContentFieldMap.get(property.getName());
                if (scXref != null && scXref.getStructuredContentField() != null) {
                    StructuredContentField structuredContentField = scXref.getStructuredContentField();
                    boolean isDirty = (structuredContentField.getValue() == null && property.getValue() != null) || (structuredContentField.getValue() != null && property.getValue() == null);
                    if (isDirty || (structuredContentField.getValue() != null && property.getValue() != null && !structuredContentField.getValue().trim().equals(property.getValue().trim()))) {
                        dirtyFields.add(property.getName());
                        dirtyFieldsOrigVals.put(property.getName(), structuredContentField.getValue());
                        structuredContentField.setValue(property.getValue());
                        scXref = dynamicEntityDao.merge(scXref);
                    }
                } else {
                    StructuredContentField structuredContentField = new StructuredContentFieldImpl();
                    structuredContentField.setFieldKey(property.getName());
                    structuredContentField.setValue(property.getValue());
                    StructuredContentFieldXref scfx = new StructuredContentFieldXrefImpl();
                    scfx.setStructuredContent(structuredContent);
                    scfx.setKey(property.getName());
                    scfx.setStrucuturedContentField(structuredContentField);
                    scfx = dynamicEntityDao.persist(scfx);
                    dirtyFields.add(property.getName());
                }
            }
        }
        List<String> removeItems = new ArrayList<String>();
        for (String key : structuredContentFieldMap.keySet()) {
            if (persistencePackage.getEntity().findProperty(key) == null) {
                removeItems.add(key);
            }
        }
        if (removeItems.size() > 0) {
            for (String removeKey : removeItems) {
                structuredContentFieldMap.remove(removeKey);
            }
        }
        Collections.sort(dirtyFields);
        Entity entity = fetchEntityBasedOnId(structuredContentId, dirtyFields);
        for (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 fetch for entity: " + ceilingEntityFullyQualifiedClassname, e);
    }
}
Also used : Entity(org.broadleafcommerce.openadmin.dto.Entity) FieldMetadata(org.broadleafcommerce.openadmin.dto.FieldMetadata) ValidationException(org.broadleafcommerce.openadmin.server.service.ValidationException) StructuredContentFieldXrefImpl(org.broadleafcommerce.cms.structure.domain.StructuredContentFieldXrefImpl) HashMap(java.util.HashMap) FieldGroup(org.broadleafcommerce.cms.field.domain.FieldGroup) FieldDefinition(org.broadleafcommerce.cms.field.domain.FieldDefinition) ArrayList(java.util.ArrayList) ServiceException(org.broadleafcommerce.common.exception.ServiceException) ValidationException(org.broadleafcommerce.openadmin.server.service.ValidationException) StructuredContent(org.broadleafcommerce.cms.structure.domain.StructuredContent) ServiceException(org.broadleafcommerce.common.exception.ServiceException) StructuredContentField(org.broadleafcommerce.cms.structure.domain.StructuredContentField) StructuredContentFieldXref(org.broadleafcommerce.cms.structure.domain.StructuredContentFieldXref) Property(org.broadleafcommerce.openadmin.dto.Property) StructuredContentFieldImpl(org.broadleafcommerce.cms.structure.domain.StructuredContentFieldImpl)

Example 4 with ValidationException

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

the class PersistenceManagerImpl method update.

@Override
public PersistenceResponse update(PersistencePackage persistencePackage) throws ServiceException {
    for (PersistenceManagerEventHandler handler : persistenceManagerEventHandlers) {
        PersistenceManagerEventHandlerResponse response = handler.preUpdate(this, persistencePackage);
        if (PersistenceManagerEventHandlerResponse.PersistenceManagerEventHandlerResponseStatus.HANDLED_BREAK == response.getStatus()) {
            break;
        }
    }
    // check to see if there is a custom handler registered
    // execute the root PersistencePackage
    Entity response;
    try {
        checkRoot: {
            for (CustomPersistenceHandler handler : getCustomPersistenceHandlers()) {
                if (handler.canHandleUpdate(persistencePackage)) {
                    if (!handler.willHandleSecurity(persistencePackage)) {
                        adminRemoteSecurityService.securityCheck(persistencePackage, EntityOperationType.UPDATE);
                    }
                    response = handler.update(persistencePackage, dynamicEntityDao, (RecordHelper) getCompatibleModule(OperationType.BASIC));
                    break checkRoot;
                }
            }
            adminRemoteSecurityService.securityCheck(persistencePackage, EntityOperationType.UPDATE);
            PersistenceModule myModule = getCompatibleModule(persistencePackage.getPersistencePerspective().getOperationTypes().getUpdateType());
            response = myModule.update(persistencePackage);
        }
    } catch (ValidationException e) {
        response = e.getEntity();
    } catch (ServiceException e) {
        if (e.getCause() instanceof ValidationException) {
            response = ((ValidationException) e.getCause()).getEntity();
        } else {
            throw e;
        }
    }
    Map<String, List<String>> subPackageValidationErrors = new HashMap<>();
    for (Map.Entry<String, PersistencePackage> subPackage : persistencePackage.getSubPackages().entrySet()) {
        try {
            // Run through any subPackages -- add up any validation errors
            checkHandler: {
                for (CustomPersistenceHandler handler : getCustomPersistenceHandlers()) {
                    if (handler.canHandleUpdate(subPackage.getValue())) {
                        Entity subResponse = handler.update(subPackage.getValue(), dynamicEntityDao, (RecordHelper) getCompatibleModule(OperationType.BASIC));
                        subPackage.getValue().setEntity(subResponse);
                        break checkHandler;
                    }
                }
                PersistenceModule subModule = getCompatibleModule(subPackage.getValue().getPersistencePerspective().getOperationTypes().getUpdateType());
                Entity subResponse = subModule.update(persistencePackage);
                subPackage.getValue().setEntity(subResponse);
            }
        } catch (ValidationException e) {
            subPackage.getValue().setEntity(e.getEntity());
        } catch (ServiceException e) {
            if (e.getCause() instanceof ValidationException) {
                response = ((ValidationException) e.getCause()).getEntity();
            } else {
                throw e;
            }
        }
    }
    // Build up validation errors in all of the subpackages, even those that might not have thrown ValidationExceptions
    for (Map.Entry<String, PersistencePackage> subPackage : persistencePackage.getSubPackages().entrySet()) {
        for (Map.Entry<String, List<String>> error : subPackage.getValue().getEntity().getPropertyValidationErrors().entrySet()) {
            subPackageValidationErrors.put(subPackage.getKey() + DynamicEntityFormInfo.FIELD_SEPARATOR + error.getKey(), error.getValue());
        }
    }
    response.getPropertyValidationErrors().putAll(subPackageValidationErrors);
    if (response.isValidationFailure()) {
        PersistenceResponse validationResponse = executeValidationProcessors(persistencePackage, new PersistenceResponse().withEntity(response));
        Entity entity = validationResponse.getEntity();
        String message = ValidationUtil.buildErrorMessage(entity.getPropertyValidationErrors(), entity.getGlobalValidationErrors());
        throw new ValidationException(entity, message);
    }
    return executePostUpdateHandlers(persistencePackage, new PersistenceResponse().withEntity(response));
}
Also used : PersistencePackage(org.broadleafcommerce.openadmin.dto.PersistencePackage) AdminMainEntity(org.broadleafcommerce.common.admin.domain.AdminMainEntity) Entity(org.broadleafcommerce.openadmin.dto.Entity) ValidationException(org.broadleafcommerce.openadmin.server.service.ValidationException) HashMap(java.util.HashMap) CustomPersistenceHandler(org.broadleafcommerce.openadmin.server.service.handler.CustomPersistenceHandler) PersistenceModule(org.broadleafcommerce.openadmin.server.service.persistence.module.PersistenceModule) ServiceException(org.broadleafcommerce.common.exception.ServiceException) RecordHelper(org.broadleafcommerce.openadmin.server.service.persistence.module.RecordHelper) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) HashMap(java.util.HashMap)

Example 5 with ValidationException

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

the class PersistenceManagerImpl method add.

@Override
public PersistenceResponse add(PersistencePackage persistencePackage) throws ServiceException {
    for (PersistenceManagerEventHandler handler : persistenceManagerEventHandlers) {
        PersistenceManagerEventHandlerResponse response = handler.preAdd(this, persistencePackage);
        if (PersistenceManagerEventHandlerResponse.PersistenceManagerEventHandlerResponseStatus.HANDLED_BREAK == response.getStatus()) {
            break;
        }
    }
    // check to see if there is a custom handler registered
    // execute the root PersistencePackage
    Entity response;
    try {
        checkRoot: {
            // entity to execute the subPackage code later
            for (CustomPersistenceHandler handler : getCustomPersistenceHandlers()) {
                if (handler.canHandleAdd(persistencePackage)) {
                    if (!handler.willHandleSecurity(persistencePackage)) {
                        adminRemoteSecurityService.securityCheck(persistencePackage, EntityOperationType.ADD);
                    }
                    response = handler.add(persistencePackage, dynamicEntityDao, (RecordHelper) getCompatibleModule(OperationType.BASIC));
                    break checkRoot;
                }
            }
            adminRemoteSecurityService.securityCheck(persistencePackage, EntityOperationType.ADD);
            PersistenceModule myModule = getCompatibleModule(persistencePackage.getPersistencePerspective().getOperationTypes().getAddType());
            response = myModule.add(persistencePackage);
        }
    } catch (ValidationException e) {
        response = e.getEntity();
    } catch (ServiceException e) {
        if (e.getCause() instanceof ValidationException) {
            response = ((ValidationException) e.getCause()).getEntity();
        } else {
            throw e;
        }
    }
    if (!MapUtils.isEmpty(persistencePackage.getSubPackages())) {
        // Once the entity has been saved, we can utilize its id for the subsequent dynamic forms
        Class<?> entityClass;
        try {
            entityClass = Class.forName(response.getType()[0]);
        } catch (ClassNotFoundException e) {
            throw new ServiceException(e);
        }
        Map<String, Object> idMetadata = getDynamicEntityDao().getIdMetadata(entityClass);
        String idProperty = (String) idMetadata.get("name");
        String idVal = response.findProperty(idProperty).getValue();
        Map<String, List<String>> subPackageValidationErrors = new HashMap<>();
        for (Map.Entry<String, PersistencePackage> subPackage : persistencePackage.getSubPackages().entrySet()) {
            Entity subResponse;
            try {
                subPackage.getValue().getCustomCriteria()[1] = idVal;
                // Run through any subPackages -- add up any validation errors
                checkHandler: {
                    for (CustomPersistenceHandler handler : getCustomPersistenceHandlers()) {
                        if (handler.canHandleAdd(subPackage.getValue())) {
                            subResponse = handler.add(subPackage.getValue(), dynamicEntityDao, (RecordHelper) getCompatibleModule(OperationType.BASIC));
                            subPackage.getValue().setEntity(subResponse);
                            break checkHandler;
                        }
                    }
                    PersistenceModule subModule = getCompatibleModule(subPackage.getValue().getPersistencePerspective().getOperationTypes().getAddType());
                    subResponse = subModule.add(persistencePackage);
                    subPackage.getValue().setEntity(subResponse);
                }
            } catch (ValidationException e) {
                subPackage.getValue().setEntity(e.getEntity());
            } catch (ServiceException e) {
                if (e.getCause() instanceof ValidationException) {
                    response = ((ValidationException) e.getCause()).getEntity();
                } else {
                    throw e;
                }
            }
        }
        // Build up validation errors in all of the subpackages, even those that might not have thrown ValidationExceptions
        for (Map.Entry<String, PersistencePackage> subPackage : persistencePackage.getSubPackages().entrySet()) {
            for (Map.Entry<String, List<String>> error : subPackage.getValue().getEntity().getPropertyValidationErrors().entrySet()) {
                subPackageValidationErrors.put(subPackage.getKey() + DynamicEntityFormInfo.FIELD_SEPARATOR + error.getKey(), error.getValue());
            }
        }
        response.getPropertyValidationErrors().putAll(subPackageValidationErrors);
    }
    if (response.isValidationFailure()) {
        PersistenceResponse validationResponse = executeValidationProcessors(persistencePackage, new PersistenceResponse().withEntity(response));
        Entity entity = validationResponse.getEntity();
        String message = ValidationUtil.buildErrorMessage(entity.getPropertyValidationErrors(), entity.getGlobalValidationErrors());
        throw new ValidationException(entity, message);
    }
    return executePostAddHandlers(persistencePackage, new PersistenceResponse().withEntity(response));
}
Also used : PersistencePackage(org.broadleafcommerce.openadmin.dto.PersistencePackage) AdminMainEntity(org.broadleafcommerce.common.admin.domain.AdminMainEntity) Entity(org.broadleafcommerce.openadmin.dto.Entity) ValidationException(org.broadleafcommerce.openadmin.server.service.ValidationException) HashMap(java.util.HashMap) CustomPersistenceHandler(org.broadleafcommerce.openadmin.server.service.handler.CustomPersistenceHandler) PersistenceModule(org.broadleafcommerce.openadmin.server.service.persistence.module.PersistenceModule) ServiceException(org.broadleafcommerce.common.exception.ServiceException) RecordHelper(org.broadleafcommerce.openadmin.server.service.persistence.module.RecordHelper) CriteriaTransferObject(org.broadleafcommerce.openadmin.dto.CriteriaTransferObject) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) HashMap(java.util.HashMap)

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