Search in sources :

Example 1 with FilterAndSortCriteria

use of org.broadleafcommerce.openadmin.dto.FilterAndSortCriteria in project BroadleafCommerce by BroadleafCommerce.

the class AdornedTargetListPersistenceModule method add.

@Override
public Entity add(PersistencePackage persistencePackage) throws ServiceException {
    String[] customCriteria = persistencePackage.getCustomCriteria();
    if (customCriteria != null && customCriteria.length > 0) {
        LOG.warn("custom persistence handlers and custom criteria not supported for add types other than BASIC");
    }
    PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
    String ceilingEntityFullyQualifiedClassname = persistencePackage.getCeilingEntityFullyQualifiedClassname();
    Entity entity = persistencePackage.getEntity();
    AdornedTargetList adornedTargetList = (AdornedTargetList) persistencePerspective.getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.ADORNEDTARGETLIST);
    if (!adornedTargetList.getMutable()) {
        throw new SecurityServiceException("Field is not mutable");
    }
    Entity payload;
    try {
        Class<?>[] entities = persistenceManager.getPolymorphicEntities(ceilingEntityFullyQualifiedClassname);
        Map<String, FieldMetadata> mergedPropertiesTarget = persistenceManager.getDynamicEntityDao().getMergedProperties(ceilingEntityFullyQualifiedClassname, entities, null, persistencePerspective.getAdditionalNonPersistentProperties(), persistencePerspective.getAdditionalForeignKeys(), MergedPropertyType.PRIMARY, persistencePerspective.getPopulateToOneFields(), persistencePerspective.getIncludeFields(), persistencePerspective.getExcludeFields(), persistencePerspective.getConfigurationKey(), "");
        Class<?>[] entities2 = persistenceManager.getPolymorphicEntities(adornedTargetList.getAdornedTargetEntityClassname());
        Map<String, FieldMetadata> mergedProperties = persistenceManager.getDynamicEntityDao().getMergedProperties(adornedTargetList.getAdornedTargetEntityClassname(), entities2, null, new String[] {}, new ForeignKey[] {}, MergedPropertyType.ADORNEDTARGETLIST, false, new String[] {}, new String[] {}, null, "");
        CriteriaTransferObject ctoInserted = new CriteriaTransferObject();
        FilterAndSortCriteria filterCriteriaInsertedLinked = ctoInserted.get(adornedTargetList.getCollectionFieldName());
        String linkedPath;
        String targetPath;
        if (adornedTargetList.getInverse()) {
            linkedPath = adornedTargetList.getTargetObjectPath() + "." + adornedTargetList.getTargetIdProperty();
            targetPath = adornedTargetList.getLinkedObjectPath() + "." + adornedTargetList.getLinkedIdProperty();
        } else {
            targetPath = adornedTargetList.getTargetObjectPath() + "." + adornedTargetList.getTargetIdProperty();
            linkedPath = adornedTargetList.getLinkedObjectPath() + "." + adornedTargetList.getLinkedIdProperty();
        }
        filterCriteriaInsertedLinked.setFilterValue(entity.findProperty(adornedTargetList.getInverse() ? targetPath : linkedPath).getValue());
        FilterAndSortCriteria filterCriteriaInsertedTarget = ctoInserted.get(adornedTargetList.getCollectionFieldName() + "Target");
        filterCriteriaInsertedTarget.setFilterValue(entity.findProperty(adornedTargetList.getInverse() ? linkedPath : targetPath).getValue());
        List<FilterMapping> filterMappingsInserted = getAdornedTargetFilterMappings(persistencePerspective, ctoInserted, mergedProperties, adornedTargetList);
        List<Serializable> recordsInserted = getPersistentRecords(adornedTargetList.getAdornedTargetEntityClassname(), filterMappingsInserted, ctoInserted.getFirstResult(), ctoInserted.getMaxResults());
        if (recordsInserted.size() > 0) {
            payload = getRecords(mergedPropertiesTarget, recordsInserted, mergedProperties, adornedTargetList.getTargetObjectPath(), null)[0];
        } else {
            Serializable instance = createPopulatedAdornedTargetInstance(adornedTargetList, entity);
            instance = createPopulatedInstance(instance, entity, mergedProperties, false, persistencePackage.isValidateUnsubmittedProperties());
            instance = createPopulatedInstance(instance, entity, mergedPropertiesTarget, false, persistencePackage.isValidateUnsubmittedProperties());
            FieldManager fieldManager = getFieldManager();
            if (fieldManager.getField(instance.getClass(), "id") != null) {
                fieldManager.setFieldValue(instance, "id", null);
            }
            if (adornedTargetList.getSortField() != null) {
                // Construct a query that gets the last element in the join list ordered by the sort property. This will
                // ensure that the new record is always the last element in the list
                CriteriaTransferObject cto = new CriteriaTransferObject();
                FilterAndSortCriteria filterCriteria = cto.get(adornedTargetList.getCollectionFieldName());
                filterCriteria.setFilterValue(entity.findProperty(adornedTargetList.getInverse() ? targetPath : linkedPath).getValue());
                FilterAndSortCriteria sortCriteria = cto.get(adornedTargetList.getSortField());
                // criteria for which way to sort should be the opposite of how it is normally sorted so that it is
                // always inserted at the end
                sortCriteria.setSortAscending(!adornedTargetList.getSortAscending());
                List<FilterMapping> filterMappings = getAdornedTargetFilterMappings(persistencePerspective, cto, mergedProperties, adornedTargetList);
                List<Serializable> joinList = getPersistentRecords(adornedTargetList.getAdornedTargetEntityClassname(), filterMappings, 0, 1);
                Object adornedLastOrdering = null;
                if (CollectionUtils.isNotEmpty(joinList)) {
                    adornedLastOrdering = fieldManager.getFieldValue(joinList.get(0), adornedTargetList.getSortField());
                }
                Field sortFieldDef = fieldManager.getField(instance.getClass(), adornedTargetList.getSortField());
                int add = (adornedLastOrdering == null) ? 0 : 1;
                if (sortFieldDef.getType().isAssignableFrom(Long.class)) {
                    adornedLastOrdering = (adornedLastOrdering == null) ? new Long(0) : adornedLastOrdering;
                    fieldManager.setFieldValue(instance, adornedTargetList.getSortField(), new Long(((Long) adornedLastOrdering).longValue() + add));
                } else if (sortFieldDef.getType().isAssignableFrom(Integer.class)) {
                    adornedLastOrdering = (adornedLastOrdering == null) ? new Integer(0) : adornedLastOrdering;
                    fieldManager.setFieldValue(instance, adornedTargetList.getSortField(), new Integer(((Integer) adornedLastOrdering).intValue() + add));
                } else if (sortFieldDef.getType().isAssignableFrom(BigDecimal.class)) {
                    adornedLastOrdering = (adornedLastOrdering == null) ? BigDecimal.ZERO : adornedLastOrdering;
                    fieldManager.setFieldValue(instance, adornedTargetList.getSortField(), ((BigDecimal) adornedLastOrdering).add(new BigDecimal(add)));
                }
            }
            instance = persistenceManager.getDynamicEntityDao().merge(instance);
            persistenceManager.getDynamicEntityDao().clear();
            List<Serializable> recordsInserted2 = getPersistentRecords(adornedTargetList.getAdornedTargetEntityClassname(), filterMappingsInserted, ctoInserted.getFirstResult(), ctoInserted.getMaxResults());
            payload = getRecords(mergedPropertiesTarget, recordsInserted2, mergedProperties, adornedTargetList.getTargetObjectPath(), null)[0];
        }
    } catch (Exception e) {
        throw new ServiceException("Problem adding new entity : " + e.getMessage(), e);
    }
    return payload;
}
Also used : Entity(org.broadleafcommerce.openadmin.dto.Entity) SecurityServiceException(org.broadleafcommerce.common.exception.SecurityServiceException) Serializable(java.io.Serializable) FieldMetadata(org.broadleafcommerce.openadmin.dto.FieldMetadata) BasicFieldMetadata(org.broadleafcommerce.openadmin.dto.BasicFieldMetadata) FilterMapping(org.broadleafcommerce.openadmin.server.service.persistence.module.criteria.FilterMapping) Field(java.lang.reflect.Field) PersistencePerspective(org.broadleafcommerce.openadmin.dto.PersistencePerspective) FilterAndSortCriteria(org.broadleafcommerce.openadmin.dto.FilterAndSortCriteria) AdornedTargetList(org.broadleafcommerce.openadmin.dto.AdornedTargetList) BigDecimal(java.math.BigDecimal) ServiceException(org.broadleafcommerce.common.exception.ServiceException) InvocationTargetException(java.lang.reflect.InvocationTargetException) SecurityServiceException(org.broadleafcommerce.common.exception.SecurityServiceException) ServiceException(org.broadleafcommerce.common.exception.ServiceException) SecurityServiceException(org.broadleafcommerce.common.exception.SecurityServiceException) CriteriaTransferObject(org.broadleafcommerce.openadmin.dto.CriteriaTransferObject) CriteriaTransferObject(org.broadleafcommerce.openadmin.dto.CriteriaTransferObject)

