X

Sundararajan's Weblog

  • Java
    September 30, 2015

Playing with Java (java9) REPL - an example that uses nashorn engine in REPL

I love "Exploratory Programming" (https://en.wikipedia.org/wiki/Exploratory_programming) tools. If you've not already played with "Java REPL" project, you may want to do so! Check out Kulla project.


Clone kulla forest @ http://hg.openjdk.java.net/kulla and build using these commands:
  1. hg clone http://hg.openjdk.java.net/kulla/dev kulla-dev
  2. cd kulla-dev
  3. sh get_sources.sh
  4. sh configure --with-boot-jdk=/path/to/jdk1.8.0
  5. make clean images
  6. make install

Once build finishes, you can use the Java REPL tool "jshell" ( $kulla-dev/build//images/jdk/bin/jshell). I built on Windows. My jshell path is D:\src\kulla-dev\build\windows-x86_64-normal-server-release\images\jdk\bin\jshell.exe.

Now, two lines to print the squares of integers in the range [0, 100):


D:\src\kulla-dev\build\windows-x86_64-normal-server-release\images\jdk\bin>jshell
| Welcome to JShell -- Version 1.9.0-internal
| Type /help for help
-> import java.util.stream.*
-> IntStream.range(0, 100).map(x->x*x).forEach(System.out::println)

Slightly bigger repl sample that pulls weather data in JSON format, uses Nashorn script engine to parse JSON and print the statistics on it using Streams API.


File: weather.repl

import java.net.*
import java.io.*
import java.util.stream.*
import javax.script.*
import java.util.*
// URL to fetch JSON for weather data for Chennai, India
URL u = new URL(
"http://api.openweathermap.org/data/2.5/forecast/daily?q=Chennai&mode=json&units=metric&cnt=7")
// read text from URL
String getText(URL u) {
StringBuilder buf = new StringBuilder();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(u.openStream()))) {
reader.lines().forEach(l->buf.append(l));
} catch (IOException exp) {
exp.printStackTrace();
}
return buf.toString();
}
// create nashorn engine
ScriptEngine e = new ScriptEngineManager().getEngineByName("js")
// expose weather data JSON as global variable to nashorn engine
e.put("str", getText(u))
// massage JSON using nashorn and get the max. temp values
double[] values = (double[]) e.eval(
"Java.to(JSON.parse(str).list.map(function(val) val.temp.max), Java.type('double[]'))")
// stat on max. temp values
printf(DoubleStream.of(values).summaryStatistics().toString())

You can evaluate the above source as follows:

jshell weather.repl
| Welcome to JShell -- Version 1.9.0-internal
| Type /help for help
-> DoubleSummaryStatistics{count=7, sum=227.160000, min=30.210000, average=32.451429, max=36.5800
00}

Yep, Chennai is HOT! 32 C average! In Chennai, we have only three seasons - hot, hotter and the hottest :)

Be the first to comment

Comments ( 0 )
Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.