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

Sending attachments via scriptrunner to another application

Edited

Hello All,

I'm trying to get attachments from the JIRA and pass them to the payload, which will send base 64 encoded data to another application.

Here's my code till now,

import groovy.transform.BaseScript
import groovy.json.JsonSlurper
import groovy.json.JsonBuilder
import groovy.json.JsonOutput
import groovy.util.logging.*
import org.apache.log4j.Logger
import org.apache.log4j.Level
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.MutableIssue
import com.atlassian.jira.issue.IssueManager
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.issue.fields.CustomField
import com.onresolve.jira.groovy.user.FieldBehaviours
import com.atlassian.jira.event.type.EventDispatchOption
import com.atlassian.core.util.DateUtils
import com.atlassian.jira.security.JiraAuthenticationContext
import com.atlassian.jira.user.ApplicationUser
import java.text.SimpleDateFormat
import com.atlassian.jira.issue.AttachmentManager
import com.atlassian.jira.issue.attachment.Attachment
import groovy.io.FileType

// Enable the logging
def log = Logger.getLogger("com.onresolve.scriptrunner.runner.ScriptRunnerImpl")
log.setLevel(Level.INFO)

/** code for getting Oauth token **//

response=get_bearer_token(****OauthRequest_url, *****OauthHeaders, *****OauthPayload)
log.info ("Response is " + response)

def ***URL="............"
def access_token=response['access_token']
def ****AppHeaders=[:]
***AppHeaders['Authorization']='Bearer '+access_token
****AppHeaders['Content-Type']='application/json'

def customFieldManager = ComponentAccessor.customFieldManager
def attachmentManager = ComponentAccessor.attachmentManager


//getting JIRA issue key for testing in script console only
def issueManager = ComponentAccessor.issueManager

def issueKey = '****'

def issue = issueManager.getIssueObject(issueKey)


def attachments = attachmentManager.getAttachments(issue)

final def jiraResourcesPath = '/..jira..path/data/attachments/'
final def project = issue.projectObject
final def projectKey = project.key
log.info(projectKey)
log.info(issueKey)

def latestAttachment = attachments.findAll {
it.filename.endsWith('.pdf')
}.sort { it.created }.last()

def fileName = latestAttachment.id
def filePath = "${jiraResourcesPath}/${projectKey}/20000/${issueKey}".toString()
def oldFile = new File("${filePath}/${fileName}")
def fileContent = new File("$oldFile").text

//Encode file to Base64 format
log.info "Encoding the file..."
def encodedFile = "$fileContent".getBytes("UTF-8").encodeBase64().toString()
log.info("Encoded File:" +encodedFile)

def PayloadJson = new JsonBuilder()
PayloadJson
{
//
//
//
fileName oldFile
fileContent encodedFile

}

log.info("Converting Json Builder to Json")
finalBodyJson = JsonOutput.toJson(PayloadJson)
log.info("Final Json object: " + finalBodyJson)
jsonContent = new JsonSlurper().parseText(finalBodyJson)
log.info("JsonContent " + jsonContent.content)
finalJsonContent = groovy.json.JsonOutput.toJson(jsonContent.content)
log.info("JsonContent "+ finalJsonContent)

def create_req(url, headers, payload,log) {
try {
def jsonSlurper = new JsonSlurper()
conn = new URL(url).openConnection()
// Adding headers
headers.each {
conn.setRequestProperty(it.key,it.value);
}
// Doing a POST with the connection obtained.
conn.setRequestMethod('POST')
conn.setDoOutput(true)
conn.outputStream.write(payload.getBytes("UTF-8"))

def retCode = conn.getResponseCode();
respText = conn.getInputStream().getText()

if(retCode.equals(202)) {
log.info("Request received. A response will be sent asynchronously.")
log.info("The response text is " + respText)
Map parsedJson= jsonSlurper.parseText(respText)
return parsedJson
}
else {
log.info("Encountered an Issue" + retCode)
}
}
finally {
conn.disconnect();
}
}

CreateResponse = create_req(**URL, ****AppHeaders, finalJsonContent,log)
log.info(CreateResponse)

 

Am I getting the attachments in the right way? is there an alternate way?

Currently i have used ".pdf" but ideally i should get all the attachments and send it across?

if I run the code i get error,

2022-12-09 12:18:59,482 ERROR [common.UserScriptEndpoint]: Script console script failed: groovy.lang.MissingMethodException: No signature of method: java.lang.Long.call() is applicable for argument types: (File) values: [/...../data/attachments/**/20000/**-14426/1344000] Possible solutions: wait(), abs(), any(), abs(), wait(long), and(java.lang.Number) at Script163$_run_closure3.doCall(Script163.groovy:125) at Script163$_run_closure3.doCall(Script163.groovy) at Script163.run(Script163.groovy:117)

Would someone be able to assist me?

 

Thank You.

1 answer

Hi @Catheline ,

 

I am pretty sure that you are getting the attachements correctly.

Please take a look here I believe this is an answear to your question:

https://stackoverflow.com/questions/11766878/sending-files-using-post-with-httpurlconnection

 

Regards,
Szymon

Suggest an answer

Log in or Sign up to answer
TAGS
AUG Leaders

Atlassian Community Events