Friday, November 22, 2024

Maximo Automation Script Performance Tip: Avoid using setQbe and setWhere

 

When accessing an MboSet, it is common to need to find a particular record. There are two primary methods for this. The first is call Query By Example (setQbe). The second is the Where clause (setWhere).

Let’s do an example. Say we need to find the Asset with the assetnum = ‘1000’. (We assume there is only one site in this example.) Here is a sample using the Query By Example:

    assetMboSet = session.getMboSet("ASSET")
    assetMboSet.setQbe("ASSETNUM", "1000")

This would work but it has consequences. First, this would return all assets that have ‘1000’ in the assetnum. The bigger consequence (at least for performance sake), is what Maximo does in the background. QBE translates to this SQL:

    SELECT * FROM ASSET WHERE ASSETNUM like ‘%1000%’

If you are truly looking for all assets that have ‘1000’ within their assetnums, then this the right approach, but if you only was the asset with the assetnum ‘1000’, this is a slow approach as Maximo will do a full scan to find all the records.

The second approach is to use the Where clause. Let’s look at the same example but using the setWhere method:

    assetMboSet = session.getMboSet("ASSET")
    assetMboSet.setWhere("ASSETNUM = '1000'")
    

This approach will return just the asset you are looking for. This approach would translate to this:

    SELECT * FROM ASSET WHERE ASSETNUM = '1000'

The setWhere method basically gives you the ability to add a SQL ‘Where’ clause to the MboSet. In reference to performance, the ‘like’ method is slower as database has to look at the data in the ASSETNUM column to see if it contains the 1000 value, whereas the ‘=’ method just checks to see if the entire content of ASSETNUM matches.

Unless you need to perform a ‘LIKE’ method, you should always use the setWhere method as it will be faster. And, if you really need to use a ‘LIKE’ query, you can always use: setWhere("ASSETNUM like ‘%1000%’”), as it would do the same thing as setQbe does. 

Now that I have shown that setWhere is better than setQbe, there is another and even better way to do this. That is to us a dynamic relationship. As you have seen, getMboSet method is passed the name of the MBO that you want to access. However, there is an overloaded version of this method that allows you to create a dynamic relationship. Using this, you can pass the condition as part of the relationship. This will allow the database to do the filtering instead of Maximo. The new code would look like this:

    assetMboSet = session.getMboSet("$tempAsset","ASSET","ASSETNUM='1000'")
 

The first parameter is a temporary name for the relationship. Make sure it starts with a dollar sign. Next is the name of the MBO and the last parameter is the where clause (without the word 'WHERE').  This method has the smallest impact on Maximo's overhead.

Happy Coding

Using Discardable MboSets in Maximo Automation Scripts

 

I would say about 90 percent of the time that, in Maximo code, when we access an MBO set, we just navigate through it, first record to last. Usually it is to retrieve a certain value for calculation or some other reason. This is a sample of what that code looks like:

    assetMboSet = mbo.getMboSet("ASSET")

    curMbo = mbo.moveFirst()
    while curMbo != None:
        # Read some value from the mbo
        curMbo = mbo.moveNext()

This is pretty straight forward code but let’s look at the impact of this code in reference to performance. Whenever you access an MboSet, Maximo automatically caches the data as it assumes that you will probably want edit it. However, if you only just want to read through a MboSet, then placing the data in cache means it is taking up memory space that you do not need to take up. A better approach for MboSets that you plan on just reading through (no updates), is to make the MboSet “Discardable.” This tells Maximo to not place the data in the cache, freeing up memory. The code to do this is:

    assetMboSet = mbo.getMboSet("ASSET")
    assetMboSet.setFlag(MboConstants.DISCARDABLE, true)
    curMbo = mbo.moveFirst()
    while curMbo != None:
        # Read some value from the mbo
        curMbo = mbo.moveNext()

As you can see it only take one line of code but can have a big impact on memory usage. One important thing to note is that a “Discardable” MboSet is always read-only. If you are struggling with JVM memory availability in your Maximo environment, this is an easy way to help free up some of it.

Happy Coding

Maximo Automation Script Debugging

 

Maximo automation script debugging

Someone once told me that “All developers would write 100% bug free code if it wasn’t for users.” Sadly for us developers, we live in a world full of users. That means we have to debug our code. One of the biggest challenges facing a Maximo developer is often trying to debug automation scripts. When you have multiple scripts that are all being trigger, trying to figure out which script is causing the system to be slow is a major problem.

This article is going to talk about two parts of debugging scripts. The first is how to make your life easier in the future by adding log statements to your scripts. The second is how to use logging to figure out what Maximo is doing and all the scripts that are running.

 Debugging your code:

The one thing that you should have in every automation script is some logging statements. They not only allow you do debug code in a production environment (by changing the debug level), but also is a great way to comment and document your code. Maximo has several loggers that you can use but since there is one for automation scripts, that would be a good choice. Here is an example of how to create a logger variable and how to write to it:

    from psdi.util.logging import MXLoggerFactory

    logger = MXLoggerFactory.getLogger("autoscript")

    logger.info("Entering SR_INIT script for ticket " + mbo.getString("TICKETID"))
    logger.debug("This is a debug message")
 

The most common log methods are: .error(), .warn(), .info() and .debug(). (There are other methods but these are the main/most commonly used.) These correspond to the Log Levels that you can select in the logging application in Maximo. Now you might feel like you should remove all the .debug() statements once your code is tested and working but you should not. Leaving them in will help in the future should some have to debug your code.

Figuring out what Maximo is doing:

Trying to figure out what Maximo is doing with automation script can be a struggle, especially if your environment has a lot of automation scripts. It turns out that the autoscript log can help a lot when you change the log level for it. Of course, anytime you turn up the volume of log entries, you run into a problem with the log file filling up to quickly. As such, I recommend you, for the purposes of debugging, having the autoscript log write to its own file. You don’t have to but if you don’t and have a lot of debugging data being written to the log, then it can be hard to determine what is from the autoscript and what isn’t. Here is how you do that:

Access the Logging application and then from the Actions menu, select Manage Appenders.

Then click New row.

·       Appender: Give it a name.

·       Description: Enter a description

·       Append Implementation Class: psdi.util.logging.MXFileAppender

·       File Name: This will be the name of the log file. Be sure to end it with “.log”

Save

No alt text provided for this image

Now edit the root logger: autoscript. On appenders, select your new appender (click the icon next to the field).

Also change the log level to INFO or DEBUG.

Be sure to perform “Apply Settings”.

No alt text provided for this image

Now Maximo will write everything from the autoscript log into your new file, making it easier for you to read it. But what information does “INFO” and “DEBUG” give you?  INFO will tell you the name of each script that runs, including the launchpoint name, user, Mbo and execution time. DEBUG will also include the name of each variable in that script that was created and all the listeners.

Example of setting ‘autoscript’ logging to DEBUG:

17 Apr 2020 13:08:11:121 [DEBUG] [MXServer] [CID-UIASYNC-5167] ScriptMboEventListener eventValidate

17 Apr 2020 13:08:11:121 [DEBUG] [MXServer] [CID-UIASYNC-5167] ASSETScriptMboEventListener eventValidate called.

17 Apr 2020 13:08:11:121 [DEBUG] [MXServer] [CID-UIASYNC-5167] ScriptMboEventListener eventValidate

17 Apr 2020 13:08:11:121 [DEBUG] [MXServer] [CID-UIASYNC-5167] ASSETScriptMboEventListener eventValidate called.

17 Apr 2020 13:08:11:121 [DEBUG] [MXServer] [CID-UIASYNC-5167] ScriptMboEventListener eventValidate

17 Apr 2020 13:08:11:121 [DEBUG] [MXServer] [CID-UIASYNC-5167] ASSETScriptMboEventListener eventValidate called.

17 Apr 2020 13:08:11:121 [DEBUG] [MXServer] [CID-UIASYNC-5167] ASSETScriptMboEventListener eventAction called. for script Z_DEFAULTNAME launch point Z_DEFAULTNAME

17 Apr 2020 13:08:11:121 [DEBUG] [MXServer] [CID-UIASYNC-5167] ASSETScriptMboEventListener eventAction called. for script USERINPUT launch point USERINPUTE2

17 Apr 2020 13:08:11:121 [DEBUG] [MXServer] [CID-UIASYNC-5167] ASSETScriptMboEventListener eventAction called. for script TEST-JDBC launch point TEST-JDBC

17 Apr 2020 13:08:11:121 [INFO] [MXServer] [CID-MXSCRIPT-5168] Correlation started.

17 Apr 2020 13:08:11:121 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] about to execute the cached compiled script for TEST-JDBC for launch point TEST-JDBC

17 Apr 2020 13:08:11:121 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] putting app value ASSET

17 Apr 2020 13:08:11:121 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] putting mboname value ASSET

17 Apr 2020 13:08:11:121 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] putting service value com.ibm.tivoli.maximo.script.ScriptService@23de5242

17 Apr 2020 13:08:11:121 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] putting interactive value true

17 Apr 2020 13:08:11:121 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] putting onupdate value false

17 Apr 2020 13:08:11:121 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] putting scriptName value TEST-JDBC

17 Apr 2020 13:08:11:121 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] putting mbo value psdi.plust.app.asset.PlusTAsset@27e1c2e1

17 Apr 2020 13:08:11:121 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] putting ondelete value false

17 Apr 2020 13:08:11:121 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] putting user value WILSON

17 Apr 2020 13:08:11:121 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] putting onadd value false

17 Apr 2020 13:08:11:121 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] putting launchPoint value TEST-JDBC

17 Apr 2020 13:08:11:121 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] created script context for cached compiled script TEST-JDBC for launch point TEST-JDBC

17 Apr 2020 13:08:11:122 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] putting MXServer value <type 'psdi.server.MXServer'>

17 Apr 2020 13:08:11:122 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] putting ConnectionKey value <type 'psdi.security.ConnectionKey'>

17 Apr 2020 13:08:11:123 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] putting DBShortcut value <type 'psdi.mbo.DBShortcut'>

17 Apr 2020 13:08:11:123 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] putting Connection value <type 'java.sql.Connection'>

17 Apr 2020 13:08:11:123 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] getting MXServer

17 Apr 2020 13:08:11:123 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] putting mxServer value psdi.server.MXServer@79db0e30

17 Apr 2020 13:08:11:123 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] getting mxServer

17 Apr 2020 13:08:11:124 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] putting conKey value psdi.security.ConnectionKey@7793b66a

17 Apr 2020 13:08:11:124 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] getting DBShortcut

17 Apr 2020 13:08:11:124 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] putting dbs value psdi.mbo.DBShortcut@2cca736

17 Apr 2020 13:08:11:124 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] getting dbs

17 Apr 2020 13:08:11:124 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] getting conKey

17 Apr 2020 13:08:11:124 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] putting c value 0

17 Apr 2020 13:08:11:124 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] getting dbs

17 Apr 2020 13:08:11:140 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] putting rs value oracle.jdbc.driver.ForwardOnlyResultSet@4752903d

17 Apr 2020 13:08:11:144 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] getting rs

17 Apr 2020 13:08:11:144 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] getting rs

17 Apr 2020 13:08:11:150 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] putting c value 686

17 Apr 2020 13:08:11:150 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] getting rs

17 Apr 2020 13:08:11:150 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] getting rs

17 Apr 2020 13:08:11:150 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] getting dbs

17 Apr 2020 13:08:11:152 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] getting dbs

17 Apr 2020 13:08:11:153 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] putting errorgroup value configure

17 Apr 2020 13:08:11:153 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] putting errorkey value BlankMsg

17 Apr 2020 13:08:11:153 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] getting c

17 Apr 2020 13:08:11:153 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] putting params value ['record count: 686']

17 Apr 2020 13:08:11:153 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] execution completed for cached compiled script TEST-JDBC for launch point TEST-JDBC

17 Apr 2020 13:08:11:153 [DEBUG] [MXServer] [CID-MXSCRIPT-5168] The total time taken to execute the TEST-JDBC script for the TEST-JDBC launch point is +32 ms.

17 Apr 2020 13:08:11:153 [INFO] [MXServer] [CID-MXSCRIPT-5168] Correlated data: BEGIN LaunchPoint:TEST-JDBC app:ASSET Script:TEST-JDBC UserName:WILSON MboName:ASSET MboId:204 ElapsedTime:32 ms  END
 

I hope this helps with your debugging tasks. 

Happy Coding

How to Retrieve a JDBC connection in Automation Scripts

 

There are times in automation scripting that you need a JDBC connection to directly access Maximo database in order to perform some job. This is not common since all Maximo data can be accessed through standard MboSets. However, you may need to access non-Maximo tables, perform specific SQL statements or bypass Mbos for performance reasons. The two main approaches to issue standard SQL code through JDBC are described here.

Of course, you could do the standard application approach where you get the connection string, username and password and then open a connection yourself. However, the Maximo Server object can give us the connect object. This eliminates the need to have the username and password stored somewhere (security audits like that). As such I will not be covering that approach here. In both examples, we will be using the Maximo Server Object (MXServer) to get the database connection.

JDBC Connection

Here is a sample that shows how to get a JDBC connection from Maximo connection pool (and correctly release it).

    from psdi.server import MXServer
    from psdi.security import ConnectionKey
    from java.sql import Connection
    from java.sql import Statement
    
    mxServer = MXServer.getMXServer()
    conKey = mxServer.getSystemUserInfo().getConnectionKey()
    con = mxServer.getDBManager().getConnection(conKey)

    c = 0
    try:
        stmt = con.createStatement()
        rs = stmt.executeQuery("select count(1) from asset")
        while rs.next():
            c = rs.getInt(1)
        rs.close()
        stmt.close()
        con.commit()
    except:
        #error do something meaningful about the error
        c = -1
    finally:
        mxServer.getDBManager().freeConnection(conKey)


If you have done any java JDBC programming at all you will see that this is a pretty standard approach. We first get the credentials for connecting to the database (conKey). Then we use it to get a connection object (con) from the Maximo database connection pool. Then we use a Statement object (stmt) to get a ResultSet object (rs). We then process that ResultSet. Take special note of the last line:

              mxServer.getDBManager().freeConnection(conKey)

This is how you tell Maximo that you are done with the JDBC connection so it can free it to the connect pool. Eventually the garbage collection would see that your script is complete and free the connection, but issuing the command makes it happen immediately, lessoning the change of running out of available connections. (e.g. when you are processing thousands of records, so the script is running thousands of times.)

DBShortcut class

A quick easy way to get a java.sql.ResultSet object is to use DBShortcut class. This object comes in the psdi.mbo package and is designed to quickly retrieve result-sets or run update statements against the database.

    from psdi.server import MXServer
    from psdi.security import ConnectionKey
    from psdi.mbo import DBShortcut
    from java.sql import Connection

    mxServer = MXServer.getMXServer()
    conKey = mxServer.getSystemUserInfo().getConnectionKey()
    dbs = DBShortcut()
    dbs.connect(conKey)

    c = 0
    try:
        rs = dbs.executeQuery("select count(1) from asset")
        while rs.next():
            c = rs.getInt(1)
        rs.close()
        dbs.commit()
    except:
        #error do something meaningful about the error
        c = -1
    finally:
        dbs.close()


The big difference here is that by using the DBShortcut class, Maximo controls all of the required connection objects (e.g. Connection, Statement) so you do not have to worry about them. It just gives you a ResultSet. Where this really is shown is in the cleanup. We don’t have a Statement object to close, instead of committing the connection, we tell DBShortcut to commit(), and by simply calling the close() method on the DBShortcut variable, it will automatically free up the connection. The DBShortcut is doing everything we did in the JDBC Connection example, it just does it for you so you can use few lines of code.

Happy Coding

The best way to process an mboSet in Maximo Automation Script

 

As with all things programming, there is more than one way to do things, including processing an MboSet of records. As it turns out, some ways are better (faster) than others. This is probably the most common approach (especially for new developers).

    mboSet = mbo.getMboSet("Asset")
    for i in range (0, mboSet.count()):
        curMbo = mboSet.getMbo(i)
        ...

This will process the ASSET MboSet just fine, however, each time the loop compares i with the top value in the range (mboSet.count()), the code will recount how many records are in the in mboSet variable. So if you have 100,000 thousand records in the ASSET table, then the count will be run 100,000 times. The more records in the MboSet, the worse the performance is. Now, granted you could do something like this:

    mboSet = mbo.getMboSet("Asset")
    recordCount = mboSet.count()
    for i in range (0, recordCount):
        curMbo = mboSet.getMbo(i)
        ...

This would only perform the count only once and would improve performance. However, there is a way you can process the mboSet without even performing the mboSet.count():

    mboSet = mbo.getMboSet("ASSET")
    curMbo = mboSet.moveFirst()
    while curMbo:
        ...
        curMbo = mboSet.moveNext()

This will process each record in the record set but since we don't call .count() at all, the performance is better. The Count() method is a costly one (performance wise) and its use should be minimal. In the world of Maximo automation scripting, performance can quickly become a big issue, so every little bit will help.

Happy coding

User Input in Maximo Automation Scripts

 

In Maximo, it appears that there is no way to get user input from a user in an Automation Script. Automation scripts are great at doing back group tasks and things that do not require addition user input. However, it turns out that you can get user input in an automation script (although it is a bit cumbersome and limited in its functionality.) You cannot have the user type in text that you need (if you need this kind of input, then create a dialog box), but you can get some input based on button selection.

This code was taken from java class development and adapted to automation script, so if you want to do this in a java class, then you can.

This code is not perfect as it will appear as an error when they save and then they will be able to make the select that will allow your script to finish.

The user input options are based on the buttons that are available to the MsgBox. They are: OK, Close, Cancel, Yes, and No.

In this example, we are going to trigger off the Asset Priority field and if the user entered a priority of 1, then we will ask them if they want to send an email. Let’s get geeky.

Steps:

1.    In the Database Configuration application, select the Messages action and create a new message with the following values:

    Message Group: XXXXX
    Message Key: yyyyy
    Display method: MSGBOX
    Message ID Prefix: BMXZZ
    Message ID Suffix: I
    Display id: 1
    Value: Asset custodian can be notified through email when priority {0} is set. Send email?
    Button Selection: Check Yes and No Buttons

2.    Go to Automation Scripts application, create a script with an attribute launch point to run the Attribute Launch Point.

3.    Specify the launch point name, and select the ASSET object and the PRIORITY attribute.

4.    In the Events section, choose the Run Action radio button.

5.    Specify the script name.

6.    Paste the following source code and then click Create.

    from psdi.util.logging import MXLoggerFactory

    logger = MXLoggerFactory.getLogger("maximo.script")

    # logic implementation if user selects Yes choice (clicks Yes button)
    def yes ():
      logger.error("you clicked yes")

    # logic implementation if user selects No choice (clicks No button)
    def no ():
      logger.error("you clicked no")


    # logic to present the choice message initially
    def dflt ():
      params=[""]
      logger.error("Throw ERROR")
      # Use the service utility's yncerror() method to push the choice message
      service.yncerror("demo", "userinput",params);

    # Declare the user input choices and the corresponding functions implemented in this script
    cases = {service.YNC_NULL:dflt, service.YNC_YES:yes, service.YNC_NO:no}

    # Make sure the choice message is presented only
    # if the field validation was triggered from user interface
    if interactive:
       if priority < 2:
         logger.error ("About to do something")
         # Use the service utility's yncuserinput() method to trigger the entire interaction
         # User's response is stored in a local variable x
         x = service.yncuserinput()
         logger.error("User input: "+str(x))
         # Process the user input using Jython's case statement
         cases[x]()

 

