Java 8 Nashorn CLI use case: adding ISO 8601 instant to CSV with UNIX timestamp
There’s a command line utility called
jjs which will execute a given script or provide you with a REPL where you can type in custom commands.
Here for demonstration purposes we’ll utilise the powerful java.time library:
We can get the time in a different time zone, such as in New York:
jjs> var instant = java.time.Instant.ofEpochSecond(1552134142)
jjs> var newYorkZone = java.time.ZoneId.of("America/New_York")
And if we wanted to go back a few years we can:
Notice the same local time and timezone but different offset due to New York’s DST.
Making a time-series CSV human-readable
Let’s suppose we had this CSV file come in from a vendor or a client:
Are you able to discern what date and time the timestamp actually refers to? Not unless you check by hand. But would you be able to visually scan through such a file if it had 40 million lines? That’s only doable with human readable timestamps.
jjs On UNIX, you can make a script to effortlessly enrich some CSV input:
When you run it against sample data, you’ll see a new column in the front:
$ ./prepend-iso-time.js <<EOF
And if this were a 40 million line file, you can use
less to scan through all the data very easily.
What about JSON?
You may also come across NDJSON, such as:
Now let’s say you are in New York and want to know attach the local time. You could do:
$ ./add-ny-time-json.js << EOF
Many other use cases
Especially where you want to do some Java calls but don’t wish to set up an IDE and a Maven/SBT project…
And where you’d like to turn your scripts into proper libraries later on.
One nice use case of mine was to reconfigure a Scala/Play app at runtime:
I hope you found this useful and will investigate what else Nashorn has to offer. It’s a very solid tool that’s available where Java 8 is and can be utilised very easily. Explore :-)
- If you liked this, definitely follow me on Twitter:
- And check out my article on Limiting Degrees of Freedom: