Java Spring Security #PostFilter performance - java

My Java Spring application, which uses ACLs, has a service method to retrieve all the objects corresponding to a given user:
#Override
#PostFilter("hasPermission(filterObject, 'READ') or hasPermission(filterObject, 'ADMINISTRATION')")
public List<SomeClass> findAll() {
return SomeClassRepository.findAll();
}
Unfortunately, where there are many objects in the database, this method takes too much time to complete (over 1 second). Probably because it will first fetch all the objects from the database, and then filter them one by one in memory. How can I optimize this without losing the benefits of Spring ACLs?
Edit: the solution I came up with for now is to create repositories for the acl_sid and acl_entry repositories and to fetch the IDs of the object of interest through those repositories. This gives me a 10x improvement in execution time compared to the method above. The new code looks like this:
#Override
#PostFilter("hasPermission(filterObject, 'READ') or hasPermission(filterObject, 'ADMINISTRATION')")
public List<SomeClass> findAll() {
List<SomeClass> result = new ArrayList<SomeClass>();
Long userId = (Long) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
AclSid sid = aclSidRepository.findBySid(Long.toString(userId));
List<AclEntry> aclEntries = aclEntryRepository.findBySid(sid);
for (AclEntry aclEntry : aclEntries) {
AclObjectIdentity aclObjectIdentity = aclEntry.getAclObjectIdentity();
AclClass aclClass = aclObjectIdentity.getObjectIdClass();
if (aclClass.getClassName().equals("com.company.app.entity.SomeClass")) {
Optional<SomeClass> SomeClass = SomeClassRepository
.findById(aclObjectIdentity.getObjectIdIdentity());
if (SomeClass.isPresent()) {
result.add(SomeClass.get());
}
}
}
return result;
}

As Spring filters the information in memory the performance will depend on the actual number of results: if there is a large amount of them, I am afraid that perhaps only caching your repository results before filtering the information may be a suitable solution.
To deal with the problem, you can filter the results at the database level. Two approaches come to my mind:
Either use Specifications, and filter the results at the database level taking into account the information about the principal exposed by Spring Security SecurityContext and including the necessary filter Predicates in order to restrict the information returned.
Or, if you are using Hibernate, use entity filters to again, based on the information about the principal exposed by Spring Security, apply the necessary data restrictions. Please, see this related SO question which provides great detail about the solution.
Please, consider for instance the use case of the Spring Data Specifications.
Instead of SomeClass, let's suppose that we are working with bank accounts. Let's create the corresponding entity:
#Entity
public class BankAccount {
#Id
private String accountNumber;
private Float balance;
private String owner;
private String accountingDepartment;
//...
}
And the corresponding repository:
public interface BankAccountRepository extends Repository<BankAccount, String>, JpaSpecificationExecutor<BankAccount, String> {
}
In order to filter the information depending on the user who is performing the query, we can define an utility method that, based on the user permissions, returns a List of Predicates that we can add later to the ones we are using in a certain Specification when filtering the bank accounts:
public static List<Predicate> getPredicatesForRestrictingDataByUser(Root<BankAccount> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
// I realized in your edit that you are returning the user id instead of the user object.
// There is nothing wrong with it but you are losing a valuable information: if you provide
// a convenient UserDetails implementation you can have direct access to the authorities a user has, etc
User user = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
// Restrict data based on actual permissions
// If the user is an admin, we assume that he/she can see everything, and we will no return any predicates
if (hasAuthority(user, 'ADMINISTRATION')) {
return Collections.emptyList();
}
// Let's introduce the accounting manager role.
// Suppose that an accounting manager can see all the accounts in his/her department
if (hasAuthority(user, 'ACCOUNTING_MANAGER')) {
return Collections.singletonList(cb.equal(root.get(BankAccount_.accountingDeparment), user.getDepartment()))
}
// In any other case, a user can only see the bank account if he/she is the account owner
return Collections.singletonList(cb.equal(root.get(BankAccount_.owner), user.getId()));
}
Where hasAuthority can look like:
public static boolean hasAuthority(User user, String... authorities) {
if (user instanceof UserDetails) {
for (String authority : authorities) {
return authentication.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.findAny(a -> a.equals(authority))
.isPresent();
}
}
return false;
}
Now, use these methods when constructing your Specifications. Consider for instance:
public static Specification<BankAccount> getBankAccounts(final BankAccountFilter filterCriteria) {
return new Specification<BankAccount>() {
#Override
public Predicate toPredicate(Root<BankAccount> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
List<Predicate> predicates = new ArrayList<Predicate>();
// Build your predicate list according to the user provided filter criteria
String accountNumber = filterCriteria.getAccountNumber();
if (accountNumber != null) {
predicates.add(cb.equal(root.get(BankAccount_.accountNmber), accountNumber);
}
//...
// And now, restrict the information a user can see
// Ideally, define getPredicatesForRestrictingDataByUser in a generic class more suitable for being reused
List<Predicate> predicatesForRestrictingDataByUser = getPredicatesForRestrictingDataByUser(root, query, cb);
predicates.addAll(predicatesForRestrictingDataByUser);
Predicate predicate = cb.and(predicates.toArray(new Predicate[predicates.size()]));
return predicate;
}
};
}
Please, forgive me for the simple use case, but I hope you get the idea.
The solution proposed in his comment by #OsamaAbdulRehman looks interesting as well, although I honestly never tested it.

Related

Spring QueryDsl pagination filter by ACL permissions

Let's assume the following Spring JPA based repository with QueryDsl support.
#Repository
public interface TeamRepository extends JpaRepository<Team, Long>, QuerydslPredicateExecutor<Team> {
}
The application uses Access Control Lists (ACL) in service layer for checking permission for individual resources using #PreAuthorize(hasPermission(#id, 'Team', 'READ') for example.
I want to allow a user to request all teams for which he has read permission. I tried to use
#PostFilter(hasPermission(filterObject, 'READ'), that works pretty good as long as I use Iterable<Team> findAll(Predicate predicate). But when I try to make use of pagination, #PostFilter seems to throw an exception.
java.lang.IllegalArgumentException: Filter target must be a collection, array, or stream type, but was Page 1 of 0 containing UNKNOWN instances
The official Spring Security Reference Documentation recommends to write a custom query using #Query which supports pagination.
How could I write such a complex query which supports QueryDsl's Predicate, Pagination and filtering based on permissions?
Approach 03/24/20
In another forum I came across the following QueryDsl based approach: Instead of a native or custom query, the ACL tables are mapped as #Immutable JPA entities, thus generating Q classes and using them to filter for permissions manually.
#Entity
#Immutable
#Table(name = "acl_object_identity")
public class AclObjectIdentity implements Serializable {
...
}
How could you do this using a custom repository, extending QueryDslRepositorySupport, so that the part of the query that checks permissions is automatically appended and hidden inside of a custom repository implementation?
Based on this approach I have developed a possibility which is more a dirty workaround than a solution.
The approach is to add an additional permission filter to existing predicates, for example those generated by web support. For this, the ACL tables must first be mapped as #Immutable JPA entities so that QueryDsl can generate the corresponding Q classes.
Such predicates to which an ACL Permission Filter should be appended are marked with the following annotation.
public Page<PostDTO> findAll(#QueryDslAclPermission(root = Post.class, permission = "READ") Predicate predicate, Pageable pageable) {
...
}
This annotation holds primarily meta information about the domain type that are required for building the filter query.
#Retention(RetentionPolicy.RUNTIME)
#Target({ElementType.PARAMETER, ElementType.TYPE})
public #interface QueryDslAclPermission {
Class<?> root();
String permission();
String identifier() default "id";
}
The actual filter query is generated and appended using the the following class and Spring's AOP Module.
#Aspect
#Component
public class QueryDslAclPermissionAspect {
private PermissionFactory permissionFactory;
#Autowired
public QueryDslAclPermissionAspect(PermissionFactory permissionFactory) {
this.permissionFactory = permissionFactory;
}
#Around(value = "execution(* *(.., #QueryDslAclPermission (*), ..))")
public Object addPermissionFilter(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Parameter[] parameters = method.getParameters();
Object[] arguments = joinPoint.getArgs();
for(int index = 0; index < parameters.length; ++index) {
if(parameters[index].getType().equals(Predicate.class) &&
parameters[index].isAnnotationPresent(QueryDslAclPermission.class)) {
Predicate predicate = (Predicate) arguments[index];
QueryDslAclPermission aclPermission = parameters[index].getAnnotation(QueryDslAclPermission.class);
arguments[index] = addPermissionFilter(predicate, aclPermission);
}
}
return joinPoint.proceed(arguments);
}
private Predicate addPermissionFilter(Predicate predicate, QueryDslAclPermission aclPermission) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if(null == authentication || !authentication.isAuthenticated()) {
throw new IllegalStateException("Permission filtering not possible for unauthenticated principal");
}
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
PrincipalSid principalSid = new PrincipalSid(userDetails.getUsername());
NumberPath<Long> idPath = new PathBuilderFactory().create(aclPermission.root())
.getNumber(aclPermission.identifier(), Long.class);
return idPath.in(selectPermitted(aclPermission.root(), principalSid,
permissionFactory.buildFromName(aclPermission.permission()))).and(predicate);
}
private JPQLQuery<Long> selectPermitted(Class<?> targetType, PrincipalSid sid, Permission permission) {
return selectAclEntry(targetType, sid, permission)
.select(QAclEntry.aclEntry.aclObjectIdentity.objectIdIdentity);
}
private JPQLQuery<AclEntry> selectAclEntry(Class<?> targetType, PrincipalSid sid, Permission permission) {
return new JPAQuery<AclEntry>().from(QAclEntry.aclEntry)
.where(QAclEntry.aclEntry.aclObjectIdentity.id.in(selectAclObjectIdentity(targetType)
.select(QAclObjectIdentity.aclObjectIdentity.id))
.and(QAclEntry.aclEntry.aclSid.id.eq(selectAclSid(sid).select(QAclSid.aclSid.id)))
.and(QAclEntry.aclEntry.mask.eq(permission.getMask())));
}
private JPQLQuery<AclObjectIdentity> selectAclObjectIdentity(Class<?> targetType) {
return new JPAQuery<AclObjectIdentity>().from(QAclObjectIdentity.aclObjectIdentity)
.where(QAclObjectIdentity.aclObjectIdentity.objectIdClass.id.eq(selectAclClass(targetType)
.select(QAclClass.aclClass.id)));
}
private JPQLQuery<AclSid> selectAclSid(PrincipalSid sid) {
return new JPAQuery<AclSid>().from(QAclSid.aclSid)
.where(QAclSid.aclSid.sid.eq(sid.getPrincipal()));
}
private JPQLQuery<AclClass> selectAclClass(Class<?> targetType) {
return new JPAQuery<AclClass>().from(QAclClass.aclClass)
.where(QAclClass.aclClass.className.eq(targetType.getSimpleName()));
}
}
Edit 09/20/2022
A more generic approach based on JPA's Specification<T> and a custom repository implementation can be found in my GitHub Gist. It is decoupled from QueryDsl.

Spring Boot and JPA Repository -- how to filter a GET by ID

I'm rewriting an application, this time using a RESTful interface from Spring. I'm presuming that server-side authorization is best. That is:
Supppose user 1 works this REST repository. He/she accesses mysite.com/heroes/1 and gets the (id = 1) hero from the hero table.
User 2 doesn't have rights to see the (id = 1) hero, but could craft a cURL statement to try anyway. I claim the server should prevent user 2 from accessing the (id = 1) hero.
I believe that the server can extract a JWT payload that gives me the user name or password (I put it in there). From that payload the server fetches the user's account and knows what heroes he/she is entitled to see.
I have already accomplished this goal through services and DAO classes. However, the Spring Boot and JPA tutorials I see promote using CrudRepository implementations to reduce coding. I'd like to know how to do my filtering using this technology.
Here is an example from the web:
#RepositoryRestResource(collectionResourceRel = "heroes", path = "heroes")
public interface HeroRepository extends CrudRepository<Hero, Long> {
}
When mysite.com/heroes/1 is accessed it automagically returns the data from hero (id = 1). I'd like to instruct it to let me choose which ID values to permit. That is, at runtime a query parameter is provided to it through code.
As a test I provided this code:
#RepositoryRestResource(collectionResourceRel = "heroes", path = "heroes")
public interface HeroRepository extends CrudRepository<Hero, Long> {
#Query ("from Hero h where id in (1, 3, 5)")
public Hero get();
}
However, it doesn't block mysite.com/heroes/2 from returning the (id = 2) hero.
How do I get to my desired goal?
Thanks, Jerome.
UPDATE 5/13, 5:50 PM
My request is being misunderstood, so I further explain my intent.
Users 1 and 2 are ordinary users, accessing their accounts.
Each user must be confined to his/her own account.
A user can't cheat by crafting requests for other peoples' data.
Thus the need for the server to extract a user ID, or such, from a JWT token and apply it in code to whatever causes the /heroes query to work.
My original example originated with this tutorial. In it the only Java classes are Hero and HeroRepository. There are no explicit classes for DAO, services or controllers. The included Spring libraries let all of the /heroes fetching occur without further coding.
Thanks again for all of your interest and help. Jerome.
You can create a custom #Query, that uses informations (here: id) of the logged in user. With this solution an user have only access to an entity with the same id as he has.
#Override
#Query("SELECT h FROM Hero h WHERE h.id=?1 AND h.id=?#{principal.id}")
public Hero findOne(Long id);
You need to enable SpEl for #Query (link) and create an custom UserDetailsService (link) with custom UserDetails, that contains the id of the user, so you can do principal.id.
In the same way you should secure the findAll() method.
I have created HeroRepository to resolve all the queries up to my understanding.
I'd like to instruct it to let me choose which ID values to permit.
You can achieve the same using.
List<Hero> findByIdIn(List<Long> ids);
Or, if you prefer Query
#Query("SELECT H FROM Hero H WHERE H.id IN :ids")
List<Hero> alternativeFindByIdIn(#Param("ids") List<Long> ids);
it doesn't block mysite.com/heroes/2 from returning the (id = 2) hero.
I cannot see your Controller/Service methods, so I am assuming that findOne() is being called. You can prevent it using..
// Disallow everybody to use findOne()
default Hero findOne(Long id) {
throw new RuntimeException("Forbidden !!");
}
OR, if you want more control over your method invocations, you can also use #PreAuthorize from spring-security.
// Authorization based method call
#PreAuthorize("hasRole('ADMIN')")
Optional<Hero> findById(Long id);
Summary
public interface HeroRepository extends CrudRepository<Hero, Long> {
// Disallow everybody to use findOne()
default Hero findOne(Long id) {
throw new RuntimeException("Forbidden !!");
}
// If u want to pass ids as a list
List<Hero> findByIdIn(List<Long> ids);
// Alternative to above one
#Query("SELECT H FROM Hero H WHERE H.id IN :ids")
List<Hero> alternativeFindByIdIn(#Param("ids") List<Long> ids);
// Authorization based method call
#PreAuthorize("hasRole('ADMIN')")
Optional<Hero> findById(Long id);
}
PS: Note that I am returning Optional<Hero> from the method. Optional.empty() will be returned if query produces no results. This will force us to check if the value is present before doing any operation, thereby avoiding NullPointerException.
use this code for Controller : -
#RestController
#RequestMapping("/cities")
public class CityController {
private static final Logger logger = LoggerFactory.getLogger(CityController.class);
#Autowired
private CityService cityService;
#RequestMapping(value = "/{id}", method = RequestMethod.GET)
public RestResponse find(#PathVariable("id") Long id) {
.
.
}
use below code for Repo :-
public interface CityRepo extends JpaRepository<FCity, Long> {
#Query("select e from FCity e where e.cityId = :id")
FCity findOne(#Param("id") Long id);
}
use below code for service :-
#Service
#Transactional
public class CityService {
#Autowired(required = true)
private CityRepo cityRepo;
public FCity findOne(Long id) {
return cityRepo.findOne(id);
}
}

JDBI getting argument class in ResultSetMapper

I am using Dropwizard with JDBI. I have a typical dao for user data:
public interface UserDao
{
#SqlQuery("select * from users where role = :id")
#Mapper(UserMapper.class)
String findNameById(#BindBean Role role);
}
The user itself has an attribute with a Role type:
class User
{
private Role role;
/* the rest: other attributes, getters, setters, etc. */
}
Role is contained in another table called roles. Now, I need to map Role in the mapper, but I do not want to change the SELECT ... statement to add the JOIN roles ... part. We all know how joins affect queries and in the long run I'd like to avoid any joins if possible.
I know, that ResultSetMapper interface has a map() method, which gets a StatementContext passed to it. That context has a getBinding() method, which returns a Binding class with all the data I need:
named = {HashMap$Node#1230} size = 3
0 = {HashMap$Node#1234} "id" -> "1"
1 = {HashMap$Node#1235} "name" -> "TestRole"
2 = {HashMap$Node#1236} "class" -> "class com.example.Role"
But that class com.example.Role is not an instance of Role, it's an instance of Argument and I can't work with it.
So, is there a way to get that Role argument and I just don't see it or do I have to instantiate it (again...) from the binding arguments (obviously they are there as debugger shows)?
I finally solved it by using a custom binder. First, I modified UserDao to use #BindRole instead of #BindBean.
Next, I had to create the binder for the role. Here the role is bound manually on separate values:
#BindingAnnotation(BindRole.RoleBinderFactory.class)
#Retention(RetentionPolicy.RUNTIME)
#Target({ElementType.PARAMETER})
public #interface BindRole
{
public static class RoleBinderFactory implements BinderFactory
{
public Binder build(Annotation annotation)
{
return new Binder<BindRole, User>()
{
public void bind(SQLStatement q, BindRole bind, Role role)
{
q.bind("id", role.getId());
q.bind("name", role.getName());
q.define("role", role);
}
};
}
}
}
Notice the define() method, it is responsible for setting attributes in StatementContext, so don't overlook it.
Next, in the mapper I just have to get the Role with getArgument():
Role role = new Role();
role.setId(1);
role.setName("TestRole");
Role r = (Role) statementContext.getAttribute("role");
boolean equals = e.equals(role);
In the debugger equals is shown as true, so problem solved. Woohoo.

Filtering database rows with spring-data-jpa and spring-mvc

I have a spring-mvc project that is using spring-data-jpa for data access. I have a domain object called Travel which I want to allow the end-user to apply a number of filters to it.
For that, I've implemented the following controller:
#Autowired
private TravelRepository travelRep;
#RequestMapping("/search")
public ModelAndView search(
#RequestParam(required= false, defaultValue="") String lastName,
Pageable pageable) {
ModelAndView mav = new ModelAndView("travels/list");
Page<Travel> travels = travelRep.findByLastNameLike("%"+lastName+"%", pageable);
PageWrapper<Travel> page = new PageWrapper<Travel>(travels, "/search");
mav.addObject("page", page);
mav.addObject("lastName", lastName);
return mav;
}
This works fine: The user has a form with a lastName input box which can be used to filter the Travels.
Beyond lastName, my Travel domain object has a lot more attributes by which I'd like to filter. I think that if these attributes were all strings then I could add them as #RequestParams and add a spring-data-jpa method to query by these. For instance I'd add a method findByLastNameLikeAndFirstNameLikeAndShipNameLike.
However, I don't know how should I do it when I need to filter for foreign keys. So my Travel has a period attribute that is a foreign key to the Period domain object, which I need to have it as a dropdown for the user to select the Period.
What I want to do is when the period is null I want to retrieve all travels filtered by the lastName and when the period is not null I want to retrieve all travels for this period filtered by the lastName.
I know that this can be done if I implement two methods in my repository and use an if to my controller:
public ModelAndView search(
#RequestParam(required= false, defaultValue="") String lastName,
#RequestParam(required= false, defaultValue=null) Period period,
Pageable pageable) {
ModelAndView mav = new ModelAndView("travels/list");
Page travels = null;
if(period==null) {
travels = travelRep.findByLastNameLike("%"+lastName+"%", pageable);
} else {
travels = travelRep.findByPeriodAndLastNameLike(period,"%"+lastName+"%", pageable);
}
mav.addObject("page", page);
mav.addObject("period", period);
mav.addObject("lastName", lastName);
return mav;
}
Is there a way to do this without using the if ? My Travel has not only the period but also other attributes that need to be filtered using dropdowns !! As you can understand, the complexity would be exponentially increased when I need to use more dropdowns because all the combinations'd need to be considered :(
Update 03/12/13: Continuing from M. Deinum's excelent answer, and after actually implementing it, I'd like to provide some comments for completeness of the question/asnwer:
Instead of implementing JpaSpecificationExecutor you should implement JpaSpecificationExecutor<Travel> to avoid type check warnings.
Please take a look at kostja's excellent answer to this question
Really dynamic JPA CriteriaBuilder
since you will need to implement this if you want to have correct filters.
The best documentation I was able to find for the Criteria API was http://www.ibm.com/developerworks/library/j-typesafejpa/. This is a rather long read but I totally recommend it - after reading it most of my questions for Root and CriteriaBuilder were answered :)
Reusing the Travel object was not possible because it contained various other objects (who also contained other objects) which I needed to search for using Like - instead I used a TravelSearch object that contained the fields I needed to search for.
Update 10/05/15: As per #priyank's request, here's how I implemented the TravelSearch object:
public class TravelSearch {
private String lastName;
private School school;
private Period period;
private String companyName;
private TravelTypeEnum travelType;
private TravelStatusEnum travelStatus;
// Setters + Getters
}
This object was used by TravelSpecification (most of the code is domain specific but I'm leaving it there as an example):
public class TravelSpecification implements Specification<Travel> {
private TravelSearch criteria;
public TravelSpecification(TravelSearch ts) {
criteria= ts;
}
#Override
public Predicate toPredicate(Root<Travel> root, CriteriaQuery<?> query,
CriteriaBuilder cb) {
Join<Travel, Candidacy> o = root.join(Travel_.candidacy);
Path<Candidacy> candidacy = root.get(Travel_.candidacy);
Path<Student> student = candidacy.get(Candidacy_.student);
Path<String> lastName = student.get(Student_.lastName);
Path<School> school = student.get(Student_.school);
Path<Period> period = candidacy.get(Candidacy_.period);
Path<TravelStatusEnum> travelStatus = root.get(Travel_.travelStatus);
Path<TravelTypeEnum> travelType = root.get(Travel_.travelType);
Path<Company> company = root.get(Travel_.company);
Path<String> companyName = company.get(Company_.name);
final List<Predicate> predicates = new ArrayList<Predicate>();
if(criteria.getSchool()!=null) {
predicates.add(cb.equal(school, criteria.getSchool()));
}
if(criteria.getCompanyName()!=null) {
predicates.add(cb.like(companyName, "%"+criteria.getCompanyName()+"%"));
}
if(criteria.getPeriod()!=null) {
predicates.add(cb.equal(period, criteria.getPeriod()));
}
if(criteria.getTravelStatus()!=null) {
predicates.add(cb.equal(travelStatus, criteria.getTravelStatus()));
}
if(criteria.getTravelType()!=null) {
predicates.add(cb.equal(travelType, criteria.getTravelType()));
}
if(criteria.getLastName()!=null ) {
predicates.add(cb.like(lastName, "%"+criteria.getLastName()+"%"));
}
return cb.and(predicates.toArray(new Predicate[predicates.size()]));
}
}
Finally, here's my search method:
#RequestMapping("/search")
public ModelAndView search(
#ModelAttribute TravelSearch travelSearch,
Pageable pageable) {
ModelAndView mav = new ModelAndView("travels/list");
TravelSpecification tspec = new TravelSpecification(travelSearch);
Page<Travel> travels = travelRep.findAll(tspec, pageable);
PageWrapper<Travel> page = new PageWrapper<Travel>(travels, "/search");
mav.addObject(travelSearch);
mav.addObject("page", page);
mav.addObject("schools", schoolRep.findAll() );
mav.addObject("periods", periodRep.findAll() );
mav.addObject("travelTypes", TravelTypeEnum.values());
mav.addObject("travelStatuses", TravelStatusEnum.values());
return mav;
}
Hope I helped!
For starters you should stop using #RequestParam and put all your search fields in an object (maybe reuse the Travel object for that). Then you have 2 options which you could use to dynamically build a query
Use the JpaSpecificationExecutor and write a Specification
Use the QueryDslPredicateExecutor and use QueryDSL to write a predicate.
Using JpaSpecificationExecutor
First add the JpaSpecificationExecutor to your TravelRepository this will give you a findAll(Specification) method and you can remove your custom finder methods.
public interface TravelRepository extends JpaRepository<Travel, Long>, JpaSpecificationExecutor<Travel> {}
Then you can create a method in your repository which uses a Specification which basically builds the query. See the Spring Data JPA documentation for this.
The only thing you need to do is create a class which implements Specification and which builds the query based on the fields which are available. The query is build using the JPA Criteria API link.
public class TravelSpecification implements Specification<Travel> {
private final Travel criteria;
public TravelSpecification(Travel criteria) {
this.criteria=criteria;
}
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
// create query/predicate here.
}
}
And finally you need to modify your controller to use the new findAll method (I took the liberty to clean it up a little).
#RequestMapping("/search")
public String search(#ModelAttribute Travel search, Pageable pageable, Model model) {
Specification<Travel> spec = new TravelSpecification(search);
Page<Travel> travels = travelRep.findAll(spec, pageable);
model.addObject("page", new PageWrapper(travels, "/search"));
return "travels/list";
}
Using QueryDslPredicateExecutor
First add the QueryDslPredicateExecutor to your TravelRepository this will give you a findAll(Predicate) method and you can remove your custom finder methods.
public interface TravelRepository extends JpaRepository<Travel, Long>, QueryDslPredicateExecutor<Travel> {}
Next you would implement a service method which would use the Travel object to build a predicate using QueryDSL.
#Service
#Transactional
public class TravelService {
private final TravelRepository travels;
public TravelService(TravelRepository travels) {
this.travels=travels;
}
public Iterable<Travel> search(Travel criteria) {
BooleanExpression predicate = QTravel.travel...
return travels.findAll(predicate);
}
}
See also this bog post.

Interface method that has different parameters in Java

Looking for some guidance on designing some code in Java.
Currently I have something like this....
#Service
class SomeService {
#Autowired
private FilterSoldOut filterSoldOut;
#Autowired
private FilterMinPriceThreshold filterMinPriceThreshold;
public List<Product> getProducts() {
List<Product> products = //...code to get some products
// Returns list of in-stock products
products = filterSoldOut.doFilter(products);
// Returns list of products above min price
products = filterMinPriceThreshold.doFilter(minPrice, products);
return products;
}
}
What I would like to be able to do is create a Filter interface with a doFilter method and then in SomeService create a List filters, which is autowired by Spring. Then in the getProducts method I can iterate the filters list and invoke doFilter. This way in the future I can, create new classes that implement the Filter interface and add them to the list via Spring configuration, and have the new filter applied without having to change the code.
But, the problem is that the parameters to the doFilter method can be different. I've read about the Command Pattern, and the Visitor Pattern but they don't quite seem to fit the bill.
Can anyone suggest a good pattern to achieve what I've described?
Thanks.
There are many ways to do this. Some are complicated, some are simpler. The simplest one would be to use varargs or an array of Object elements. The problem here is that you have to cast each objetc to its proper type in order to use them and that can be a little tricky if there are multiple types in an unknown order.
Another option is to use a Map<String,Object> (which you can wrap in a class of your own if required, something lile FilterParams) that stores parameters based on a name, and you can then obtain them and cast them accordingly.
Edit
Considering that the parameters vary on runtime, you'll need someone "well informed" about the current configuration.
Not pattern-wise but I'd rather keep it simple without using too many fancy names. What about introducing a FilterConfigurator that has a simple overloaded method configure that recieves the particular filter and configures it based on its type?. This configurator is the informed entity that knows the current values for those parameters.
The goal is to rid Service from the responsibility of configuring a filter.
In addition, if you create your Filter class, you'll be able to implement a single doFilter that you can invoke without changes.
There's another Idea... and it involves a FilterFactory that creates and initializes filters, thus having a filter 100% configured from scratch. This factory can rely on the very same FilterConfigurer or do it itself.
old:
I'd suggest you setting the filter state at construction time or at
least before you getProducts().
In your example with the two filters one of them is (probably)
checking a database for availability of the product and the other one
is comparing the product's price to some preset value. This value
(minPrice) is known before the filter is applied. It can
also be said that the filter depends on it, or that it's part of the
filter's state. Therefore I'd recommend you putting the
minPrice inside the filter at construction time (or via a
setter) and then only pass the list of products you want to filter.
Use the same pattern for your other filters.
new suggestion (came up with it after the comments):
You can create a single object (AllFiltersState) that holds all the values for all the filters. In your controller set whatever criteria you need in this object (minPrice, color, etc.) and pass it to every filter along the products - doFilter(allFiltersState, products).
As Cris say you can use next function definition:
public List<Product> doFilter(Object...args) {
if (args.length != 2)
throw new IllegalArgumentException();
if (! (args[0] instanceof String))
throw new IllegalArgumentException();
if (! (args[2] instanceof Integer))
throw new IllegalArgumentException();
String stringArgument = (String) args[0];
Integer integerArgument = (Integer) args[1];
// your code here
return ...;
}
or with command pattern:
public interface Command {
}
public class FirstCommand implements Command {
private String string;
// constructor, getters and setters
}
public class SecondCommand implements Command {
private Integer integer;
// constructor, getters and setters
}
// first service function
public List<Product> doFilter(Command command) {
if (command instanceof FirstCommand)
throw new IllegalArgumentException();
FirstCommand firstCommand = (FirstCommand) command;
return ...;
}
// second service function
public List<Product> doFilter(Command command) {
if (command instanceof SecondCommand)
throw new IllegalArgumentException();
SecondCommand secondCommand = (SecondCommand) command;
return ...;
}
EDIT:
Ok, i understand your question. And think you can create various session scoped filters.
#Service
class SomeService {
#Autowired(required = false)
private List<Filter> filters;
public List<Product> getProducts() {
List<Product> products = //...code to get some products
if (filters != null) {
for (Filter filter : filters)
products = filter.doFilter(products);
}
return products;
}
}
And then create filters with settings fields:
public PriceFilter implements Filter {
private Integer minPrice;
private Integer maxPrice;
// getters and setters
public List<Product> doFilter(List<Product> products) {
// implementation here
}
}
public ContentFilter implements Filter {
private String regexp;
// getters and setters
public List<Product> doFilter(List<Product> products) {
// implementation here
}
}
Then user can configure this filters for session and use service function getProducts to get result.
Having a list of filters getting autowired is not a very good approach to solve your problem.
Every filter depends on different types of parameters which would need to be passed to the doFilter method. Needing to do so makes the approach highly unflexible. Yes you could use varargs but it would just create a mess. That's why it's probably easier to implement a builder to build you a chain of filters to be applied to the collection of products. Adding new filters to the builder becomes a trivial task. The Builder Pattern is very useful when a lot of different parameters are at play.
Consider having this interface:
public interface CollectionFilter<T> {
public Collection<T> doFilter(Collection<T> collection);
}
A filter chaining class which applies all filters to the collection:
public class CollectionFilterChain<T> {
private final List<CollectionFilter<T>> filters;
public CollectionFilterChain(List<CollectionFilter<T>> filters) {
this.filters = filters;
}
public Collection<T> doFilter(Collection<T> collection) {
for (CollectionFilter<T> filter : filters) {
collection = filter.doFilter(collection);
}
return collection;
}
}
The two CollectionFilter<T> implementations:
public class InStockFilter<T> implements CollectionFilter<T> {
public Collection<T> doFilter(Collection<T> collection) {
// filter
}
}
public class MinPriceFilter<T> implements CollectionFilter<T> {
private final float minPrice;
public MinPriceFilter(float minPrice) {
this.minPrice = minPrice;
}
public Collection<T> doFilter(Collection<T> collection) {
// filter
}
}
And a builder to let you build the filter chain in a easy way:
public class CollectionFilterChainBuilder<T> {
List<CollectionFilter<T>> filters;
public CollectionFilterChainBuilder() {
filters = new ArrayList<CollectionFilter<T>>();
}
public CollectionFilterChainBuilder<T> inStock() {
filters.add(new InStockFilter<T>());
return this;
}
public CollectionFilterChainBuilder<T> minPrice(float price) {
filters.add(new MinPriceFilter<T>(price));
return this;
}
public CollectionFilterChain<T> build() {
return new CollectionFilterChain<T>(filters);
}
}
With the builder it's easy to create a filter chain as follows:
CollectionFilterChainBuilder<Product> builder =
new CollectionFilterChainBuilder();
CollectionFilterChain<Product> filterChain =
builder.inStock().minPrice(2.0f).build();
Collection<Product> filteredProducts =
filterChain.doFilter(products);
In a more dynamic settings you could use the builder like:
CollectionFilterChainBuilder<Product> builder = new CollectionFilterChainBuilder();
if (filterInStock) {
builder.inStock();
}
if (filterMinPrice) {
builder.minPrice(minPrice);
}
// build some more

Categories

Resources