Transpile Java vol. 2 - Debugging

It has already been described that DukeScript makes it quite easy to transpile Java into JavaScript. Today’s post is going to show the easiest way to debug when behavior of your code diverges between classical desktop Java and Java running in the browser.

Start from command line

While knowing there is a visual way of getting started, let’s again stick with old good command line. Install Java, install Maven and invoke:

$ mvn archetype:generate \
  -DarchetypeGroupId=com.dukescript.archetype \
  -DarchetypeArtifactId=knockout4j-archetype \
  -DarchetypeVersion=0.17 \
  -Dwebpath=client-web \
  -DgroupId=org.your.test \
  -DartifactId=runjavainbrowser \
  -Dversion=1.0-SNAPSHOT
$ cd runjavainbrowser
$ mvn install -DskipTests

and that is it! Just three shell commands and you have all the environment you need!

Test Your Code!

Follow the advice of the previous article to write your code into DataModel.java class, if you want, but as our main focus is on finding the problems, let’s do something else. Locate IntegrationTest.java and let’s add there the Java code we are about to check for misbehaving:

$ vi client-web/src/test/java/org/your/test/IntegrationTest.java

there is already a @Test method present, so let’s write another one:

    @Test
    public void stringBehavior() {
      String res = String.format("A%dB%sC", 54.3, "Hi");
      assertEquals("A54BHiC", res);
    }

to test the behavior of String.format (which is known to be slightly less optimally implemented in Bck2Brwsr virtual machine). After saving the file it is time to run the code:

$ mvn -f client-web/pom.xml package

That is it! The system executes your stringBehavior test in classical Java HotSpot VM, and in Bck2Brwsr VM, compares the results and fails. Fails as the HotSpot VM throws an IllegalFormatConversion exception, while Bck2Brwsr produces some string output.

Report a Bug

If you have such failing test, it is time to report a bug. Either use DukeScript forum or premium support or report the bug directly to Bck2Brwsr issue tracker. Attach the test case you have written, so the failure can be easily reproduced.

Simplify your Code

While waiting for resolution of the bug, it may be reasonable to simplify your code to use constructs fully supported by all VMs you are about to target. For example by rewriting the @Test code to:

    @Test
    public void stringBehavior() {
      String res = "A" + 54.3 + "B" + "Hi" + "C";
      assertEquals("A54.3BHiC", res);
    }

and running mvn -f client-web/ package again one gets code that is behaving the same in HotSpot as well as in Bck2Brwsr VM.

Improve Java in the Browser!

Enjoy transpiling of Java for a browser and help the system get better by writing more @Test examples and sharing them (the failing ones) with other DukeScripters!

Long live transpiled Java code!