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

How to copy attachments from one Jira instance to an other Jira instance

Cedric Delavy May 23, 2023

Hello.

I'd like to copy attachments from one Issue from one Jira instance to an other Issue in a other Jira instance. Both Jira instances are "Data Center". For this I use JIRA API to get attachments from the source instance and use the REST API to add attachments to the destination instance.

But I don't know how to pass attachments to the REST API. In my code I set body with the attachment filename, but of course is not correct. Any idea to pass the data (stream ?) of the attachment (with or without REST API) ? My code is a Groovy Scriptrunner.

Thanks for any help

import com.atlassian.jira.component.ComponentAccessor 
import com.atlassian.jira.issue.attachment.Attachment
import com.atlassian.jira.issue.AttachmentManager
import groovyx.net.http.*
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.URIBuilder
import javax.servlet.http.HttpServletRequest
import javax.ws.rs.core.MultivaluedMap
import javax.ws.rs.core.Response
import static groovyx.net.http.Method.*

def user = ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser()
def sourceAttachmentManager = ComponentAccessor.getComponent(AttachmentManager)
def sourceIssue = ComponentAccessor.getIssueManager().getIssueByCurrentKey(sourceIssueKey)
def sourceAttachments = sourceAttachmentManager.getAttachments(sourceIssue)

def sourceBaseUrl = "URL SOURCE INSTANCE"
def sourceIssueKey = "SOURCE ISSUE"
def destinationBaseUrl = "URL DESTINATION INSTANCE"
def destinationIssueKey = "DESTINATION ISSUE"

def http = new HTTPBuilder(destinationBaseUrl, ContentType.JSON)
sourceAttachments.each { Attachment attachment ->
try {
http.request(POST, ContentType.JSON) {
headers.'Accept' = '*/*'
headers.'Content-Type' = 'multipart/form-data'
headers.'Authorization' = "Bearer " + "TOKEN"
headers.'X-Atlassian-Token' = 'nocheck'
uri.path = '/rest/api/2/issue/' + destinationIssueKey + '/attachment'
body = attachment.filename

response.success = { resp, reader ->
log.error(resp)
}

response.failure = { resp, reader ->
log.error(resp.statusLine)
}
}
}
catch (Exception e) {
log.error(e.getMessage())
}
}

 

2 answers

1 accepted

1 vote
Answer accepted
Ram Kumar Aravindakshan _Adaptavist_
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
May 24, 2023

Hi @Cedric Delavy

Can you please confirm if both instances have ScriptRunner installed? 

If yes then you can try the following approach:-

1. Create a REST Endpoint from the source instance as shown below:-

import com.atlassian.jira.component.ComponentAccessor
import com.onresolve.scriptrunner.runner.rest.common.CustomEndpointDelegate
import groovy.json.JsonBuilder
import groovy.transform.BaseScript
import groovyx.net.http.HttpResponseDecorator
import groovyx.net.http.RESTClient
import javax.ws.rs.core.MultivaluedMap
import javax.ws.rs.core.Response

@BaseScript CustomEndpointDelegate delegate
getAttachments { MultivaluedMap queryParams, String body ->
def applicationProperties = ComponentAccessor.applicationProperties
def hostUrl = applicationProperties.getString('jira.baseurl')
def issueKey = queryParams.getFirst('issueKey')

def username = 'admin'
def password = 'q'
def path = "/rest/api/2/issue/${issueKey}"

final def headers = ['Authorization': "Basic ${"${username}:${password}".bytes.encodeBase64()}", 'Accept': 'application/json'] as Map
def http = new RESTClient(hostUrl)

http.setHeaders(headers)
def resp = http.get(path: path) as HttpResponseDecorator

if (resp.status != 200) {
log.warn 'Commander did not respond with 200 for retrieving project list'
}

def issueJson = resp.data as Map
def attachments = issueJson['fields']['attachment']
Response.ok(new JsonBuilder(attachments).toPrettyString()).build()
}

Below is a screenshot of the REST Endpoint configuration:-

rest_config.png

2. In the destination instance use the ScriptRunner console code below:-

import com.adaptavist.hapi.jira.issues.Issues
import groovy.json.JsonSlurper

def sourceIssueKey = 'MOCK-1'

def destinationIssue = Issues.getByKey('MOCK-1')

final def host = 'http://localhost:9292'

final def restEndpointName = 'getAttachments'

def baseUrl = "${host}/rest/scriptrunner/latest/custom/${restEndpointName}?issueKey=${sourceIssueKey}".toString()

def response = baseUrl.toURL().text

def json = new JsonSlurper().parseText(response) as List<Map>

def downloadedFiles = [] as List<File>

def files = json.collect {
it['content'] as String
}

def fileNames = json.collect {
it['filename'] as String
}

files.each { fileUrl ->
fileNames.each { fileName ->
downloadedFiles << (new File("/tmp/${fileName}") << new URL (fileUrl).text)
}
}

downloadedFiles.unique().findAll {
destinationIssue.addAttachment(it)
}

Please note that the sample codes above are not 100% exact to your environment. Hence, you will need to make the required modifications.

The destination instance will read the REST Endpoint from the source instance, store the file in a local folder and add it to the issue.

I hope this helps to answer your question. :-)

I am looking forward to your feedback.

Thank you and Kind regards,

Ram

Cedric Delavy May 25, 2023

Thanks Ram for the answer.

Yes scriptrunner is installed on both instances.

But when I fetch attachments from the destination instance at the following row:

downloadedFiles << (new File("/tmp/${fileName}") << new URL (fileUrl).text)

I get the Jira login html page instead of attachment because I'm not logged in. I tried to login before with an other rest api call with credentials, but nothing changes.

Any idea ?

Thanks

Cedric

Cedric Delavy May 26, 2023

I found the way to connect to the source Jira instance from the destination Jira Instance. I've added a remoteAuth like this:

new File("/tmp/${fileName}").withOutputStream { out ->
def url = new URL(fileUrl).openConnection()
def remoteAuth = "Basic " + "USERNAME:PASSWORD".bytes.encodeBase64()
url.setRequestProperty("Authorization", remoteAuth);
out << url.inputStream
}

Thanks a lot Ram for all your help

Regards

Cedric

Ram Kumar Aravindakshan _Adaptavist_
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
May 26, 2023

Hi @Cedric Delavy

Great to hear you have found the solution. :-)

Please accept the answer provided.

Thank you and Kind regards,
Ram

Ram Kumar Aravindakshan _Adaptavist_
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
May 28, 2023

This is the updated working version of the code to invoke the Source Instance's REST Endpoint from the Destination Instance and add the files to the attachments:-

import com.adaptavist.hapi.jira.issues.Issues
import groovy.json.JsonSlurper
import org.apache.tools.ant.util.FileUtils

def issueKey = 'MOCK-1'
def destinationIssue = Issues.getByKey(issueKey)

final def host = 'http://localhost:9292' //Chage to the Source Instance's URL
final def restEndpointName = 'getAttachments'
final def username = 'admin'
final def password = 'q'
final def baseUrl = "${host}/rest/scriptrunner/latest/custom/${restEndpointName}?issueKey=${issueKey}".toString()

def response = baseUrl.toURL().text
def json = new JsonSlurper().parseText(response) as List<Map>

def files = json.collect { it['content'] as String }
def fileNames = json.collect { it['filename'] as String }

files.eachWithIndex { fileUrl, index ->
def obj = new URL(fileUrl)
def con = obj.openConnection() as HttpURLConnection
con.setRequestMethod('GET')
con.setRequestProperty('Authorization', "Basic ${"${username}:${password}".bytes.encodeBase64()}")
int responseCode = con.responseCode
if (responseCode == HttpURLConnection.HTTP_OK) {
def inputStream = con.inputStream
def file = new File("/tmp/${fileNames[index]}")
def outputStream = new FileOutputStream(file)
def bytesRead = -1
def buffer = new byte[4096]
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead)
}
} else {
log.warn "Commander's GET request failed."
}
}

fileNames.collect { new File("/tmp/${it}") }.findAll {
destinationIssue.addAttachment(it)
FileUtils.delete(it) //house keeping - remove the temporary files
//after it is added to the attachment
}

The code that I provided in my earlier comment does copy the attachments, but the data in the attachments is incorrect. The updated code resolves the issue.

Like Cedric Delavy likes this
0 votes
Amit Shaw October 5, 2023

Hi Team, Is there any script for the attachment files for same jira instance. 

I want to copy the new attachment files from one Jira project to another JSD project but right after the attachment has been update comments needs to be add with newly attachment file name

Is there any way to do that ? 

Regards, 

Amit

Suggest an answer

Log in or Sign up to answer
DEPLOYMENT TYPE
SERVER
VERSION
4.20
TAGS
AUG Leaders

Atlassian Community Events