Saturday, June 20, 2015

Nashorn Scripts in Mac OS Yosemite's Notification Center

Or rather: Another use-case for Today Scripts

Users of Yosemite enjoy the rather useful new side-bar called 'Today' which shows a configurable list of widgets.
Here's how you can use a combination of Today-Scripts  and Nashorn to display information.

This little tip is only useful to you if you run Mac OS Yosemite (obviously) have a recent JDK installed.


Install Today Scripts

This very useful swiss knifes of widgets by Sam Rothenberg allows you to run any bash script and display its output (with ANSI-color support!).
Note that you either have to lower your security settings to run Today Script.app or simply right-click and Open the app. Once it is run, you have a new widget available for the 'Today' section.

Write some Nashorn scripts

jjs, the Nashorn script interpreter should be in /usr/bin/jjs on your system. 
I'm putting my scripts in ~/.jjs and here's a demo script that will show a list of currently running java processes with PID and main class. Save it as jps.js


// List running Java Processes
// ansicolors
var a = { reset : "\u001B[0m", black: "\u001B[30m", red: "\u001B[31m", green: "\u001B[32m",
yellow: "\u001B[33m", blue: "\u001B[34m", purple: "\u001B[35m", cyan: "\u001B[36m",
white: "\u001B[37m"
};
var jps = `jps -vl`.split('\n').slice(0,-1);
var ownPID = java.lang.management.ManagementFactory.getRuntimeMXBean().getName().split('@')[0];
jps.forEach(function(j) {
var params = j.split(' ');
if (params[0] != ownPID)
print(a.red + params[0] + a.white + ' ' + (!params[1] || (params[1][0] == '-') ? 'unknown' : params[1]) + a.reset);
});
view raw jps.js hosted with ❤ by GitHub


Now let's add that to Today Script.
Create a new script, use /bin/bash and as script use this:

jjs -scripting ~/.jjs/jps.js

Here's a screenshot of the script configuration.





And that is all there is to it.
Pretty simple, but really the shortest way of running some juicy JavaScript/Java combo in your Notification Center.