Rest endpoint redirected when executed

Pradeep A August 3, 2021

Hi Im working with custom webitem. When I click on the web item I run the script written in the rest endpoint. But the issue I'm facing is the response is redirected instead of showing a flag on the same issue page. 

I have attached an image for reference

As you can see instead of displaying the flag it is re-directing

 

My code

import com.onresolve.scriptrunner.runner.rest.common.CustomEndpointDelegate // Importing the required classes

 

import groovy.json.JsonOutput

 

import groovy.json.*

 

import groovy.transform.BaseScript

 

import javax.ws.rs.core.MultivaluedMap

 

import javax.ws.rs.core.Response

 

import groovy.json.JsonSlurper;

               

import java.util.ArrayList;

 

import com.atlassian.jira.issue.IssueInputParameters

 

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 org.apache.commons.codec.binary.Base64; 

 

import groovyx.net.http.HTTPBuilder 

 

import static groovyx.net.http.ContentType.* 

 

import groovyx.net.http.ContentType 

 

import static groovyx.net.http.Method.* 

 

import groovy.json.JsonSlurper 

 

import groovy.json.JsonBuilder 

 

import net.sf.json.groovy.JsonSlurper 

 

import groovy.json.JsonOutput 

 

import com.atlassian.jira.issue.MutableIssue 

 

import com.atlassian.jira.event.type.EventDispatchOption 

 

import java.net.URLEncoder;

 

@BaseScript CustomEndpointDelegate delegate

createMSTeam(httpMethod: "GET") { MultivaluedMap queryParams ->   

String clientId="70261761-8a09-414f-89bc-0493f38e4e30"  // Provide the appropriate Client ID here

String clienSecret ="2xJ_5Pl0_RuMROdoMaO_FHd4H.S9c044Yg";// Provide the appropriate Client Seceret here 

String tenantId="2d7a229a-252c-4c3c-85ac-4698827052af"; // Provide the appropriate Tenant ID here

def customFieldManager = ComponentAccessor.getCustomFieldManager() 

def currentUser = ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser() 

def issueManager = ComponentAccessor.getIssueManager()

def issueId = queryParams.getFirst("issueId") as long // getting the Issue Id from the query Params  

log.warn(issueId)

Issue issue = issueManager.getIssueObject(issueId)  

log.warn("The issue ID"+issueId)

def issueSum=issue.getSummary() 

def ContainerPath = """  "LDAP://OU=BU3,OU=BU2,OU=BU1,OU=Employees,OU=contoso,DC=consto,DC=com"  """ 

def displayName= issueSum.toString();

//---------------------------------------------------------Generating the Bearer Token--------------------------------------------------//

 

def accessBody = "grant_type=client_credentials&client_id="+clientId+"&scope=https://graph.microsoft.com/.default&client_secret="+clienSecret

def accessUrl1 = "https://login.microsoftonline.com/"+tenantId+"/oauth2/v2.0/token"

URL accessTokenUrl1 = new URL(accessUrl1); 

HttpURLConnection connection1 = accessTokenUrl1.openConnection() as HttpURLConnection; 

connection1.requestMethod = "POST" 

connection1.doOutput = true 

connection1.setRequestProperty("Content-Type", "application/x-www-form-urlencoded") 

def json_object;

try 

{

    OutputStream os = connection1.getOutputStream()

    byte[] input = accessBody.getBytes("utf-8");

    os.write(input, 0, input.length);           

    connection1.connect();

}

catch(Exception ex){

    log.warn(ex.toString());

}

try { // Reading the Response

    BufferedReader br = new BufferedReader(

    new InputStreamReader(connection1.getInputStream(), "utf-8"))

    StringBuilder response = new StringBuilder();

    String responseLine = null;

    while ((responseLine = br.readLine()) != null) {

    response.append(responseLine.trim());

    }

    def jsonSlurper = new JsonSlurper() //Parsing the Json

                json_object = jsonSlurper.parseText(response.toString())

    //def jsonValue = json_object.value

    assert json_object instanceof Map  

    log.warn(json_object.access_token)

    log.warn(response.toString());

}

catch(Exception ex){

    log.warn(ex.toString())

}

def bearer_token = json_object.access_token.toString() 

log.warn(bearer_token);

// --------------------------------------Fetching the user details-------------------------------------------------------//

   

log.warn("the user email"+issue.reporter.emailAddress)

def userInfoUrl = "https://graph.microsoft.com/v1.0/users/"+issue.reporter.emailAddress; //Passing the Issue Reporter Mail Address

def userId;

URL obj = new URL(userInfoUrl);

  HttpURLConnection con = (HttpURLConnection) obj.openConnection();

   con.setRequestMethod("GET");

   con.doOutput = true ;

   con.setRequestProperty("Authorization","Bearer " + bearer_token);

   con.setRequestProperty("Content-Type","application/json");

   con.setRequestProperty("Accept","application/json");

   con.connect();

   try {//Reading the response

   BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));

                StringBuilder sb = new StringBuilder();

                String line;

                while ((line = br.readLine()) != null) {

                    sb.append(line+"\n");

                }

                br.close();

                log.warn(sb.toString());

   def jsonResponse = new JsonSlurper() //Parsing the Json Response

   userId = jsonResponse.parseText(sb.toString())    

   assert userId instanceof Map  

   log.warn(userId.id)

   }

   catch(Exception ex){

    log.warn(ex.toString())

}

