How to execute a groovy script when click a button

Udara Manupriya January 16, 2025

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.pngsubscribe.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"

1 answer

1 vote
Manne Kjærby - ProProces
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.
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.

 

Suggest an answer

Log in or Sign up to answer
DEPLOYMENT TYPE
CLOUD
PRODUCT PLAN
PREMIUM
TAGS
AUG Leaders

Atlassian Community Events