def jsonSlurper = new groovy.json.JsonSlurper();
String dlEmail = "[email protected]";
String controlMCallerSysId = "83833d21db84bf44f8e2de1a48961952"; //"Sunanda Khose (643026664)"
String controlM_Indicator = "NAP_SAP"
def masterCiList=[]
def defaultCiMap=[:]
def sucessfulTicketDetails=[]
def failedTicketDetails=[:]
def outpoutMessage=[]

LOG.info("Starting of CI Correction Process");

try{	

    //Step 2: Create Connection Object with IRIS
    IgnioNode ignioNode = new IgnioNode();
	ignioNode.setLabel("_entity");
	ignioNode.setLabel("ServiceNowAPIGEE");
	ignioNode.setLabel("_root");
	ignioNode.setNodeType(com.digitate.ignio.utils.ceb.model.NodeType.NODE);
 
	com.digitate.ignio.data.graph.model.criteria.Filter filter1 = new com.digitate.ignio.data.graph.model.criteria.Filter();
	filter1.setField("name");
	filter1.setValue("ServiceNow-incident-IBM"); // Need to fetch Data from Input parameter
	filter1.setOperator("=");	
 
	com.digitate.ignio.data.graph.model.criteria.Filter filter2 = new com.digitate.ignio.data.graph.model.criteria.Filter();
	filter2.setField("tableName");
	filter2.setValue("incident");
	filter2.setOperator("=");
 
	List<com.digitate.ignio.data.graph.model.criteria.Filter> list = new ArrayList<>();
	list.add(filter1);
	list.add(filter2);
 
	com.digitate.ignio.data.graph.model.criteria.Filters filters = new com.digitate.ignio.data.graph.model.criteria.Filters();
	filters.setFilters(list);
	filters.setLogic("AND");

	ignioNode.setFilters(filters);
  			
	LOG.info("#TraverseToServiceNowEntity#Finding serviceNow node")
    //Step 2.1: Execute method to get ServiceNowNode Object
	IgnioNode serviceNowNode = ceb.getIgnioNodeWithRelation(ignioNode);
	
	LOG.info("#TraverseToServiceNowEntity#serviceNow node : {}", serviceNowNode)
    //outpoutMessage.add("serviceNowNode Object ->"+serviceNowNode)
    
	//Need to check whether service now connection object is not null
    if( serviceNowNode != null ){
	
       //Step 3: Execute Get operation to fetch the Incident list from IRIS
	   // In this fields parameter we can customize the response field which we need our operation, as like number,CI value, Assignment group, Caler & Description 
	   String fields = "number,assignment_group,cmdb_ci,parent,short_description"	   
       String taskTableName = "sc_task"
	   //Need to build query based upon filer criteria
	   //String queryString = "sys_created_onONToday@javascript:gs.beginningOfToday()@javascript:gs.endOfToday()&u_state=200&assignment_group=b6cf16b5db8b6700cd4ea2aa48961907&opened_by=nagent"
       def sysDisplayParam="sysparm_display_value=all"
	   def sysParmFieldsParam="sysparm_fields=" + fields
	   String queryString = inputMap.queryString + "&" + sysDisplayParam + "&" + sysParmFieldsParam
	   
	   //Step 3.1: Call the get getAllIncidentsByQuery method to fetch Incident List
	   def requestTaskResponse= subject.getObjectDetailsByQueryParam(taskTableName,queryString)	   
	   
	   //Convert stream to object
	   def requestTaskList=jsonSlurper.parseText(requestTaskResponse?.response?.toString())
	   
	   LOG.info("#TraverseToServiceNowEntity#RequestTaskList List : {}", requestTaskList)
	   //outpoutMessage.add("RequestTaskList ->"+ requestTaskList.toString())
	   //Need to check return list 
	   if( (requestTaskList !=null) ){
	      
		  //Now need to check whether the result list is empty or not
		  if( ( requestTaskList.result?.size() > 0) ){
		     
			  //Step 4: Now need to iterate the received list
			  requestTaskList.result.each{ it -> 
			    
				try{
				
				   outpoutMessage.add("Task number ->"+ it?.number?.value)
				   LOG.info("#TraverseToServiceNowEntity#Task number : {}", it?.number?.value)
				
				   def assignmentGroup=  it?.assignment_group?.display_value
				   outpoutMessage.add("AssignmentGroup value ->" + assignmentGroup)

                   def taskCmdb_CiValue =  it?.cmdb_ci?.display_value
				   outpoutMessage.add("Task Cmdb_Ci value ->" + taskCmdb_CiValue)

                   def ritmNumber =  it?.parent?.display_value
				   outpoutMessage.add("RITM Number value ->" + ritmNumber)				   
				       
				   if(ritmNumber != null && ritmNumber?.trim()){
                   
				       //Get the RITM Details                          
	                   def ritmSysParmFieldsParam="sysparm_fields=" + "number,cmdb_ci,configuration_item,short_description"
	                   String ritmQueryString = "number=" + ritmNumber + "&" + sysDisplayParam + "&" + ritmSysParmFieldsParam    						  
					   String ritmTableName = "sc_req_item"
					   
					   def ritmDetailsObj= subject.getObjectDetailsByQueryParam(ritmTableName,ritmQueryString)	   
					   
					   //Convert stream to object
	                   def ritmDetails =jsonSlurper.parseText(ritmDetailsObj?.response?.toString())
					   
					   if(ritmDetails != null){
					   
					      //outpoutMessage.add("RITM Details ->" + ritmDetails)
						  
						  def ritmCmdb_CiValue =  ritmDetails?.result[0]?.cmdb_ci?.display_value
				          outpoutMessage.add("RITM Cmdb_Ci value ->" + ritmCmdb_CiValue)
						  
						  def ritmConfigurationItemValue =  ritmDetails?.result[0]?.configuration_item?.display_value
				          outpoutMessage.add("RITM configuration_item value ->" + ritmConfigurationItemValue)
						  
						  //Update the Task
						  
						  try{
						  
					          //Step 7.1: Populate InputMap
							  def correctCiValue="BACKTOBASICS-ECC-PROD-RPG"
						      def workNotes= "CI updated from "+ taskCmdb_CiValue +" to "+ correctCiValue

					          Map<String, String> taskDetails = new HashMap<String, String>();
			                  taskDetails.put("work_notes", workNotes);
			                  taskDetails.put("cmdb_ci", correctCiValue);
			             
						      //Step 7.2: Now convert the Map into JSON string
						      def builder = new groovy.json.JsonBuilder()
			                  builder(taskDetails)
						 
					          //Step 7.3: Execute update method
                              def taskUpdateResponse=serviceNowNode.updateIncidentOrTask(it?.number?.value, builder.toString(),taskTableName)

                             //outpoutMessage.add("Task Update Response->"+taskUpdateResponse)
                             //Step 7.4: Check the response status
                             if( ( taskUpdateResponse?.returnCode == 0 ) ){
                    
					            //Step 7.5.1: Add the Incident number into sucessful ticket list
					            sucessfulTicketDetails.add(it?.number)
						   
					         }else{
                                //Step 7.5.2: Add the Incident number into failed ticket list
							    def failedReason;
							    //outpoutMessage.add("Incident Failed Response->"+taskUpdateResponse)
							    def failedResponse=taskUpdateResponse?.errorStream?.split("\n")
                                failedResponse?.each{ val ->
                                 if(val?.contains("result")){
								    //outpoutMessage.add("Failed Response->"+val)
                                    def failedOutputRes = new groovy.json.JsonSlurper().parseText(val.toString());  
                                    failedReason= failedOutputRes?.result?.status_message + "-" + failedOutputRes?.result?.return_response
                                 }    
                                }
						      failedTicketDetails.put(it?.number,failedReason)
					        } 					 
				        
				           }catch(Exception e){  
                               LOG.error("#Error while executing CI Correction function : {}", e)
					           outpoutMessage.add("CI_UpdateFailed with incidentNumber"+it?.number + "Exception :"+ e.toString())
                           }                          
					   }				   
				   }	      
				
				}catch(Exception e){  
                    LOG.error("#Error while executing CI Correction function : {}", e)
					outpoutMessage.add("CI_CorrectionFailed with incidentNumber"+it?.number + "Exception :"+ e.toString())
                }				
											
			  }			 
		    }else{
		      //No Incident Ticket fetch from IRIS, either no ticket is availabe or some error occur to fetch the list 
		      LOG.info("#EmptyListReturnFromIRIS")
			  outpoutMessage.add("EmptyListReturnFromIRIS : No Incident Ticket fetch from IRIS")
		    }		 
	   }else{
	     LOG.info("#EmptyListReturnFromIRIS#NullList")
	     outpoutMessage.add("#EmptyListReturnFromIRIS#NullList : No Incident Ticket fetch from IRIS")
	   }   
    }else{
	     LOG.info("#UnableToConnectIRIS#ErrorOccur")
	     outpoutMessage.add("#UnableToConnectIRIS#ErrorOccur : Unable to Connect IRIS due to some error !!")
	}
    outpoutMessage.add(" SucessfulTicketDetails->"+ sucessfulTicketDetails)
    outpoutMessage.add(" FailedTicketDetails->"+ failedTicketDetails)
	
	
	
	
}catch(Exception e){  
  LOG.error("#Error while executing CI Correction function : {}", e)
  outpoutMessage.add("#UnableToConnectIRIS#ErrorOccur : Unable to Connect IRIS due to some error !!" + e.toString())
}
outputMap.MessageDetails = outpoutMessage;

 

Groovy online compiler

Write, Run & Share Groovy code online using OneCompiler's Groovy online compiler for free. It's one of the robust, feature-rich online compilers for Groovy language, running the latest Groovy version 2.6. Getting started with the OneCompiler's Groovy editor is easy and fast. The editor shows sample boilerplate code when you choose language as Groovy and start coding.

Read inputs from stdin

OneCompiler's Groovy online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample Groovy program which takes name as input and prints hello message with your name.

def name = System.in.newReader().readLine()
println "Hello " + name

About Groovy

Groovy is an object-oriented programming language based on java. Apache Groovy is a dynamic and agile language which is similar to Python, Ruby, Smalltalk etc.

Key Features

  • It's not a replacement for java but it's an enhancer to Java with extra features like DSL support, dynamic typing, closures etc.
  • Accepts Java code as it extends JDK
  • Greater flexibility
  • Concise and much simpler compared to Java
  • Can be used as both programming language and scripting language.

Syntax help

Data Types

Data typeDescriptionRange
StringTo represent text literalsNA
charTo represent single character literalNA
intTo represent whole numbers-2,147,483,648 to 2,147,483,647
shortTo represent short numbers-32,768 to 32,767
longTo represent long numbers-9,223,372,036,854,775,808 to +9,223,372,036,854,775,807
doubleTo represent 64 bit floating point numbers4.94065645841246544e-324d to 1.79769313486231570e+308d
floatTo represent 32 bit floating point numbers1.40129846432481707e-45 to 3.40282346638528860e+38
byteTo represent byte value-128 to 127
booleanTo represent boolean values either true or falseTrue or False

Variables

You can define variables in two ways

Syntax:

data-type variable-name;

[or]

def variable-name;

Loops

0.upto(n) {println "$it"}

or

n.times{println "$it"}

where n is the number of loops and 0 specifies the starting index

Decision-Making

1. If / Nested-If / If-Else:

When ever you want to perform a set of operations based on a condition or set of conditions, then If / Nested-If / If-Else is used.

if(conditional-expression) {
  // code
} else {
  // code
}

2. Switch:

Switch is an alternative to If-Else-If ladder and to select one among many blocks of code.

switch(conditional-expression) {    
case value1:    
 // code    
 break;  // optional  
case value2:    
 // code    
 break;  // optional  
...    
    
default:     
 //code to be executed when all the above cases are not matched;    
} 

List

List allows you to store ordered collection of data values.

Example:

def mylist = [1,2,3,4,5];
List MethodsDescription
size()To find size of elements
sort()To sort the elements
add()To append new value at the end
contains()Returns true if this List contains requested value.
get()Returns the element of the list at the definite position
pop()To remove the last item from the List
isEmpty()Returns true if List contains no elements
minus()This allows you to exclude few specified elements from the elements of the original
plus()This allows you to add few specified elements to the elements of the original
remove()To remove the element present at the specific position
reverse()To reverse the elements of the original List and creates new list