### Find versions starting with RC in specific projects Source: https://docs.adaptavist.com/sr4jc/latest/features/scriptrunner-enhanced-search/scriptrunner-enhanced-search-jql-functions/match-functions Use this query to find issues with versions starting with 'RC' but restricted to the 'DEMO', 'EXAMPLE', and 'TEST' projects. Specifying projects improves query performance. ```jql fixVersion in versionMatch("^RC.*", "DEMO, EXAMPLE, TEST") ``` -------------------------------- ### Handling Pagination with GET /rest/api/2/search Source: https://docs.adaptavist.com/sr4jc/latest/release-notes/breaking-changes/atlassian-rest-api-search-endpoints-deprecation Example of how to handle pagination when querying the search API using GET requests. It demonstrates fetching all pages by utilizing the `nextPageToken`. ```APIDOC ## GET /rest/api/2/search ### Description This endpoint is used to search for issues using JQL. The response may include a `nextPageToken` for paginated results. ### Method GET ### Endpoint /rest/api/2/search ### Query Parameters - **jql** (string) - Required - The JQL query to execute. - **maxResults** (integer) - Optional - The maximum number of results to return per page. Default is usually 50. - **fields** (string) - Optional - A comma-separated list of fields to include in the response. - **expand** (string) - Optional - A comma-separated list of extra information to expand in the response. - **nextPageToken** (string) - Optional - Token to retrieve the next page of results. ### Request Example ```groovy def results = [] def nextPageToken = null final jqlQuery = "project = TEST AND issueType = Bug" do { def request = get("/rest/api/2/search") .queryString("jql", jqlQuery) .queryString("maxResults", 1) .queryString("fields", "key, status, assignee") .queryString("expand", "names, schema") if (nextPageToken) { request.queryString("nextPageToken", nextPageToken) } def searchReq = request.asObject(Map) assert searchReq.status == 200 def searchResult = searchReq.body as Map results << searchResult nextPageToken = searchResult.nextPageToken } while (nextPageToken) return results ``` ### Response #### Success Response (200) - **nextPageToken** (string) - Token for the next page of results, if available. - **results** (array) - The list of issues matching the query. ``` -------------------------------- ### Example Script Listener Code Source: https://docs.adaptavist.com/sr4jc/latest/features/script-listeners This is an example script that can be loaded and used for a script listener. It demonstrates basic functionality that can be triggered by specific events. ```groovy import com.atlassian.jira.component.ComponentAccessor def log = ComponentAccessor.getLog() log.warn("Work Item Updated Listener Triggered") return true ``` -------------------------------- ### Get Target Start Date Value Source: https://docs.adaptavist.com/sr4jc/latest/features/behaviours/behaviours-api Retrieves the target start date as a string, or null if not set. ```javascript // returns target start date const targetStart = getFieldById("customfield_10022").getValue(); //example return value "2024-11-05" ``` -------------------------------- ### Perform Action Condition Examples Source: https://docs.adaptavist.com/sr4jc/latest/features/workflow-rules/perform-actions/fields Use these examples to define conditions for when a perform action should execute. They can range from simple boolean checks to complex field validations. ```groovy issue.fields.summary ==~ /^(?i)foo.**/** ``` ```groovy false ``` ```groovy ((Map) issue.fields.issuetype)?.name == 'Task' ``` ```groovy issue.fields.assignee != null ``` -------------------------------- ### GET /rest/api/2/search - Rewrite Guidance Source: https://docs.adaptavist.com/sr4jc/latest/release-notes/breaking-changes/atlassian-rest-api-search-endpoints-deprecation Guidance on rewriting scripts that use the deprecated GET /rest/api/2/search endpoint, with examples using HAPI and Unirest for pagination and field selection. ```APIDOC ## GET /rest/api/2/search ### Description This section provides guidance on how to rewrite scripts using the deprecated GET /rest/api/2/search endpoint. It recommends using HAPI for simplified JQL queries and pagination, or modifying Unirest requests for direct API interaction. ### Rewrite Guidance If you are not using HAPI, you must update your implementation using a different method. In most cases, the response processing from the old endpoint can be retained with modifications to request parameters when adopting the new API. Some exclusions apply specifically in handling pagination. #### Without pagination ```groovy final jqlQuery = "project = TEST AND issueType = Bug" def searchReq = get("/rest/api/2/search/jql") \ .queryString("jql", jqlQuery) \ .queryString("maxResults", 100) // Adjust as needed, default is usually 50 .queryString("fields", "key, status, assignee") // Specify required fields .queryString("expand", "names, schema") // Optional expansions .asObject(Map) assert searchReq.status == 200 def searchResult = searchReq.body as Map // If the user would like to return or print the issue key (searchReq.body.issues as List)?.each { logger.info("The issue key is ${it.key}") } return searchResult ``` ``` -------------------------------- ### Regex Examples for Pattern Matching Source: https://docs.adaptavist.com/sr4jc/latest/features/scriptrunner-enhanced-search/terminology These examples demonstrate various regular expression patterns used for flexible searching within ScriptRunner Enhanced Search JQL functions. ```regex ^ABC.* ``` ```regex .*Beta$ ``` ```regex \d+ ``` ```regex release-\d{4} ``` ```regex QA|Testing ``` ```regex .*API.* ``` -------------------------------- ### Example Escalation Service Script Source: https://docs.adaptavist.com/sr4jc/latest/features/escalation-service This is an example script that can be used with the Escalation Service. It demonstrates how to access and modify work items. The script is executed for each work item found by the JQL query. ```groovy import com.atlassian.jira.component.ComponentAccessor def issueManager = ComponentAccessor.getIssueManager() def loggedInUser = ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser() def commentManager = ComponentAccessor.getCommentManager() def issue = issueManager.getIssueObject(issue.id) commentManager.addComment(issue, loggedInUser, "This issue has been escalated due to inactivity.", false) ``` -------------------------------- ### Handle Pagination with GET /rest/api/2/search/jql Source: https://docs.adaptavist.com/sr4jc/latest/release-notes/breaking-changes/atlassian-rest-api-search-endpoints-deprecation Fetches all paginated results from the Jira search API using a GET request. Include `nextPageToken` in subsequent requests to retrieve all pages. ```groovy def results = [] def nextPageToken = null final jqlQuery = "project = TEST AND issueType = Bug" do { def request = get("/rest/api/2/search/jql") .queryString("jql", jqlQuery) .queryString("maxResults", 1) .queryString("fields", "key, status, assignee") .queryString("expand", "names, schema") if (nextPageToken) { request.queryString("nextPageToken", nextPageToken) } def searchReq = request.asObject(Map) assert searchReq.status == 200 def searchResult = searchReq.body as Map results << searchResult nextPageToken = searchResult.nextPageToken } while (nextPageToken) return results ``` -------------------------------- ### Make a GET REST Request Source: https://docs.adaptavist.com/sr4jc/latest/features/behaviours/behaviours-api Use `makeRequest` to call Jira Cloud REST API endpoints. This example shows a GET request to retrieve user information. ```js const res = await makeRequest("/rest/api/2/myself"); if(res.body.accountId == "the accountId") { logger.info("User is bob"); } ``` -------------------------------- ### Get Parent Object Key (After HAPI) Source: https://docs.adaptavist.com/sr4jc/latest/release-notes/breaking-changes/atlassian-epic-and-parent-fields-jira-rest-api-deprecation This example demonstrates how to retrieve the parent issue's key using HAPI, which replaces the deprecated 'Parent Link' functionality. ```groovy def issueKey = 'TEST-1' def issue = Issues.getByKey(issueKey) issue.getParentObject().getKey() ``` -------------------------------- ### Example: issuesInEpics JQL Function Source: https://docs.adaptavist.com/sr4jc/latest/features/scriptrunner-enhanced-search Use the `issuesInEpics` JQL function to find issues within specific epics. This example retrieves all stories within open epics in a given project and filters them by status. ```jql issuesInEpics( epicsOf(project = "PROJECT_KEY" AND status = "Open") ) AND status = "In Progress" ``` -------------------------------- ### Example: epicsOf JQL Function Source: https://docs.adaptavist.com/sr4jc/latest/features/scriptrunner-enhanced-search Use the `epicsOf` JQL function to query for epics based on their linked issues. This example finds all epics that have unresolved stories. ```jql epicsOf( project = "PROJECT_KEY" AND status = "In Progress" ) ``` -------------------------------- ### String Properties Source: https://docs.adaptavist.com/sr4jc/latest/hapi/work-with-entity-properties Methods for setting and getting string properties. ```APIDOC ## setString, getString ### Description Sets or retrieves a string property using a specified key. ### Method `setString(String key, String value)` `getString(String key)` ### Parameters - **key** (String) - The key of the property. - **value** (String) - The string value to set. ### Response - **Success Response (200)**: Returns the retrieved string value or void for setter. ``` -------------------------------- ### Make GET Request with Unirest Source: https://docs.adaptavist.com/sr4jc/latest/scriptrunner-migration-to-cloud/rewrite-scripts-for-cloud-hints-and-tips/unirest-library Use GET requests to retrieve data from Jira. Unirest is auto-imported in ScriptRunner for Jira Cloud. Ensure you replace 'YOUR_ACCESS_TOKEN' with a valid token and 'your-domain.atlassian.net' with your Jira Cloud domain. ```groovy def response = Unirest.get("https://your-domain.atlassian.net/rest/api/3/issue/{issueIdOrKey}") .header("Authorization", "Bearer YOUR_ACCESS_TOKEN") .header("Accept", "application/json") .routeParam("issueIdOrKey", "TEST-123") .asJson() if (response.getStatus() == 200) { def issueData = response.getBody().getObject() log.info("Issue Summary: ${issueData.getString('fields').getString('summary')}") } else { log.error("Failed to retrieve issue: ${response.getStatusText()}") } ``` -------------------------------- ### Integer Properties Source: https://docs.adaptavist.com/sr4jc/latest/hapi/work-with-entity-properties Methods for setting and getting integer properties. ```APIDOC ## setInteger, getInteger ### Description Sets or retrieves an integer property using a specified key. ### Method `setInteger(String key, Integer integer)` `getInteger(String key)` ### Parameters - **key** (String) - The key of the property. - **integer** (Integer) - The integer value to set. ### Response - **Success Response (200)**: Returns the retrieved integer value or void for setter. ``` -------------------------------- ### Get Project Components (REST API) Source: https://docs.adaptavist.com/sr4jc/latest/scriptrunner-migration-to-cloud/rewrite-scripts-for-cloud-hints-and-tips Retrieve a list of components for a project using this REST API endpoint. ```REST GET /rest/api/3/component ``` -------------------------------- ### Connect to MySQL Database Source: https://docs.adaptavist.com/sr4jc/latest/features/script-console/example-scripts This script demonstrates connecting to a MySQL database and running SQL queries. The MySQL Connector/J driver is required. ```groovy import groovy.sql.Sql import java.sql.Driver def db = [url:'jdbc:mysql://my.example.com', user:'username', password:'password', driver:'com.mysql.cj.jdbc.Driver'] def sql = Sql.newInstance(db.url, db.user, db.password, db.driver) sql.rows ''' SELECT * FROM "example" LIMIT 100 ''' ``` -------------------------------- ### Basic Script Compilation Example Source: https://docs.adaptavist.com/sr4jc/latest/get-started/technical-background This script demonstrates a basic method call. It compiles without errors but may result in a MissingPropertyException at runtime if 'foo' is not defined in the script's binding. ```groovy foo.bar() ``` -------------------------------- ### Get Epic Link (Before HAPI) Source: https://docs.adaptavist.com/sr4jc/latest/release-notes/breaking-changes/atlassian-epic-and-parent-fields-jira-rest-api-deprecation This example shows how to retrieve the 'Epic Link' custom field using the Jira REST API before the deprecation. ```groovy def issueKey = 'TEST-1' def issue = get("/rest/api/2/issue/${issueKey}") .header('Content-Type', 'application/json') .asObject(Map) //get Epic Link def epic = issue.fields.customfield_10014 epic ``` -------------------------------- ### Create a space using a template Source: https://docs.adaptavist.com/sr4jc/latest/hapi/work-with-spaces Create a new space pre-configured with a specified template key. Available templates are discoverable via completions. ```groovy Spaces.create("TIS", "Teams in Space"){ setSpaceTemplateKey('Kanban') } ``` -------------------------------- ### Set details when creating a new space Source: https://docs.adaptavist.com/sr4jc/latest/hapi/work-with-spaces Customize space creation by setting specific values for lead account ID, space type, description, URL, default assignee, and avatar ID. ```groovy Spaces.create("TIS", "Teams in Space") { setLeadAccountId('user account id') setSpaceTypeKey('business') setDescription("This is a new space!") setUrl("https://google.com") setDefaultAssigneeToProjectLead() setAvatarId(10001) } ``` -------------------------------- ### IssueSecurityLevelManager / IssueSecuritySchemeManager Source: https://docs.adaptavist.com/sr4jc/latest/scriptrunner-migration-to-cloud/rewrite-scripts-for-cloud-hints-and-tips Provides a multi-step process to retrieve issue security levels in Jira Cloud. First, get all security schemes (GET /rest/api/3/issuesecurityschemes), identify the required scheme ID, and then use GET /rest/api/3/securitylevel/{id} to get the specific security level. ```APIDOC ## Get all security schemes ### Description Retrieves all available security schemes. ### Method GET ### Endpoint /rest/api/3/issuesecurityschemes ## Get security level by ID ### Description Retrieves a specific security level using its ID. ### Method GET ### Endpoint /rest/api/3/securitylevel/{id} ``` -------------------------------- ### Set Target Start Date Source: https://docs.adaptavist.com/sr4jc/latest/features/behaviours/behaviours-api Updates the 'Target Start Date' field with a date string in 'yyyy-mm-dd' format. ```javascript const targetStart = getFieldById("customfield_10022").setValue("2024-11-05") ``` -------------------------------- ### Connect to PostgreSQL Database Source: https://docs.adaptavist.com/sr4jc/latest/features/script-console/example-scripts Use this script to establish a connection to a PostgreSQL database and execute SQL queries. Ensure the PostgreSQL JDBC driver is available. ```groovy import groovy.sql.Sql import java.sql.Driver def db = [url:'jdbc:postgresql://my.example.com:1234/', user:'username', password:'password', driver:'org.postgresql.Driver'] def sql = Sql.newInstance(db.url, db.user, db.password, db.driver) sql.rows ''' SELECT * FROM "example" LIMIT 100 ''' ``` -------------------------------- ### Get all members of a group Source: https://docs.adaptavist.com/sr4jc/latest/hapi/work-with-groups Retrieve a list of all users who are members of a specified group. First, get the group object by its name. ```groovy def group = Groups.getByName('jira-developers') group.getMembers() ``` -------------------------------- ### ApplicationProperties Source: https://docs.adaptavist.com/sr4jc/latest/scriptrunner-migration-to-cloud/rewrite-scripts-for-cloud-hints-and-tips Maps the 'ApplicationProperties' Java API (get properties) to the 'Get application properties' REST API endpoint in Jira Cloud. ```APIDOC ## Get application properties ### Description Retrieves application properties. ### Method GET ### Endpoint /rest/api/3/application-properties ``` -------------------------------- ### getValue for Target Start Date Field Source: https://docs.adaptavist.com/sr4jc/latest/features/behaviours/behaviours-api Retrieves the value of the Target Start Date field, which is a string representing a date or null. ```APIDOC ## getValue for Target Start Date Field ### Description Retrieves the value of the Target Start Date field, which is a string representing a date or null. ### Method ```javascript getFieldById("customfield_10022").getValue(); ``` ### Parameters None ### Response #### Success Response - (string | null) - The target start date in 'YYYY-MM-DD' format, or null if not set. ### Response Example ```json "2024-11-05" ``` ``` -------------------------------- ### Find versions starting with RC across all projects Source: https://docs.adaptavist.com/sr4jc/latest/features/scriptrunner-enhanced-search/scriptrunner-enhanced-search-jql-functions/match-functions Use this query to find all issues with versions that begin with 'RC' across all projects. This is useful for tracking release candidates. ```jql fixVersion in versionMatch("^RC.*") ``` -------------------------------- ### Search Issues without Pagination (Groovy) Source: https://docs.adaptavist.com/sr4jc/latest/release-notes/breaking-changes/atlassian-rest-api-search-endpoints-deprecation Perform a search for issues using the new `/search/jql` endpoint without manual pagination. This example demonstrates setting JQL, max results, fields, and expansions, then logging issue keys. ```groovy final jqlQuery = "project = TEST AND issueType = Bug" def searchReq = get("/rest/api/2/search/jql") .queryString("jql", jqlQuery) .queryString("maxResults", 100) // Adjust as needed, default is usually 50 .queryString("fields", "key, status, assignee") // Specify required fields .queryString("expand", "names, schema") // Optional expansions .asObject(Map) assert searchReq.status == 200 def searchResult = searchReq.body as Map // If the user would like to return or print the issue key (searchReq.body.issues as List)?.each { logger.info("The issue key is ${it.key}") } return searchResult ``` -------------------------------- ### ProjectManager Source: https://docs.adaptavist.com/sr4jc/latest/scriptrunner-migration-to-cloud/rewrite-scripts-for-cloud-hints-and-tips Maps the 'ProjectManager' Java API (get project details) to various REST API endpoints in Jira Cloud: GET /rest/api/3/project/{projectIdOrKey} for project details, GET /rest/api/3/project/search} for project search, PUT /rest/api/3/project/{projectIdOrKey} for updating projects, and DELETE /rest/api/3/project/{projectIdOrKey} for deleting projects. ```APIDOC ## Get project details by ID or key ### Description Retrieves details for a specific project using its ID or key. ### Method GET ### Endpoint /rest/api/3/project/{projectIdOrKey} ## Search projects ### Description Searches for projects using project key or name with pagination. ### Method GET ### Endpoint /rest/api/3/project/search ## Update project by ID or key ### Description Updates an existing project using its ID or key. ### Method PUT ### Endpoint /rest/api/3/project/{projectIdOrKey} ## Delete project by ID or key ### Description Deletes a specific project using its ID or key. ### Method DELETE ### Endpoint /rest/api/3/project/{projectIdOrKey} ``` -------------------------------- ### Handling Pagination with POST /rest/api/2|3|latest/search Source: https://docs.adaptavist.com/sr4jc/latest/release-notes/breaking-changes/atlassian-rest-api-search-endpoints-deprecation Example of how to handle pagination when searching for issues using the POST /rest/api/2|3|latest/search endpoint. It demonstrates fetching all pages by utilizing the `nextPageToken`. ```APIDOC ## POST /rest/api/2|3|latest/search ### Description This endpoint searches for issues using a JQL query and handles pagination automatically by checking for `nextPageToken` and looping through all pages. ### Method POST ### Endpoint /rest/api/2|3|latest/search ### Request Body - **fields** (array) - Optional - A list of fields to include in the response. - **fieldsByKeys** (boolean) - Optional - If true, fields are identified by their keys. - **jql** (string) - Required - The JQL query to execute. - **maxResults** (integer) - Optional - The maximum number of results to return. Default is usually 50. - **nextPageToken** (string) - Optional - Token to retrieve the next page of results. ### Request Example ```groovy final jqlQuery = "project = TEST AND issueType = Bug" def bodyData = [ fields : ["key", "assignee", "summary", "description"], fieldsByKeys : true, jql : jqlQuery, maxResults : 100 ] def allResults = [] def nextPageToken = null do { def requestBody = nextPageToken ? bodyData + [nextPageToken: nextPageToken] : bodyData def searchReq = post("/rest/api/2/search") .header("Content-Type", "application/json") .body(requestBody) .asObject(Map) assert searchReq.status == 200 def searchResult = searchReq.body as Map allResults += searchResult.issues nextPageToken = searchResult.nextPageToken } while (nextPageToken) return allResults ``` ### Response #### Success Response (200) - **issues** (array) - The list of issues matching the query. - **nextPageToken** (string) - Token for the next page of results, if available. ``` -------------------------------- ### Create a new space with default values Source: https://docs.adaptavist.com/sr4jc/latest/hapi/work-with-spaces Use this to create a new space with basic parameters. The space lead is set to the current user, space type to 'business', and default assignee to 'Unassigned'. ```groovy Spaces.create("TIS", "Teams in Space") ``` -------------------------------- ### ProjectComponentManager Source: https://docs.adaptavist.com/sr4jc/latest/scriptrunner-migration-to-cloud/rewrite-scripts-for-cloud-hints-and-tips Maps the 'ProjectComponentManager' Java API (get components) to the 'GET /rest/api/3/component' REST API endpoint for retrieving project components in Jira Cloud. ```APIDOC ## Get project components ### Description Retrieves a list of project components. ### Method GET ### Endpoint /rest/api/3/component ``` -------------------------------- ### Create Sub-task Example Source: https://docs.adaptavist.com/sr4jc/latest/features/workflow-rules/perform-actions/built-in-workflow-actions This script demonstrates how to create a sub-task for a given parent work item. It retrieves issue types and constructs the necessary payload for the Jira API. Ensure the 'Sub-task' issue type exists in your Jira instance. ```groovy // Here we specify and retrieve the details of the parent work item // If you copied this code into a Perform actions rule or an item-related Script Listener you could remove // the first 5 lines of code as an work item variable would already be available to your script def parentKey = 'DEMO-1' def issueResp = get("/rest/api/2/issue/${parentKey}") .asObject(Map) assert issueResp.status == 200 def issue = issueResp.body as Map // We retrieve all issue types def typeResp = get('/rest/api/2/issuetype') .asObject(List) assert typeResp.status == 200 def issueTypes = typeResp.body as List // Here we set the basic subtask work item details def summary = "Subtask summary" def issueType = "Sub-task" def issueTypeId = issueTypes.find { it.subtask && it.name == issueType }?.id assert issueTypeId : "No subtasks issue type found called '${issueType}'" def createDoc = [ fields: [ project: (issue.fields as Map).project, issuetype: [ id: issueTypeId ], parent: [ id: issue.id ], summary: summary ] ] // Now we create the subtask def resp = post("/rest/api/2/issue") .header("Content-Type", "application/json") .body(createDoc) .asObject(Map) def subtask = resp.body assert resp.status >= 200 && resp.status < 300 && subtask && subtask.key != null subtask ``` -------------------------------- ### Get Security Schemes (REST API) Source: https://docs.adaptavist.com/sr4jc/latest/scriptrunner-migration-to-cloud/rewrite-scripts-for-cloud-hints-and-tips Retrieve all security schemes available to the admin user. This is the first step to getting a security level ID. ```REST GET /rest/api/3/issuesecurityschemes ``` -------------------------------- ### Issue Update Payload Example Source: https://docs.adaptavist.com/sr4jc/latest/scriptrunner-migration-to-cloud/rewrite-scripts-for-cloud-hints-and-tips Example of the JSON structure for updating issue fields via the PUT endpoint. This replaces the need for `issueService.newIssueInputParameters()` in Server. ```JSON fields: [ (fieldId): newValue, // Text Field ] ``` -------------------------------- ### Import and Reuse a Groovy Script Method Source: https://docs.adaptavist.com/sr4jc/latest/features/script-manager Demonstrates how to import a script from a specific package and instantiate it to call its methods. This is useful for modularizing code. ```groovy import com.myapp.simplescripts.reusablescript def script = new reusablescript() script.greet('Admin') ``` -------------------------------- ### Handle Pagination with /rest/api/2/search/jql Source: https://docs.adaptavist.com/sr4jc/latest/release-notes/breaking-changes/atlassian-rest-api-search-endpoints-deprecation This script demonstrates how to handle pagination when retrieving issues using the /rest/api/2/search/jql endpoint. It loops through results using nextPageToken until all issues are retrieved. ```groovy def issueIds = [] def nextPageToken = null final jqlQuery = [ jql: "project = TEST AND issueType = Bug" ] do { def requestBody = nextPageToken ? [ nextPageToken: nextPageToken ] : jqlQuery def searchReq = post("/rest/api/2/search/jql") .header("Content-Type", "application/json") .body(requestBody) .asObject(Map) assert searchReq.status == 200 def searchResult = searchReq.body as Map issueIds += searchResult.issues.collect { ((Map) it).id } nextPageToken = searchResult.nextPageToken } while (nextPageToken) return issueIds ``` -------------------------------- ### AttachmentManager Source: https://docs.adaptavist.com/sr4jc/latest/scriptrunner-migration-to-cloud/rewrite-scripts-for-cloud-hints-and-tips Maps the 'AttachmentManager' Java API (get attachments) to the 'GET /rest/api/3/attachment/content/{id}' REST API endpoint for retrieving attachment content in Jira Cloud. ```APIDOC ## Get attachment content ### Description Retrieves the content of an attachment. ### Method GET ### Endpoint /rest/api/3/attachment/content/{id} ``` -------------------------------- ### Find issues with components starting with 'Web' Source: https://docs.adaptavist.com/sr4jc/latest/features/scriptrunner-enhanced-search/scriptrunner-enhanced-search-jql-functions/match-functions Use `componentMatch` to find issues where the component name begins with a specified pattern. This is useful for managing tasks related to a specific set of components, like those in web development. ```JQL component in componentMatch("^Web.*?") ``` -------------------------------- ### Get Jira Version Source: https://docs.adaptavist.com/sr4jc/latest/features/script-console/example-scripts Retrieves the Jira version information from the server. This script makes a GET request to the serverInfo API endpoint and extracts the version number. ```groovy get('/rest/api/2/serverInfo') .queryString('doHealthCheck', 'true') .asObject(Map) .body .version ``` -------------------------------- ### Create a Basic Work Item Source: https://docs.adaptavist.com/sr4jc/latest/hapi/work-with-work-items Use this to create a new work item with only the mandatory fields: Space, Work type, Summary, and Reporter. Ensure your space's configuration scheme allows for this. ```groovy WorkItems.create('ABC', 'Task') { setSummary('my first HAPI 😍') } ``` -------------------------------- ### Set values by option name Source: https://docs.adaptavist.com/sr4jc/latest/hapi/update-fields Demonstrates how to set specific values for a custom field by providing the option names directly using the `set()` method. ```APIDOC ## Set values by option name ### Description Sets specific values for a custom field by their names, allowing replacement or setting of multiple options. ### Method `setCustomFieldValue(fieldName) { set(value1, value2, ...) }` ### Parameters - **fieldName** (String) - The name of the custom field. - **value1, value2, ...** (String) - The option names to set. ### Request Example ```groovy workItem.update { setCustomFieldValue('My checkboxes') { set('Yes', 'No') } } ``` ``` -------------------------------- ### Get Issue IDs with HAPI (Groovy) Source: https://docs.adaptavist.com/sr4jc/latest/release-notes/breaking-changes/atlassian-rest-api-search-endpoints-deprecation Retrieve issue IDs using HAPI by searching with a JQL query. This is a concise way to get a list of issue identifiers. ```groovy Issues.search("project = TEST AND issueType = Bug").collect{it.id} ``` -------------------------------- ### Create a Work Item with HAPI Source: https://docs.adaptavist.com/sr4jc/latest/hapi Use HAPI to create a new work item in Jira. This example demonstrates the basic syntax for creating a task. ```groovy WorkItems.create('ABC', 'Task') { setSummary('my first HAPI') } ``` -------------------------------- ### CommentManager Source: https://docs.adaptavist.com/sr4jc/latest/scriptrunner-migration-to-cloud/rewrite-scripts-for-cloud-hints-and-tips Maps the 'CommentManager' Java API (get, add comments) to the 'GET /rest/api/3/issue/{issueIdOrKey}/comment' REST API endpoint for retrieving or adding comments to an issue in Jira Cloud. ```APIDOC ## Get or add comments to an issue ### Description Retrieves existing comments or adds new comments to a specified issue. ### Method GET or POST ### Endpoint /rest/api/3/issue/{issueIdOrKey}/comment ``` -------------------------------- ### JQL Function: addedAfterSprintStart() Source: https://docs.adaptavist.com/sr4jc/latest/features/scriptrunner-enhanced-search/comparison-with-scriptrunner-for-jira-server Identifies issues that were added to a sprint after it commenced. Consult ScriptRunner Enhanced Search JQL Functions for further guidance. ```jql issueFunction in addedAfterSprintStart(boardName, sprintName) ``` -------------------------------- ### Use projectMatch to Find Projects by Key Pattern Source: https://docs.adaptavist.com/sr4jc/latest/features/scriptrunner-enhanced-search/scriptrunner-enhanced-search-jql-functions/match-functions Use projectMatch to search for projects whose keys match a given text pattern. This is beneficial for managing large Jira instances and cross-project reporting. Supports regex syntax. ```JQL project in projectMatch("^DEV.*") ``` -------------------------------- ### Example: linkedIssuesOf JQL Function Source: https://docs.adaptavist.com/sr4jc/latest/features/scriptrunner-enhanced-search Use the `linkedIssuesOf` JQL function to find issues that are linked to other issues based on specific criteria. This example returns unresolved issues that are blocked by open issues. ```jql linkedIssuesOf( issueFunction = blockedByOpenIssues() ) AND status != "Resolved" ``` -------------------------------- ### Additional Code Example for Commenting Source: https://docs.adaptavist.com/sr4jc/latest/features/workflow-rules/perform-actions/fields This snippet demonstrates how to add a comment to a parent work item when it's transitioned as part of a Perform Actions rule. The comment includes the issue key that triggered the transition. ```groovy addComment.body = "$ {issue.key} caused this to be transitioned" ``` -------------------------------- ### Get Transition ID for a Specific Workflow Transition Source: https://docs.adaptavist.com/sr4jc/latest/features/behaviours/create-and-modify-behaviours This script demonstrates how to get the current transition ID and check if it matches a specific transition, such as 'Done'. Use this to apply behaviours to specific workflow transitions. ```javascript // The transition ID for Done const transitionToDone = 41; // Get current transition ID const transitionId = await getContext().then(context => context.extension.issueTransition.id); // If the current transition is to Done then do something if (transitionId == transitionToDone) { } ``` -------------------------------- ### Example JQL with Custom Date Function Source: https://docs.adaptavist.com/sr4jc/latest/features/scriptrunner-enhanced-search/scriptrunner-enhanced-search-technical-background Demonstrates a JQL query that includes a custom 'dateCompare' function, which is not natively supported by Jira Cloud. ```jql assignee = currentUser() AND issueFunction in dateCompare("project = SRCLOUD", "created +1w < firstCommented") AND status = "In progress" ``` -------------------------------- ### Make a POST REST Request with Options Source: https://docs.adaptavist.com/sr4jc/latest/features/behaviours/behaviours-api Use `makeRequest` with `method: "POST"` and custom headers to send data to the Jira Cloud REST API. This example evaluates a Jira expression. ```js const body = `{ "expression": "issue.description.plainText.length >25", "context": { "issue": { "key": "DEMO-1" // Specify the Issue key to test agains }, "project": { "key": "DEMO" // Specify the project key here for the project of the issue being tested against } } }`; const res = await makeRequest("/rest/api/3/expression/eval?expand=meta.complexity", { method: "POST", headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: body }); if(res.body.value === false){ getFieldById("summary").setValue("Description field has less than 25 characters"); }else{ getFieldById("summary").setValue("Description field has more than 25 characters"); } ``` -------------------------------- ### Retrieve a space by key Source: https://docs.adaptavist.com/sr4jc/latest/hapi/work-with-spaces Fetch a specific space using its unique key. ```groovy Spaces.getByKey("TIS") ``` -------------------------------- ### Compare Comment Date Before Start of Week JQL Source: https://docs.adaptavist.com/sr4jc/latest/features/scriptrunner-enhanced-search/comparison-with-scriptrunner-for-jira-server Compares JQL for issues with comments added before the start of the current week. ScriptRunner for Jira Server uses `issueFunction in commented('before startOfWeek()')`, while Jira Cloud uses `firstCommentedDate < startOfWeek()`. ```jql issueFunction in commented("before startOfWeek()") ``` ```jql firstCommentedDate < startOfWeek() ``` -------------------------------- ### IssueService Source: https://docs.adaptavist.com/sr4jc/latest/scriptrunner-migration-to-cloud/rewrite-scripts-for-cloud-hints-and-tips Maps the 'IssueService' Java API (create, update, delete) to the corresponding REST API endpoints in Jira Cloud: GET /rest/api/3/issue/{issueIdOrKey} for getting issues, PUT /rest/api/3/issue/{issueIdOrKey} for updating issues, and DELETE /rest/api/3/issue/{issueIdOrKey} for deleting issues. ```APIDOC ## Get issue ### Description Retrieves details for a specific issue. ### Method GET ### Endpoint /rest/api/3/issue/{issueIdOrKey} ## Update issue ### Description Updates an existing issue. ### Method PUT ### Endpoint /rest/api/3/issue/{issueIdOrKey} ## Delete issue ### Description Deletes a specific issue. ### Method DELETE ### Endpoint /rest/api/3/issue/{issueIdOrKey} ``` -------------------------------- ### Map all direct and indirect dependencies of an issue Source: https://docs.adaptavist.com/sr4jc/latest/features/scriptrunner-enhanced-search/scriptrunner-enhanced-search-jql-functions/links-and-relationships Use this query to visualize all direct and indirect dependencies for a specific issue. This aids in thorough planning and risk assessment by understanding the full extent of interdependencies. ```jql issueFunction in linkedIssuesOfRecursive("issue = DEMO-1") ``` -------------------------------- ### CustomFieldManager Source: https://docs.adaptavist.com/sr4jc/latest/scriptrunner-migration-to-cloud/rewrite-scripts-for-cloud-hints-and-tips Maps the 'CustomFieldManager' Java API (get custom fields) to 'GET /rest/api/3/field' for retrieving fields and 'POST /rest/api/3/field' for creating fields in Jira Cloud. Note: Do not use these endpoints to update field values; use the issues PUT endpoint instead. ```APIDOC ## Get fields ### Description Retrieves a list of available fields. ### Method GET ### Endpoint /rest/api/3/field ## Create fields ### Description Creates new fields. ### Method POST ### Endpoint /rest/api/3/field ``` -------------------------------- ### Copy Versions to a New Space Source: https://docs.adaptavist.com/sr4jc/latest/features/script-console/example-scripts Copies project versions from a source space to a destination space. It only copies versions if a version with the same name does not already exist in the destination space. Requires specifying source and destination space keys. ```groovy // Specify the master space to get the versions form final sourceSpaceKey = 'SRC' // Specify the key of the space to copy the version to final destinationSpaceKey = 'DST' // Get the space versions def versions = get("/rest/api/2/project/${sourceSpaceKey}/versions") .header('Content-Type', 'application/json') .asObject(List).body as List // Loop over each version returned and create a version in the new space def successStatusByVersionId = versions.collectEntries { // Copy the version and specify the destination project def versionCopy = it.subMap(['name', 'description', 'archived', 'released', 'startDate', 'releaseDate', 'project']) versionCopy['project'] = destinationSpaceKey // Make the rest call to create the version logger.info("Copying the version with id '${it.id}' and name '${it.name}'") def createdVersionResponse = post('/rest/api/2/version') .header('Content-Type', 'application/json') .body(versionCopy) .asObject(Map) // Log out the versions copied or which failed to be copied if (createdVersionResponse.status == 201) { logger.info("Version with id '${it.id}' and name '${it.name}' copied. New id: ${createdVersionResponse.body.id}") } else { logger.warn("Failed to copy version with id '${it.id}' and name '${it.name}'. ${createdVersionResponse.status}: ${createdVersionResponse.body}") } [(it.id): (createdVersionResponse.status == 201)] } "Status by source version id (copied?): ${successStatusByVersionId}" ``` -------------------------------- ### Estimate Initial Sync Time Source: https://docs.adaptavist.com/sr4jc/latest/features/scriptrunner-enhanced-search/scriptrunner-enhanced-search-jql-keywords-synchronization Use this formula to estimate the time required for the initial JQL Keyword sync based on the total number of issues in your Jira instance. ```text ( * 0.00029) / 50 ``` -------------------------------- ### JSON Properties Source: https://docs.adaptavist.com/sr4jc/latest/hapi/work-with-entity-properties Methods for setting and getting JSON properties. ```APIDOC ## setJson, getJson ### Description Sets or retrieves a JSON property using a specified key. The JSON string must be correctly formatted. ### Method `setJson(String key, String json)` `getJson(String key)` ### Parameters - **key** (String) - The key of the property. - **json** (String) - The JSON string value to set. ### Response - **Success Response (200)**: Returns the retrieved JSON string or void for setter. ``` -------------------------------- ### LocalDateTime Properties Source: https://docs.adaptavist.com/sr4jc/latest/hapi/work-with-entity-properties Methods for setting and getting LocalDateTime properties. ```APIDOC ## setLocalDateTime, getLocalDateTime ### Description Sets or retrieves a LocalDateTime property using a specified key. ### Method `setLocalDateTime(String key, LocalDateTime dateTime)` `getLocalDateTime(String key)` ### Parameters - **key** (String) - The key of the property. - **dateTime** (LocalDateTime) - The LocalDateTime value to set. ### Response - **Success Response (200)**: Returns the retrieved LocalDateTime value or void for setter. ``` -------------------------------- ### addedAfterSprintStart JQL Function Syntax Source: https://docs.adaptavist.com/sr4jc/latest/features/scriptrunner-enhanced-search/scriptrunner-enhanced-search-jql-functions/agile-and-sprint-management Use this function to identify issues added after a sprint has started. The 'Board' parameter is mandatory, while 'Sprint' is optional. If 'Sprint' is omitted, it defaults to the current active sprint, but requires specification if multiple sprints are active. ```jql addedAfterSprintStart(Board, [Sprint]) ``` -------------------------------- ### LocalDate Properties Source: https://docs.adaptavist.com/sr4jc/latest/hapi/work-with-entity-properties Methods for setting and getting LocalDate properties. ```APIDOC ## setLocalDate, getLocalDate ### Description Sets or retrieves a LocalDate property using a specified key. ### Method `setLocalDate(String key, LocalDate date)` `getLocalDate(String key)` ### Parameters - **key** (String) - The key of the property. - **date** (LocalDate) - The LocalDate value to set. ### Response - **Success Response (200)**: Returns the retrieved LocalDate value or void for setter. ``` -------------------------------- ### Boolean Properties Source: https://docs.adaptavist.com/sr4jc/latest/hapi/work-with-entity-properties Methods for setting and getting boolean properties. ```APIDOC ## setBoolean, getBoolean ### Description Sets or retrieves a boolean property using a specified key. ### Method `setBoolean(String key, Boolean bool)` `getBoolean(String key)` ### Parameters - **key** (String) - The key of the property. - **bool** (Boolean) - The boolean value to set. ### Response - **Success Response (200)**: Returns the retrieved boolean value or void for setter. ``` -------------------------------- ### Long Properties Source: https://docs.adaptavist.com/sr4jc/latest/hapi/work-with-entity-properties Methods for setting and getting long properties. ```APIDOC ## setLong, getLong ### Description Sets or retrieves a long property using a specified key. ### Method `setLong(String key, Long along)` `getLong(String key)` ### Parameters - **key** (String) - The key of the property. - **along** (Long) - The long value to set. ### Response - **Success Response (200)**: Returns the retrieved long value or void for setter. ``` -------------------------------- ### Add/Remove from Sprint Script Example Source: https://docs.adaptavist.com/sr4jc/latest/features/workflow-rules/example-workflow-rules This script can be used to add or remove an issue from a sprint. Ensure the correct board name and run-as user are configured. ```groovy import com.onresolve.jira.groovy.user.UserScript import com.atlassian.jira.component.ComponentAccessor def sprintManager = ComponentAccessor.getComponent(com.atlassian.greenhopper.service.sprint.SprintManager) def boardService = ComponentAccessor.getComponent(com.atlassian.greenhopper.service.board.BoardService) def user = ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser() def issue = issue def boardName = "Board Name" def action = "add" // or "remove" def sprints = sprintManager.getOrderedSprintsForBoard(boardService.getBoard(user, boardName).get()) def activeSprint = sprints.find { it.state == com.atlassian.greenhopper.service.sprint.SprintInfo$State.ACTIVE } if (action == "add") { sprintManager.addIssueToSprint(user, activeSprint.id, issue.id) } else if (action == "remove") { sprintManager.removeIssueFromSprint(user, activeSprint.id, issue.id) } ```