Example 2 with FilterAndSortCriteria

use of org.broadleafcommerce.openadmin.dto.FilterAndSortCriteria in project BroadleafCommerce by BroadleafCommerce.

the class AdornedTargetListPersistenceModule method remove.

@Override
public void remove(PersistencePackage persistencePackage) throws ServiceException {
    String[] customCriteria = persistencePackage.getCustomCriteria();
    if (customCriteria != null && customCriteria.length > 0) {
        LOG.warn("custom persistence handlers and custom criteria not supported for remove types other than BASIC");
    }
    PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
    Entity entity = persistencePackage.getEntity();
    try {
        AdornedTargetList adornedTargetList = (AdornedTargetList) persistencePerspective.getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.ADORNEDTARGETLIST);
        if (!adornedTargetList.getMutable()) {
            throw new SecurityServiceException("Field is not mutable");
        }
        Class<?>[] entities = persistenceManager.getPolymorphicEntities(adornedTargetList.getAdornedTargetEntityClassname());
        Map<String, FieldMetadata> mergedProperties = persistenceManager.getDynamicEntityDao().getMergedProperties(adornedTargetList.getAdornedTargetEntityClassname(), entities, null, new String[] {}, new ForeignKey[] {}, MergedPropertyType.ADORNEDTARGETLIST, false, new String[] {}, new String[] {}, null, "");
        CriteriaTransferObject ctoInserted = new CriteriaTransferObject();
        FilterAndSortCriteria filterCriteriaInsertedLinked = ctoInserted.get(adornedTargetList.getCollectionFieldName());
        filterCriteriaInsertedLinked.setFilterValue(entity.findProperty(adornedTargetList.getLinkedObjectPath() + "." + adornedTargetList.getLinkedIdProperty()).getValue());
        FilterAndSortCriteria filterCriteriaInsertedTarget = ctoInserted.get(adornedTargetList.getCollectionFieldName() + "Target");
        filterCriteriaInsertedTarget.setFilterValue(entity.findProperty(adornedTargetList.getTargetObjectPath() + "." + adornedTargetList.getTargetIdProperty()).getValue());
        List<FilterMapping> filterMappings = getAdornedTargetFilterMappings(persistencePerspective, ctoInserted, mergedProperties, adornedTargetList);
        List<Serializable> recordsInserted = getPersistentRecords(adornedTargetList.getAdornedTargetEntityClassname(), filterMappings, ctoInserted.getFirstResult(), ctoInserted.getMaxResults());
        Assert.isTrue(!CollectionUtils.isEmpty(recordsInserted), "Entity not found");
        persistenceManager.getDynamicEntityDao().remove(recordsInserted.get(0));
    } catch (Exception e) {
        throw new ServiceException("Problem removing entity : " + e.getMessage(), e);
    }
}
Also used : Entity(org.broadleafcommerce.openadmin.dto.Entity) SecurityServiceException(org.broadleafcommerce.common.exception.SecurityServiceException) Serializable(java.io.Serializable) FieldMetadata(org.broadleafcommerce.openadmin.dto.FieldMetadata) BasicFieldMetadata(org.broadleafcommerce.openadmin.dto.BasicFieldMetadata) FilterMapping(org.broadleafcommerce.openadmin.server.service.persistence.module.criteria.FilterMapping) ServiceException(org.broadleafcommerce.common.exception.ServiceException) InvocationTargetException(java.lang.reflect.InvocationTargetException) SecurityServiceException(org.broadleafcommerce.common.exception.SecurityServiceException) PersistencePerspective(org.broadleafcommerce.openadmin.dto.PersistencePerspective) ServiceException(org.broadleafcommerce.common.exception.ServiceException) SecurityServiceException(org.broadleafcommerce.common.exception.SecurityServiceException) FilterAndSortCriteria(org.broadleafcommerce.openadmin.dto.FilterAndSortCriteria) AdornedTargetList(org.broadleafcommerce.openadmin.dto.AdornedTargetList) CriteriaTransferObject(org.broadleafcommerce.openadmin.dto.CriteriaTransferObject)

Example 3 with FilterAndSortCriteria

use of org.broadleafcommerce.openadmin.dto.FilterAndSortCriteria in project BroadleafCommerce by BroadleafCommerce.

the class DefaultBasicPersistenceModuleExtensionHandler method rebalanceForAdd.

@Override
public ExtensionResultStatusType rebalanceForAdd(BasicPersistenceModule basicPersistenceModule, PersistencePackage persistencePackage, Serializable instance, Map<String, FieldMetadata> mergedProperties, ExtensionResultHolder<Serializable> resultHolder) {
    try {
        PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
        ForeignKey foreignKey = (ForeignKey) persistencePerspective.getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.FOREIGNKEY);
        CriteriaTransferObject cto = new CriteriaTransferObject();
        FilterAndSortCriteria sortCriteria = cto.get(foreignKey.getSortField());
        sortCriteria.setSortAscending(foreignKey.getSortAscending());
        List<FilterMapping> filterMappings = basicPersistenceModule.getFilterMappings(persistencePerspective, cto, persistencePackage.getCeilingEntityFullyQualifiedClassname(), mergedProperties);
        int totalRecords = basicPersistenceModule.getTotalRecords(persistencePackage.getCeilingEntityFullyQualifiedClassname(), filterMappings);
        Class<?> type = basicPersistenceModule.getFieldManager().getField(instance.getClass(), foreignKey.getSortField()).getType();
        boolean isBigDecimal = BigDecimal.class.isAssignableFrom(type);
        basicPersistenceModule.getFieldManager().setFieldValue(instance, foreignKey.getSortField(), isBigDecimal ? new BigDecimal(totalRecords + 1) : Long.valueOf(totalRecords + 1));
        resultHolder.setResult(instance);
    } catch (IllegalAccessException e) {
        throw ExceptionHelper.refineException(e);
    } catch (InstantiationException e) {
        throw ExceptionHelper.refineException(e);
    }
    return ExtensionResultStatusType.HANDLED;
}
Also used : PersistencePerspective(org.broadleafcommerce.openadmin.dto.PersistencePerspective) FilterAndSortCriteria(org.broadleafcommerce.openadmin.dto.FilterAndSortCriteria) FilterMapping(org.broadleafcommerce.openadmin.server.service.persistence.module.criteria.FilterMapping) ForeignKey(org.broadleafcommerce.openadmin.dto.ForeignKey) CriteriaTransferObject(org.broadleafcommerce.openadmin.dto.CriteriaTransferObject) BigDecimal(java.math.BigDecimal)

