---
title: "Variables and functions used in a Groovy script"
canonical: "https://support.appfire.com/space/JMCF/465732169/Variables%20and%20functions%20used%20in%20a%20Groovy%20script"
format: markdown
---
> Macro (aura-html)

<span style="color: #333333">When running Groovy scripts, JMCF makes contextual information available to your script through built-in variables and functions. This document details them. Note that you can also define custom variables in your Groovy script.</span>

## Variables availability

The variables in JMCF are available on the custom field configuration screen when you write a `Groovy script` in the `Groovy Formula` field to return a value expected by a calculated custom field.

Clicking on :question_mark: provided under the Groovy [editor](https://appfire.atlassian.net/wiki/spaces/JMCF/pages/465600948) displays the list of available variables.

### Available variables

| Variable name | Type | Description |
| --- | --- | --- |
| [Variables and functions used in a Groovy script#issue](#VariablesandfunctionsusedinaGroovyscript-issue) | [Issue](https://appfire.atlassian.net/wiki/spaces/JMCF/pages/465764748) | The `issue` variable points to the current issue being processed. |
| **[Variables and functions used in a Groovy script#value](#VariablesandfunctionsusedinaGroovyscript-value)** | [String](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html) | The value of the calculated field |
| [Variables and functions used in a Groovy script#textutils](#VariablesandfunctionsusedinaGroovyscript-textutils) | [TextUtils](http://www.docjar.com/docs/api/com/opensymphony/xwork2/util/TextUtils.html) | textutils is<span style="color: #707070"> a </span><span style="color: #000000">utility object of class </span><span style="color: #000000">[TextUtils](http://www.docjar.com/docs/api/com/opensymphony/xwork2/util/TextUtils.html)</span><span style="color: #000000"> providing useful methods to manipulate text and HTML</span> |
| [Variables and functions used in a Groovy script#log](#VariablesandfunctionsusedinaGroovyscript-log) | [Logger](http://www.slf4j.org/api/org/slf4j/Logger.html) | The `log` variable is a [Logger](http://www.slf4j.org/api/org/slf4j/Logger.html) instance that writes into atlassian-jira.log (useful for [debugging](https://appfire.atlassian.net/wiki/spaces/JMCF/pages/465764674)) |
| [Variables and functions used in a Groovy script#numberTool](#VariablesandfunctionsusedinaGroovyscript-numberTool) | [NumberTool](https://docs.atlassian.com/software/jira/docs/api/7.6.1/com/atlassian/jira/util/velocity/NumberTool.html) | A [NumberTool](https://docs.atlassian.com/software/jira/docs/api/7.6.1/com/atlassian/jira/util/velocity/NumberTool.html) instance that can be used to format number values. |


> ⚠️ In JMCF versions prior to 2.0.0, the `issue` variable was a wrapper around the Issue object that just implemented a *get()* method to access the value of any field, and the *issueObject* represented Jira's main Issue object. Now, these two variables are merged into one, `issue. `This variable now exposes all the methods of Jira's [Issue](https://docs.atlassian.com/jira/server/com/atlassian/jira/issue/Issue.html) interface as well as additional methods such as *get(), getEpic()* etc. You can still use the `issueObject` but it is deprecated and it will be removed in a future version.

#### issue

The `issue` variable exposes the methods of the main [Issue](https://docs.atlassian.com/jira/server/com/atlassian/jira/issue/Issue.html) interface, including methods not native to Jira such as like *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 priority of the issue. 

#### value

The v`alue` represents the value of the calculated field returned by the Groovy script in the custom field configuration. This is applicable *only* while c<span style="color: #333333">ustomizing the display of</span> a [Calculated (Scripted) Number custom field type](https://appfire.atlassian.net/wiki/spaces/JMCF/pages/465535236) to format it using the [Variables and functions used in a Groovy script#numberTool](#VariablesandfunctionsusedinaGroovyscript-numberTool) variable. The data type of the variable is a Double.  

#### numberTool

The `numberTool` variable is a [NumberTool](https://docs.atlassian.com/software/jira/docs/api/7.6.1/com/atlassian/jira/util/velocity/NumberTool.html) instance that can be used to format the value of the calculated field returned by the Groovy script in the custom field configuration. This is applicable *only* while c<span style="color: #333333">ustomizing the display of</span> a [Calculated (Scripted) Number custom field type](https://appfire.atlassian.net/wiki/spaces/JMCF/pages/465535236) to format it. <span style="color: #333333"> </span>

**For example:** If the value of a calculated number custom field is `22` you can format it using the numberTool variable available in the [Groovy editor](https://appfire.atlassian.net/wiki/spaces/JMCF/pages/465600948) of the `Format Expression` field.

**To format it to a currency: **

```
numberTool.format('currency',value)
```

The value is formatted to `$40`.

**To **<span style="color: #333333">**add an IMG tag to display an icon to the left of the number:**</span>

```
"<img src='/images/icons/priority_trivial.gif'> "+numberTool.format(value);
```

So the number is formatted and displayed as > Macro (inline-media-image)



#### textutils

The `textutils `variable is a utility<span style="color: #707070"> </span><span style="color: #000000">object of class </span><span style="color: #000000">[TextUtils](http://www.docjar.com/docs/api/com/opensymphony/xwork2/util/TextUtils.html)</span><span style="color: #000000"> providing useful methods to manipulate text and HTML</span>. 

**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](http://www.slf4j.org/api/org/slf4j/Logger.html) 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](https://appfire.atlassian.net/wiki/spaces/JMCF/pages/465764674) result panel during script development and [debugging](https://appfire.atlassian.net/wiki/spaces/JMCF/pages/465764674/Groovy+script+tester+in+JMCF#GroovyscripttesterinJMCF-Usingthelogvariable). 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](https://confluence.atlassian.com/jirakb/how-to-set-logging-level-for-a-package-in-jira-629178605.html) for the com.innovalog package.  

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

```
if(issue?.get("assignee")?.getName())
{
  return(issue.get("assignee").getName()) 
}
else
{
  log.warn("This issue is unassigned")
  return null
}  
```

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

### Custom variables

<span style="color: #3e4349">In addition to the above variables, you can also define your own variables in the Groovy script. </span>

<span style="color: #3e4349">**For example,**</span><span style="color: #3e4349"> </span>Condition to check whether the Fix Version/s has a particular version.

```groovy
//Define a boolean variable to false
boolean isValue = false;
//Run a loop on all the current values of the field
issue.get("fixVersions").each {
  if (it.getName == "2.0")
    isValue = true;
}
return isValue;
```

### Deprecated variables

| Variable name | Type | Description |
| --- | --- | --- |
| `issueObject` | [Issue](https://appfire.atlassian.net/wiki/spaces/JMCF/pages/465764748) | **Deprecated.** The `issueObject` variable is a synonym for the `issue` variable. |

## <span style="color: #333333">Functions</span>

### <span style="color: #333333">Functions availability</span>

The functions in JMCF are available on the custom field configuration screen when you write a `Groovy script` in the `Groovy Formula` field to return a value expected by a calculated custom field.

### Available functions

| Function Name | Returns | Description |
| --- | --- | --- |
| [jqlSearch("<JQL expression>", <maxResults>)](#) | [List](http://docs.oracle.com/javase/7/docs/api/java/util/List.html)`<`[Issue](https://appfire.atlassian.net/wiki/spaces/JMCF/pages/465764748)`>` | <span style="color: #333333">Search for issues using JQL</span> |
| [Variables and functions used in a Groovy script#getComponent(Class interface)](#) | `Component/Service` | <span style="color: #172b4d">Global function to get a Component/Service from Jira or any loaded add-on</span> |

####   
<span style="color: #172b4d">jqlSearch("<JQL expression>", <maxResults>)</span>

`jqlSearch("<JQL expression>", <maxResults>)`<span style="color: #172b4d">is a simple function that you can use to search for issues using a JQL. The function expects the following:</span>  


- <span style="color: #333333">**JQL expression: **</span><span style="color: #333333">A </span><span style="color: #000000">JQL query</span>
- <span style="color: #333333">**maxResults: **</span><span style="color: #333333">maximum number of issues to return</span>

When you pass a valid JQL query and number of issues, the function returns a [List](http://docs.oracle.com/javase/7/docs/api/java/util/List.html)`<`[Issue](https://appfire.atlassian.net/wiki/spaces/JMCF/pages/465764748)`> `<span style="color: #333333">of issues that match the JQL.</span>

<span style="color: #333333">**Example: **</span><span style="color: #000000">Calculate the Story points of all issues of a specific project and display them on the current issue as Total Story points.</span>

```
issueCount = ComponentAccessor.getIssueManager().getIssueCountForProject("<Project ID>")
issues = jqlSearch("project = TP and cf[10006] >= 0",issueCount.intValue())
storyPoints = 0
issues.each{
  storyPoints += it.get("Story Points")
}
storyPoints
```

#### 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. Importing classes from third-party add-ons or some classes of Jira and its Java dependencies is not easy. You need 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:

```
import com.atlassian.jira.component.ComponentAccessor
def classLoader = issue.get("Rank").getClass().getClassLoader()
def RapidViewServiceIntf = classLoader.findClass("com.atlassian.greenhopper.service.rapid.view.RapidViewService")
def RapidViewService = ComponentAccessor.getOSGiComponentInstanceOfType(RapidViewServiceIntf)
```

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

```
import com.atlassian.greenhopper.service.rapid.view.RapidViewService
def RapidViewService = getComponent(RapidViewService);
```

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.)

```
import com.atlassian.jira.plugin.devstatus.api.DevStatusSummaryService
getComponent(DevStatusSummaryService)
```

**Some more examples:**

```
def issueManager = getComponent(com.atlassian.jira.issue.IssueManager.class)
def SprintService = getComponent(com.atlassian.greenhopper.service.sprint.SprintService.class)
```

#### secondsBetween(Date from, Date to)

`secondsBetween(<Date from>, <Date to>)` is a global function that returns a [Long](https://docs.oracle.com/javase/7/docs/api/java/lang/Long.html) representing the number of seconds between two [Date](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html) 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](https://docs.oracle.com/javase/7/docs/api/java/lang/Long.html) representing the number of seconds between two [Date](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html) 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>`: <span style="color: #000000">is either "max" or one of "weeks", "days", "hours", "minutes" (or their equivalent: "w", "d", "h", "m"). </span>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>)`<span style="color: #091e42"> is a global function that returns a</span>[Long](https://docs.oracle.com/javase/7/docs/api/java/lang/Long.html)<span style="color: #091e42">representing the </span><span style="color: #172b4d">number of work days (excluding Saturdays and Sundays) between two </span>[Date](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html)<span style="color: #091e42">objects. It returns</span>`null`<span style="color: #091e42">if one of the two parameters is</span>`null`<span style="color: #091e42">. For example:</span>

  returns the number of days between the issue creation and the due date
  returns the number of days from the issue creation to now.

#### 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**: <span style="color: #000000">Code block to run while impersonating a user</span>

<span style="color: #000000">For example:</span>

```
asUser("jdoe") {
  ComponentAccessor.jiraAuthenticationContext.loggedInUser.name
}
```

returns `jdoe`, regardless of who the current user is. 

:warning:<span style="color: #000000"> Note that the current user will be restored when the code block is exited.</span>

#### 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](https://appfire.atlassian.net/wiki/spaces/JMWE/pages/461472599)**: User to impersonate
- **codeblock**: <span style="color: #000000">Code block to run while impersonating a user</span>

<span style="color: #000000">For example:</span>

```
asUser(issue.assignee) {
  ComponentAccessor.jiraAuthenticationContext.loggedInUser?.name
}
```

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

:warning:<span style="color: #000000"> Note that the current user will be restored when the code block is exited.</span>

#### getOrganization(String organizationNameOrID)

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

For example:

```
getOrganization("Appfire")
```

returns the Organization named “Appfire”.

```
getOrganization("5")
```

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](/wiki/spaces/JMWE/pages/132972574/ApplicationUser+interface)> and expects a [CustomerOrganization](https://docs.atlassian.com/jira-servicedesk/4.17.0/com/atlassian/servicedesk/api/organization/CustomerOrganization.html) object. 

For example:

```
getUsersInOrganization(getOrganization("Appfire"))
```

returns the users that belong to the Appfire organization.