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

How to execute a groovy script when click a button

Udara Manupriya January 16, 2025 edited

I need to execute a groovy script which is created in the script runner in JSM when user click on a button

Scenario

I need to execute the below groovy script when user click on the "subscribe" button in the email subscription


Note:- Filter Subscriptions flow as below

add_subscription.png subscribe.png

 

Script 

 

import java.nio.file.Files
import java.nio.file.Paths
import com.atlassian.mail.Email
import com.atlassian.mail.server.SMTPMailServer
import com.atlassian.jira.component.ComponentAccessor


// Replace with your filter ID
def filterId = 14276

// Step 1: Fetch filter details
def filterDetails = get("/rest/api/2/filter/${filterId}")
        .header('Content-Type', 'application/json')
        .asObject(Map).body

// Extract the JQL query from the filter
def jqlQuery = filterDetails.jql
logger.warn "Executing JQL: ${jqlQuery}"

// Step 2: Execute the JQL query to fetch all fields
def searchResponse = post('/rest/api/2/search')
        .header('Content-Type', 'application/json')
        .body([
            jql: jqlQuery // No 'fields' parameter means all fields are returned
        ])
        .asObject(Map).body

def issues = searchResponse.issues

// Dynamically retrieve all field names from the first issue
def fieldNames = issues ? issues[0].fields.keySet() : []
logger.warn "Fields found: ${fieldNames}"

// Step 3: Prepare the CSV content
def csvContent = new StringBuilder()

// Add CSV headers dynamically based on the fields
csvContent.append("Issue Key,")
csvContent.append(fieldNames.join(","))
csvContent.append("\n")

// Iterate through the issues and format them as CSV
issues.each { Map issue ->
    def key = issue.key
    def fields = issue.fields

    // Start with the issue key
    def row = [key]

    // Add each field's value, handling nulls and formatting where necessary
    fieldNames.each { fieldName ->
        def value = fields[fieldName]
        row << (value?.toString()?.replaceAll(",", "") ?: "") // Remove commas to avoid CSV breaking
    }

    // Append the row to CSV content
    csvContent.append(row.join(",")).append("\n")
}

// Step 4: Save the CSV to a file
def outputFilePath = "/tmp/jira_filter_${filterId}_issues.csv" // Dynamic file name based on filter ID
Files.write(Paths.get(outputFilePath), csvContent.toString().getBytes("UTF-8"))

// Log success message
logger.warn "CSV file created at: ${outputFilePath}"

// Step 5 (Optional): Send the CSV via email
def mailServer = ComponentAccessor.getMailServerManager().defaultSMTPMailServer
if (!mailServer) {
    throw new IllegalStateException("SMTP mail server is not configured in Jira")
}

def email = new Email("recipient@example.com") // Replace with the recipient's email
email.setSubject("Jira Filter Results CSV Report")
email.setBody("Please find the attached CSV report for filter ID ${filterId}.")
email.addAttachment("jira_filter_${filterId}_issues.csv", new File(outputFilePath))

// Send the email
mailServer.send(email)
logger.warn "Email sent successfully to recipient@example.com"

2 answers

3 votes
Manne Kjærby - ProProces
Atlassian Partner
January 16, 2025

Hi Udara.

 

I'm certain that it is not possible to do on Cloud.

1. You are referencing the Java api on the on-premise version - That won't work on cloud.

2. There isn't an trigger/listener for the subscription button on a filter in scripter runner.

 

I'm not entirely sure of the purpose of the script, but I believe you have to find another way of doing it.

 

Udara Manupriya January 20, 2025 edited

Hi @Manne Kjærby - ProProces 

  1. Yes , I am referring to the cloud version.

  2. Is there any other mechanism to do that
Manne Kjærby - ProProces
Atlassian Partner
January 21, 2025

Hi Udara.

I'm not sure if you will succeed doing it with scriptrunner on Cloud - it's not a quick fix.

Maybe you can use a app from marketplace?

https://marketplace.atlassian.com/search?query=export&product=jira&hosting=cloud

The one below have some of the features you seek.

https://marketplace.atlassian.com/apps/1217474/advanced-export?hosting=cloud&tab=overview

0 votes
Kristian Walker _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.
January 21, 2025 edited

Hi Uddara,

I can confirm, as Manne mentioned, that ScriptRunner for Jira Cloud provides no mechanism to run code when a filter is subscribed to, which means it will not be possible to achieve your requirement.

I hope this information helps.

Regards,

Kristian

Suggest an answer

Log in or Sign up to answer
DEPLOYMENT TYPE
CLOUD
PRODUCT PLAN
PREMIUM
TAGS
atlassian, ace, atlassian community event, donation, girls who code, women in tech, malala fund, plan international, kudos, community badge, badge, atlassian badge, International Women’s month, International Women’s Day, women's month, women's day

10 for Change at Atlassian Community Events

Show up and give back by attending an Atlassian Community Event: we’ll donate $10 for every event attendee in March!

Join an Atlassian Community Event!
AUG Leaders

Upcoming Jira Service Management Events