Create
cancel
Showing results for 
Search instead for 
Did you mean: 
Sign up Log in

It's not the same without you

Join the community to find out what other Atlassian users are discussing, debating and creating.

Atlassian Community Hero Image Collage

ScriptRunner listener does not update custom field Edited

I have a The Table Grid Next Generation plugin custom field.

The issue is supposed to be created from JSD customer portal.

Then I tried to use ScriptRunner listener to modify the value of this custom field based on the result of an API call in the issue create transition.

However, the customfield value is modified if the issue is created from customer portal. If I create the issue from Jira (agent view) or clone an existing issue, the following script in the listener works just fine.

Could anyone please help what's wrong with the following script why it does not work for issue created from Customer Portal?

 

import groovy.json.JsonSlurper;
import groovy.json.StreamingJsonBuilder;
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 com.atlassian.jira.event.issue.IssueEvent
import org.apache.commons.codec.binary.Base64;
import groovyx.net.http.*
import groovyx.net.http.ContentType.*
import groovyx.net.http.Method.*
import net.sf.json.*
import groovy.json.JsonBuilder
import com.atlassian.jira.issue.link.LinkCollectionImpl;
import com.atlassian.jira.issue.link.IssueLink;
import com.atlassian.jira.issue.util.DefaultIssueChangeHolder;
import com.atlassian.jira.event.type.EventDispatchOption;
import com.atlassian.jira.issue.ModifiedValue;
import com.atlassian.jira.bc.issue.IssueService.TransitionValidationResult;
import com.atlassian.jira.workflow.TransitionOptions;
import com.atlassian.jira.issue.IssueInputParametersImpl;
import org.apache.log4j.Logger;
import static org.apache.log4j.Level.DEBUG;
import com.atlassian.jira.issue.MutableIssue;
import com.atlassian.jira.issue.index.IssueIndexingService;
import com.atlassian.jira.util.ImportUtils;
import com.atlassian.jira.event.type.EventDispatchOption;
import com.atlassian.jira.issue.CustomFieldManager;
import com.atlassian.jira.issue.UpdateIssueRequest;

log.setLevel(DEBUG);

//user
def user = ComponentAccessor.jiraAuthenticationContext.loggedInUser;
def issueService = ComponentAccessor.getIssueService();
TransitionOptions transitionOptions = new TransitionOptions.Builder().skipConditions().skipPermissions().skipValidators().build();
/* Get Insight Object Facade from plugin accessor */
Class objectFacadeClass = ComponentAccessor.getPluginAccessor().getClassLoader().findClass("com.riadalabs.jira.plugins.insight.channel.external.api.facade.ObjectFacade");
def objectFacade = ComponentAccessor.getOSGiComponentInstanceOfType(objectFacadeClass);

Class customFieldFacadeClass = ComponentAccessor.getPluginAccessor().getClassLoader().findClass("com.riadalabs.jira.plugins.insight.services.core.CustomFieldService");
def customFieldFacade = ComponentAccessor.getOSGiComponentInstanceOfType(customFieldFacadeClass);

IssueManager issueManager = ComponentAccessor.getIssueManager()
def customFieldManager = ComponentAccessor.getCustomFieldManager()
IssueEvent event = event //comment
def eventIssue = event.getIssue(); //comment
def issueID = eventIssue.getKey(); //comment
def issue = issueManager.getIssueObject(issueID)
def eventTypeId = event.getEventTypeId();

//Long eventTypeId = 10211;
//def issueID = "CSDA-345"; //uncomment
//def eventIssue = issueManager.getIssueObject(issueID) //uncomment

//Getting Firewall Policy Grid custom field object. It is a Table Grid Next Generation custom field.
def firewallPolicyObj = customFieldManager.getCustomFieldObjectByName("Firewall Policy Grid")//customFieldManager.getCustomFieldObject("customfield_11092")
assert firewallPolicyObj : "could not find Disk Type custom field"
def firewallPolicyValue = eventIssue.getCustomFieldValue(firewallPolicyObj);
def customFieldID = firewallPolicyObj.getId();

def jsonSlurper = new JsonSlurper()
def optimizedFirewallGrid = customFieldManager.getCustomFieldObjectByName("Optimized Firewall Policy Grid")//customFieldManager.getCustomFieldObject("customfield_11093")
def FirewallGridJson = jsonSlurper.parseText(firewallPolicyValue)
assert FirewallGridJson instanceof Map : "Not a JSON"

// initialize a new builder and give a default URL
def baseURL = ""
def path = ""
def gridCustomFieldId = "";
def gridCustomFieldName = "";
//Encode credentials

String credentials = "username:password" //Change username with your Jira username and password with your Jira password
String encoded_credentials = credentials.bytes.encodeBase64().toString() //We are encoding the credentials
//if the Status is Under Optimization or Approval. We need to call external app service to optimize the firewall request. Otherwise, send to the external app end point to review the Firewall Policy Request
if(eventTypeId == 10402){//Firewall Issue Created event id
baseURL = new HTTPBuilder("http://localhost") //change to the Firewall review endpoint
path = "/api/v1/validate" //change to the Firewall review endpoint
}else{//approved
baseURL = new HTTPBuilder("http://localhost") //change to the Firewall optimization endpoint
path = "/api/v1/optimize" //change to the Firewall optimization endpoint
}

String results = "";
def newJson = new groovy.json.JsonBuilder(FirewallGridJson)
int size = newJson.content.rows.size()

for (int i=0;i<size;i++){

if(newJson.content.rows[i].columns.destination_ip == null){
newJson.content.rows[i].columns.destination_ip = "";
}
if(newJson.content.rows[i].columns.destination_nat_ip == null){
newJson.content.rows[i].columns.destination_nat_ip = "";
}
if(newJson.content.rows[i].columns.source_nat_ip == null){
newJson.content.rows[i].columns.source_nat_ip = "";
}
if(newJson.content.rows[i].columns.destination_port == null){
newJson.content.rows[i].columns.destination_port = "";
}
if(newJson.content.rows[i].columns.destination_ip == null){
newJson.content.rows[i].columns.destination_ip = "";
}
if(newJson.content.rows[i].columns.action == null){
newJson.content.rows[i].columns.action = "";
}
if(newJson.content.rows[i].columns.protocol == null){
newJson.content.rows[i].columns.protocol = "";
}
if(newJson.content.rows[i].columns.source_hostname == null){
newJson.content.rows[i].columns.source_hostname = "";
}
if(newJson.content.rows[i].columns.source_ip == null){
newJson.content.rows[i].columns.source_ip = "";
}
if(newJson.content.rows[i].columns.destination_hostname == null){
newJson.content.rows[i].columns.destination_hostname = "";
}
if(newJson.content.rows[i].columns.review_status == null){
newJson.content.rows[i].columns.review_status = "OK";
}
if(newJson.content.rows[i].columns.remark == null){
newJson.content.rows[i].columns.remark = "";
}
}


MutableIssue mutableIssue = ComponentAccessor.getIssueManager().getIssueObject(eventIssue.getKey());
/*
def changeHolder = new DefaultIssueChangeHolder();
firewallPolicyObj.updateValue(null, mutableIssue, new ModifiedValue(eventIssue.getCustomFieldValue(firewallPolicyObj),newJson.toString()), changeHolder)
*/
log.info newJson.toString();
mutableIssue.setCustomFieldValue(firewallPolicyObj, newJson.toString());
//mutableIssue.setSummary("tesss");
ComponentAccessor.getIssueManager().updateIssue(
ComponentAccessor.getJiraAuthenticationContext().getUser()
, mutableIssue
, UpdateIssueRequest.builder().eventDispatchOption(EventDispatchOption.ISSUE_UPDATED).sendMail(false).build()
)

log.info mutableIssue.getCustomFieldValue(firewallPolicyObj)
return
def jsonBody = new groovy.json.JsonBuilder()
jsonBody {
grid FirewallGridJson
}

baseURL.request(Method.POST, ContentType.JSON){ req ->
uri.path = path
headers."Authorization" = "Basic "+encoded_credentials
headers."Content-Type" = "application/json"
body = jsonBody.toPrettyString()

response.success = { resp, json ->
assert resp.status == 200
def jsonResult = new groovy.json.JsonBuilder(json)

// if(!jsonResult.content.grid.ducketId){
jsonResult{
ducketId jsonBody.content.grid.ducketId
rows json.grid.rows
}
//}
log.info jsonResult.toString();
//issue = issueManager.getIssueObject(issueID)
if(json){
if(eventTypeId == 10004){//Firewall Issue Created event id
firewallPolicyObj.updateValue(null, eventIssue, new ModifiedValue(firewallPolicyValue,jsonResult.toString()), changeHolder)
//issue.get
//issue.setCustomFieldValue(firewallPolicyObj, jsonResult.toString());
//issueManager.updateIssue(user,issue, EventDispatchOption.DO_NOT_DISPATCH,false);
//reindexing the issue

log.info "after update value" + issue.getCustomFieldValue(firewallPolicyObj);
int EVENT_ID = 11;//the event id for "Complete review" transition
TransitionValidationResult validationResult = issueService.validateTransition(user, issue.id, EVENT_ID as Integer, new IssueInputParametersImpl(), transitionOptions)
log.info "Validation result: " + validationResult.errorCollection;
if(validationResult.isValid()) {
log.info "valid";
issueService.transition(user, validationResult)
}
}else{//update optimized FirewallGrid
log.info issue.getStatusId();
optimizedFirewallGrid.updateValue(null, eventIssue, new ModifiedValue(eventIssue.getCustomFieldValue(optimizedFirewallGrid),jsonResult.toString()), changeHolder)
//issue.setCustomFieldValue(optimizedFirewallGrid, jsonResult.toString());
//issueManager.updateIssue(user,issue, EventDispatchOption.DO_NOT_DISPATCH,false);
int EVENT_ID = 31;//the event id for "Complete optimization" transition
//reindexing the issue

log.info issue.statusObject.name
TransitionValidationResult validationResult = issueService.validateTransition(user, issue.id, EVENT_ID as Integer, new IssueInputParametersImpl(), transitionOptions)
if(validationResult.isValid()) {
issueService.transition(user, validationResult)
}
return issue.statusObject.name
}
}
}
// not logged in response
response.'302' = { resp ->
throw new Exception("Stopping at item POST: uri: " + uri + "\n" +
" You are not logging in properly. Item will not be created.")
}
response.failure = { resp, json ->
throw new Exception("Stopping at item POST: uri: " + uri + "\n" +
" Unknown error trying to create item: ${resp.status}, not creating Item." +
"\njson = ${json}")
}
}


boolean isIndex = ImportUtils.isIndexIssues();
ImportUtils.setIndexIssues(true);
IssueIndexingService IssueIndexingService = (IssueIndexingService) ComponentAccessor.getComponent(IssueIndexingService.class);
IssueIndexingService.reIndex(mutableIssue);

ImportUtils.setIndexIssues(isIndex);

1 answer

0 votes
brbojorque Community Leader Jan 04, 2020

Hi @Priska Aprilia ,

There should be a logger for every run of the script listener.

What is the error when you create the issue via JSD?

Suggest an answer

Log in or Sign up to answer
TAGS
Community showcase
Published in Statuspage

New feature: Slack notifications for Statuspage

We're excited to announce the release of a long-requested feature on Statuspage. Now visitors to your status page can subscribe to get notified in Slack when you report an incident or maintenance. Th...

81 views 0 9
Read article

Community Events

Connect with like-minded Atlassian users at free events near you!

Find an event

Connect with like-minded Atlassian users at free events near you!

Unfortunately there are no Community Events near you at the moment.

Host an event

You're one step closer to meeting fellow Atlassian users at your local event. Learn more about Community Events

Events near you