Creating automation script

An automation script consists of a launch point, variables with corresponding binding values, and the source code.

Two automation scripts created:
  1. To create a JIRA issue whenever any Maximo IT incident is raised based on input provided.
  2. To update the Maximo IT incident whenever any JIRA issue is updated

Automation script to create a JIRA issue

  1. Open the Automation Scripts application.
  2. On the navigation panel, click Create and select Script with Object Launch Point.
  3. On the Create Script with Object Launch Point : Step 1 of 3 pop-up, fill the fields as follows:
    • Launch Point: Specify the launch point name, for example, INCIDENTTEST.
    • Object: Search for the INCIDENT object and select.
    • Object Event Condition: Fill below condition in this box:
    • Click the Save button, check the checkbox for the Update?, and click After Save button.
    • Click the Next.
  4. On the Create Script with Object Launch Point : Step 2 of 3 pop-up, fill the fields as follows:
    • Script: Specify as jython
    • Script Language: Search and select jython
    • Log Level: Search and select Debug
    • Click Next
  5. Save the below code as a JSON file and save it in your directory such as C:\Users\Administrator\Documents\priority_mapping.json.
    Note:
    • The below is the sample JSON code, update the code as per your JIRA server.
    • Make sure that this same JSON file directory is mentioned in the below step 6 script as necessary.
    {
    1:10000,
    2:2,
    3:3,
    4:4,
    5:10001
    }
  6. On the Create Script with Object Launch Point : Step 3of 3 pop-up, fill the script box with the below script, and click Create
    Note:
    • The below script is a sample and for reference only, update the script as per your custom field ID's and other changes as necessary.
    • The priority_mapping.json file directory must be the same in below script as you save the JSON file in the above step 5.
    • The custom filed ID's in the below script must be same as it was generated in Creating custom fields in JIRA.
# Copyright (C) Altran ACT S.A.S. 2021.  All rights reserved
# This script is used to create defect in jira whenever an incident is created from ICD.

from com.ibm.json.java import JSONObject

from java.io import BufferedReader, IOException, InputStreamReader
from java.lang import System, Class, String, StringBuffer
from java.nio.charset import Charset
from java.util import Date, Properties, List, ArrayList

from org.apache.commons.codec.binary import Base64
from org.apache.http import HttpEntity, HttpHeaders, HttpResponse, HttpVersion
from org.apache.http.client import ClientProtocolException, HttpClient
from org.apache.http.client.entity import UrlEncodedFormEntity
from org.apache.http.client.methods import HttpPost
from org.apache.http.client.methods import HttpGet
from org.apache.http.entity import StringEntity
from org.apache.http.impl.client import DefaultHttpClient
from org.apache.http.message import BasicNameValuePair
from org.apache.http.params import BasicHttpParams, HttpParams, HttpProtocolParamBean

from psdi.mbo import Mbo, MboRemote, MboSet, MboSetRemote
from psdi.security import UserInfo
from psdi.server import MXServer
from psdi.mbo import SqlFormat
from psdi.iface.router import Router
from psdi.iface.mic import EndPointCache
from psdi.iface.router import HTTPHandler
from java.util import HashMap

from sys import *

def getIncidentData():
    System.out.println( 'getIncidentData invoked')
    System.out.println( mbo)
    description = mbo.getString("DESCRIPTION")
    System.out.println( description)
    return mbo;
    
def getJIRAPriority(reported_priority):
    priority = "3"
    # read mapping file
    with open('C:\Users\Administrator\Documents\priority_mapping.json', 'r') as myfile:
        data=myfile.read()
    
    # converting string to json
    final_dictionary = eval(data)
    for key, value in final_dictionary.items():
        if (str)(key) == reported_priority:
            priority = (str)(value)
    
    return priority;

# method for creating the JSON string which is sent in http POST body
def createJSONstring():
    jsonStr = ""
    project = JSONObject()
    project.put("key", "IJI")
    
    issuetype = JSONObject()
    issuetype.put("name", "Task")
    
    reported_priority = mbo.getString("REPORTEDPRIORITY")
    priority = JSONObject()
    priority.put("id", getJIRAPriority(reported_priority))
    
    obj = JSONObject()
    obj.put("summary", mbo.getString("DESCRIPTION"))
    obj.put("project", project)
    obj.put("issuetype", issuetype)
    obj.put("priority", priority)
    obj.put("customfield_10200", mbo.getString("TICKETUID"))
    obj.put("customfield_10201", mbo.getString("TICKETID"))
    obj.put("customfield_10202", mbo.getString("CREATEDBY"))
    
    create_jira_ticket = mbo.getBoolean("CREATEJIRATICKET")
    
    fields = JSONObject()
    fields.put("fields", obj)
    jsonStr = fields.serialize(True)
    return jsonStr

# method for http POST using the path, JSON body and token with bearer authorization
def httpPost(url,username,password, jsonstring):
    reference = None
    
    path = "/rest/api/2/issue"
    uri = url + path
    
    # get authentication header
    auth = username + ":" + password
    encodedAuth = String(Base64.encodeBase64(String.getBytes(auth, 'ISO-8859-1')),"UTF-8")
    authHeader = "Basic " + str(encodedAuth)
    
    # get http parameters
    params = BasicHttpParams()
    paramsBean = HttpProtocolParamBean(params)
    
    # get http body entities
    entity = StringEntity(jsonstring)

    # get client, http headers and request
    client = DefaultHttpClient()
    request = HttpPost(uri)
    request.setParams(params)
    request.addHeader(HttpHeaders.CONTENT_TYPE, "application/json")
    request.addHeader('Authorization', authHeader)
    request.setEntity(entity)
    
    # get client response
    response = client.execute(request)
    # return JSON response and reference number
    status = response.getStatusLine().getStatusCode()
    
    return 'success'

# method for creating JIRA ticket 
def createJIRATicket():
    
    jira_end_point = mbo.getString("JIRAENDPOINT")

    # get Endpoint/Handler.
    print "using end point: ", jira_end_point

    handler = Router.getHandler(jira_end_point)

    print "credentials being used: ", jira_end_point
    # get the username, password and url from the endpoint mbo
    username = handler.getUserName();
    print "username = ", username

    endPointInfo = EndPointCache.getInstance().getEndPointInfo(jira_end_point)
    password  = endPointInfo.getProperty("PASSWORD").getValue()

    url = handler.getUrl()
    print "url =", url
    
    jsonstr = createJSONstring()
    try:
        System.out.println( 'addCompany2Logo try block invoked')
        reference = httpPost(url,username,password, jsonstr)
    except:
        System.out.println( 'Error:' + str(exc_info()[0]) + str(exc_info()[1]))
    finally:
        System.out.println( 'finally - all connections closed')

# Main part
createJIRATicket()

Automation script to update the Maximo IT incident

Prerequisite:

Save the below code as a JSON file and save it in your directory such as C:\Users\Administrator\Documents\status_mapping.json.
Note:
  • The below is the sample JSON code, update the code as per your JIRA server.
  • Make sure that the above JSON file directory is mentioned in the below step 3 script as necessary.
{
"Done":"CLOSED",
"Pending":"QUEUED",
"Work in progress":"INPROG",
"Open":"NEW"
}
  1. Go to the Automation Scripts application.
  2. On the left-hand side navigation panel, click Create and select Script.
  3. On the Create Script pop-up, fill the fields as follows:
    • Script: Specify the script name such as UPDATEINCIDENT
    • Script Language: Search and select jython
    • Log Level: Search and select Debug
    • Fill the script box at the bottom of pop-up with the below script and click Create.
      Note:
      • The below script is a sample and for reference only, update the script as per your custom field ID's and other changes as necessary.
      • The status_mapping.json file directory must be the same in the below script as you saved the JSON file in the prerequisite above.
      • The custom filed ID's in the below script must be same as it was generated in Creating custom fields in JIRA.
      # Copyright (C) Altran ACT S.A.S. 2021.  All rights reserved
      # This script is used to update icd incident when an update is being triggered from jira.
      
      from java.util import Calendar
      from org.python.core import PyTuple
      
      #from org.json import JSONObject
      
      from java.io import BufferedReader, IOException, InputStreamReader, BufferedInputStream
      from java.lang import System, Class, String, StringBuffer, Integer
      from java.nio.charset import Charset
      from java.util import Date, Properties, List, ArrayList
      
      from org.apache.commons.codec.binary import Base64
      from org.apache.http import HttpEntity, HttpHeaders, HttpResponse, HttpVersion
      from org.apache.http.client import ClientProtocolException, HttpClient
      from org.apache.http.client.entity import UrlEncodedFormEntity
      from org.apache.http.client.methods import HttpGet
      from org.apache.http.entity import StringEntity
      from org.apache.http.util import EntityUtils
      from org.apache.http.impl.client import DefaultHttpClient
      from org.apache.http.message import BasicNameValuePair
      from org.apache.http.params import BasicHttpParams, HttpParams, HttpProtocolParamBean
      
      from com.google.gson import JsonObject, JsonParser, JsonElement
      
      from psdi.mbo import Mbo, MboRemote, MboSet, MboSetRemote
      from psdi.security import UserInfo
      from psdi.server import MXServer
      from psdi.mbo import SqlFormat
      from psdi.mbo import MboConstants
      from sys import *
      
      def getICDStatus(jira_status):
          status = ""
          # read mapping file
          with open('C:\Users\Administrator\Documents\status_mapping.json', 'r') as myfile:
              data=myfile.read()
          
          # converting string to json
          final_dictionary = eval(data)
          
          status = final_dictionary.get(jira_status)
          return status;
          
      def getICDPriority(jira_priority):
          priority = ""
          # read mapping file
          with open('C:\Users\Administrator\Documents\priority_mapping.json', 'r') as myfile:
              data=myfile.read()
          
          # converting string to json
          final_dictionary = eval(data)
          
          # converting string to json
          final_dictionary = eval(data)
          for key, value in final_dictionary.items():
              if jira_priority == value :
                  return key;
                  
          return priority;
      
      def getJsonValue(val):
          
          if val.isJsonPrimitive():
              p = val.getAsJsonPrimitive()
              if p.isString():
                  return p.getAsString()
              if p.isBoolean():
                  return p.getAsBoolean()
              if p.isNumber():
                  return p.getAsNumber().intValue()
          else:
              return
          
      def invokeUpdateMbo():
          #set content-type here
          responseHeaders.put("content-type","application/json")
              
          #convert request body to json object
          jsonElement = JsonElement
          jsonObject = JsonObject
          try:
              jsonElement = JsonParser().parse(requestBody)
              jsonObject = jsonElement.getAsJsonObject()
          except:
      	    System.out.println('error while parsing json')
      	    
          # ticket uid 
          ticketuid = jsonObject.get('fields').get('customfield_10200')
          
          # read mapping file
          with open('C:\Users\Administrator\Documents\incident_icd_jira_mapping.json', 'r') as myfile:
              data=myfile.read()
          
          # converting string to json
          final_dictionary = eval(data)
          
          #get incident mbo
          ticketSet = MXServer.getMXServer().getMboSet("TICKET", request.getUserInfo());
          format = SqlFormat("ticketuid=:1");
          
          format.setObject(1, "TICKET", "ticketuid", getJsonValue(ticketuid));
          ticketSet.setWhere(format.format());
          ticketSet.reset();
          
          incidentMbo = ticketSet.getMbo(0);
          
          #iterate json object
          jsonObject1 = jsonObject
          for key, value in final_dictionary.items():
              
              temp = value
              arr = temp.split(".")
              val = ""
              length = len(arr)
              for i in arr:
                  if length == 1:
                      val = jsonObject.get(i)
                  
                  else :
                      tempjson = jsonObject.get(i)    
                      jsonObject = tempjson
                  
                  length = length -1
              
              jsonObject = jsonObject1
              incidentMbo.setValue(key, getJsonValue(val), MboConstants.NOACCESSCHECK | MboConstants.NOVALIDATION_AND_NOACTION)
              
          jira_status = jsonObject.get('fields').get('status').get('name')
          icd_status = getICDStatus(getJsonValue(jira_status))
          
          if icd_status == '':
              System.out.println( 'icd_status is empty')
          else :    
              incidentMbo.setValue('STATUS',icd_status,MboConstants.NOACCESSCHECK | MboConstants.NOVALIDATION_AND_NOACTION)
          
          jira_priority = jsonObject.get('fields').get('priority').get('id')
          icd_priority = getICDPriority(getJsonValue(jira_priority))
          incidentMbo.setValue('REPORTEDPRIORITY',icd_priority,MboConstants.NOACCESSCHECK | MboConstants.NOVALIDATION_AND_NOACTION)
          
          #save incident mbo
          incidentMbo.getThisMboSet().save();
      
      # Main part
      invokeUpdateMbo()