Foreach Loop on Reader

Andrew Downs September 4, 2018

Hi guys,

 

I have looked at various google pages and searched the forums but don't seem to be comming right. If this question has been asked and answered before then I apologize. and I will rap myself over my knuckles :)

 

The process is run via a script on a workflow post function.

 

The code I am using is as follows:

 

import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.ContentType.*
import groovyx.net.http.ContentType
import static groovyx.net.http.Method.*
import groovy.json.JsonSlurper
import net.sf.json.groovy.JsonSlurper
import com.atlassian.jira.ComponentManager
import com.atlassian.jira.issue.CustomFieldManager
import com.atlassian.jira.issue.fields.CustomField
import com.atlassian.jira.issue.IssueManager
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.MutableIssue
import com.atlassian.jira.issue.Issue
import com.atlassian.jira.issue.UpdateIssueRequest
import com.atlassian.jira.issue.comments.CommentManager
import com.atlassian.jira.user.ApplicationUser
import com.atlassian.jira.util.json.JSONObject
import com.atlassian.jira.issue.Issue
import org.apache.log4j.Category
import com.atlassian.jira.bc.issue.comment.property.CommentPropertyService
import com.atlassian.jira.component.ComponentAccessor

// Enable Logging
def Category log = Category.getInstance("com.onresolve.jira.groovy")
log.setLevel(org.apache.log4j.Level.DEBUG)

// Define Required Component Access

def customFieldManager = ComponentAccessor.getCustomFieldManager()
def issueManager = ComponentAccessor.getIssueManager()

// Get Issue ID that contains the Data
def issueKey = issue.getKey()
MutableIssue issue = issueManager.getIssueObject(issueKey)
//Issue issue = issueManager.getIssueObject( "TT-20636" );

// Get field values
def computerName = customFieldManager.getCustomFieldObjectByName("Computer Name");
def computerNameValue = issue.getCustomFieldValue(computerName);

// Define HTTP URL and call API

def httpBuilder = new HTTPBuilder("https://api.contoso.com")
httpBuilder.setHeaders([Authorization: "Basic <redacted>"])

httpBuilder.get(
    path: "/api/AdComputers",
    requestContentType: ContentType.JSON,
    query: [search: "${computerNameValue}", container: "DC=contoso,DC=com"]
){
    resp, reader ->
        computerList(resp, reader)
}

def computerList(def resp, def reader){
           
      log.debug "Response is $resp"
      log.debug"Reader is $reader"
     
      def name = reader.name
    def location = reader.description
     
    if (!(name)){
        commentBody = "No existing computers have been found."
        updateValue = "No existing computers have been found."
        }else{
            commentBody = "The following computer account(s) have been found: ${name} with location ${location}"
            updateValue = "A computer account with ${name} and Location ${location} has been found"
        }
    
        // Define Required Component Access

    def issueManager = ComponentAccessor.getIssueManager()

    // Get Issue ID that contains the Data
    def issueKey = issue.getKey()
    MutableIssue issue = issueManager.getIssueObject(issueKey)

    // Define Comment Manager
    def commentManager = ComponentAccessor.getCommentManager()
    def user = ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser()
    //def commentBody = "Account has been validated"

    commentManager.create(issue, user, commentBody, false)    
    
}

 

I get the results in reader as I can access them and the comment is updated, however the result is as follows:

 

The following computer account(s) have been found: [NB-ANDREWD, NB-ANDREWDA] with location [OU1, OU1]

What I would like to do is add a comment for each result.

 

Ideally I would like it do the following:

The following computer account(s) have been found: NB-ANDREWD with location OU1

The following computer account(s) have been found: NB-ANDREWDA with location OU1

 

But I cannot seem to figure out the looping to get this working, I have tried as follows:

 

reader.name.each{

.....

}

 

and

 

foreach (name in reader){

....

}

 

All to no avail, I am sure it is something very simply that I am missing here. And I am happy to change the code if required, I also don't know if the code I am using is optimized, as I am new to Groovy and script runner as I have only been working with it for the last month or two.

 

Any assistance is highly appreciated.

 

 

3 answers

0 votes
Ken McClean
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
May 4, 2023

We could do something like this.  Reader.name and reader.description seem to be arrays, rather than individual values.  So if we loop for as many times as there are usernames in the array, we'll loop through everyone.

Each time we loop through the array, we have a value for x.  We retrieve the values stored in the arrays at that point, with getAt().  In other words, when x = 1, we get the values stored at position 1 in each array.

After we retrieve each value and set the commentBody, we increase x by 1 and loop again.

Worth nothing is that I don't think this will actually do anything; we're setting the comment body variable but not doing anything with it.   We'd have to pass it to a method like updateIssue()






def name = ''
def location = ''

if (!(name)) {
commentBody = "No existing computers have been found."
updateValue = "No existing computers have been found."
} else {

def x = 0

while (x < reader.name.size() {

name = reader.name.getAt(x)


location = name = reader.location.getAt(x)

commentBody = "The following computer account(s) have been found: ${name} with location ${location}"
updateValue = "A computer account with ${name} and Location ${location} has been found"

x++
}

}

}

0 votes
Ken McClean
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
May 4, 2023

We could do something like this.  Reader.name and reader.description seem to be arrays, rather than individual values.  So if we loop for as many times as there are usernames in the array, we'll loop through everyone.

Each time we loop through the array, we have a value for x.  We retrieve the values stored in the arrays at that point, with getAt().  In other words, when x = 1, we get the values stored at position 1 in each array.

After we retrieve each value and set the commentBody, we increase x by 1 and loop again.

Worth nothing is that I don't think this will actually do anything; we're setting the comment body variable but not doing anything with it.   We'd have to pass it to a method like updateIssue()




def name = ''
def location = ''

if (!(name)) {
commentBody = "No existing computers have been found."
updateValue = "No existing computers have been found."
} else {

def x = 0

while (x < reader.name.size() {

name = reader.name.getAt(x)


location = name = reader.location.getAt(x)

commentBody = "The following computer account(s) have been found: ${name} with location ${location}"
updateValue = "A computer account with ${name} and Location ${location} has been found"

x++
}

}

}

0 votes
Ken McClean
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
May 4, 2023

For anyone who stumbles across this, it looks like name and location were both arrays rather than being individual values.  We create a new loop, and run it as many times as there are users in the array.

Each time the loop runs, we grab the next user and location, and set the values in the body statement that particular user and location. In this way, we avoid referencing the entire array in the update statement.




    if (!(reader.name)){
        commentBody = "No existing computers have been found."
        updateValue = "No existing computers have been found."
        }else{


def x = 0

while(x < reader.name.size()){
 def name = ''
  def location = ''

reader.name.each{userName ->
name = userName
}

reader.location.each{OU ->
location = OU
}

commentBody = "The following computer account(s) have been found: ${name} with location ${location}"
updateValue = "A computer account with ${name} and Location ${location} has been found"

x++
}

            
        }

Suggest an answer

Log in or Sign up to answer