Class CrudEntityHelper

  • All Implemented Interfaces:
    ChangeNotifier, PropagationIntegrator

    public class CrudEntityHelper
    extends Object
    implements ChangeNotifier, PropagationIntegrator
    Helper class responsible for providing basic CRUD support for business domain types. Using a repository instance and a DomainMapperManager instance, this helper is capable of mapping a business domain object to a repository specific domain object and performing persistence operations using that business domain instance and the repository instance. This helper is intended to be used in support of CrudEntityServices when interacting with Trackable repository domain. Most of the methods require supplying the TrackableRepository from those services.

    Typically, it is sufficient to extend BaseCrudEntityService in order to gain access to this helper; however, if a service implementation spans several repository types, it is recommend to inject this class instead:

     @Service
     public class DefaultMyService<P extends MyPayload> implements MyService<P> {
    
        private final CrudEntityHelper helper;
        private final MyTrackableRepository repository;
    
        public DefaultMyService(MyTrackableRepository repository, DomainMapperManager mapper) {
            this.helper = new CrudEntityHelper(mapper);
            this repository = repository;
        }
    
     }
     
    Author:
    Jeff Fischer, Nathan Moore (nathandmoore)
    • Method Detail

      • setNotificationManager

        @Autowired(required=false)
        public void setNotificationManager​(@Nullable
                                           com.broadleafcommerce.common.messaging.notification.NotificationManager notificationManager)
      • setSingleIndexRequestMessageFactory

        @Autowired(required=false)
        public void setSingleIndexRequestMessageFactory​(@Nullable
                                                        com.broadleafcommerce.common.messaging.notification.MessageFactory<SingleIndexRequest<Identifiable>> singleIndexRequestMessageFactory)
      • notify

        public void notify​(@Nullable
                           Trackable domain,
                           @Nullable
                           ContextInfo context,
                           @NonNull @NonNull
                           @NonNull com.broadleafcommerce.common.messaging.notification.NotificationStateRepository repository)
        Notify the system of the change. The default implementation invokes NotificationManager.handle(NotificationStateRepository, NotificationStateAware, String) for the following:
        Specified by:
        notify in interface ChangeNotifier
        Parameters:
        domain - The Trackable repository domain instance that was changed. May also wrap with a proxy exposing the MessageAdditionalInformationAware interface to engage message creation at MessageFactory.createMessage(Object, Map).
        context - context information around sandbox and author
        repository - The service responsible for making the state change. Usually a Repository instance.
      • prepare

        @Nullable
        public String prepare​(@Nullable
                              Trackable updated,
                              @Nullable
                              ContextInfo context,
                              @NonNull @NonNull
                              @NonNull OperationType operationType)
        Description copied from interface: PropagationIntegrator
        Prepare a Trackable entity for propagation, if applicable. Usually involves preparing ChangeDetail instances and FieldOverride instances contained therein.
        Specified by:
        prepare in interface PropagationIntegrator
        Parameters:
        updated - The Trackable repository domain instance that was changed
        context - Context information around sandbox and author
        operationType - The type of change operation performed
        Returns:
        The propagationId, or null if not applicable
      • readByContextId

        public <P> P readByContextId​(@NonNull
                                     String id,
                                     @Nullable
                                     ContextInfo context,
                                     @NonNull
                                     TrackableRepository<Trackable> repository)
        Read a single instance of an entity in the form of a business domain.
        Parameters:
        id - The context id for the entity. This is the id by which the business recognizes the item.
        context - Context information used to discriminate the correct version of an entity by context id when multiple verions may be available across sandboxes, catalogs and applications.
        repository - A TrackableRepository to perform the persistence operation
        Returns:
        The narrowed entity instance in the form of a business instance, or EntityMissingException if not available.
      • readAllByContextId

        public <P> Iterable<P> readAllByContextId​(@NonNull
                                                  Iterable<String> ids,
                                                  @Nullable
                                                  ContextInfo context,
                                                  @NonNull
                                                  TrackableRepository<Trackable> repository)
        Retrieve all business instances based on a list of context ids.
        Parameters:
        ids - A list of context ids for the entitys. This is the id by which the business recognizes the item.
        context - Context information used to discriminate the correct version of an entity by context id when multiple verions may be available across sandboxes, catalogs and applications.
        repository - A TrackableRepository to perform the persistence operation
        Returns:
        The narrowed iterable collection of data in the form of business instances
      • readAll

        public <P> org.springframework.data.domain.Page<P> readAll​(@NonNull
                                                                   org.springframework.data.domain.Pageable pageable,
                                                                   @Nullable
                                                                   ContextInfo context,
                                                                   @NonNull
                                                                   TrackableRepository<Trackable> repository)
        Read a page of narrowed instances in the form of the business instance.
        Parameters:
        pageable - The current page information
        context - Context information used to discriminate the correct version of an entity by context id when multiple verions may be available across sandboxes, catalogs and applications.
        repository - A TrackableRepository to perform the persistence operation
        Returns:
        The narrowed page of data in the form of business instances
      • readAll

        public <P> List<P> readAll​(@Nullable
                                   ContextInfo context,
                                   @NonNull
                                   TrackableRepository<Trackable> repository)
        Read a list of narrowed instances in the form of the business instance.
        Parameters:
        context - Context information used to discriminate the correct version of an entity by context id when multiple versions may be available across sandboxes, catalogs and applications.
        repository - A TrackableRepository to perform the persistence operation
        Returns:
        The narrowed list of data in the form of business instances
      • readAll

        public <P> List<P> readAll​(@NonNull
                                   org.springframework.data.domain.Sort sort,
                                   @Nullable
                                   ContextInfo context,
                                   @NonNull
                                   TrackableRepository<Trackable> repository)
        Read a list of narrowed instances in the form of the business instance. Also apply the given sort.
        Parameters:
        sort - The sort to be performed on the results
        context - Context information used to discriminate the correct version of an entity by context id when multiple versions may be available across sandboxes, catalogs and applications.
        repository - A TrackableRepository to perform the persistence operation
        Returns:
        The narrowed list of sorted data in the form of business instances
      • update

        public <P> P update​(@NonNull
                            String id,
                            @NonNull
                            P businessInstance,
                            @Nullable
                            ContextInfo context,
                            @NonNull
                            TrackableRepository<Trackable> repository)
        Update a single, narrowed instance of an entity based on a business instance containing relevant property values. See TrackableRepository for more information on entity persistence behavior in light of sandboxing and multitenant concerns.
        Parameters:
        id - The context id for the entity. This is the id by which the business recognizes the item.
        businessInstance - The payload type that domain class should be converted to. In general, the payload is what the rest API responds with.
        context - Context information used to discriminate the correct version of an entity by context id when multiple versions may be available across sandboxes, catalogs and applications.
        repository - A TrackableRepository to perform the persistence operation
        Returns:
        The updated, narrowed entity instance in the form of a payload instance, or EntityMissingException if not available.
        Throws:
        com.broadleafcommerce.common.error.validation.ValidationException - if the businessInstance failed validation
        EntityMissingException - if a managed instance corresponding to the given id could not be found
      • validateAllForUpdateAndThrowIfError

        protected <P> void validateAllForUpdateAndThrowIfError​(Iterable<P> businessInstances,
                                                               ContextInfo contextInfo)
      • applyUpdate

        @Nullable
        protected <P> org.springframework.data.util.Pair<P,​Trackable> applyUpdate​(String entityToUpdateId,
                                                                                        P change,
                                                                                        Map<String,​Trackable> foundEntitiesByContextId,
                                                                                        List<BulkPersistenceResponse.PersistenceFailure<P>> failures,
                                                                                        @Nullable
                                                                                        ContextInfo contextInfo)
        Parameters:
        entityToUpdateId - the context ID of the entity to which the change should be applied
        change - the changes to apply to the entity (only non-null values from this object will be applied)
        foundEntitiesByContextId - a map of entities by context ID. This will be used to get the entity to which the change will be applied.
        failures - if the update cannot be applied for whatever reason, the details of the failure will be added to this list
        contextInfo - context information surrounding sandboxing and multitenant state
        Returns:
        a pair of the business-domain and trackable representations of the entity after successfully applying the update. If the entity to update could not be found in foundEntitiesByContextId or if there was some error in mapping the updates, the return value will be null and the failure details will be added to failures.
      • validateAllForUpdate

        protected <P> void validateAllForUpdate​(List<org.springframework.data.util.Pair<P,​Trackable>> businessInstancesToValidate,
                                                ContextInfo contextInfo,
                                                List<org.springframework.data.util.Pair<P,​Trackable>> valid,
                                                List<BulkPersistenceResponse.PersistenceFailure<P>> failed)
        Validates the business instance within each pair for update. If it passes validation, the pair is added to the valid list. If it fails validation, a BulkPersistenceResponse.PersistenceFailure is created with the business instance and that failure is added to the failed list.
        Parameters:
        businessInstancesToValidate - a list of pairs containing the business instances to validate for update, and the trackable representation of the same instance
        contextInfo - the sandboxing/multitenant context for the persistence operation
        valid - the list to which successfully validated entities should be added
        failed - the list to which entities that failed validation should be added
      • replace

        public <P> P replace​(@NonNull
                             String id,
                             @NonNull
                             P businessInstance,
                             @Nullable
                             ContextInfo context,
                             TrackableRepository<Trackable> repository)
        Replace a single, narrowed instance of an entity based on a business instance containing relavant property values.
        Parameters:
        id - The context id for the entity. This is the id by which the business recognizes the item.
        businessInstance - The payload type that domain class should be converted to. In general, the payload is what the rest API responds with.
        context - Context information used to discriminate the correct version of an entity by context id when multiple versions may be available across sandboxes, catalogs and applications.
        repository - A TrackableRepository to perform the persistence operation
        Returns:
        The replaced, narrowed entity instance in the form of a payload instance, or EntityMissingException if not available.
        Throws:
        com.broadleafcommerce.common.error.validation.ValidationException - if the given businessInstance failed validation on replacement
        EntityMissingException - if a managed instance corresponding to the given id could not be found
      • validateAllForReplaceAndThrowIfError

        protected <P> void validateAllForReplaceAndThrowIfError​(Iterable<P> businessInstances,
                                                                ContextInfo contextInfo)
      • applyReplace

        @Nullable
        protected <P> Trackable applyReplace​(String entityToReplaceId,
                                             P replacement,
                                             Map<String,​Trackable> foundEntitiesByContextId,
                                             List<BulkPersistenceResponse.PersistenceFailure<P>> failures,
                                             @Nullable
                                             ContextInfo contextInfo)
        Parameters:
        entityToReplaceId - the context ID of the entity which needs to be replaced
        replacement - the replacement entity
        foundEntitiesByContextId - a map of entities by context ID. This will be used to get the entity to which the change will be applied.
        failures - if the update cannot be applied for whatever reason, the details of the failure will be added to this list
        contextInfo - context information surrounding sandboxing and multitenant state
        Returns:
        the trackable representation of the entity after successfully applying the replacement. If the entity to replace could not be found in foundEntitiesByContextId or if there was some error in mapping the change, the return value will be null and the failure details will be added to failures.
      • validateAllForReplace

        protected <P> void validateAllForReplace​(List<Update<P>> businessInstancesToValidate,
                                                 ContextInfo contextInfo,
                                                 List<Update<P>> valid,
                                                 List<BulkPersistenceResponse.PersistenceFailure<P>> failed)
        Validates the business instance within each Update for replacement. If it passes validation, the update is added to the valid list. If it fails validation, a BulkPersistenceResponse.PersistenceFailure is created with the business instance and that failure is added to the failed list.
        Parameters:
        businessInstancesToValidate - a list of updates containing the business instances to validate for replace
        contextInfo - the sandboxing/multitenant context for the persistence operation
        valid - the list to which successfully validated entities should be added
        failed - the list to which entities that failed validation should be added
      • create

        public <P> P create​(@NonNull
                            P businessInstance,
                            @Nullable
                            ContextInfo context,
                            @NonNull
                            TrackableRepository<Trackable> repository)
        Create an instance of an entity based on a business instance containing relavant property values.
        Parameters:
        businessInstance - The business domain instance. In general, the DomainMapperManager is responsible for converting to a repository platform type for persistence.
        context - Context information used to discriminate the correct version of an entity by context id when multiple versions may be available across sandboxes, catalogs and applications.
        repository - A TrackableRepository to perform the persistence operation
        Returns:
        The new entity instance in the form of a business type instance.
        Throws:
        com.broadleafcommerce.common.error.validation.ValidationException - if the given businessInstance could not be created
      • validateAllForCreateAndThrowIfError

        protected <P> void validateAllForCreateAndThrowIfError​(Iterable<P> businessInstances,
                                                               ContextInfo contextInfo)
      • validateAllForCreate

        protected <P> void validateAllForCreate​(List<P> businessInstancesToValidate,
                                                ContextInfo contextInfo,
                                                List<P> valid,
                                                List<BulkPersistenceResponse.PersistenceFailure<P>> failed)
        Validates each of the given business instances for creation. If it passes validation, it is added to the valid list. If it fails validation, a BulkPersistenceResponse.PersistenceFailure is created for it and that failure is added to the failed list.
        Parameters:
        businessInstancesToValidate - the business instances to validate for creation
        contextInfo - the sandboxing/multitenant context for the persistence operation
        valid - the list to which successfully validated entities should be added
        failed - the list to which entities that failed validation should be added
      • delete

        public void delete​(@NonNull
                           String id,
                           @Nullable
                           ContextInfo context,
                           @NonNull
                           TrackableRepository<Trackable> repository)
        Perform a delete operation on the entity identified by the context id. This could result in an archival, or a raw delete, depending on the result of processing through DomainMapper.deleteMap(Object, ContextInfo).
        Parameters:
        id - The context id for the entity. This is the id by which the business recognizes the item.
        context - Context information used to discriminate the correct version of an entity by context id when multiple verions may be available across sandboxes, catalogs and applications.
        repository - A TrackableRepository to perform the persistence operation
        Throws:
        EntityMissingException - if no instance was found in the backing store corresponding to id
      • updateSort

        public <P> P updateSort​(@NonNull
                                SortPositionRequest sortPositionRequest,
                                @Nullable
                                ContextInfo context,
                                @NonNull
                                TrackableRepository<Trackable> repository,
                                @NonNull
                                SortPositionStrategy<P> sortPositionStrategy)
        Apply a sort field value change
        Parameters:
        sortPositionRequest - Information about the item being moved and the position to which it's moving
        context - context information used to discriminate the correct version of an entity by context id when multiple versions may be available across sandboxes, catalogs and applications.
        repository - A TrackableRepository to perform the persistence operation
        sortPositionStrategy - The SortPositionStrategy to use when updating the sort
        Returns:
        The updated business domain
      • transform

        @NonNull
        public org.springframework.data.domain.Sort transform​(@Nullable
                                                              org.springframework.data.domain.Sort sort,
                                                              @NonNull
                                                              TrackableRepository<Trackable> repository)
        Transforms the given sort from properties targeting the projection layer into a Sort that targets properties at the domain layer
        Parameters:
        sort - the projection-targeted sort, can be null
        repository - A TrackableRepository form which to get information about the entity's type
        Returns:
        null if sort is null, otherwise a Sort targeting the repository provider domain
        See Also:
        SortTransformer
      • transformSort

        @NonNull
        public org.springframework.data.domain.Pageable transformSort​(@NonNull
                                                                      org.springframework.data.domain.Pageable pageable,
                                                                      @NonNull
                                                                      TrackableRepository<Trackable> repository)
        Transforms the sort inside of a Pageable (if applicable). Convert the sort from properties targeting the projection layer into a Sort that targets properties at the domain layer
        Parameters:
        pageable - The Pageable containing the Sort instance to convert
        repository - A TrackableRepository from which to get information about the entity's type
        Returns:
        The Pageable exposing the converted Sort instance
      • convertToPersistentDomain

        public <P> Trackable convertToPersistentDomain​(P businessInstance,
                                                       Class<Trackable> persistentType,
                                                       ContextInfo context)
        Convenience method to use the mapper to convert a business domain instance to its persistent equivalent.
        Type Parameters:
        P - The business domain type
        Parameters:
        businessInstance - The business domain instance
        persistentType - The persistent domain type
        context - Context information used to discriminate the correct version of an entity by context id when multiple verions may be available across sandboxes, catalogs and applications.
        Returns:
        The persistent domain instance equivalent to the given business instance.
        Throws:
        IllegalArgumentException - Thrown if the business type could not be determined
      • convertFromPersistentDomain

        public <P> P convertFromPersistentDomain​(Trackable domain,
                                                 ContextInfo contextInfo)
        Convenience method to use the mapper to convert a persistent domain instance to its business equivalent.
        Parameters:
        domain - The persistent domain instance
        Returns:
        The business domain instance equivalent to the given persistent instance.
      • getNotificationManager

        @Nullable
        protected com.broadleafcommerce.common.messaging.notification.NotificationManager getNotificationManager()
      • setPropagationManager

        @Autowired
        public void setPropagationManager​(@Nullable
                                          PropagationManager propagationManager)
      • setTypeFactory

        @Autowired
        public void setTypeFactory​(@Nullable
                                   com.broadleafcommerce.common.extension.TypeFactory typeFactory)