Example 4 with FilterAndSortCriteria

use of org.broadleafcommerce.openadmin.dto.FilterAndSortCriteria in project BroadleafCommerce by BroadleafCommerce.

the class BasicFieldPersistenceProvider method addSearchMapping.

@Override
public MetadataProviderResponse addSearchMapping(AddSearchMappingRequest addSearchMappingRequest, List<FilterMapping> filterMappings) {
    if (!canHandleSearchMapping(addSearchMappingRequest, filterMappings)) {
        return MetadataProviderResponse.NOT_HANDLED;
    }
    Class clazz;
    try {
        clazz = Class.forName(addSearchMappingRequest.getMergedProperties().get(addSearchMappingRequest.getPropertyName()).getInheritedFromType());
    } catch (ClassNotFoundException e) {
        throw new PersistenceException(e);
    }
    Field field = addSearchMappingRequest.getFieldManager().getField(clazz, addSearchMappingRequest.getPropertyName());
    Class<?> targetType = null;
    if (field != null) {
        targetType = field.getType();
    }
    BasicFieldMetadata metadata = (BasicFieldMetadata) addSearchMappingRequest.getMergedProperties().get(addSearchMappingRequest.getPropertyName());
    FilterAndSortCriteria fasc = addSearchMappingRequest.getRequestedCto().get(addSearchMappingRequest.getPropertyName());
    FilterMapping filterMapping = new FilterMapping().withInheritedFromClass(clazz).withFullPropertyName(addSearchMappingRequest.getPropertyName()).withFilterValues(fasc.getFilterValues()).withSortDirection(fasc.getSortDirection()).withOrder(fasc.getOrder()).withNullsLast(fasc.isNullsLast());
    filterMappings.add(filterMapping);
    if (fasc.hasSpecialFilterValue()) {
        filterMapping.setDirectFilterValues(new EmptyFilterValues());
        // Handle special values on a case by case basis
        List<String> specialValues = fasc.getSpecialFilterValues();
        if (specialValues.contains(FilterAndSortCriteria.IS_NULL_FILTER_VALUE)) {
            filterMapping.setRestriction(new Restriction().withPredicateProvider(new IsNullPredicateProvider()));
        }
        if (specialValues.contains(FilterAndSortCriteria.IS_NOT_NULL_FILTER_VALUE)) {
            filterMapping.setRestriction(new Restriction().withPredicateProvider(new IsNotNullPredicateProvider()));
        }
    } else {
        if (fasc.getRestrictionType() != null) {
            filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(fasc.getRestrictionType().getType(), addSearchMappingRequest.getPropertyName()));
        } else {
            switch(metadata.getFieldType()) {
                case BOOLEAN:
                    if (targetType == null || targetType.equals(Boolean.class) || targetType.equals(boolean.class)) {
                        filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.BOOLEAN.getType(), addSearchMappingRequest.getPropertyName()));
                    } else {
                        filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.CHARACTER.getType(), addSearchMappingRequest.getPropertyName()));
                    }
                    break;
                case DATE:
                    filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.DATE.getType(), addSearchMappingRequest.getPropertyName()));
                    break;
                case DECIMAL:
                case MONEY:
                    filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.DECIMAL.getType(), addSearchMappingRequest.getPropertyName()));
                    break;
                case INTEGER:
                    filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.LONG.getType(), addSearchMappingRequest.getPropertyName()));
                    break;
                case BROADLEAF_ENUMERATION:
                    filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.STRING_EQUAL.getType(), addSearchMappingRequest.getPropertyName()));
                    break;
                default:
                    filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.STRING_LIKE.getType(), addSearchMappingRequest.getPropertyName()));
                    break;
                case FOREIGN_KEY:
                    if (!addSearchMappingRequest.getRequestedCto().get(addSearchMappingRequest.getPropertyName()).getFilterValues().isEmpty()) {
                        ForeignKey foreignKey = (ForeignKey) addSearchMappingRequest.getPersistencePerspective().getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.FOREIGNKEY);
                        if (metadata.getForeignKeyCollection()) {
                            if (ForeignKeyRestrictionType.COLLECTION_SIZE_EQ.toString().equals(foreignKey.getRestrictionType().toString())) {
                                filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.COLLECTION_SIZE_EQUAL.getType(), addSearchMappingRequest.getPropertyName()));
                                filterMapping.setFieldPath(new FieldPath());
                            } else {
                                filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.LONG.getType(), addSearchMappingRequest.getPropertyName()));
                                filterMapping.setFieldPath(new FieldPath().withTargetProperty(addSearchMappingRequest.getPropertyName() + "." + metadata.getForeignKeyProperty()));
                            }
                        } else if (addSearchMappingRequest.getRequestedCto().get(addSearchMappingRequest.getPropertyName()).getFilterValues().get(0) == null || "null".equals(addSearchMappingRequest.getRequestedCto().get(addSearchMappingRequest.getPropertyName()).getFilterValues().get(0))) {
                            filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.IS_NULL_LONG.getType(), addSearchMappingRequest.getPropertyName()));
                        } else if (metadata.getSecondaryType() == SupportedFieldType.STRING) {
                            filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.STRING_EQUAL.getType(), addSearchMappingRequest.getPropertyName()));
                            filterMapping.setFieldPath(new FieldPath().withTargetProperty(addSearchMappingRequest.getPropertyName() + "." + metadata.getForeignKeyProperty()));
                        } else {
                            filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.LONG_EQUAL.getType(), addSearchMappingRequest.getPropertyName()));
                            filterMapping.setFieldPath(new FieldPath().withTargetProperty(addSearchMappingRequest.getPropertyName() + "." + metadata.getForeignKeyProperty()));
                        }
                    }
                    break;
                case ADDITIONAL_FOREIGN_KEY:
                    int additionalForeignKeyIndexPosition = Arrays.binarySearch(addSearchMappingRequest.getPersistencePerspective().getAdditionalForeignKeys(), new ForeignKey(addSearchMappingRequest.getPropertyName(), null, null), new Comparator<ForeignKey>() {

                        @Override
                        public int compare(ForeignKey o1, ForeignKey o2) {
                            return o1.getManyToField().compareTo(o2.getManyToField());
                        }
                    });
                    ForeignKey foreignKey = null;
                    if (additionalForeignKeyIndexPosition >= 0) {
                        foreignKey = addSearchMappingRequest.getPersistencePerspective().getAdditionalForeignKeys()[additionalForeignKeyIndexPosition];
                    }
                    // default to just using a ForeignKeyRestrictionType.ID_EQ
                    if (metadata.getForeignKeyCollection()) {
                        if (ForeignKeyRestrictionType.COLLECTION_SIZE_EQ.toString().equals(foreignKey.getRestrictionType().toString())) {
                            filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.COLLECTION_SIZE_EQUAL.getType(), addSearchMappingRequest.getPropertyName()));
                            filterMapping.setFieldPath(new FieldPath());
                        } else {
                            filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.LONG.getType(), addSearchMappingRequest.getPropertyName()));
                            filterMapping.setFieldPath(new FieldPath().withTargetProperty(addSearchMappingRequest.getPropertyName() + "." + metadata.getForeignKeyProperty()));
                        }
                    } else if (CollectionUtils.isEmpty(addSearchMappingRequest.getRequestedCto().get(addSearchMappingRequest.getPropertyName()).getFilterValues()) || addSearchMappingRequest.getRequestedCto().get(addSearchMappingRequest.getPropertyName()).getFilterValues().get(0) == null || "null".equals(addSearchMappingRequest.getRequestedCto().get(addSearchMappingRequest.getPropertyName()).getFilterValues().get(0))) {
                        filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.IS_NULL_LONG.getType(), addSearchMappingRequest.getPropertyName()));
                    } else if (metadata.getSecondaryType() == SupportedFieldType.STRING) {
                        filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.STRING_EQUAL.getType(), addSearchMappingRequest.getPropertyName()));
                        filterMapping.setFieldPath(new FieldPath().withTargetProperty(addSearchMappingRequest.getPropertyName() + "." + metadata.getForeignKeyProperty()));
                    } else {
                        filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.LONG_EQUAL.getType(), addSearchMappingRequest.getPropertyName()));
                        filterMapping.setFieldPath(new FieldPath().withTargetProperty(addSearchMappingRequest.getPropertyName() + "." + metadata.getForeignKeyProperty()));
                    }
                    break;
                case ID:
                    switch(metadata.getSecondaryType()) {
                        case INTEGER:
                            filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.LONG_EQUAL.getType(), addSearchMappingRequest.getPropertyName()));
                            break;
                        case STRING:
                            filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.STRING_EQUAL.getType(), addSearchMappingRequest.getPropertyName()));
                            break;
                    }
                    break;
            }
        }
    }
    return MetadataProviderResponse.HANDLED;
}
Also used : IsNotNullPredicateProvider(org.broadleafcommerce.openadmin.server.service.persistence.module.criteria.predicate.IsNotNullPredicateProvider) IsNullPredicateProvider(org.broadleafcommerce.openadmin.server.service.persistence.module.criteria.predicate.IsNullPredicateProvider) FieldPath(org.broadleafcommerce.openadmin.server.service.persistence.module.criteria.FieldPath) FilterMapping(org.broadleafcommerce.openadmin.server.service.persistence.module.criteria.FilterMapping) ForeignKey(org.broadleafcommerce.openadmin.dto.ForeignKey) Field(java.lang.reflect.Field) EmptyFilterValues(org.broadleafcommerce.openadmin.server.service.persistence.module.EmptyFilterValues) Restriction(org.broadleafcommerce.openadmin.server.service.persistence.module.criteria.Restriction) BasicFieldMetadata(org.broadleafcommerce.openadmin.dto.BasicFieldMetadata) PersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.PersistenceException) FilterAndSortCriteria(org.broadleafcommerce.openadmin.dto.FilterAndSortCriteria)

Example 5 with FilterAndSortCriteria

use of org.broadleafcommerce.openadmin.dto.FilterAndSortCriteria in project BroadleafCommerce by BroadleafCommerce.

the class ProductCustomPersistenceHandler method fetch.

@Override
public DynamicResultSet fetch(PersistencePackage persistencePackage, CriteriaTransferObject cto, DynamicEntityDao dynamicEntityDao, RecordHelper helper) throws ServiceException {
    boolean legacy = parentCategoryLegacyModeService.isLegacyMode();
    // which seeks matching values in  allParentCategoryXRefs instead
    if (!legacy) {
        FilterAndSortCriteria fsc = cto.getCriteriaMap().get("defaultCategory");
        if (fsc != null) {
            List<String> filterValues = fsc.getFilterValues();
            cto.getCriteriaMap().remove("defaultCategory");
            List<Long> transformedValues = BLCCollectionUtils.collectList(filterValues, new TypedTransformer<Long>() {

                @Override
                public Long transform(Object input) {
                    return Long.parseLong(((String) input));
                }
            });
            CriteriaBuilder builder = dynamicEntityDao.getStandardEntityManager().getCriteriaBuilder();
            CriteriaQuery<Long> criteria = builder.createQuery(Long.class);
            Root<CategoryProductXrefImpl> root = criteria.from(CategoryProductXrefImpl.class);
            criteria.select(root.get("product").get("id").as(Long.class));
            List<Predicate> restrictions = new ArrayList<Predicate>();
            restrictions.add(builder.equal(root.get("defaultReference"), Boolean.TRUE));
            if (CollectionUtils.isNotEmpty(transformedValues)) {
                restrictions.add(root.get("category").get("id").in(transformedValues));
            }
            criteria.where(restrictions.toArray(new Predicate[restrictions.size()]));
            TypedQuery<Long> query = dynamicEntityDao.getStandardEntityManager().createQuery(criteria);
            List<Long> productIds = query.getResultList();
            productIds = sandBoxHelper.mergeCloneIds(ProductImpl.class, productIds.toArray(new Long[productIds.size()]));
            if (productIds.size() == 0) {
                return new DynamicResultSet(null, new Entity[0], 0);
            }
            if (productIds.size() <= queryLimit) {
                FilterMapping filterMapping = new FilterMapping().withFieldPath(new FieldPath().withTargetProperty("id")).withDirectFilterValues(productIds).withRestriction(new Restriction().withPredicateProvider(new PredicateProvider() {

                    @Override
                    public Predicate buildPredicate(CriteriaBuilder builder, FieldPathBuilder fieldPathBuilder, From root, String ceilingEntity, String fullPropertyName, Path explicitPath, List directValues) {
                        return explicitPath.in(directValues);
                    }
                }));
                cto.getAdditionalFilterMappings().add(filterMapping);
            } else {
                String joined = StringUtils.join(transformedValues, ',');
                LOG.warn(String.format("Skipping default category filtering for product fetch query since there are " + "more than " + queryLimit + " products found to belong to the selected default categories(%s). This is a " + "filter query limitation.", joined));
            }
        }
    }
    if (eagerFetchAssociations) {
        cto.getNonCountAdditionalFilterMappings().add(new FilterMapping().withDirectFilterValues(new EmptyFilterValues()).withRestriction(new Restriction().withPredicateProvider(new PredicateProvider() {

            @Override
            public Predicate buildPredicate(CriteriaBuilder builder, FieldPathBuilder fieldPathBuilder, From root, String ceilingEntity, String fullPropertyName, Path explicitPath, List directValues) {
                root.fetch("defaultSku", JoinType.LEFT);
                root.fetch("defaultCategory", JoinType.LEFT);
                return null;
            }
        })));
    }
    return helper.getCompatibleModule(OperationType.BASIC).fetch(persistencePackage, cto);
}
Also used : FieldPath(org.broadleafcommerce.openadmin.server.service.persistence.module.criteria.FieldPath) ArrayList(java.util.ArrayList) FilterMapping(org.broadleafcommerce.openadmin.server.service.persistence.module.criteria.FilterMapping) Predicate(javax.persistence.criteria.Predicate) EmptyFilterValues(org.broadleafcommerce.openadmin.server.service.persistence.module.EmptyFilterValues) CategoryProductXrefImpl(org.broadleafcommerce.core.catalog.domain.CategoryProductXrefImpl) List(java.util.List) ArrayList(java.util.ArrayList) FilterAndSortCriteria(org.broadleafcommerce.openadmin.dto.FilterAndSortCriteria) DynamicResultSet(org.broadleafcommerce.openadmin.dto.DynamicResultSet) CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) Path(javax.persistence.criteria.Path) FieldPath(org.broadleafcommerce.openadmin.server.service.persistence.module.criteria.FieldPath) From(javax.persistence.criteria.From) FieldPathBuilder(org.broadleafcommerce.openadmin.server.service.persistence.module.criteria.FieldPathBuilder) Restriction(org.broadleafcommerce.openadmin.server.service.persistence.module.criteria.Restriction) ProductImpl(org.broadleafcommerce.core.catalog.domain.ProductImpl) PredicateProvider(org.broadleafcommerce.openadmin.server.service.persistence.module.criteria.predicate.PredicateProvider) CriteriaTransferObject(org.broadleafcommerce.openadmin.dto.CriteriaTransferObject)

