Created
August 8, 2014 21:10
-
-
Save jimwhite/3d15160781911b855796 to your computer and use it in GitHub Desktop.
This file contains 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
package groovyx.cli; | |
import groovy.lang.Binding; | |
import groovy.lang.MissingPropertyException; | |
import groovy.lang.Script; | |
import java.util.HashMap; | |
import java.util.Map; | |
/** | |
* Groovy Script base class that keeps bindings in a ThreadLocal so that scripts can | |
* be run concurrently without much interference. Note that the class properties of | |
* the Script object *are* shared, which may or may not be what you want. If you | |
* don't want that then getProperty/setProperty/invokeMethod also need to be overridden. | |
* | |
* @author Jim White (<a href='https://github.com/jimwhite'>https://github.com/jimwhite</a>) on 8/8/14. | |
*/ | |
abstract public class ThreadLocalScript extends Script { | |
ThreadLocalScript() { super(new ThreadLocalBinding()); } | |
public ThreadLocalScript(Binding binding) { | |
super(new ThreadLocalBinding(binding)); | |
} | |
@Override | |
public void setBinding(Binding binding) { | |
super.setBinding(new ThreadLocalBinding(binding)); | |
} | |
static class ThreadLocalBinding extends Binding { | |
ThreadLocal<Map> variables = new ThreadLocal<Map>(); | |
public ThreadLocalBinding() { | |
variables.set(new HashMap()); | |
} | |
public ThreadLocalBinding(Binding binding) { | |
variables.set(binding.getVariables()); | |
} | |
@Override | |
public Object getVariable(String name) { | |
Map map = variables.get(); | |
Object result = map.get(name); | |
if (result == null && !map.containsKey(name)) { | |
throw new MissingPropertyException(name, this.getClass()); | |
} | |
return result; | |
} | |
@Override | |
public boolean hasVariable(String name) { | |
Map map = variables.get(); | |
return map != null && map.containsKey(name); | |
} | |
@Override | |
public Map getVariables() { | |
return variables.get(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment