...
2. Script to prompt the user if they want to close the parent ticket when all sub-tasks under the ticket are done (Cloud)
Code Block | ||
---|---|---|
| ||
// Check if issue types are sub-tasks
if (!issue.fields.issuetype.subtask) {
return
}
// Get the parent issue as a Map
def parent = (issue.fields as Map).parent as Map
// Retrieve all the subtasks of this issue's parent
def parentKey = parent.key
logger.info("Parent Key: " + parentKey)
// Specify the name of the version to extract from the issue
def closedStatus = "Done"
logger.info("Closed Status: " + closedStatus)
// Get the parent issue object
def result = get('/rest/api/2/issue/' + parentKey)
.header('Content-Type', 'application/json')
.asObject(Map)
//Find the assignee name
def assignee = result.body.fields.assignee.displayName
logger.info("Assignee name is :" + assignee)
// Find the subtasks status
String[] subTasks = result.body.fields.subtasks
logger.info("Subtasks length: " + subTasks.length)
def allSubTasksResolved;
for(int i = 0; i < subTasks.length; i++) {
def subTasksStatus = result.body.fields.subtasks[i].fields.status.name
logger.info("sub task status: " + subTasksStatus)
if(subTasks.findAll{subTasksStatus.contains(closedStatus)}){
allSubTasksResolved = true
}
// If all subtasks have the Done status set the flag to true
if(subTasks.findAll{!subTasksStatus.contains(closedStatus)}){
allSubTasksResolved = false
}
}
if(allSubTasksResolved == true){
logger.info("All sub tasks are in Done status")
def prompt = post("/rest/api/2/issue/" + parentKey + "/notify")
.header("Content-Type", "application/json")
.body([
subject: 'All sub-tasks transitioned to Done status',
textBody: "All the sub-tasks related to " + parentKey + " are transitioned to Done status",
htmlBody: "<p>Do you want to close the </p>" + parentKey + "<p> issue?</p>" ,
to: [
users: [[
name: assignee,
active: true
]]
]
])
.asString()
} else if (allSubTasksResolved == false){
logger.info("All sub tasks are not in Done status")
} |
3. Script to change the fixVersions field of sub-tasks based on parent task on update event (Server)
Code Block | ||
---|---|---|
| ||
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.event.type.EventDispatchOption
import com.atlassian.jira.issue.Issue
import com.atlassian.jira.issue.IssueManager
import com.atlassian.jira.issue.MutableIssue
import com.atlassian.jira.project.version.Version
IssueManager issueManager = ComponentAccessor.getComponent(IssueManager.class)
Issue updatedIssue = event.getIssue()
log.error "Issue is: " + updatedIssue
Collection<Version> fixVersions = new ArrayList<Version>()
fixVersions = updatedIssue.getFixVersions()
log.error "Fix versions of parent are: " + fixVersions
Collection<Issue> subTasks = updatedIssue.getSubTaskObjects()
log.error "Sub tasks are: " + subTasks
subTasks.each {
log.error "Type : " + it.issueType.getName()
if(it.issueType.getName() == "Migration") {
if (it instanceof MutableIssue) {
((MutableIssue) it).setFixVersions(fixVersions)
issueManager.updateIssue(event.getUser(), it, EventDispatchOption.ISSUE_UPDATED, false)
log.error "Fix version of subbtask"
}
}
} |
4. Script to set a default value for fixVersion field (Server)
Code Block | ||
---|---|---|
| ||
def versionIdProductionMaintenance = "10214"
def versionIdProductionUAT = "10306"
def actionName = "Create"
if (getActionName() != actionName) {
return // not the initial action, so don't set default values
}
//get fixVersion ID
def fixVersionsField = getFieldById("fixVersions")
//set fixVersion value
def fixVersionsNewValue = fixVersionsField.setFormValue([versionIdProductionMaintenance, versionIdProductionUAT]) |
5. Adding Custom filed value while changing the status to the particular screen(post-function)
Code Block |
---|
import groovy.json.JsonSlurper;
import groovy.json.StreamingJsonBuilder;
import com.atlassian.jira.issue.util.DefaultIssueChangeHolder;
import com.atlassian.jira.issue.ModifiedValue;
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.Issue;
import com.atlassian.jira.issue.MutableIssue
import org.apache.commons.codec.binary.Base64;
def url = new URL("https://jsonplaceholder.typicode.com/posts").openConnection();
def message = '{"title": "foo","body": "bar", "userId": "1"}';
url.setRequestMethod("POST")
url.setDoOutput(true)
url.setRequestProperty("Content-Type", "application/json")
url.getOutputStream().write(message.getBytes("UTF-8"));
def postRC = url.getResponseCode();
IssueManager im = ComponentAccessor.getIssueManager()
MutableIssue issue = im.getIssueObject("SP-5519")
if(issue){
def customFieldManager = ComponentAccessor.getCustomFieldManager()
def cField = customFieldManager.getCustomFieldObject("customfield_10401")
def cFieldValue = issue.getCustomFieldValue(cField)
def changeHolder = new DefaultIssueChangeHolder()
cField.updateValue(null, issue, new ModifiedValue(cFieldValue, url.getInputStream().getText()),changeHolder)
}else {
return "Issue doesn't exist"
} |
6. Changing the status of particular issue
Code Block |
---|
import com.atlassian.jira.issue.IssueManager;
import com.atlassian.jira.issue.MutableIssue;
import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.user.ApplicationUser;
//Workflow imports
import com.atlassian.jira.issue.IssueInputParametersImpl
import com.atlassian.jira.bc.issue.IssueService
import com.atlassian.jira.workflow.JiraWorkflow
import com.atlassian.jira.workflow.WorkflowManager
ApplicationUser currentUser = ComponentAccessor.getJiraAuthenticationContext().loggedInUser
IssueManager im = ComponentAccessor.getIssueManager();
MutableIssue issue = im.getIssueObject("SP-5519");
//Workflow
WorkflowManager workflowManager = ComponentAccessor.getWorkflowManager()
JiraWorkflow workflow = workflowManager.getWorkflow(issue)
def actionId = 41
IssueService issueService = ComponentAccessor.getIssueService()
def transitionValidationResult = issueService.validateTransition(currentUser, issue.id, actionId, new IssueInputParametersImpl())
def transitionResult = issueService.transition(currentUser, transitionValidationResult)
return transitionResult |
Learning:
Knowledge on how scriptrunner script-runner listener works for both cloud and server
Got to understand different scenarios for Jira based on which scripts were written
Basic knowledge on groovy
While setting the value for multi-select system fields always set the values based on “id’s of values” and not “values itself“ in behaviors
While setting the value for single select system fields we can directly give “values” instead of “id’s of values”
scriptrunner script-runner behaviors
While setting the value for single select custom field we have to give “id’s of values” only (can also be directly configured in field setting as these are custom fields)
...
No | Date | Topics learnt | ||||||||||
1 | 12-03-2020 | Introduction to Groovy, how groovy works, static and dynamic compilation, optional typed, how to use scriptrunner script-runner to execute scripts in script console, how to look up to javadoc java doc for methods and classes | ||||||||||
2 | 13-03-2020 | Variables, rules, operators, built in scripts and scenarios in scriptrunnerscript-runner, listeners, exception handling, how to get all the details related to a specific issue (code) | ||||||||||
3 | 16-03-2020 | Conditional statements (if else, switch), looping (for, for in, while), String, string functions, interpolation, multilinesmulti-lines, methods / functions, closures, how to get all the subtasks sub-tasks related to issues, fetch their data and manipulate their information (code) | ||||||||||
4 | 17-03-2020 | Worked on setting a default value to a fix version system field (includes reading and understanding the behaviors of scriptrunnerscript-runner, sample examples, and implementation of the code)
| ||||||||||
5 | 18-03-2020 | Collections, lists, maps, ranges, types of ranges, iterations over collections, functions available for different collections, IO operations, how to set values based on system and custom fields (code) |
...