Aggregations

FilterAndSortCriteria (org.broadleafcommerce.openadmin.dto.FilterAndSortCriteria)20 FilterMapping (org.broadleafcommerce.openadmin.server.service.persistence.module.criteria.FilterMapping)10 BasicFieldMetadata (org.broadleafcommerce.openadmin.dto.BasicFieldMetadata)8 Entity (org.broadleafcommerce.openadmin.dto.Entity)8 FieldMetadata (org.broadleafcommerce.openadmin.dto.FieldMetadata)8 DynamicResultSet (org.broadleafcommerce.openadmin.dto.DynamicResultSet)7 ArrayList (java.util.ArrayList)6 PersistencePackageRequest (org.broadleafcommerce.openadmin.server.domain.PersistencePackageRequest)6 List (java.util.List)5 PersistencePerspective (org.broadleafcommerce.openadmin.dto.PersistencePerspective)5 FieldPath (org.broadleafcommerce.openadmin.server.service.persistence.module.criteria.FieldPath)5 Restriction (org.broadleafcommerce.openadmin.server.service.persistence.module.criteria.Restriction)5 Serializable (java.io.Serializable)4 CriteriaBuilder (javax.persistence.criteria.CriteriaBuilder)4 From (javax.persistence.criteria.From)4 Path (javax.persistence.criteria.Path)4 ServiceException (org.broadleafcommerce.common.exception.ServiceException)4 CriteriaTransferObject (org.broadleafcommerce.openadmin.dto.CriteriaTransferObject)4 ForeignKey (org.broadleafcommerce.openadmin.dto.ForeignKey)4 Property (org.broadleafcommerce.openadmin.dto.Property)4