Manipulating the Java Classpath and Imports

The magic %classpath allows you to add jars to your kernel. And the magics %import and %unimport control which classes are visible by default in your code. These magics work in all the BeakerX JVM kernels.

This first cell shows that you get an error if you try to import a class not built-in to BeakerX:

In [ ]:
import com.example.Demo

Then load a jar into the kernel with this magic

In [ ]:
%classpath add jar ../resources/jar/demo.jar

Then it imports and runs

In [ ]:
import com.example.Demo
In [ ]:
import com.example.Demo
Demo demo = new Demo();
println demo.getObjectTest()

You can add multiple jars. Wildcards also work.

In [ ]:
%classpath add jar ../resources/jar/demo.jar
%classpath add jar ../resources/jar/BeakerXClasspathTest.jar

println com.example.Demo.staticTest();

import com.twosigma.beakerx.jvm.object.OutputCell
import com.example.Demo

Demo demo = new Demo();
println demo.getObjectTest()

import com.beaker.BeakerXClasspathTest
BeakerXClasspathTest t = new BeakerXClasspathTest();
println com.beaker.BeakerXClasspathTest.staticTest;
println t.getObjectTest();
OutputCell.HIDDEN

With no arguments you can printout all loaded jars.

In [ ]:
%classpath

Loading Dependencies with Grapes and Maven

Groovy has a dependency manager called Grape built-in and you can access it as follows:

In [ ]:
@Grab(group='com.google.code.gson', module='gson', version='2.2.4')
import com.google.gson.GsonBuilder
new GsonBuilder().create().toJson("Hello", System.out)

The %classpath magic also supports loading from maven central:

In [ ]:
%classpath add mvn com.google.code.gson gson 2.2.4
new com.google.gson.GsonBuilder().create().toJson("Hello", System.out)

You can either use gradle like syntax to load dependency

In [ ]:
%classpath add mvn com.sun.jersey:jersey-core:1.19.4
import com.sun.jersey.api.uri.UriBuilderImpl
return new UriBuilderImpl()
            .path("http://beakerx.com/")
            .path("documentation")
            .build();

The %classpath config resolver gives you able to define custom repository

In [ ]:
%classpath config resolver repository.spring.snapshot http://repo.spring.io/snapshot
In [ ]:
%classpath add mvn org.springframework spring-context 5.0.3.BUILD-SNAPSHOT

Import and Unimport

Normally import in Groovy only works in the cell where you use it. To make a class import automatically into all cells, use %import magic.

In [ ]:
%import com.twosigma.beakerx.widgets.integers.IntSlider
w = new IntSlider()
w.value = 60
w
In [ ]:
w2 = new IntSlider()
In [ ]:
%unimport com.twosigma.beakerx.widgets.integers.IntSlider
In [ ]:
w3 = new IntSlider()
In [ ]:
%import static java.lang.Math.PI
In [ ]:
PI

More details of the implementation:

In [ ]:
%classpath add jar ../resources/jar/demo.jar
%classpath
5+5
In [ ]:
%classpath
%classpath add jar ../resources/jar/demo.jar
In [ ]:
%classpath add jar ../resources/jar/demo.jar
%classpath
In [ ]:
%import static com.example.Demo.staticTest