Forums

Articles
Create
cancel
Showing results for 
Search instead for 
Did you mean: 

Mail handler how to check attachment exist or not

Omprakash Thamsetty
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.
August 12, 2019

How to validate the attached file in email response is exist or not in Issue. Using below code to create attachment but I would like to validate if the attachment exist or not? Does anyone know on it.

 

def attachments = MailUtils.getAttachments(message)

attachments.each { MailUtils.Attachment attachment ->
def destination = new File(jiraHome.home, FileService.MAIL_DIR).getCanonicalFile()
def file = FileUtils.getFile(destination, attachment.filename) as File
FileUtils.writeByteArrayToFile(file, attachment.contents)
messageHandlerContext.createAttachment(file, attachment.filename, attachment.contentType, user, issue)
}

Thanks

1 answer

0 votes
PD Sheehan
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.
August 12, 2019

When I was very new to groovy and java ... I wrote this function.

def compareAttachments(File file1, File file2) {
if(file1.length() != file2.length()){
log.debug("compareAttachments: file sizes different")
return false;
}

try {
InputStream in1 =new BufferedInputStream(new FileInputStream(file1));
InputStream in2 =new BufferedInputStream(new FileInputStream(file2));
int value1,value2
value1 = in1.read()
value2 = in2.read()
while (value1 >=0){
if(value1 !=value2){
log.debug("compareAttachments: reads are different")
return false
}
//since we're buffered read() isn't expensive
value1 = in1.read()
value2 = in2.read()
}
//since we already checked that the file sizes are equal, if we're here
//then we reached the end of both files without a mismatch. The files appear to be the same
log.debug("compareAttachments: files are the same")
return true;
}
catch (e) {
//return Response.serverError().entity([error: e.message]).build()
}
}

Today, I'd probably look into hashing both files.

That function was getting called from within this loop (again, I'd write this very differently today):

// variables already defined before
// File file
// Issue issue

def fileExists = false
def nameExists = false
def existingFileName  = ''
def attachmentList = attachmentManager.getAttachments(issue)
for (i=0; i < attachmentList.size; i++) {
log.debug("Attachment ${i} == ${attachmentList[i].filename}")
att = attachmentList[i]
if(!fileExists){
log.debug("comparing new ${file.name} against attachment ${att.filename}")
File attachmentFile = null
try {
attachmentFile = attachmentManager.streamAttachmentContent(att, new FileInputStreamConsumer( att.filename))
if(compareAttachments(newAttachment, attachmentFile)){
fileExists = true
existingFileName = att.filename
break
}
}
catch (final IOException e) {
log.error("Error reading existing attachments: '${att.filename}'. \nError Message: ${e.message}")
//return Response.serverError().entity([error: "Error reading existing attachment '${att.filename}'. Error Message: ${e.message}"]).build()
}
}
if(!nameExists){
if( att.filename == file.name ){
log.debug("filename ${file.name} already exists")
nameExists = true
}
}
}

if (!fileExists) {
def newName = file.name
while (nameExists) {
(FilenameUtils.getBaseName(newName) =~ /^(.*?)[\s_-]*(\d*)$/).each { fullname, name, nb ->
nb = nb ?: 0
nb++
newName = "${name}_${nb}.${FilenameUtils.getExtension(newName)}"
}
nameExists = (attachmentList.find { it.filename == newName})
}
def bean = new CreateAttachmentParamsBean.Builder()
.file(newAttachment)
.filename(newName)
.contentType(file.toURL().openConnection().getContentType())
.author(user)
.issue(issue)
.build()

def changeBean
try {
log.debug("Creating attachment with name '${newName}' for issue ${issue.key} using '${user.name}' as author")
changeBean = attachmentManager.createAttachment(bean)
log.debug("Created Attachment with Id=${changeBean.to}")
} catch (e) {
log.error("addAttachment failed when calling the createAttachment JIRA method: ${e.message}")
return Response.serverError().entity([error: "Error with the createAttachment JIRA method: ${e.message}"]).build()
}

log.debug("Re-index the issue to make sure the new attachment is in the index")
boolean wasIndexing = ImportUtils.isIndexIssues()
ImportUtils.setIndexIssues(true)
ComponentAccessor.getComponent(IssueIndexingService.class).reIndex(issue)
ImportUtils.setIndexIssues(wasIndexing)
} else {
// the file already exists ... you can return the existingFileName variable
// in case you want to use that (perhaps for inline embeding in the comment)
}

This loop works on a single incoming attachment. It will automatically increment the filename in order to generate unique attachment files.

This whole bit was in a custom REST API that was being called by a custom email handler coded in php by a colleague. That was before scriptrunner mail handlers were available and before we bought JEMH.

I wouldn't recommend using as is... but it might give you some ideas.

Omprakash Thamsetty
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.
August 15, 2019

@PD SheehanYes, I used some of your code to verify attachment exist or not with file name. I am now trying to validate size also. Sometimes people update the file and send to ticket so we needs to validate the size. If the both size match then it will not attach otherwise it will attach. Do you have any idea?

PD Sheehan
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.
August 15, 2019

The compareAttachment method above already does file size comparison

if(file1.length() != file2.length()){
log.debug("compareAttachments: file sizes different")
return false;
}
Omprakash Thamsetty
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.
March 10, 2020

@PD SheehanI am unable to do compareattachment for file size comparision with outlook mail attachment with existing issue file attachment. How can I get outlook mail attached file size in code?

As well as Jira issue attachment file size? If I get these two then comparing can done quickly.

Any help on this.

PD Sheehan
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.
March 10, 2020

Sorry, I don't know. I've never worked with outlook mail.

But if you can get a file object, you should be able to look a the "length()" attribute.

Suggest an answer

Log in or Sign up to answer