//---------------------------------------Getting Teams List--------------------------------------------------------------//

def teamsListUrl = "https://graph.microsoft.com/beta/groups?\$select=Team&\$filter=displayName+eq+'"+displayName+"'";

//String encodedUrl = URLEncoder.encode(teamsListUrl, "UTF-8");

def teamsDisplayName;

String stringResponse;

URL objTeamsList = new URL(teamsListUrl.replace(" ", "%20"));

  HttpURLConnection objTeamsListConnection = (HttpURLConnection) objTeamsList.openConnection();

   objTeamsListConnection.setRequestMethod("GET");

   objTeamsListConnection.doOutput = true ;

   objTeamsListConnection.setRequestProperty("Authorization","Bearer " + bearer_token);

   objTeamsListConnection.setRequestProperty("Content-Type","application/json");

   objTeamsListConnection.setRequestProperty("Accept","application/json");

   objTeamsListConnection.connect();

   try {//Reading the response

   BufferedReader teamsListBuffer = new BufferedReader(new InputStreamReader(objTeamsListConnection.getInputStream()));

                StringBuilder teamsListBuilder = new StringBuilder();

                String teamsListLine;     

                while ((teamsListLine = teamsListBuffer.readLine()) != null) {

                    teamsListBuilder.append(teamsListLine+"\n");            

                }

                teamsListBuffer.close();      

                                               String display = teamsListBuilder.toString();

                                               log.warn(display.length())

                                               log.warn("look here")

                                               log.warn(display);

                                                def teamListResponse = new JsonSlurper() 

                teamsDisplayName = teamListResponse.parseText(teamsListBuilder.toString())

                                                                assert teamsDisplayName instanceof Map  

                                               def stringName = teamsDisplayName.value;

                                               stringResponse =stringName;

                log.warn(stringResponse)

                                               log.warn(stringResponse.getClass())

               

               

   }

  catch(Exception ex){

    log.warn(ex.toString())

}     

// --------------------------------------Creating Team------------------------------------------------------------------//

String userIdMS = userId.id;

String userIdString=userIdMS.toString()  

String jsonBody = "{ \"template@odata.bind\":\"https://graph.microsoft.com/v1.0/teamsTemplates('standard')\",  \"displayName\":\"" + displayName + "\", \"description\":\"My Sample Team’s Description\", \"members\":[ {\"@odata.type\":\"#microsoft.graph.aadUserConversationMember\",\"roles\":[ \"owner\"], \"user@odata.bind\":\"https://graph.microsoft.com/v1.0/users('"+userIdString+"')\"}]}\"}"

def baseURL = "https://graph.microsoft.com/v1.0/teams"   

URL url = new URL(baseURL);

if(stringResponse=="[]"){

HttpURLConnection connection = url.openConnection() as HttpURLConnection;    

connection.requestMethod = "POST"     

connection.doOutput = true  

connection.setRequestProperty("Authorization","Bearer " + bearer_token); 

connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8")  

connection.outputStream      

OutputStream os = connection.getOutputStream();

        os.write(jsonBody.getBytes());

        os.flush(); 

connection.connect();      

String responseHeader = connection.getHeaderField("Content-Location"); //Fetching the Team Id from the Response Header     

String [] teamId=responseHeader.split("'");   

log.warn ("URL For Channel creation="+url+"Status="+connection.getResponseCode() as String)  

log.warn ("URL For accessToken new="+accessTokenUrl1+"Status="+connection1.getResponseCode() as String)     

log.warn(jsonBody)

                

 

//-------------------------------------------Getting the details of Issue assignee---------------------------------------------------//

 

def assigneeInfoUrl = "https://graph.microsoft.com/v1.0/users/"+issue.assignee.emailAddress;

def assigneeId;

log.warn("issue assignee name is : "+issue.assignee.emailAddress)

URL objAssigneeUrl = new URL(assigneeInfoUrl);

  HttpURLConnection objAssigneeConnection = (HttpURLConnection) objAssigneeUrl.openConnection();

   objAssigneeConnection.setRequestMethod("GET");

   objAssigneeConnection.doOutput = true ;

   objAssigneeConnection.setRequestProperty("Authorization","Bearer " + bearer_token);

   objAssigneeConnection.setRequestProperty("Content-Type","application/json");

   objAssigneeConnection.setRequestProperty("Accept","application/json");

   objAssigneeConnection.connect();

   try {//Reading the response

   BufferedReader assigneeBuffer = new BufferedReader(new InputStreamReader(objAssigneeConnection.getInputStream()));

                StringBuilder assigneeBuilder = new StringBuilder();

                String assigneeLine;

                while ((assigneeLine = assigneeBuffer.readLine()) != null) {

                    assigneeBuilder.append(assigneeLine+"\n");

                }

                assigneeBuffer.close();

                log.warn("assignee mail address"+assigneeBuilder.toString());

                                                log.warn("response text for assignee "+assigneeBuilder)

                                                def assigneeResponse = new JsonSlurper()

                                                    assigneeId = assigneeResponse.parseText(assigneeBuilder.toString())

                                                                assert assigneeId instanceof Map  

                                                                log.warn("Assignee ID"+assigneeId.id)

   }

  catch(Exception ex){

    log.warn(ex.toString())

}   

//------------------------------------------Adding member to created team------------------------------------------------------------//

String addMemberBody = "{\"@odata.type\":\"#microsoft.graph.aadUserConversationMember\",\"roles\":[ \"owner\"], \"user@odata.bind\":\"https://graph.microsoft.com/v1.0/users('"+assigneeId.id+"')\"}"

def addMemberUrl = "https://graph.microsoft.com/v1.0/teams/"+teamId[1]+"/members"  

URL memberUrl = new URL(addMemberUrl);  

HttpURLConnection objAddMember = memberUrl.openConnection() as HttpURLConnection;   

objAddMember.requestMethod = "POST"    

objAddMember.doOutput = true    

objAddMember.setRequestProperty("Authorization","Bearer " + bearer_token); 

objAddMember.setRequestProperty("Content-Type", "application/json;charset=UTF-8")  

objAddMember.setRequestProperty("Accept","application/json");

objAddMember.outputStream      

OutputStream outputStream = objAddMember.getOutputStream();

        outputStream.write(addMemberBody.getBytes());

        outputStream.flush();

objAddMember.connect();  

log.warn ("URL member addition new="+addMemberUrl+"Status="+objAddMember.getResponseCode() as String)       

//-------------------------------------------Creating the flag to display the output-------------------------------------------------//

    def flag = [

        type : 'success',

        title: "Teams Created",

        close: 'auto',

        body : "The Team "+displayName+" have been successfully created",

        issueID:issueId,

        display_Name:displayName,

        token:bearer_token as String,

        status: con.getResponseCode() as String,

        Team_Id:teamId[1],       

        original_response:responseHeader as String

       

    ]

    Response.ok(JsonOutput.toJson(flag)).build()

}

else{   

def flag = [

        type : 'Failed',

        title: "OOPs Team already exists",

        close: 'auto',

        body : "The Team "+displayName+" have been successfully created",

        issueID:issueId,

        display_Name:displayName,  

    ]

    Response.ok(JsonOutput.toJson(flag)).build()    

}

}             

jira response.jpg

1 answer

0 votes
Peter-Dave Sheehan
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
August 5, 2021

Can you share more details about the configuration of you web item? Specifically, what section is configured to go in?

The underlying code to bind your custom web item's click and generate a flag instead of just navigating natively to the URL is not available in all contexts.

You can get around that by changing the webItem behaviour to "do nothing - you will use javascript to bind an action".

Then you will need to include a js resource in the same context that your webitem appears in

There is an example of how to trigger the flag from javascript in this post

Suggest an answer

Log in or Sign up to answer