Wednesday, March 09, 2011

How To Externalise JavaScript in ITIM Workflow

Every now and again, I seem to hit on a problem which requires that my JavaScript seems to be veering towards being environment specific. As we all know, we want our ITIM workflows to be consistent between our development, test and production environments and workflow which contains environment specific code has got to be a bad thing.

But, it happens.

What if, however, we could maintain the same workflow between the environments but externalise the JavaScript to a file. The pain point of altering the workflow between environments would just go away!

Achieving this is really quite simple and has been alluded to in other forums - though rarely in a way that gives the reader all the information they require to complete the task. The following method works with ITIM v5.1.

JavaScript Node
To read an external JavaScript file, we require the following code:

// Open the external JavaScript file
var myScriptFile = new java.io.BufferedReader(new java.io.FileReader("/path/to/file");
var myLineOfCode = null;
var myCode = "";

// Read the file and add each line of code we find to a variable
while ((myLineOfCode = myScriptFile.readLine()) != null) {
   myCode += myLineOfCode;
}

// Close the file
myScriptFile.close();

// Execute the code that we have gathered together
eval(myCode);

Our external JavaScript file can contain any JavaScript code we require for our node:

Enrole.log("external", "Hello world - I'm an external script!");

scriptframework.properties
Of course, to expose the java.io methods to our JavaScript, we need to configure this ability in our scriptframework.properties file (and restart ITIM). Adding the following property to scriptframework.properties will do the trick:

ITIM.java.access.io=java.io.*

And there you go... from within our script nodes, we have access to the java.io classes. We can externalise our scripts. We can read files. We can write files. Why not let me know how you put your java.io capability to use in the script nodes.

No comments: