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

Earn badges and make progress

You're on your way to the next level! Join the Kudos program to earn points and save your progress.

Deleted user Avatar
Deleted user

Level 1: Seed

25 / 150 points

Next: Root

Avatar

1 badge earned

Collect

Participate in fun challenges

Challenges come and go, but your rewards stay with you. Do more to earn more!

Challenges
Coins

Gift kudos to your peers

What goes around comes around! Share the love by gifting kudos to your peers.

Recognition
Ribbon

Rise up in the ranks

Keep earning points to reach the top of the leaderboard. It resets every quarter so you always have a chance!

Leaderboard

Come for the products,
stay for the community

The Atlassian Community can help you and your team get more value out of Atlassian products and practices.

Atlassian Community about banner
4,466,928
Community Members
 
Community Events
176
Community Groups

HTTP Post request in Groovy with Script Runner

Hello people

Could someone please advise me on this. I'm trying to write a REST endpoint with Groovy in Script Runner for Server and I'm using this link for help: https://library.adaptavist.com/entity/using-external-apis-in-sr?_ga=2.219398361.1787316567.1649252482-1069130235.1604398767 

In JavaScript it's working and it looks like this:

var payload = {
"query": "mutation (\$jiraIssueId: String!, \$number: String!, \$createdBy: String!, \$jiraAttachmentInputType: [JiraAttachmentRequest]!) { moveJiraPdfAttachmentToCprSharePoint(jiraIssueId: \$jiraIssueId, number: \$number, createdBy: \$createdBy, jiraAttachmentRequestInput: \$jiraAttachmentInputType) { isSuccessful }}",
"variables": { "jiraIssueId": issueKey, "number": document.getElementById("zsrnumber").value, "createdBy": createdBy, "jiraAttachmentInputType": jiraAttachments }
}
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
console.debug(this);
};

xhttp.open("POST", "https://hiddenurl/ApiGateway/api/v1/graphql/public", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send(JSON.stringify(payload));


Now I'm trying to do exactly the same, but with SR Groovy. This is my script:

import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.Issue
import groovy.json.JsonBuilder
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import groovyx.net.http.ContentType
import groovyx.net.http.HttpResponseDecorator
import groovyx.net.http.RESTClient

def issue = event.issue
def issueType = issue.getIssueType().getName()
def allAttachments = issue.getAttachments()
def currentUser = ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser().getName()
def jiraAttachments = []

// If current issue is not a 'Memo', then exit the script
if (issueType != 'Memo') {
return
}

// Plattform Test
List<String> CustomFieldIDs = [
"customfield_15501",
"customfield_15502"
]

if (allAttachments) {
def number = event.issue.getCustomFieldValue(ComponentAccessor.getCustomFieldManager().getCustomFieldObject(CustomFieldIDs[0]))
if(number == null) {
number = event.issue.getCustomFieldValue(ComponentAccessor.getCustomFieldManager().getCustomFieldObject(CustomFieldIDs[1]))
}
if(number == null) {
number = ""
}

def count = 0;
for (item in allAttachments) {
if (item.getFilename().endsWith(".pdf")) {
jiraAttachments.push("attachmentId: " + item.getId() + ", documentType: UNCLASSIFIED, comment: Automatisch hinzugefuegtes PDF vom IssueType Memo")
count++;
}
}

def jsonBody = [:]
jsonBody.put("jiraIssueId", issue)
jsonBody.put("number", number)
jsonBody.put("createdBy", currentUser)
jsonBody.put("jiraAttachmentInputType", jiraAttachments)

final externalUrl = "https://hiddenurl"
def body = JsonOutput.toJson([data: jsonBody])


// The host URL will be the consistent prefix to every request is made. e.g.: https://<YOUR API HOST URL>/
// The endpoint will be the specific API method to hit. e.g.: /GetResults
// The query will be the variable parameter the endpoint will use to get the data. e.g.: /objectId=1
// The body is the JSON version of the data that will be sent to an API, only used for PUT and POST
def postResponse = post(externalUrl, "/ApiGateway/api/v1/graphql/public", "", body)

if(number != "" && count != 0) {
postResponse
}
}

def post(def hostUrl, def endpoint, def query, def bodyJson) {
def client = new RESTClient(hostUrl)
client.setHeaders([
'Accept' : ContentType.JSON
])
client.handler.success = { HttpResponseDecorator response, json ->
json
}
client.handler.failure = { HttpResponseDecorator response ->
// Failure can be handled here
log.error response.entity.content.text
[:]
}
client.post(
path: endpoint,
queryString: query,
contentType: ContentType.JSON,
body: bodyJson
)
}


In the listener menu (I need to add the script to the Listeners and not to the REST Endpoints by the way) I get a failed execution in History column, but unfortunately I can't really see any error. It's just repeating this lines:

at groovy.json.DefaultJsonGenerator.writeMap(DefaultJsonGenerator.java:375)  
at groovy.json.DefaultJsonGenerator.writeObject(DefaultJsonGenerator.java:237)

Could anyone help with this or tell what is wrong in my script? I think it has something to do this part:

def jsonBody = [:]
jsonBody.put("jiraIssueId", issue)
jsonBody.put("number", number)
jsonBody.put("createdBy", currentUser)
jsonBody.put("jiraAttachmentInputType", jiraAttachments)

def body = JsonOutput.toJson([data: jsonBody])

This should do the same as this in Javascript&colon;

 var payload = {
"query": "mutation (\$jiraIssueId: String!, \$number: String!, \$createdBy: String!, \$jiraAttachmentInputType: [JiraAttachmentRequest]!) { moveJiraPdfAttachmentToCprSharePoint(jiraIssueId: \$jiraIssueId, number: \$number, createdBy: \$createdBy, jiraAttachmentRequestInput: \$jiraAttachmentInputType) { isSuccessful }}",
"variables": { "jiraIssueId": issueKey, "number": document.getElementById("zsrnumber").value, "createdBy": createdBy, "jiraAttachmentInputType": jiraAttachments }
}

xhttp.send(JSON.stringify(payload));

 

Thanks a lot if someone could give me an input on this.

Best regards
Nicole

1 answer

Hi @Nicole Mueller can you describe the usecase a little. On the beginning you says that you need to write the REST Endpoint in script runner (we can call it REST API side). But in your code you are trying to invoke some other endpoint "/ApiGateway/api/v1/graphql/public" (we can call it REST Client).

Because if you need REST Endpoint, you need to check following documentation:

https://docs.adaptavist.com/sr4js/latest/features/rest-endpoints

Thank you for clarification :) 

Hi @Martin Bayer _MoroSystems_ s_r_o__ 

Thanks a lot for your answer! What I'm trying to do is:

Adding a Script Runner listener which runs when an issue is created and then check, if any attachment got added. Afterwards, if the attachment is a PDF file, it should send it together with some other parameters to https://hiddenurl/ApiGateway/api/v1/graphql/public"

In the JS you can see, which variables should be sent. 

Is this clear enough, or should I try to explain it more clearly? I'm not really experienced in this, sorry ;) So it definitely could be, I don't need a REST Endpoint, I thought, this is what it's called. Thank you so much, if you could clarify what I actually need to look for :)

Best regards
Nicole

Hi @martin 

Did you get a clearer understanding of what I am trying to do? I'm still stuck here. Mainly because I'm not sure of what I'm doing wrong. In the Script runner listener history it says "2 of 15 executions have failed, including the last one" but when I open the history I can't really see where the problem is so this is quite difficult to debug. Thank you lots for advises on this.

Best regards
Nicole

Hi @Martin Bayer _MoroSystems_ s_r_o__ 

Do you have any advices on this issue? I'm still stuck. Mainly because I don't know how to best debug this or find the mistake. In the history of the Script runner listener I can see "2 of 15 executions have failed, including the last one" so I know something is wrong. But when I open the history and the log I can't see what's wrong. Can you see what's wrong here:

customlistener.png

Or you think I need to approach another way? As I've mentioned in Javascript this was the way to do it:

 
var payload = {
                    "query": "mutation (\$jiraIssueId: String!, \$number: String!, \$createdBy: String!, \$jiraAttachmentInputType: [JiraAttachmentRequest]!) { moveJiraPdfAttachmentToCprSharePoint(jiraIssueId: \$jiraIssueId, number: \$number, createdBy: \$createdBy, jiraAttachmentRequestInput: \$jiraAttachmentInputType) { isSuccessful }}",
                "variables": { "jiraIssueId": issueKey, "number": document.getElementById("zsrnumber").value, "createdBy": createdBy, "jiraAttachmentInputType": jiraAttachments }
                    }
                    var xhttp = new XMLHttpRequest();
                    xhttp.onreadystatechange = function() {
                        console.debug(this);
                    }; 
                   
                    xhttp.open("POST", "https://url/ApiGateway/api/v1/graphql/public", true);          
                    xhttp.setRequestHeader("Content-type", "application/json");
                    xhttp.send(JSON.stringify(payload));
And it works fine. But now I need to send the exact same data in Groovy. Or is there a way to this in the custom listener of Script runner in Javascript for the create issue event? Thank you for help.
Best regards
Nicole

Suggest an answer

Log in or Sign up to answer
TAGS

Atlassian Community Events