ShrinkWrap Resolver in JavaScript via Nashorn


#1

With the new Resolver bootstrap module as mentioned here; ShrinkWrap Resolver single jar bootstrap module we could very easily use Resolver as a ‘Java Module’ loader for e.g. JavaScript applications on Nashorn.

I wrote this little ShrinkWrap JavaScript wrapper as a prototype:

shrinkwrap = function() {
	
	var resolverCl = new java.net.URLClassLoader(
			[new java.io.File("shrinkwrap-resolver-bootstrap-maven-2.2.0-beta-3-SNAPSHOT.jar").toURL()]);
	
	var resolver = java.lang.Class.forName("org.jboss.shrinkwrap.resolver.bootstrap.maven.Resolver", true, resolverCl).static;
	
	return {
		resolve: function(options) {
			var classloader = resolver.resolveAsClassLoader(
					java.lang.Thread.currentThread().getContextClassLoader(),
					options.deps);
			if(options.classes != null) {
				for(var i = 0; i < options.classes.length; i++) {
					var className = options.classes[i];
					var clazz = java.lang.Class.forName(className, true, classloader).static;
					options.target[clazz.class.getSimpleName()] = clazz;
				}
			}
			return classloader;
		},
	}
}

this.ShrinkWrap = shrinkwrap();
this.loadModule = this.ShrinkWrap.resolve

Essentially it dynamically loads the shrinkwrap-bootstrap.jar to invoke the minimal Resolver API that then again dynamically resolves the internally packaged Resolver jars. From there we can resolve any jars from a Maven repository.

The mapped javascript methods takes a object with the options;

  • deps - Array of Strings with gavs to resolve
  • classes - Array of Strings with fully qualified classes to dynamically load from the resolved gavs
  • target - Object to map the loaded classes for access via SimpleName

Usage:

load("shrinkwrap.js")
loadModule({
	deps: ["junit:junit:4.10"],
	classes: ["org.junit.runner.JUnitCore"],
	target: this
})

Test = function() {
	return {
		run: function() {
			print(JUnitCore)
		}
	}
}

Test().run()

Arquillian in JavaScript via Nashorn