Monday, June 25, 2018

Reading and writing files in a Maximo automation script


All of the product documentation tells you to use the product provided logging for debugging automation scripts (see here, for example: ). For quick debugging, however, I thought that was cumbersome, so I decided to figure out how to access files directly from within an automation script. This post goes over exactly what's required to do that. Maximo supports Jython and Rhino-JavaScript for automation scripting, and I'll cover both of those here.


This one was straightforward, since the Python documentation can be followed exactly. Jython is simply an implementation of Python written completely in Java. All you need to open a file is:

my_file = open('c:/tmp/outfile.txt','a')

where 'a' specifies that we're appending to the file (and creating it if it doesn't exist). You then do need to flush and close the file, and this is my function to do that:

def logit(mytext):
  my_file = open('c:/tmp/jout.txt','a')
  my_file.write(mytext + '\n')

So to log a string, just run:

logit("this is my string")

Reading from a file is just as easy:

my_read = open('c:/tmp/computers.json')
my_json = my_read.readline()

In my case, the file contains one long line of JSON data, so readline() works great to store all of the text of the file into the string named my_json.


This one is quite a bit more painful than Jython, which is really just one more reason that all of your automation scripts should be written in Jython. Specifically, the Rhino implementation in Maximo doesn't seem to completely adhere to the documentation you'll fine online. For example, there is no "ReadFile()" method available in Maximo. There are also other limitations, and the only way I found to get over them was to use Java classes. I thought that would make it easy, but then you have to deal with the fact that Java objects (specifically Array objects) are absolutely not the same as JavaScript objects. 

So, writing a file isn't too difficult once you realize that you need to use Java. Here's how you open and write a file:

var outFile = new"c:/tmp/autoscriptout.txt");
outfile.write("my string");

The hard part is actually reading data from the file. Using the same JSON file as above with one long line of JSON, the following is required to read that data into a JavaScript string that can then be parsed:

  thefile = new"c:/tmp/computers.json"),
  filelength = thefile.length(),
  thefilereader = new,
  jsonData = java.lang.reflect.Array.newInstance(java.lang.Character.TYPE,filelength),
  res =,0,filelength),
  jsonString = new java.lang.String(jsonData);

And now all of the JSON data is in the string named jsonString.


No comments: