How can I create an attachment to an issue in a post-function?

Ilya Stekolnikov
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
June 2, 2021

Hi. The problem:

I need to generate attachment based on summary and description on create transaction.

For example exactly after moment when user create issue. Attache should appear after issue was created.

Attach could be like some Html/DOCx/RTF document which contain some template filled information based on description, summary and some CF.

May be some one have example how to make this in scriptrunner.

 

1 answer

1 accepted

2 votes
Answer accepted
Ilya Stekolnikov
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
June 2, 2021

My own solution

 

import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.attachment.CreateAttachmentParamsBean
import com.atlassian.jira.issue.Issue
import com.atlassian.jira.issue.IssueManager
import java.time.*


def attachmentManager = ComponentAccessor.getAttachmentManager()

def user = ComponentAccessor.getJiraAuthenticationContext()?.getUser()

def Reporter = issue.getReporter() as String
def Desc = issue.getDescription()


LocalDateTime CurrentTime = LocalDateTime.now();

def String filename = "1.html"
def Template = """
<!DOCTYPE html>
<html>
<head>
<title>Some title</title>
</head>
<body>
<p style="text-align:right">From ${Reporter}</p>

<p style="text-align:right">NAME</p>

<p>&nbsp;</p>

<p>&nbsp;</p>

<p style="text-align:center"><strong>Some Main TEXT</strong></p>

<p>&nbsp;</p>

<p>${Desc}</p>

<p>&nbsp;</p>

<p><strong>Date ${CurrentTime}</strong></p>
</body>
</html>


"""

File f = new File("/tmp/"+filename);

f.getParentFile().mkdirs();
f.createNewFile();


FileWriter fw = new FileWriter("/tmp/"+filename, true)
BufferedWriter bw = new BufferedWriter(fw)
PrintWriter out = new PrintWriter(bw)

out.println(Template);

out.close()

def bean = new CreateAttachmentParamsBean.Builder()
.file(f)
.filename(filename)
.contentType("text/plain")
.author(user)
.issue(issue)
.build()
attachmentManager.createAttachment(bean)

Samar Elsayed October 6, 2021

Hi @Ilya Stekolnikov 

where did you apply that script ? in send custom email postfunction ?

Ilya Stekolnikov
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
October 6, 2021

hi @Samar Elsayed  - i just used it at regular post-function. Script generate attach inside issue.

Samar Elsayed October 7, 2021

Thanks @Ilya Stekolnikov 

I can see email template but I dont see the part where you send that email.

why I am asking that is that I want to create an attachment that contain a result from script and then send that attachment by email in postfunction but I dont know how to do that.

Ilya Stekolnikov
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
October 7, 2021

ok, i am understand you. In my script i generate attach inside issue. i didn`t send it with e-mail. So you can use my script for generate attach, and add next post-function just for sending e-mail. I think you will understand me, just use this script in post function and you will understand how it works.

Samar Elsayed October 12, 2021

@Ilya Stekolnikov  Thank you so much, one last question :

 

when I use /tmp/ as the path for the attachment , run the script and go to /tmp/ on jira server I can see one file but when I delete the attachment from the issue and rerun my script , I can still see only the same old file there on the server and also when I delete that file from /tmp/ and rerun the script, the new attachment is created successfully in the issue but I cant find it in /tmp/

 

can you explain to me why this is happening and where can I find these attachments on jira server?

 

Thanks

Ilya Stekolnikov
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
October 26, 2021
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.AttachmentManager
import com.atlassian.jira.issue.IssueManager
import com.atlassian.jira.issue.MutableIssue
import com.atlassian.jira.issue.attachment.Attachment
import com.atlassian.jira.issue.search.SearchProvider
import com.atlassian.jira.user.ApplicationUser
import com.atlassian.jira.user.util.UserManager
import com.atlassian.jira.util.AttachmentUtils
import org.apache.log4j.Logger
import org.slf4j.MDC
import java.nio.file.Files
import com.atlassian.jira.bc.issue.IssueService
import com.atlassian.query.Query
import com.atlassian.jira.issue.search.SearchResults
import com.atlassian.jira.jql.parser.JqlQueryParser
import com.atlassian.jira.bc.issue.search.SearchService
import com.atlassian.jira.web.bean.PagerFilter
import com.atlassian.jira.jql.parser.*
import java.lang.*
import com.atlassian.jira.issue.IssueInputParameters
import java.util.ArrayList
import com.atlassian.jira.util.ImportUtils
import com.atlassian.jira.util.JiraUtils
import com.atlassian.jira.workflow.WorkflowTransitionUtilImpl
import com.atlassian.jira.workflow.TransitionOptions
import java.util.List

IssueManager issueManager = ComponentAccessor.getIssueManager();
UserManager userManager = ComponentAccessor.getUserManager();
AttachmentManager attachmentManager = ComponentAccessor.getAttachmentManager();
IssueService issueService = ComponentAccessor.getComponent(IssueService)

ApplicationUser actingUser = ComponentAccessor.jiraAuthenticationContext.loggedInUser
def jqlQueryParser = ComponentAccessor.getComponent(JqlQueryParser)
def searchService = ComponentAccessor.getComponent(SearchService)
String jqlSearch = "key in (dias-1, dias-8)"

Query query = jqlQueryParser.parseQuery(jqlSearch)
SearchResults results = searchService.search(actingUser,query, PagerFilter.getUnlimitedFilter())
if (results.total == 0) { //если результат 0 не идем дальше
return
}

ArrayList issues = results.results.collect {issueManager.getIssueObject (it.id)} //ArrayList с результатом поиска
issues.each { issue ->
MutableIssue curIssue = issueManager.getIssueObject(issue.id)
String date = new Date().format('dd-MM-yyyy', TimeZone.getTimeZone('BST')) //текущая дата и время
String folderName = date //название будущей папки в директории (название проекта + номер заявки + текущая дата)
String folderName2 = curIssue.getKey()
List<Attachment> attachmentList = attachmentManager.getAttachments(curIssue); //List с вложениями текущего issue в цикле по перебору результата jql
for(Attachment attachment:attachmentList) { // цикл по перебору вложении по issue
String attachmentFileName = attachment.getFilename(); //получение Filename вложения
File attachmentFile = AttachmentUtils.getAttachmentFile(attachment)
byte[] encodedFile = Files.readAllBytes(attachmentFile.toPath()); //Файл в байт
new File("/opt/atlassian/application-data/jira/testAttachment/${folderName}").mkdir() //создание папки в директории

new File("/opt/atlassian/application-data/jira/testAttachment/${folderName}/${folderName2}").mkdir() //создание папки в директории

String fileNewFullPath = "/opt/atlassian/application-data/jira/testAttachment/${folderName}/${folderName2}/"+ attachmentFileName; //String с Path
try {
OutputStream stream = new FileOutputStream(fileNewFullPath) //запись байтов в файл
stream.write(encodedFile);
stream.close();
} catch(Exception e){
log.warn(e.getMessage())
}
}

}

 @Samar Elsayed  May be this one can help you. This script find all attachments in issues from JQL Result and copy them in some folder at server.

Dennis Ebner February 1, 2024

@Ilya Stekolnikov 

Do you also have a Script for creating a pdf instead of html?

Suggest an answer

Log in or Sign up to answer