Skip to content

Instantly share code, notes, and snippets.

@Abhi-Codes
Created September 30, 2022 05:44
Show Gist options
  • Save Abhi-Codes/d7ecc25ba3fda7e65ad4e188fde23d74 to your computer and use it in GitHub Desktop.
Save Abhi-Codes/d7ecc25ba3fda7e65ad4e188fde23d74 to your computer and use it in GitHub Desktop.
Parse the filters passed by controller and build Search Criteria
/**
* Format search criteria.
*
* @param filter the filter
* @return the list
*/
public List<SearchCriteria> formatSearchCriteria(String[] filter) {
List<SearchCriteria> criterias = new ArrayList<>();
if (null != filter) {
Collection<SearchCriteria> collect = Arrays.asList(filter).parallelStream().map(this::validateFilterPattern)
.collect(Collectors.toList());
criterias.addAll(collect);
}
return criterias;
}
/**
* Gets the and boolean expression.
*
* @param criterias the criterias
* @param t the t
* @return the and boolean expression
*/
public BooleanExpression getAndBooleanExpression(List<SearchCriteria> criterias, Class<Post> t) {
return new CommonPredicateBuilder<>(t).and(criterias).build();
}
/**
* Validate filter pattern.
*
* @param filter the filter
* @return the search criteria
*/
private SearchCriteria validateFilterPattern(String filter) {
final Pattern pattern = Pattern.compile("([\\w.]+?)(:|<|>|<=|>=|%|-|\\(\\))([\\w\\s\\(\\),.:-]+?)\\|");
Matcher m = pattern.matcher(filter + "|");
if (m.find()) {
return SearchCriteria.builder().key(m.group(1)).operator(m.group(2)).value(m.group(3)).build();
} else {
throw new RuntimeException("Invalid Filter format");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment