### Call Automation Script with Parameters Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/rest/scripthandler Example of invoking the script with a specific site ID parameter via a GET or POST request. ```http https://myurl.com/maximo/oslc/script/setinsertsite?lean=1&siteid=BEDFORD ``` -------------------------------- ### Setup Logic for Virtual MBOs Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/objectscripts/objectlaunch Use this script point for the 'setup' event on non-persistent objects to fill the MBOSET with MBOs. The 'onsetup' variable must be true for this event. Ensure the Maximo property 'mxe.script.callsetuponinit' is set to 1 and refresh the script cache or bounce the server for changes to take effect. ```python if onsetup: mbo = mboset.add() mbo.setValue("attr1","value1") mbo.setValue("attr2","value2") ``` -------------------------------- ### Example GET Request with Custom Query Parameters Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/rest/osquery This example shows how to call the Maximo REST API using a GET request, including custom query parameters for an object structure. The 'savedQuery' parameter specifies the custom query, and 'sqp:' parameters pass values to the script. ```http https://myurl.com/maximo/oslc/os/mxapiwodetail?lean=1&oslc.select=wonum,description,siteid&oslc.pageSize=40&savedQuery=OSQUERY.MXAPIWODETAIL.EMXWOFILTER&sqp:assetnum=11430&sqp:location=BR430 ``` -------------------------------- ### Set WS Security Header Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/integration/endpointhandler Example of how to set a WS Security header using the setupHeaders function. Requires importing JDOM and XMLUtils. ```python from org.jdom import Element from org.jdom import Namespace from java.util import HashMap from java.util import ArrayList from psdi.iface.util import XMLUtils from javax.xml.namespace import QName def setupHeaders(req): ``` -------------------------------- ### Example Role Automation Script Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/otherlaunch/rolelaunch This script demonstrates how to resolve a person or person group based on record data. It uses the ScriptRoleContext to access MBOs and retrieve specific person groups. ```python def evalToPerson(ctx): # This method comes from the ScriptService mbo=ctx.getMbo() personGroup=None if mbo.getString("SITEID")=="BEDFORD": personSet=mbo.getMboSet("$EMXPERSONGROUP","PERSONGROUP","persongroup='TIER1'") personGroup=personSet.moveFirst() else: ``` -------------------------------- ### Log a message using service.log Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/coreconcepts/servicevariable Example usage of the log function to record messages at DEBUG or INFO levels. ```text service.log("setting the replacementcost..") ``` -------------------------------- ### Perform HTTP GET Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/coreconcepts/servicevariable Invokes an HTTP GET request to a specified URL and returns the response as a string. ```text respData = service.httpget("some url") ``` -------------------------------- ### Object Structure Action Script Example Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/rest/osaction This script retrieves a 'template' query parameter and uses it to set a TEMPLATEID on a communication MBO, then sends the message. It's designed to be triggered by an Object Structure Action. ```python template=request.getQueryParam("template") if template: commMbo=mbo.createComm() commMbo.setValue("TEMPLATEID", template) commMbo.sendMessage() ``` -------------------------------- ### XML Structure for MXITEM Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/integration/osevents Example XML payload used for importing items into Maximo via the MXITEM object structure. ```xml Centrifugal Pump 100-1 GPM, 60 FT-HD PUMP \ CNTRFGL PUMP100-1 SET1 ITEM ``` -------------------------------- ### Test Formula via REST API Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/otherlaunch/formulafunc Example REST API call to retrieve an asset and its calculated formula value. ```http GET /oslc/os/mxapiasset?lean=1&oslc.select=assetnum,siteid,exp.assetwocoststd&oslc.where=assetnum="11430" ``` -------------------------------- ### Example SQL for Object Structure Query Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/rest/osquery This SQL statement demonstrates how to filter Work Orders (WOs) by status, referencing a specific asset or location. It's useful for complex filtering scenarios not directly supported by standard API parameters. ```sql historyflag=0 and istask=0 and status='INPRG' and (location='BR430' or assetnum='11430') ``` -------------------------------- ### REST API GET Request with Script Attribute Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/rest/restscriptattr Example of invoking the custom script via the oslc.select parameter in a REST API URL. ```http https://myurl.com/maximo/api/os/mxapicntbookline?lean=1&oslc.pageSize=1&oslc.select=countbooknum,siteid,script.vendorcatalog ``` -------------------------------- ### Copy Custom Object Set During Duplication Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/objectscripts/duplicateobject This example shows how to copy a custom object set from the original record to the newly duplicated record. Ensure that relationships and any record-specific identifiers (like WONUM) are updated to point to the new record. ```maximo-automation-script # Copy custom object set into new record # NOTE: You most likely would need to update the values that point to your record, such as WONUM, to the new record. origChildSet=mbo.getMboSet("MYCUSTOMRELATIONSHIP") origChildSet.copy(dupmbo.getMboSet("MYCUSTOMRELATIONSHIP")) ``` -------------------------------- ### Get System Locale Script Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/mmiscripts/mmioverview This script retrieves the system's default locale and sets it as a property named 'syslocale' using the 'br' object. The 'br' object provides methods like setProperty and getProperty. ```Python from java.util import Locale br.setProperty("syslocale",Locale.getDefault().toString()) ``` -------------------------------- ### GET/POST /maximo/api/script/{SCRIPTNAME} Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/rest/scripthandler Invokes a specific automation script via a REST API call. The script can be triggered using either GET or POST methods. ```APIDOC ## GET/POST /maximo/api/script/{SCRIPTNAME} ### Description Invokes an automation script by its name. This is useful for scenarios where standard REST APIs are insufficient for processing data. ### Method GET or POST ### Endpoint /maximo/api/script/{SCRIPTNAME}?lean=1 ### Parameters #### Path Parameters - **SCRIPTNAME** (string) - Required - The name of the automation script to execute. #### Query Parameters - **lean** (integer) - Optional - Set to 1 to enable lean response format. ### Implicit Variables - **request** (OslcRequest) - Provides access to query parameters, headers, and UserInfo. - **requestBody** (string) - Contains the data submitted in the request body (for POST/PATCH/PUT). - **httpMethod** (string) - The HTTP method used for the request. - **responseBody** (byte[]/string) - Used to set the response content. - **responseHeaders** (HashMap) - Used to set custom response headers. ``` -------------------------------- ### Initialize Attribute Value with Python Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/bestpractice/overview Use this script with an Attribute Launch Point for the Initialize Value event to set an attribute's value. The script only executes when the attribute is referenced. ```python if priority is not None: thisvalue=2*priority ``` -------------------------------- ### Open a URL Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/coreconcepts/servicevariable Opens a specified URL in the browser, with an option to open in a new window. ```text service.openURL("weather.com", False) ``` -------------------------------- ### Invoke a library script using a HashMap Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/coreconcepts/libraryscripts Demonstrates calling a library script named CALC by passing a Java HashMap. ```python from java.util import HashMap map = HashMap() map.put("a",2) map.put("b",3) service.invokeScript("CALC",map) res = map.get("r") ``` -------------------------------- ### Set Attribute Values for 'On Add' Event Testing Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/troubleshooting/testingscripts Prepare attribute values for testing 'On Add' object events. Ensure attribute values are consistent to avoid errors. ```Maximo Scripting ASSETNUM TESTADD10 ASSETTYPE FLEET ``` -------------------------------- ### Override Specific Attribute for POLINE in Outbound Processing Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/integration/osevents This example demonstrates how to override the 'REMARK' attribute for a 'POLINE' MBO when the 'itemnum' is 'ITM1' during outbound processing. ```python def overrideValues(ctx): if ctx.getMboName()=='PO' and ctx.getMbo().isNull("description")==True: ctx.overrideCol("DESCRIPTION","PO "+ctx.getMbo().getString("ponum")) elif ctx.getMboName()=='POLINE' and ctx.getMbo().getString("itemnum")=="ITM1": ctx.overrideCol("REMARK","Speacial Item") ``` -------------------------------- ### Set Object Path for Virtual MBO Testing Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/troubleshooting/testingscripts Configure the object path for testing virtual (non-persistent) MBOs, including setting specific properties like status and memo. Ensure the 'mxe.script.callsetuponinit' property is set to 1. ```Maximo Scripting ASSET[assetnum=‘ASSET1’ and siteid = ‘BEDFORD’]/ASCHANGESTATUS ``` -------------------------------- ### Launch a dialog from an Action launch point Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/uiscripting/dialoginteraction Opens a specific dialog by its ID from an Action launch point script. ```jython service.launchDialog("dialogid") ``` -------------------------------- ### afterMboData Example for ITEM Object Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/integration/osevents Use the 'afterMboData' function to set field values after the MIF has processed them. This requires the field to be marked as 'Set Restricted' in the object structure to prevent the MIF from overriding your value. ```xml New Item PUMP \ CNTRFGL NEWITEM01 MOTOR SET1 ``` ```javascript function afterMboData(ctx) { if (ctx.getMosDetailInfo().getObjectName() == "ITEM") { var hier=ctx.getData().getCurrentData("HIERARCHYPATH") if (hier == "PUMP \\ CNTRFGL") { var mbo = ctx.getMbo(); ``` -------------------------------- ### Calculate spare part quantity on initialization Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/objectscripts/objectlaunch Calculates the sum of spare part quantities and assigns it to the sparepartqty attribute using an array variable. ```jython if qtys is not None: sptqt = sum(qtys) ``` -------------------------------- ### Initialize Priority Attribute Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/attributescripts/attributelaunch This script initializes the 'priority' attribute to 1 for new records in the 'BEDFORD' site. It uses the implicit variable `thisvalue` which represents the attribute for the current launch point. ```python if mbo.toBeAdded()==True and mbo.getString("site")=="BEDFORD": thisvalue = 1 ``` -------------------------------- ### beforeMboData Example for ITEM Object Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/integration/osevents Use the 'beforeMboData' function to conditionally set field values before the MIF processes them. Ensure the field is marked as 'Set Restricted' in the object structure if you want to prevent the MIF from setting it. ```xml New Item PUMP \ CNTRFGL NEWITEM01 MOTOR SET1 ``` ```javascript function beforeMboData(ctx) { if (ctx.getMosDetailInfo().getObjectName() == "ITEM") { var hier=ctx.getData().getCurrentData("HIERARCHYPATH") if (hier == "PUMP \\ CNTRFGL") { var mbo = ctx.getMbo(); var MboConstants = Java.type("psdi.mbo.MboConstants"); ``` -------------------------------- ### Real-time Sparepart Quantity Calculation Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/attributescripts/attributelaunch Implement real-time updates for calculated fields like 'sparepartqty' by creating an attribute launch point for the 'quantity' attribute on the 'sparepart' object. Use the 'Action' event and INOUT variable binding to update the owner's attribute. ```python sptqt=sptqt+quantity-quantity_previous ``` -------------------------------- ### Automation Script for oslc.select Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/rest/restscriptattr This script retrieves catalog codes from an INVVENDOR set based on the current MBO's item information. It must be created without a launch point and assigned the name VENDORCATALOG. ```python from psdi.mbo import SqlFormat catalogCodes=[] sqf=SqlFormat(mbo,"itemnum = :itemnum and orgid = :orgid and (siteid is null or siteid = :siteid)") invVendorSet=mbo.getThisMboSet().getSharedMboSet("INVVENDOR",sqf.format()) invVendorMbo=invVendorSet.moveFirst() while invVendorMbo: if invVendorMbo.getString("CATALOGCODE"): catalogCodes.append(invVendorMbo.getString("CATALOGCODE")) ``` -------------------------------- ### Set Vendor Required and Calculate Replacement Cost Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/attributescripts/attributelaunch Use the 'action' event in an Attribute Launch Point to control the 'vendor' attribute's required state and calculate 'replacementcost' based on 'purchaseprice'. Explicit OUT variables 'vend_required' and 'rc' can be used. ```python if purchaseprice >= 100: vend_required=True else: vend_required=False rc = purchaseprice/2 ``` -------------------------------- ### Calculate Asset Meter Value Script Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/otherlaunch/actionlaunch Jython script to calculate a new meter reading based on existing meter values. ```Jython y=float(iplr)+float(olr) if y!=float(plr): pnr=str(y) ``` -------------------------------- ### REST API Call for Object Structure Action Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/rest/osaction Example of how to call a custom Object Structure Action (SENDCOMM) via a POST request to the Maximo REST API. Ensure to use the correct object structure and provide necessary parameters. ```http https://myurl.com/maximo/api/os/mxapisr/_U1IvMTA2Nw--?lean=1&action=SENDCOMM&template=1014 ``` -------------------------------- ### Conditional MboSet Fetch Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/objectscripts/objectrelation This script fetches different MboSets ('openwo' or 'allwo') based on whether the 'priority' field is null. It's useful for dynamically selecting related records. ```python if mbo.isNull("priority")==False: mboset = mbo.getMboSet("openwo") else: mboset = mbo.getMboSet("allwo") ``` -------------------------------- ### Calculate and set read-only attribute on initialization Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/objectscripts/objectlaunch Sets the sparepartqty attribute to read-only and calculates its value during the Asset initialization event. ```jython sptqt_readonly=True if qtys is not None: sptqt = sum(qtys) ``` -------------------------------- ### Create Lookup Script for Address Attribute Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/attributescripts/attributelaunch This Nashorn JS script fetches country data from an external API and populates a COUNTRY MBO set. It uses implicit variables `service`, `userInfo`, `srcKeys`, and `targetKeys` for integration and data mapping. ```javascript importPackage(java.util) importPackage(Packages.psdi.server) var jsonResp = service.httpget("..url..","..userid..","..password.."); var countries = JSON.parse(jsonResp); var countriesSet = MXServer.getMXServer().getMboSet("COUNTRY", userInfo); for(var cnt in countries) { var cntMbo = countriesSet.add(); ``` -------------------------------- ### Conditional Costly Initialization with Python Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/bestpractice/overview Execute costly initialization logic only when the object is initialized from the Main tab and not from the List tab, using UIContext to check the current context. ```python from psdi.common.context import UIContext if UIContext.getCurrentContext() is not None and UIContext.isFromListTab()==False: ..costly initlization.. ``` -------------------------------- ### EJB Configuration for Scripted MDB Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/integration/mdb XML configuration for the ejb-jar.xml file to link the MDB to the specified script. ```xml JMSScriptListenerBean-1 psdi.iface.jms.JMSScriptListenerBean Container javax.jms.Queue SCRIPTNAME java.lang.String CUSTMDB ``` -------------------------------- ### Test Object Structure Query Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/troubleshooting/testingscripts Define the object structure name, MBO path, and parameters to test query functionality. This applies a WHERE clause to the MboSet based on the provided parameters. ```Maximo Scripting WORKORDER ``` -------------------------------- ### Set Object Path for Script Testing Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/troubleshooting/testingscripts Use this format to specify an MBO for testing. It selects an asset with a specific asset number and uses its MBO for the 'mbo' variable in the script context. This is useful for testing various launch point types. ```Maximo Scripting ASSET[assetnum='SPFN0001'] ``` -------------------------------- ### Outbound External Exit Script for Invoke Channel Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/integration/invocationevents Prepares the outbound request by dynamically setting query parameters from the current MBO data. ```python from java.util import HashMap from psdi.iface.router import HTTPHandler from psdi.iface.mic import IntegrationContext from psdi.iface.mic import MetaDataProperties epProps = HashMap() urlProps = HashMap() zip = irData.getCurrentData("ADDRESS4"); urlProps.put("zips",zip) epProps.put(HTTPHandler.HTTPGET_URLPROPS,urlProps) ``` -------------------------------- ### Properly Close MboSet Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/bestpractice/overview When an MboSet is created using MXServer.getMXServer().getMboSet(), the script is responsible for closing it. Use a try-finally block to ensure mboset.cleanup() is called, preventing potential OutOfMemory errors. ```python try: ..some code.. finally: mboset.cleanup() ``` -------------------------------- ### Implement custom web service handler with WS-Security Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/integration/endpointhandler Leverages JAXWSClient and JDOM to manually construct WS-Security UserNameToken headers for web service calls. ```python from org.jdom import Element from org.jdom import Namespace from psdi.iface.webservices import JAXWSClient from java.util import HashMap from java.util import ArrayList from psdi.iface.util import XMLUtils from javax.xml.namespace import QName ns = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" ``` -------------------------------- ### Control Vendor Readonly and Set Replacement Cost using MBO APIs Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/attributescripts/attributelaunch Leverage standard MBO APIs and the implicit 'mbo' variable within an Attribute Launch Point's 'action' event to control field states and values. This provides more granular control but requires awareness of MBO API behavior and potential read-only constraints. ```python from psdi.mbo import MboConstants if purchaseprice >= 100: mbo.setFieldFlag("vendor",MboConstants.READONLY, True) else: mbo.setFieldFlag("vendor",MboConstants.READONLY, False) mbo.setValue("replacementcost",purchaseprice/2) ``` -------------------------------- ### Set Object Path for Attribute Init Event Testing Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/troubleshooting/testingscripts Specify the object path to test attribute initialization scripts. The script can set values based on existing MBO attributes. ```Maximo Scripting ASSET[assetnum=‘1001’] ``` -------------------------------- ### Error and Warning Handling Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/coreconcepts/servicevariable Functions for throwing exceptions and setting warnings in the MBO set. ```APIDOC ## error ### Description Throws an MXException with the specified group and key. ### Parameters - **group** (String) - Required - **key** (String) - Required - **params** (String[]) - Optional ## setWarning ### Description Sets a warning to the MBO set in context, used by REST APIs and classic UI. ### Parameters - **group** (String) - Required - **key** (String) - Required - **params** (String[]) - Required ``` -------------------------------- ### Logging Functions Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/coreconcepts/servicevariable Functions for real-time logging at various severity levels. ```APIDOC ## log ### Description Logs a message at DEBUG or INFO level based on script settings. ### Parameters - **log message** (String) - Required ## log_debug / log_info / log_warn / log_error / log_fatal ### Description Logs messages at specific severity levels. Overloads exist to include a Throwable error object. ### Parameters - **logMsg** (String) - Required - **error** (Throwable) - Optional ``` -------------------------------- ### Define a basic library script Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/coreconcepts/libraryscripts A simple script that performs a calculation using variables a and b. ```python r=a*b ``` -------------------------------- ### Real-time Logging with service.log Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/troubleshooting/debugscript Leverage the `service.log` API for real-time logging, which is more effective for debugging long-running scripts than traditional print statements. This method logs immediately, unlike the autoscript logger which logs after script execution. ```Python service.log("hey there - I am in Asset "+mbo.getString("assetnum")) ``` -------------------------------- ### Set Work Order Priority in After User Exit Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/integration/enterpriseevents An after user exit script to set the work order priority to 1 if the vendor is 'A0001' and the priority is not already set. ```python if irData.getCurrentData("vendor")=="A0001" and irData.isCurrentDataNull("wopriority")==True: irData.setCurrentDataAsInt("wopriority",1) ``` -------------------------------- ### Throw Real-time Errors with MXApplicationException Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/objectscripts/objectlaunch Uses the MXApplicationException API to trigger real-time validation errors. ```Jython from psdi.util import MXApplicationException if : params = [prefix,assettype] raise MXApplicationException('asset','invalidassetprefix', params) ``` -------------------------------- ### Specify Object Path for 'Can Add' Event Testing Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/troubleshooting/testingscripts Define the object path to test 'Can Add' events, especially when dealing with related objects like POLINEs that depend on parent PO data. ```Maximo Scripting PO[ponum=‘1056’]/POLINE ``` -------------------------------- ### Set Domain ID for Lookup Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/attributescripts/attributelaunch This script sets the 'domainid' based on the 'assettype' attribute, intended to be used in conjunction with a Retrieve List launch point script. ```python if mbo.isNull("assettype"): domainid="ASSETP" else: domainid="ASSETP2" ``` -------------------------------- ### Python Script for Dynamic SQL Query Generation Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/rest/osquery This Python script dynamically constructs a SQL WHERE clause based on provided 'assetnum' and 'location' parameters. It handles cases where one or both parameters are provided, or if they are not provided (using a default '*' value). ```python def isSet(variable): return variable and variable!='*' from psdi.mbo import SqlFormat query="historyflag=0 and istask=0 " if isSet(assetnum) and isSet(location): query+=" and (assetnum=:1 or location=:2) " elif isSet(assetnum): query+=" and assetnum=:1 " ``` -------------------------------- ### Specify Object Path for 'Can Delete' Event Testing Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/troubleshooting/testingscripts Use this object path format to test 'Can Delete' events, ensuring that conditions like asset type are met before deletion. ```Maximo Scripting ASSET[assetnum=‘7500’] ``` -------------------------------- ### Context (ctx) APIs Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/integration/osevents This section outlines the Context (ctx) APIs and their common uses within Maximo Autoscript functions. The `ctx` variable provides access to various functionalities for handling integration data and processing logic. ```APIDOC ## Context (ctx) APIs ### Description Provides access to integration data dictionary cache information for the object structure being processed. ### Method `ctx.getMosDetailInfo()` ### Applicability Inbound and outbound --- ### Description Supports the skipping of a MBO (Maximo Business Object) that should not be processed in the inbound/outbound message. ### Method `ctx.skipMbo()` ### Applicability Inbound and outbound --- ### Description Supports skipping an entire transaction or message from processing. ### Method `ctx.skipTxn()` ### Applicability Inbound and outbound --- ### Description Supports ending the processing at the point of execution. It will not process the children data of the message. ### Method `ctx.complete()` ### Applicability Inbound and outbound --- ### Description Supports continuing the processing at the point of execution, likely used as part of conditional logic. ### Method `ctx.process()` ### Applicability Inbound and outbound --- ### Description Retrieves the parent MBO, which can be used from a child that does not yet have an MBO created. ### Method `ctx.getParentMbo()` ### Applicability Inbound --- ### Description Identifies if the current MBO is the root level MBO of the object structure. ### Method `ctx.isPrimary()` ### Applicability Inbound --- ### Description Supports the retrieval of user information, which would be needed for a script to create a new MBO. ### Method `ctx.getUserInfo()` ### Applicability Inbound and outbound --- ### Description Supports by-passing the MBO creation and continuing to the next MBO to be processed. This could be used when one MBO creates a child MBO, and the integration processing wants to bypass the creation of that child MBO. ### Method `ctx.bypassMbo()` ### Applicability Inbound --- ### Description Provides access to the message type (for example, Sync, Create). ### Method `ctx.getMsgType()` ### Applicability Inbound --- ### Description Provides support to set the message type (for example, Sync, Create). It can be used before processing only. ### Method `ctx.setMsgType(String msgType)` ### Applicability Inbound --- ### Description Provides access to StructureData (XML message). ### Method `ctx.getData()` ### Applicability Inbound --- ### Description Gets the mboset in context for the level that is getting processed. ### Method `ctx.getMboSet()` ### Applicability Inbound --- ### Description Sets the mboset for the current level. This is leveraged for cases where you would want to create the mboset for that level in a custom way. ### Method `ctx.setMboSet()` ### Applicability Inbound --- ### Description Sets the MBO for the level. This is done when you want to create or find the MBO in a custom way. ### Method `ctx.setMbo(MboRemote mbo)` ### Applicability Inbound --- ### Description Gets the primary mboset (the root object) for this object structure. ### Method `ctx.getPrimaryMboSet()` ### Applicability Inbound --- ### Description Provides support for retrieving the primary (root) MBOs of an object structure when processing a child MBO. ### Method `ctx.getPrimaryMbo()` ### Applicability Inbound --- ### Description Used for setting the table for a process, for example, when you have a non-persistent MBO such as MXRECEIPT, it has processing logic to determine the table (MBO) to be updated (either MATRECTRANS or SERVRECTRANS). This API should be used in the `beforeProcess(ctx)` function. ### Method `ctx.setProcessTable(String processTable)` ### Applicability Inbound --- ### Description Used in the `preSaveRules(ctx)` function, this can be used to inject custom logic to operate on a completed object structure that is now prepared at this point in the processing. ### Method `ctx.setSkipBaseAdditionalRules()` ### Applicability Inbound --- ### Description Sets the processing action of a MBO to be an Update (versus an Add or Delete). ### Method `ctx.processAsUpdate()` ### Applicability Inbound --- ### Description Sets the processing action of a MBO to be an Add (versus an Update or Delete). ### Method `ctx.processAsAdd()` ### Applicability Inbound --- ### Description Sets the processing action of a MBO to be an Add (versus an Update or Delete) and will create the MBO at the end of the collection rather than by default it would be created at the top of the MBO collection. ### Method `ctx.processAsAtEnd()` ### Applicability Inbound ``` -------------------------------- ### Sample JSON Response Structure Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/integration/invocationevents The expected JSON format returned by the external REST service. ```json { "zips":[ { "state":"Blah", "city":"Blah1" …. } ] } ``` -------------------------------- ### Email Sending Endpoint Handler Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/integration/endpointhandler This section describes how to set up an endpoint handler for sending emails using automation scripts in Maximo. ```APIDOC ## Setting up an Email Sending Endpoint Handler ### Description This process outlines the steps to configure Maximo to send emails using custom automation scripts. ### Steps 1. **Add/Modify Handler**: In the Endpoints application, use the 'Add/Modify' handlers action. Name the handler 'SCRIPT' and set the class name to `com.ibm.tivoli.maximo.script.ScriptRouterHandler`. (Requires Maximo 7.6.1.2 or later). 2. **Create Endpoint**: In the Endpoints app, create a new endpoint. 3. **Set Handler**: Set the handler for the new endpoint to 'SCRIPT'. 4. **Set Script Property**: Set the 'script' property to the name of your automation script (e.g., 'emailme'). ### Implicit Variables - `requestData` (Byte[]): Raw byte data for endpoints. - `requestDataS` (String): String data for endpoints (if conversion from byte[] is possible). - `responseData` (OUT, String or Byte[]): Variable to store the response from the endpoint call. All endpoint `metaData` content is available as script variables. For Publish Channel endpoints, JMS/Kafka message headers are set as variables (e.g., `destination`). ### Example Script Snippet (Sending Email) ```java from psdi.server import MXServer from java.lang import String MXServer.getMXServer().sendEMail( to, from, subject, String(requestData)) ``` ### Configuration Notes - Define `to`, `from`, and `subject` as literal variables within your script. - The `subject` can be static (e.g., "Email from Maximo") or dynamically generated. - Email addresses and subjects can be derived from the incoming `requestData`. ``` -------------------------------- ### Define a function-based library script Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/coreconcepts/libraryscripts A library script containing multiple utility functions. ```python def mult(a,b): return a*b def add(a,b): return a+b ``` -------------------------------- ### Test Inbound Object Structure Script - beforeProcess Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/troubleshooting/testingscripts Test the `beforeProcess` function for inbound object structure processing by selecting XML or JSON files. This function can skip transactions based on specific conditions. ```XML MXITEM1.XML ``` ```JSON MXITEM1.JSON ``` -------------------------------- ### ScriptSOAPReq Methods Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/integration/endpointhandler Methods available for the ScriptSOAPReq object to manage SOAP request headers and configuration. ```APIDOC ## ScriptSOAPReq Methods ### Description Methods to configure SOAP requests within a web service handler exit. ### Methods - **getData()** (byte[]) - Get request byte data. - **getMetaData()** (Map) - Get request metadata. - **getEndPointName()** (String) - Get the endpoint name. - **setURL(String url)** (void) - Set or override the target URL. - **getURL()** (String) - Get the target URL. - **addHeader(String ns, String name, String value)** (void) - Add a SOAP header with namespace. - **getHeaderProps()** (Map) - Get current SOAP headers. ``` -------------------------------- ### Update User Default Site via Automation Script Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/rest/scripthandler This Python script updates the user's default insert site for the current session based on a provided query parameter. ```python # This example will change the user's default insert site based on the query parameter. # This is different than setting it on the MAXUSER record because this updates for the current session. from psdi.server import MXServer maxServer=MXServer.getMXServer() siteid=request.getQueryParam("siteid") if siteid and maxServer.isValidSite(siteid): userInfo=request.getUserInfo() userSet=maxServer.getMboSet("MAXUSER",userInfo) userSet.setQbeExactMatch(True) ``` -------------------------------- ### Implement a dynamic session count monitoring cron script Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/otherlaunch/cronscript A modified Python script that uses the 'arg' implicit variable to dynamically set the session count threshold via the SCRIPTARG parameter. ```python from psdi.server import MXServer argval = int(arg) cnt = MXServer.getMXServer().getMboSet("maxsession",runAsUserInfo).count(); if cnt>argval: service.logError("cnt exceeds 1::"+str(cnt)) ``` -------------------------------- ### Import and Use MboConstants Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/coreconcepts/mboconstants Import the MboConstants class to use its flags for suppressing access checks when setting attribute values. This improves code readability compared to using literal values. ```python from psdi.mbo import MboConstants mbo.setValue("DESCRIPTION","My description",MboConstants.NOACCESSCHECK) ``` -------------------------------- ### Customize Change Status with Autoscript Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/integration/osevents Use this script to set a custom memo and status date during the change status process. Ensure the MBO supports manual status date overrides before implementation. ```javascript function changeStatus(ctx) { var mbo = ctx.getMbo(); var struc = ctx.getData(); var stat = struc.getCurrentData("STATUS"); var statdate = struc.getCurrentDataAsDate("STATUSDATE"); var memo = struc.getCurrentData("NP_STATUSMEMO"); if(struc.isCurrentDataNull("NP_STATUSMEMO")) ``` -------------------------------- ### Implement an Event Filter for Publish Channels Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/integration/publishevents Use this script to conditionally filter events based on MBO status changes. Access the event MBO via service.getMbo() instead of the direct mbo variable. ```python if service.getMbo().isModified("status") and service.getMbo().getString("status")=="BROKEN": evalresult = False else: evalresult = True ``` -------------------------------- ### Create Maximo Company from External XML Data Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/integration/enterpriseevents An external exit script that creates a Maximo company by mapping data from an incoming XML document to the MXVENDOR Object Structure. It retrieves vendor and organization details from the XML. ```python from psdi.iface.mic import EnterpriseServiceCache from psdi.server import MXServer from org.jdom import Namespace doc = erData.getData() extXMLRoot = doc.getRootElement() vendor = extXMLRoot.getChildText("vendor", Namespace.getNamespace("http://some_ns.org")) organization = extXMLRoot.getChildText("organization", Namespace.getNamespace("http://some_ns.org")) srv = EnterpriseServiceCache.getInstance().getEnterpriseServiceInfo("MXVENDORInterface") ``` -------------------------------- ### Set Object Path for Lookup Script Testing Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/troubleshooting/testingscripts Define the object and attribute for testing lookup scripts. The object path specifies the MBO to query, and the attribute indicates which field's lookup is being tested. ```Maximo Scripting ASSET[assetnum=’ASSET1’] ``` -------------------------------- ### Context-Aware Relation Script Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/objectscripts/objectrelation This script demonstrates how to leverage context information passed via API calls (e.g., from the 'ctx' parameter) to dynamically filter related records. It checks if the current context is an API call and retrieves parameters if available, otherwise defaults to fetching the 'assetmeter' MboSet. ```python from psdi.iface.mic import IntegrationContext if IntegrationContext.getCurrentContext() is not None and IntegrationContext.getCurrentContext().isAPICall(): val1 = IntegrationContext.getCurrentContext().getParameter("param1") #create a filter clause based on the val1 and set the mboset else: mboset = mbo.getMboSet("assetmeter") ``` -------------------------------- ### Validate POLINE addition with Can Add event Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/objectscripts/objectlaunch Prevents adding a POLINE to a PO if the vendor information is missing. Uses the mboset variable as the MBO is not yet created. ```python if mboset.getOwner() is not None and mboset.getOwner().getName()=="PO" and mboset.getOwner().isNull("vendor"): service.error("po","novendor_noline") ``` -------------------------------- ### Validate Purchase Price Exceeding Limit Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/attributescripts/attributelaunch Use the 'validate' event in an Attribute Launch Point to check if the purchase price exceeds a maximum allowed value. The implicit 'purchaseprice' variable is available, and 'service.error()' throws an MXException. ```python if purchaseprice > 200: service.error("some","error") ``` -------------------------------- ### Displaying a Warning Message in Maximo Scripts Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/coreconcepts/errorhandling Use `service.setWarning()` to display a warning message to the user. This is useful for non-critical issues, such as saving a purchase order with no lines. Ensure the warning message is pre-defined in the 'Messages' dialog. ```javascript if (mbo.getMboSet("POLINE").count()==0 && interactive) { service.setWarning("po","nolines", None) } ``` -------------------------------- ### Implement Standard Deviation Formula Function Source: https://ibm-maximo-dev.github.io/maximo-autoscript-documentation/otherlaunch/formulafunc A Python script for Maximo Formulas that calculates standard deviation using the Apache Commons Math library. ```python from org.apache.commons.math3.stat.descriptive import DescriptiveStatistics from java.lang import Math relation = ctx.getExpression().getCalculatedValue(params[0]) attr = ctx.getExpression().getCalculatedValue(params[1]) dstats = DescriptiveStatistics() workOrders = mbo.getMboSet(relation) wo = workOrders.moveFirst() while wo is not None: ```