Now go into assets and change the priority of an asset to. Now save. You should receive a message about errors. Click on the error, click Yes or No and you script will process accordingly.

If you are wondering how this code works, what happens is when the user is presented with the message box, your script is actually done executing. When a users clicks on one of the buttons, the script is called again. Keep this in mind as your code as your code will be executed twice.

This is a nice piece of code to have in your tool box but probably not one you will use much.

Happy Coding

Understanding Zombies in Maximo Development

 

No, this is not a diatribe on survival techniques in a hypothetical post apocalyptic world. We will be talking about real zombies. In Maximo zombies do exists. Chances are, if you have done any coding in Maximo, you have created a zombie but never had to deal with it as once you created it, because you were done processing and you let garbage collection clean up your zombie.

The first thing we need to do is define what a zombie is (for those that don't know). All Maximo Mbos are part of a transaction. That means that once you are done making your changes and execute the save() method, your changes are written to the database. Since the save() command will update the database, the Mbo is considered to a "Live" Mbo. An Mbo becomes a Zombie when it loses that transaction. The Mbo will still function and act like a live Mbo (all field classes, autoscripts, etc will still function), but when you call the save() method, nothing happens. The data is NOT written to the database and you do NOT get an error. In your code it will look like everything processed correctly but your data did not get updated to the database. So how does an Mbo lose its transaction (aka, become a zombie)? It turns out that when you call the save() method, Maximo closes the transaction that the Mbo was part of. Since Maximo does NOT assign it a new transaction, the Mbo becomes disconnected from the database. It becomes a Zombie data record.

Let's look at an example. Here we assume we have a valid Asset Mbo and MboSet objects and we want to update the description:

     …  
     assetMbo.setValue("Description", "This is our new Truck.")  
     assetMboSet.save();  
     assetMbo.setValue("Description", "Now it is a car.");  
     assetMboSet.save();  
     String description = assetMbo.getString("Description");  
     … 

So what do you think the value of the Description will be in the database? The answer is "This is our new Truck.". However, the value of the variable "description" is "Now it is a car." The reason is that once the save() method was called, the assetMbo object became a zombie and although it still acts like live Mbo, it will not update the database. The object (assetMbo) has one value while the database has another. The worst part is that you did not receive an error or anything in your code to tell you that the save did not work.

There is no way to make the assetMbo a live Mbo once it has gone zombie. (Just like in real life, there is no cure for zombism.) Once a save is called, all Mbos that are part of the MboSet become zombies. That means if you ask the MboSet for an Mbo, it will be a zombie Mbo. You have to go back to the database and re-retrieve the record. Also, any child MboSet created from a zombie Mbo will have zombies Mbos.

Now in our example it is pretty easy to see that after the first save, the Mbo is a Zombie, but Maximo is pretty complex and someone else's code could be performing a save that you are not aware of. IBM does have a way to detect if an Mbo has gone zombie on you. You can call isZombie() method on the Mbo object.

     …  
     if assetMbo.isZombie():
       # how rude, someone zombified our Mbo  
       # now we have to either throw an error so someone can go find that save and remove it   
       # or go retrieve the record again.  
     …  

It is a simple check and, given good coding practices, will probably only be used for debugging. This check is ONLY available to the Mbo. There is no way to directly see if all Mbos on an MboSet have gone zombie. You would have to grab each Mbo from it and check to see if they are zombies.

So far we have talked about Zombie Mbos like they are a bad things but they have a good use too. Since they act just like a live Mbo but can never update the database, they are great for passing to class files that should never be updating the record anyway. One example I can think of would be a third party API that wants you to pass it an Mbo. Giving the API a Zombie will ensure that they cannot affect the data while providing them the full functionality of the Mbo. Basically any situation where you want to make sure the code can never update the database, a zombie is a good option.

So, how do you get a zombie Mbo? Well you could get the Mbo and then call save(), but I would not recommend this. This would cause the "changed by" field to be updated. As it turns out, IBM provides a method to get an Mbo from an MboSet as a Zombie. Here is an example:

     …  
     assetMboSet.moveFirst()  
     zombieMbo = assetMboSet.getZombie()
     …  

Now our Mbo is a zombie. Although it is a zombie, it is still a full MboRemote object and since we got it from asset, we can even cast it to an asset object Mbo (which will still be a zombie object). While assetMboSet object can still give out "live" Mbos, zombieMbo will only give out zombie Mbos. Sadly there is only one getZombie() method so you can't call getZombie(0) to get the first Mbo. Instead you have to use the MboSet "move" commands (moveNext(), movePrev(), moveFirst(), moveLast()) to move to the record you want and then call the getZombie() to get the record.

As you can see zombies are real. If you have called the MboSet.save() method, then you have created Zombies but since logically, the save() should be the very last thing you do, you have never had to deal with a zombie. Even so, it is important to be aware that they do exist and if, in your code, you see behavior where your updates are not making it into the database after you call save(), then you might be dealing with a Zombie. 

Happy Coding

Understanding Maximo Transactions

 

When you are adding or updating records in Maximo via code (e.g. Java, Autoscript, etc), then you need to understand Maximo transactions and when you are adding something in the current transaction (so when the user clicks 'save', you record will be saved) or when you have created a new transaction (and you have to save it via code).

I recently had this requirement: when a user tries to save an asset with a location, the system must go out and look at the location for other assets. If there are no other assets attached to the location, then add a dummy asset and attach it to the asset also. (Yes there was a functional reason for this.)

This is a really good example to show both ways of working with transactions in Maximo. For the new asset, we can either attached it to the current save so when the save process finishes, it will also save our new asset. This has a benefit of, should something go wrong on the save, then our changes are also not saved. Here is the code snippet (autoscript):

    ...  
    # get Locatoins MBO Set. this is the key our transaction  
    locationMboSet = mbo.getMboSet("LOCATIONS")

    # get current location record  
    curLocation = locationMboSet.getMbo(0)

    # get all assets for the current location  
    assetMboSet = curLocation.getMboSet("ASSETS")

    # don't look at the current record (in case the users is updating the record).  
    assetMboSet.setWhere("assetnum != " + mbo.getString("ASSETNUM") + "'")
    assetMboset.reset()
    # check for no records  
    if assetMboSet.count() == 0:
       # add dummy asset  
       dummyAsset = assetMboSet.add()
       dummyAsset.setValue("assetnum", "DUMMY"+ mbo.getString("assetuid").substring(7))
       dummyAsset.setValue("description","DUMMY place holder Asset do not use")  
    ...  

In our example how we got the Locations MBO Set is very import. You will notice that I used the current mbo (the getMboSet() method). By doing this, it keeps that record set as part of the current transaction in Maximo. So later in the code, when I add the new Asset, it is also part of the same transaction and Maximo will save or roll it back with the main record that is being added/updated. Doing it this way you would never want to perform a save via code as it would cause an error to the user when the save tried to happen within Maximo (the dreaded "record has been updated by another user").

However, had I used this line of code to get the locations MBO Set:

     ... 
     locationMboSet = MXServer.getMXServer().getMboSet("LOCATIONS",...)  
     ...  

Maximo would have created a new transaction for the locations MBO set. That means that for this code to work, I would have to add a locationMboSet.save(). Without the save(), I would lose my new asset record. The other thing is that since I have done my save, the new asset would exist before the user has officially saved theirs. (This transaction completes before the Maximo transaction does.)

Both methods have their place and I have used both. It is important to understand how to use each and what that means to your code.

Happy Coding

Trouble with Maximo Relationships

 

No this is not going to be advice for your love life. I ran into an issue with adding an Mbo to an MboSet that caused unexpected behavior in processing of the Record set.

First a little background. The business requirement was that for every Work Order task of type "X", an automation script needed to create a new task of type "Y" on the same work order. This automation script would be called either by an escalation or workflow. With the base mbo being the work order, I created the following code:

     woTasksMboSet = mbo.getMboSet("WOACTIVITY") 
     woTaskMbo = woTasksMboSet.moveFirst() 
     while woTaskMbo is not None: 
       if woTaskMbo.getString("TASKTYPE","X"): 
         newWoTaskMbo = woTasksMboSet().add() 
         newWoTaskMbo.setValue("TASKTYPE","Y") 
         … set fields 
       woTaskMbo = woTasksMboSet.moveNext() 

In testing, when there was only one task with type "X", the code worked fine but if there were two "X" tasks, the first record would process and then the loop would stop. After adding a few logging statements, I found that when the new record was added, it was re-organizing the records already in the woTaskMboSet object so that the record I was on became the last record. Very strange. Next I had the idea of using a setWhere to filter the records to just the records I want. That way when I add the new record, it would not meet the 'where' condition and thus not affect my current record set. So I tried the following:

     woTasksMboSet = mbo.getMboSet("WOACTIVITY") 
     woTasksMboSet.setWhere("tasktype = 'X'") 
     woTaskMbo = woTasksMboSet.moveFirst() 
     while woTaskMbo is not None: 
       newWoTaskMbo = woTasksMboSet().add() 
       newWoTaskMbo.setValue("TASKTYPE","Y") 
       … set fields 
       woTaskMbo = woTasksMboSet.moveNext() 

Sadly, this returned the same results as before, once the first record was processed, it would stop processing. Adding a '.count()’ in the logging I found that even though I was adding a new record with tasktype "Y", it was still being added to my record set, even with the setWhere() condition. My next thought was maybe the issue was that I was using the same MboSet object to loop through the records and add. So next I created a separate MboSet object just for adding records.

     woTasksMboSet = mbo.getMboSet("WOACTIVITY") 
     woTasksMboSet.setWhere("tasktype = 'X'") 
     addWOTasksMboSet = mbo.getMboSet("WOACTIVITY") 
     woTaskMbo = woTasksMboSet.moveFirst() 
     while woTaskMbo is not None: 
       newWoTaskMbo = addWOTasksMboSet().add() 
       newWoTaskMbo.setValue("TASKTYPE","Y") 
       … set fields 
       woTaskMbo = woTasksMboSet.moveNext() 

Unfortunately, this still caused the new records to be added to the woTasksMboSet object and re-arranged the order of the records. It was very frustrating. It turns out that the solution was in the relationship. As long as I use the same relationship to read and add records, the new record will affect the record set. I created a relationship that returns just records with tasktype = "X" and then used the WOACTIVITY relationship to add the record.

     woTasksMboSet = mbo.getMboSet("WOACTTASKTYPEX") 
     addWOTasksMboSet = mbo.getMboSet("WOACTIVITY") 
     woTaskMbo = woTasksMboSet.moveFirst() 
     while woTaskMbo is not None: 
       newWoTaskMbo = addWOTasksMboSet().add() 
       newWoTaskMbo.setValue("TASKTYPE","Y") 
       … set fields 
       woTaskMbo = woTasksMboSet.moveNext() 

This bit of code finally worked as it processed both Tasks with tasktype = 'X' and added two new records with tasktype = 'Y'. As long as the relationship I use for processing (WOACTTASKTYPEX) excludes the record I am adding, then it will never appear in my record set (messing up the order).

Happy Coding.

How to use a KPI to monitor cron tasks and scheduled reports in Maximo

 

Requirement:

In order to provide better system monitoring, a solution needs to be developed that will allow support staff to quickly and easily monitor the status for Maximo cron tasks and reports that are mission critical and need to run daily. This solution should have little impact on the Maximo system as well as easy to maintain. Currently when a cron task or report does not run, there is no way for the support staff to know this, aside from waiting for a user to call in a help desk ticket. This had caused cron tasks and reports to be down for days.

Solution:

Use the tools within Maximo to help monitor the status of cron tasks and reports. This can be done by creating a KPI for each cron task and report that needs to be monitored. These can then be added to the start center of the support status. This will allow the support status to log into the system daily and quickly see the status of those cron tasks and reports.

It is recommended that only a small set of cron tasks and reports be monitored in this way. These should be the most critical of job/reports. This will help the log in performance of the support staff.

Steps to fix:

Create a KPI for each cron task to be monitored (one for each cron task instance to be monitored):

     KPI Name: Give it a unique name.
     Description: Something like 'Number of days since <cron task name> has run".  
     Select: select sysdate - endtime from (select crontaskname,instancename, max(endtime) as endtime from crontaskhistory group by crontaskname,instancename)
     Where:  where crontaskname = '<cronTaskName>' and instancename = '<instanceName>' 
     Target: 0
     Caution: 1
     Alert: 1

 Create a KPI for each Report to be monitored (one for each report to be monitored):

 

     KPI Name: Give it a unique name.
     Description: Something like 'Number of days since <Report name> has run".  
     Select: select sysdate - lastrundate from report
     Where:  where reportname = '<reportName>'
     Target: 0
     Caution: 1
     Alert: 1

Then on the default start center for support staff, add the created KPIs. Now when the support staff logs in, they will see alerts for whenever a cron task/report did not run within the last day.

This example is set up for jobs that need to run everyday, but you could change this to monitor jobs that do not run as often by changing the Target, Caution and Alert values on the KPI to match the job schedule.

Happy Coding

Calling an Automation Script from another Automation Script in Maximo

 

The introduction of automation scripts in Maximo has radically changed and (in many ways) improved the development process in Maximo. However, it has come with a few drawbacks. One of the biggest is the fact that instead of a consolidated single piece of code, you now have several pieces of code, all triggering off a common event. The problem is that most of these scripts all trigger, checking for a condition they need and exiting when that condition is not met. Another issue is that you cannot guarantee what order scripts will trigger. This situation, if poorly implemented, can cause major performance issue and become a debugging nightmare.

This can be mitigated (to some extent). A big piece of this is by having an automation script call anther automation script. Using this approach, you could create a single, central "triggering" script that would check for the required condition and then call the subsequent automation script to perform the required action. Of course, this approach requires a lot more planning and following of your processes. So enough of the philosophical talk, let's get your hand geeky.

There are two different ways to call an automation script from another and each have their strengths and weaknesses. First is to call the script directly:

    service.invokeScript("YOUR SCRIPT NAME")

This will execute the script. That script will have access to the system variables (e.g. mbo) that your current script has. When the script is done, it will continue executing your code in the calling script. This example is great if you just want to execute the script but don't need to pass it any specific values. However, it would be nice if you could pass in values to the script. Turns out this can be done. If the child script has variables, those can be passed in using a hashmap. For example, let's say we have a script that multiples two values ("IN" variables X and Y) and stores the results in and "OUT" variable Z. We would call that script this way:

    from java.util import HashMap

    x = 5
    y = 3
    vars = HashMap()
    vars.put("X",x)
    vars.put("Y",y)
    service.invokeScript("Multiply",vars)
    z = vars.get("Z")

The above code calls a script called "Multiply" and passes in a 5 and a 3. Then then retrieves the value Z from the script after it has executed. Using this method allows you to create functions that you can call with in any script.

The second way to call another script is by calling it as an ACTION. First you would create an action the executes your desired script. Then you would call it this way:

    actionSet = MXServer.getMXServer().getMboSet("ACTION", mbo.getUserInfo())
    actionSet.setWhere("action = 'action_name'")
    actionSet.reset()
    actionSet.getMbo(0).executeAction(mbo) 

This code would call an action called 'action_name'. It may appear that this approach is less desirable as 1) the only variable you can pass in an an mbo object and 2) it takes more lines of code. However, the fact that you pass in an mbo object is where this method shines. There is nothing saying that the mbo object has to be the current mbo object. You could be processing an Asset object but call a script that takes an workorder mbo.

I realize that these two methods won't meet every requirement you might have for calling another automation scripts but these two methods can help you clean up your scripts as well as allow you to build a library of reusable code.

Both of these methods have their place and are pieces of code to keep in your coding tool box.

 Happy Coding.

Using and Autoscript as a Cron Task

 

Normally, in Maximo, if you want to create a cron task to perform some function in Maximo, you would have to create a Java Class files and build and deploy it with the ear. However, custom java class development is being discouraged by many companies and trying to deploy a class file in a cloud environment can be challenging at best. It turns out that you don't have to create a java class file to create a cron task. Instead you can create an Automation Script to perform the same function and then call/schedule your automation script from the cron task screen. Since in an automation script you have full access to the java library, there is little you can do in an class file that you can't do in an automation script. This is possible because of a built in class file from IBM that will call your class file for you. You can even pass in parameters to your class file. Here is how.

Automation Script

  1. In the Automation Scripts application, on the List tab, select the Create > Script action.
  2. Specify a name, description, and log level for the script.
  3. If the script requires variables, in the Variables section, add new rows to declare the variable and bindings. You cannot specify bindings to a Maximo® business object. You can specify only LITERAL, SYSPROP, and MAXVAR bindings. No mbo fields allowed.
  4. Enter the source code of the automation script and click Create to save the automation script in the database.

Cron Task

  1. In the Cron Task Setup application, create a new cron task definition.
  2. Enter a name and description for the cron task.
  3. In the Class field, enter com.ibm.tivoli.maximo.script.ScriptCrontask. (copy and paste as case matters)
  4. In the Cron Task Instances section, add a row.
  5. Specify the cron task instance name.
  6. Set the schedule for when the cron task is run.
  7. Select Run As User. The security authorizations that are granted to the specified user determines whether business logic that is related to Maximo business object can run in the script code. For example, a value cannot be set in a record unless the specified user has the security authorization to write values into that record.
  8. In the Parameters tab, in the SCRIPTARG row, specify a value(s) that represents an argument for the cron task. To specify more than one value, separate them by commas. This is where you pass in values to the script.
  9. In the SCRIPTNAME row, specify the name of the script that you created to run as part of the cron task. SCRIPTNAME is a mandatory parameter that must be populated. The script name that you specify is passed to the automation script in the form of the scriptName implicit variable.
  10. In the Details section, select the Active check box to activate the cron task instance.
  11. Save the record.

To access the values from SCRIPTARG, in your automation script, you access a variable call 'arg'. Here is an example of how to access it:

    if arg:
       srOwner,wfProcess = arg.split(",")

This example assumes that the cron task will be passing in two variables, the owner of the SR and the workflow process name. Also, using the split method we can use something other than a comma as the delimiter for the arguments, in case you need to pass in a comma for some reason.

Remember, since you are calling this from a cron task and not a screen, there is no mbo object attached. This means the variable 'mbo' is undefined in your script.

So let's talk about the pros and cons of this approach.

Pros:

  • No class file to deploy
  • Can be implemented in a cloud hosted environment without the need for file or web server access.
  • Changes are instant, so quicker debug times (no rebuild/deploy)
  • Development language is not limited to Java (see Maximo's supported Automation Script Languages).

Cons:

  • Interpreted script so will be slower for processing large amount of data.
  • Passing in parameters can be awkward since they have to be a comma delimited list.

Happy Coding