8.0 Using the State Variable to Cache and Store Information

In situations when a script runs multiple times on a Operations Center server or console, it is advantageous to cache or store information that subsequent invocations of the script can use. Use the Operations Center state variable to store and share data among scripts.

The state variable is by default an empty object. Its unique feature is having only one value in the entire process. It is shared across invocations of scripts and between scripts running on different threads in the same process. For this reason, it is possible to place variables on the state object that are used elsewhere.

For example, assume that a script must open a file and write some data to it. Later, run the script again, which means opening and closing the file again. Use the state variable to cache the value of the stream that the script opens, and then reuse the stream during another invocation of the script. For example:

if( ! state.fileStream )
   state.fileStream = new java.io.PrintWriter( new java.io.OutputStreamWriter( new java.io.FileOutputStream( '/output', true ) ) )
state.fileStream.println( 'Some more data right now: ' + new java.util.Date() )
state.fileStream.flush()

The convention on line 1 checks for the presence of the fileStream value in the state variable. If it is not found, fileStream is opened. Whether it is initially opened or reused from the state variable, the script simply writes data to the stream, then flushes it.

If the script places many variables in the state variable, consider placing them in an object held by the state variable:

if( ! state.mystuff )
{
   state.mystuff = new Object()
   state.mystuff.fileStream = new java.io.FileInputStream( '/output' )
   state.mystuff.iterations = 0
}
state.mystuff.iterations++