Last active
August 29, 2015 14:01
-
-
Save smasty/4c7967a31365bed30608 to your computer and use it in GitHub Desktop.
Filter projects based on criteria. Uses a filterable Iterator with custom predicate, regexps and reflection.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* List projects based on criteria. | |
* @param action | |
* @param user | |
*/ | |
public Iterable<IProject> executeAction(ListProjectsAction action, IUser user) { | |
Iterable<IProject> items = projects.values(); | |
if(action.getParams().containsKey("filter")){ | |
Pattern pattern = Pattern.compile(Pattern.quote(action.getParam("pattern")) | |
.replace("*", "\\E.*\\Q") | |
.replace("?", "\\E.?\\Q")); | |
IFilterPredicate<IProject> predicate = null; | |
try { | |
switch (action.getParam("filter")) { | |
case "type": | |
predicate = new RegexpPropertyGetterPredicate(pattern, AbstractProject.class.getMethod("getType")); | |
break; | |
case "language": | |
predicate = new RegexpPropertyGetterPredicate(pattern, AbstractProject.class.getMethod("getLang")); | |
break; | |
case "client": | |
predicate = new RegexpPropertyGetterPredicate(pattern, AbstractProject.class.getMethod("getClient")); | |
break; | |
default: | |
break; | |
} | |
} catch (NoSuchMethodException | SecurityException e) {} | |
items = new FilterIterator<>(items, predicate); | |
} | |
return items; | |
} | |
// ............ | |
private class RegexpPropertyGetterPredicate implements IFilterPredicate<IProject> { | |
private Pattern pattern; | |
private Method propertyGetter; | |
public RegexpPropertyGetterPredicate(Pattern pattern, Method propertyGetter){ | |
this.pattern = pattern; | |
this.propertyGetter = propertyGetter; | |
} | |
public boolean eval(IProject project) { | |
try { | |
return pattern.matcher((String) propertyGetter.invoke(project)).matches(); | |
} catch (InvocationTargetException | IllegalAccessException | IllegalArgumentException e) { | |
return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment