Groovy Variables and Functions

When running Groovy scripts, JMWE makes contextual information available to your script through built-in variables, functions, the Component/Service Manager and Jira Standard Services. 

Note: you can also define custom variables in your Groovy script!

Using Groovy Variables and Functions

The variables are available anywhere that a Groovy editor is used. Additionally, clicking on the Globals tab provided under the Groovy editor displays the list of available variables and functions. These are categorized below based on the context.

Current issue

issue

The issue variable exposes the methods of the main Issue interface, including methods not native to Jira such as get()getLinkedIssues() etc. It points to the current issue being processed. You can access the fields of the issue by accessing the properties and methods of this variable.

For example: issue.get("priority").getName() returns the name of priority of the issue. 

originalIssue

The originalIssue variable exposes the methods of the main Issue interface, including methods not native to Jira such as get()getLinkedIssues() etc. It points to the current Issue object, as it was before the transition started. You can access the fields of the issue by accessing the properties and methods of this variable. 

For example: originalIssue.get("assignee")?.name returns the assignee of the issue before the transition.

relatedIssue

The relatedIssue variable is similar to the issue variable except that it points to the related issue in the Groovy context. It is a synonym to the Variables and functions used in a Groovy expression#linkedIssue variable (is now obsolete) and is only available from post-functions that work on related issues. It is used to insert data of each related issue being processed by the post-function, in turn. You can access the fields of the related issue by accessing the properties and methods of this variable. 

For example: relatedIssue.get("status").getName() returns the status of the related issue in context.

linkedIssue

This variable is obsolete. Use relatedIssue variable instead.

The linkedIssue variable is similar to the Variables and functions used in a Groovy expression#issue variable except that it points to the linked issue in the Groovy context. You can access the fields of the linked issue by accessing the properties and methods of this variable. This is available in the post-functions that process the linked issues of the current issue. 

For example: linkedIssue.get("status").getName() returns the status of the linked issue

parentIssue

The parentIssue variable is similar to the Variables and functions used in a Groovy expression#issue variable except that it points to the parent issue in the Groovy context. You can access the fields of the parent issue by accessing the properties and methods of this variable. This is available in the post-functions that process the parent of the current issue.

For example: return(parentIssue?.get("assignee")?.getName()) returns the username of the user the parent issue is assigned to.

Execution context

currentUser

The currentUser variable holds an ApplicationUser representing the current user (i.e. the user triggering the transition) in the Groovy context. 

For example: currentUser.name returns the username of the current user.

transientVars

transientVars

Note: the elements listed below are available for all issue events except those related to issue watchers being added or deleted.

The transientVars variable is a Map of variables that provide important information about the current transition. 

These include the raw event object as well as variables for comment-related events, change history related events, worklog data, and new issue events, if any.

Note: the content of the raw event object will vary depending on the event! The list below is a sample of the data returned.

Example raw event object variables

issue: the issue id
user: the user who triggered the event
comment: the comment, if any, of the original event
subtasksUpdated: true/false flag on whether or not subtasks were updated
sendMail: true/false flag on whether or not email notifications were sent
time: the time of the original event

Comment-related event variables

comment: the comment body
roleLevel: role level id for the minimum role to see the comment (if any)
commentLevel: the group level required to see the comment (if any)
commentProperty: the entityProperty for the comment (if available)

Change history event variables

fieldChanges: a List<ChangeItemBean with all the changes contained in the event
originalAssigneeId: the old assignee, if changed by what triggered the event
oldStatus: the old status, if changed by what triggered the event

For example:

Comment added during the current transition:

transientVars.comment

Assign the linked issue to the assignee of the issue before the current transition

transientVars.originalAssigneeId

Copy the attachments of the issue to the newly created issue

import com.atlassian.jira.component.ComponentAccessor import com.atlassian.jira.issue.AttachmentManager AttachmentManager attachmentManager = ComponentAccessor.getAttachmentManager() def attach = issue.get("attachment") attach.each{ attachmentManager.copyAttachment(it,currentUser,transientVars.newIssue?.key) }

 

Html rendered comment added during the current transition:

Others

now

The now variable holds the current date and time, as a java.util.Date object.

today

The today variable contains a java.util.Date object representing the current date (without time) in the time zone of the current user. To get the current date in the time zone of a specific user, use new DateOnly(ApplicationUser user). For example: new DateOnly(issue.assignee) will return the current date in the time zone of the current issue’s Assignee.

currentValue

The currentValue variable holds the current value of the field being set by a post-function. This is applicable only in the Set field value and Set field value of linked issues post-functions. The data type of the variable depends on the field being set.

For example: 

currentValue returns a user object if the field being set is Assignee

currentValue returns a collection of versions if the field being set is Fix Version/s

newIssueKey

The newIssueKey variable holds the key of the newly created issue. This is applicable only in the Create/Clone issue post-function. The data type of the variable is a String.

For example:

newIssueKey returns the key of the newly created issue.

linkTypeName

The linkTypeName variable holds the name of the link type linking the current issue to the linked issue being considered for removal. This is applicable only in the Unlink issues from the current issue post-function. The data type of the variable is a String.

For example: 

linkTypeName returns the name of the first link type linking the current issue to the linked issue

textutils

The textutils variable is a utility object of class TextUtils providing useful methods to manipulate text and HTML. This is applicable only in the post-functions that use Groovy templating.

For example:

textutils.noNull(issue.get("description")) + issue.key returns a text avoiding null in case there is no Description of the issue.

log

The log variable is a Logger instance that is used to output information like errors and warnings into the atlassian-jira.log file located in your Jira home directory. You can also use the log variable to output data to the script tester result panel during script development and debugging. There are five logging levels available in log4j, and they are all output to the script tester result panel. However, by default, only WARN and ERROR level logs are output to the atlassian-jira.log file, so you should only use log.warn(...) and log.error(...) for run-time logging (as opposed to development-time logging). To see other levels in atlassian-jira.log, you can raise the logging level for the com.innovalog package.  

For example: Set a user field with the assignee and be warned when the issue is unassigned.

So when the issue is unassigned, the warning message is displayed in the atlassian-jira.log file.

Custom variables

In addition to the above variables, you can also define your own variables in the Groovy script.

For example, Condition to check whether the Fix Version/s has a particular version.

Deprecated variables

Variable name

Type

Description

Variable name

Type

Description

issueObject

Issue

Deprecated. The issueObject variable is a synonym for the issue variable.

linkedIssue

Issue

Deprecated. The linkedIssue variable is a synonym for the relatedIssue variable.

 

Functions

The functions are available in the:

  • Post-function configuration screen when you select:

    • Groovy expression/Groovy Template as Value type in the post-functions that set a field value

    • Groovy expression/Groovy Template as Comment type in the post-functions that comment an issue

    • the Conditional execution option in any post-function

  • Post-function configuration screen of the Create/Clone issue post-function when you select:

    • Calculated as Project

    • Calculated as Parent issue

    • Set field value from Groovy or Set field value from Groovy template while setting a field in Set fields of new issue

    • Groovy expression/Groovy Template as Comment type while adding a comment to the current issue

  • Post-function configuration screen of the Email issue post-function while writing the Email content and recipients

  • Post-function configuration screen of the Link issues to the current issue post-function while writing the JQL search expression

  • Post-function configuration screen of the Unlink issues from the current issue post-function

  • Configuration screens of the Scripted (Groovy) conditionScripted (Groovy) validator and Scripted (Groovy) operation on issue post-function

  • Groovy script tester admin screen that allows you to test/run Groovy script.

  • Target issues section of all post-functions that operate on related issues when Issues returned by a Groovy script or Issues returned by JQL search is selected under Which Issues field.

  • Shared Groovy Scripts under JMWE administration

Global Functions

jqlSearch("<JQL expression>", <maxResults>)

jqlSearch("<JQL expression>", <maxResults>) is a simple function that you can use to search for issues using a JQL. The function expects the following:

  • JQL expression: A JQL query

  • maxResults: maximum number of issues to return

When you pass a valid JQL query and number of issues, the function returns a List<Issueof issues that match the JQL.

Examples:

  • Fetch the first ticket of a specific project that has the same Cascading value set as of the current issue

     

  • Fetch the first 10 issues that have the same Fix Version/s as the first Fix Version/s of the current issue.

     

secondsBetween(Date from, Date to)

secondsBetween(<Date from>, <Date to>) is a global function that returns a Long representing the number of seconds between two Date objects. It returns null if one of the two parameters is null. For example:

  • returns the number of seconds between the issue creation and the due date.

  • returns the number of seconds from the issue creation to now.

secondsBetween(Date from, Date to, String roundTo)

secondsBetween(<Date from>, <Date to>, String roundTo) is a global function that returns a Long representing the number of seconds between two Date objects optionally rounding the number of seconds to the nearest minute, hour, day or week. It returns null if one of the two parameters is null.

<roundTo>: is either "max" or one of "weeks", "days", "hours", "minutes" (or their equivalent: "w", "d", "h", "m"). If the rounding is "max", it will be rounded to the largest unit reached by the duration. For example:

  • If secondsBetween(issue.created, issue.duedate) returns 2 hours 51 minutes,

    will be rounded to 10800 seconds (3*60*60 seconds) and will be displayed as 3 hours.

  • If secondsBetween(issue.created, issue.duedate) returns 65328 seconds

    will be rounded and displayed as 64800 seconds

workdaysBetween(Date from, Date to)

workdaysBetween(<Date from>, <Date to>) is a global function that returns a Long representing the number of work days (excluding Saturdays and Sundays) between two Date objects. It returns null if one of the two parameters is null. For example:

  • returns the number of days between the issue creation and the due date

  • returns the number of days from the issue creation to now.

workdaysBetween(Date from, Date to, calendarId)

workdaysBetween(<Date from>, <Date to>, <calendarId>) is a global function that returns a Long representing the number of work days between two Date objects using the specified Jira Service Management calendar. It returns null if the calendarId parameters is null

For example:

  • returns the number of days between the issue creation and the due date using the JSM calendar with an id of '2'.

  • returns the number of days from the issue creation to now using the JSM calendar with an id of '2'.

workdaysBetween(Date from, Date to, Project, calendarName)

workdaysBetween(<Date from>, <Date to>, <project>, <calendarName>) is a global function that returns a Long representing the number of work days between two Date objects using the specified Jira Service Management calendar. It returns null if the calendarId parameters is null

For example:

  • returns the number of days between the issue creation and the due date using the Project <project> and the JSM calendar with a name of <name>.

  • returns the number of days from the issue creation to now using the Project <project> and the JSM calendar with a name of <name>.

asUser(String username){codeblock}

asUser() is a simple global function that runs a code impersonating a user. During the execution of the code block, the current user will be set to the user with the specified username. The function expects the following:

  • username: Username of the user to impersonate

  • codeblock: Code block to run while impersonating a user

For example:

returns jdoe, regardless of who the current user is. 

asUser(ApplicationUser user){codeblock}

asUser(ApplicationUser user) is a simple global function that runs a code impersonating a user. During the execution of the code block, the current user will be set to the specified user. The function expects the following:

  • ApplicationUser: User to impersonate

  • codeblock: Code block to run while impersonating a user

For example:

returns the name of the assignee of the issue, regardless of who the current user is.

getCurrentTransition()

getCurrentTransition is a global function that returns data on the current transition, including the actionId, name of the transition, and the targetStatus of the transition.

getOrganization(String organizationNameOrID)

getOrganization is a global function that returns a Jira Service Management Organization from its name or ID.

For example:

returns the Organization named “Appfire”.

return the Organization with ID 5.

getUsersInOrganization(CustomerOrganization organization)

getUsersInOrganization is a global function that returns the users that belong to an organization. The function returns a Set<ApplicationUser> and expects a CustomerOrganization object.

For example:

returns the users that belong to the Appfire organization.

Additionally, you can use the usersInOrganization attribute of the CustomerOrganization interface that returns the users in a Jira Service Management Organization.

For example:

getTransitionAttachments()

getTransitionAttachments is a global function that returns the Attachments that have been added on the transition or issue creation screen. The function returns a List<Attachment>.

renderAsHTML(String content)

renderAsHTML is a global function that accepts String input and returns that string formatted as HTML.

Accessing any Component/Service Manager

getComponent(Class interface)

getComponent(Class interface) is a global function to get a Component/Service from Jira or any loaded add-on. The function expects a Class interface as the parameter. Until 5.1.0 importing classes from third party add-ons or some classes of Jira and its Java dependencies was not easy. You had to get the Class loader and find the class followed by getting the Component/Service. For example to get the RapidViewServiceInterface you had to write the following code:

But now you can directly import the class and get the Service, as shown below:

Note that you can also access the internal components/services that are registered as private (not "public") using this function. For example to get the DevStatusSummaryService from Jira's development integration plugin (which gives access to builds, commits, etc.)

Some more examples:

replace customfield_xxxxx with the custom field id of the field.

Accessing Standard Jira Services

You can access a few Standard Jira's services from the Groovy editor. Hover over any button to get the information, click on it to insert it into the editor. 

Jira Standard Service

Returns

Example

Jira Standard Service

Returns

Example

AttachmentManager

Jira's AttachmentManager service. Manages all attachment related tasks in JIRA, which involves retrieving an attachment, creating an attachment and deleting an attachment.

Copy attachments from the current issue to issue whose key is TEST-123

ComponentAccessor.attachmentManager.copyAttachments(issue, currentUser , "TEST-123" )

ChangeManager

Returns Jira's ChangeHistoryManager service, which manages the change history of issues.ChangeHistoryManager

To get the change history of the current issue:

ComponentAccessor.changeHistoryManager.getChangeHistories(issue)

ConstantsManager

Returns Jira's ConstantsManager service, which manages issue types, statuses, priorities and resolutions

To get all the Resolutions of the instance

ComponentAccessor.constantsManager.resolutionObjects

GroupManager

Returns Jira's GroupManager service, which manages user groups.

To get all the users in a group

ComponentAccessor.groupManager.getUsersInGroup("jira-administrators")

IssueLinkManager

Returns Jira's IssueLinkManager service, which manages issue links.

To check whether Issue Linking is currently enabled in Jira

ComponentAccessor.issueLinkManager.isLinkingEnabled()

IssueManager

Returns Jira's IssueManager service, which, in particular, allows you to load issues from keys.

To get the Issue that has the given key

ComponentAccessor.issueManager.getIssueObject("TEST-123")

IssueSecurityLevelManager

Returns Jira's IssueSecurityLevelManager service.

To get the different levels of security that the current user can see across all projects.

ComponentAccessor.issueSecurityLevelManager.getAllSecurityLevelsForUser(currentUser)

JiraAuthenticationContext

Returns Jira's JiraAuthenticationContext service. The JiraAuthenticationContext is used for tracking a user's session in JIRA and all it's custom parameters, such as Locale and I18n.

To get the logged in user

ComponentAccessor.jiraAuthenticationContext.loggedInUser

JiraDurationUtils

Returns Jira's JiraDurationUtils service, which is reponsible for printing durations in various formats.

 

ProjectComponentManager

Returns Jira's ProjectComponentManager service, which manages project Components.

To find components by the lead

ComponentAccessor.projectComponentManager.findComponentsByLead(currentUser.name)

ProjectManager

Returns Jira's ProjectManager service

To get all projects ordered by name:

ComponentAccessor.projectManager.projectObjects

ProjectRoleManager

Returns Jira's ProjectRoleManager service, which allows you to check role membership.

To get project role object by name

getComponent(com.atlassian.jira.security.roles.ProjectRoleManager).getProjectRole("Administrators")

UserManager

Returns Jira's UserManager service.

To get a user by username

ComponentAccessor.userManager.getUserByName("jdoe")

UserPropertyManager

Returns Jira's UserPropertyManager service, which gives access to user properties.

To get user property set of the current user

ComponentAccessor.userPropertyManager.getPropertySet(currentUser)

UserUtil

Returns Jira's UserUtil service, which provides user management capabilities.

To get a list of Jira Admin users:

ComponentAccessor.userUtil.jiraAdministrators

VersionManager

Returns Jira's VersionManager service, which manages project Versions.

To get all the released versions including archived

ComponentAccessor.versionManager.getAllVersionsReleased(true)