RhinoContainerBuilder

NanoContainerの使い方がよく分からなかったんで、作成。
Mockが作りやすくて、便利便利。


public class RhinoContainerBuilder {

public static MutablePicoContainer build(InputStream in, String filename, Map props) throws IOException {
MutablePicoContainer container = new DefaultPicoContainer();
build(in, filename, props, container);
return container;
}

public static void build(InputStream in, String filename, Map props, MutablePicoContainer container) throws IOException {
Context cx = Context.enter();
Reader reader = new InputStreamReader(in);

try {
Global global = new Global();
ShellContextFactory factory = new ShellContextFactory();
global.init(factory);

for (Object name : props.keySet()) {
putProperty(name.toString(), props.get(name), global);
}

putProperty("$container", container, global);
Script script = cx.compileReader(reader, filename, 1, null);
script.exec(cx, global);
} finally {
reader.close();
in.close();
Context.exit();
}
}

private static void putProperty(String name, Object value, Scriptable scope) {
Object jsObj = Context.javaToJS(value, scope);
ScriptableObject.putProperty(scope, name, jsObj);
}

}