Last active
April 15, 2016 18:31
-
-
Save seregasheypak/2d7f5a16fa31018c8212754c8e94f9a4 to your computer and use it in GitHub Desktop.
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
public class ScriptFactory{ | |
private final Map<String, Script> cache = new HashMap<>() | |
private static final GroovyClassLoader CLASS_LOADER = new GroovyClassLoader() | |
private String template | |
/** | |
@param source is a dynamic expression to be evaluated: user.attr1 == 'x' || user.attr2 == 'y' | |
@return instance of script | |
*/ | |
public Script create(String source) throws InstantiationException, IllegalAccessException, IOException{ | |
if (!cache.containsKey(source)) { | |
cache.put(source, | |
CLASS_LOADER.parseClass(String.format(loadTemplate(), source))newInstance() | |
) | |
} | |
return cache.get(source) | |
} | |
/** | |
@return template used for dynamic expression execution | |
*/ | |
protected String loadTemplate() throws IOException | |
{ | |
return """ | |
def evaluateExpression(Map context){ | |
def user =context.user | |
%s | |
} | |
""" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If a single instance of this is used in a highly concurrent app I'd recommend a ConcurrentHashMap to make sure all threads can see the puts.