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

I want a script to read a jira issue key (ID) in Jira cloud.

Vrabiel Attila Bela June 13, 2024

I created a script in script listener  when an attachment is created in a Jira issue  it converts the attached file in base 64 . This converted file i must send in a  ServiceNow incident. To do this i need to find the Jira issue number from where i must extract de incident number. I tried different solutions but i am unable to get the jira issue id (key) Can somebody help me with this issue?

I tried this script but i have errors

 

 

 

import com.onresolve.scriptrunner.runner.customisers.WithPlugin
import com.onresolve.scriptrunner.runner.util.UserMessageUtil
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.event.issue.IssueEvent
import com.atlassian.jira.event.type.EventDispatchOption

@WithPlugin("com.onresolve.scriptrunner.canned.jira.workflow.postfunctions.FireIssueEvent")
void execute(IssueEvent event) {
    def issue = event.issue

    // Log the issue key and other details
    log.info("Issue Created: ${issue.key}, Summary: ${issue.summary}, Project: ${issue.projectObject.key}")

    // Display a message to the user (optional)
    UserMessageUtil.success("Issue Created: ${issue.key}, Summary: ${issue.summary}, Project: ${issue.projectObject.key}")

    // Additional actions can be performed here
}

2 answers

1 accepted

Suggest an answer

Log in or Sign up to answer
0 votes
Answer accepted
Vrabiel Attila Bela June 14, 2024
This is the script that i tried to make
import java.util.Base64
import com.atlassian.jira.*
//import com.atlassian.jira.issue.fields.CustomField;
//import com.atlassian.jira.component.ComponentAccessor;
//import com.atlassian.jira.issue.CustomFieldManager;
//import com.atlassian.jira.event.issue.DelegatingJiraIssueEvent;
//import com.atlassian.jira.event.issue.IssueEvent;

import com.onresolve.scriptrunner.runner.customisers.WithPlugin


String base64Output= '';


    try {
        URL fileUrl = new URL((attachment.get("self")).toString());
        // URLConnection ucon = fileUrl.openConnection();
        // String base64Authorization = "${USER}:${PASSWORD}".bytes.encodeBase64().toString();
        // logger.info(base64Authorization);
        // ucon.setRequestProperty("Authorization","Basic ${base64Authorization}");
        // ucon.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        // ucon.setRequestProperty("User-Agent", "Mozilla/5.0");

        HttpURLConnection httpURLConnection = (HttpURLConnection) fileUrl.openConnection();
        httpURLConnection.setRequestProperty("User-Agent", "my-agent");
        httpURLConnection.setRequestProperty("Cookie","ajs_anonymous_id=%229a0c04ff-accb-43cf-94fd-6d8014b60186%22; atlassian.account.xsrf.token=18f0430c-e1ba-4be9-8c60-1e7768364eb9; atlassian.xsrf.token=e4b92c1172d56d80e01877e5e590a7cc4aec3657_lin; cross.join.nudges.confluence.visited=true; tenant.session.token=eyJraWQiOiJzZXNzaW9uLXNlcnZpY2UvcHJvZC0xNTkyODU4Mzk0IiwiYWxnIjoiUlMyNTYifQ.eyJhc3NvY2lhdGlvbnMiOltdLCJzdWIiOiI3MTIwMjA6OTc3MzljMDMtNjdkMC00MjExLTlhM2QtNDNhYTdmNWVjYzAzIiwiZW1haWxEb21haW4iOiJnZW5lcml4Z3JvdXAuY29tIiwiaW1wZXJzb25hdGlvbiI6W10sImNyZWF0ZWQiOjE3MTQzNzQ4NDUsInJlZnJlc2hUaW1lb3V0IjoxNzE4MTE5NDUzLCJ2ZXJpZmllZCI6dHJ1ZSwiaXNzIjoic2Vzc2lvbi1zZXJ2aWNlIiwic2Vzc2lvbklkIjoiYWRmNTY0MTgtOGVlNC00Y2I3LTlhYzktNTM5YzgyZjE1MTlmIiwic3RlcFVwcyI6W10sImF1ZCI6ImF0bGFzc2lhbiIsIm5iZiI6MTcxODExODg1MywiZXhwIjoxNzIwNzEwODUzLCJpYXQiOjE3MTgxMTg4NTMsImVtYWlsIjoiYWJ2cmFiaWVsQGdlbmVyaXhncm91cC5jb20iLCJqdGkiOiJhZGY1NjQxOC04ZWU0LTRjYjctOWFjOS01MzljODJmMTUxOWYifQ.BW_OyiCo096Nb3K_j0HCIp-OalUoCvBy-YNP6-r25PPH1oYBFknBZ7zgA_k7KOeb6O9wi8WN4VU9cSLoqTFJfl1_CXL4cMhabaWqcLMkSewWWDeW5TirIEZGbmm_AtJ73EWMej-7I0ZmwC85HexfCitw45cawQmzfdu_sywXwZH3LhipXLb3XKBfQhRWkh2tVl3cg5POj0hW_foizmXDxGOhjLNov0bI71M5xE_UseQYKDCrL945cVvMDKqeFDp0xbZVX0zEcMpCmUdJwLc-7igZ2v-4m6fEVGTBEKKsgd_RsftL4FCvGGQyczjHQGkW5pRiC_sZaji61-A_Tw8tXA; JSESSIONID=F1906576917038203521A5A7F2E04500");
        httpURLConnection.connect();


        InputStream is = httpURLConnection.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int read = 0;
        while ((read = is.read(buffer, 0, buffer.length)) != -1) {
            baos.write(buffer, 0, read);
        }
        baos.flush();
        Base64.getEncoder().encodeToString()
        base64Output = Base64.getEncoder().encodeToString(baos.toByteArray());
    } catch (Exception e) {
        logger.error("CEVAAA  eerrrrrrrrrrrrrrrrrrr");
        logger.error("Error converting to Base 64 "+e.getMessage() +" "+attachment.get("self"));
    }
    //return null;
logger.debug("something")
logger.error("CEVAAA");
logger.error(attachment.get("self").toString());
//logger.error(attachment);
logger.error('OUTPUT:  '+base64Output);

    def issueManager = ComponentAccessor.getIssueManager();
def aM= ComponentAccessor.getAttachmentManager();
String attId = attachment.get("self").substring(attachment.get("self").lastIndexOf('/') + 1).trim();
logger.error(attId);
Object att = aM.getAttachment(Long.parseLong(attId));
logger.error(att);



// @WithPlugin("com.onresolve.scriptrunner.canned.jira.workflow.postfunctions.FireIssueEvent")
// void execute(IssueEvent event) {
//     def issue = event.issue

//     // Log the issue key and other details
//     log.info("Issue Created: ${issue.key}, Summary: ${issue.summary}, Project: ${issue.projectObject.key}")

//     // Display a message to the user (optional)
//     UserMessageUtil.success("Issue Created: ${issue.key}, Summary: ${issue.summary}, Project: ${issue.projectObject.key}")

//     // Additional actions can be performed here
// }






//ucon.setRequestProperty("Authorization","Basic ${base64Authorization}");
        // ucon.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        // ucon.setRequestProperty("User-Agent", "Mozilla/5.0");

//import com.onresolve.scriptrunner.runner.customisers.PluginModule
//import com.onresolve.scriptrunner.runner.customisers.WithPlugin
//import com.almworks.jira.structure.AllPublicStructureComponents

// Inject plugin module
//@PluginModule
//AllPublicStructureComponents structureComponents

// Specify that classes from this plugin should be available to this script
//@WithPlugin("com.almworks.jira.structure")

// This function will be triggered by an event
//def onIssueEvent(IssueEvent event) {
    // Retrieve the issue from the event
    //Issue issue = event.getIssue()
   
    // Get the issue ID
    //def issueId = issue.getId()
    //issue.id
    // Now you can use the issue ID as needed
   //println "Issue ID: $issueId"
//}

// Register the listener for issue events
//ComponentAccessor.getIssueManager().addListener(onIssueEvent)

2024-06-14_17h58_16.png
0 votes
serge calderara
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 14, 2024

Hello ,

First of all it would be less agressive if you start your question by "I would like " instead of "I want"

Second, the way to extract the ke of an issue as long as you get the correct issue object you need that information from .

Please try the getKey() method.

def myIssue = event.issue
def myIssueKey = myIssue.getKey()

Something like this should work if you are fetching from an event.

If it is from a workflow, they a simple issue.key should normally return your issue key.

Vrabiel Attila Bela June 14, 2024

First of all i apologize for how i put the question ( apologize for  the " I want")

I tried that method that you suggested me but i have this message

Static type checking - The variable event is undeclared.
No quick fixes available 


I hope that somebody can help with this issue. Thanks in advanced.
serge calderara
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 14, 2024

The error is on from your event object which is not recognised not the GetKey

 

Vrabiel Attila Bela June 14, 2024

Sorry i am a beginner in Jira script runner(listener)  if i ask you nicely can you help me with my problem? here is a full description of the issue. I  was asked to interconnect Jira cloud with Service Now. The task that was assigned to me is that when in a Jira issue is added an attachment,  that attachment must be sent to an incident in Service Now (incident that created the Jira issue) I realized that an attachment can be sent to Service Now just if is coded in Base 64 (this part of the script is working well) , but i do not know how to get the Jira issue key or id to read from that issue the incident number. When i created the script listener  on the section: On these events: i put the argument When an attachment is created.  

I hope that you understand what i tried to explain and i hope that you can help me.

Thanks in advanced.

serge calderara
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 14, 2024

screen capture will help to understand where you are runing that script and your script code

Vrabiel Attila Bela June 14, 2024

2024-06-14_17h58_16.png

Vrabiel Attila Bela June 14, 2024

And this is the script that i tried to make:

 

import java.util.Base64
import com.atlassian.jira.*
//import com.atlassian.jira.issue.fields.CustomField;
//import com.atlassian.jira.component.ComponentAccessor;
//import com.atlassian.jira.issue.CustomFieldManager;
//import com.atlassian.jira.event.issue.DelegatingJiraIssueEvent;
//import com.atlassian.jira.event.issue.IssueEvent;

import com.onresolve.scriptrunner.runner.customisers.WithPlugin


String base64Output= '';


    try {
        URL fileUrl = new URL((attachment.get("self")).toString());
        // URLConnection ucon = fileUrl.openConnection();
        // String base64Authorization = "${USER}:${PASSWORD}".bytes.encodeBase64().toString();
        // logger.info(base64Authorization);
        // ucon.setRequestProperty("Authorization","Basic ${base64Authorization}");
        // ucon.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        // ucon.setRequestProperty("User-Agent", "Mozilla/5.0");

        HttpURLConnection httpURLConnection = (HttpURLConnection) fileUrl.openConnection();
        httpURLConnection.setRequestProperty("User-Agent", "my-agent");
        httpURLConnection.setRequestProperty("Cookie","ajs_anonymous_id=%229a0c04ff-accb-43cf-94fd-6d8014b60186%22; atlassian.account.xsrf.token=18f0430c-e1ba-4be9-8c60-1e7768364eb9; atlassian.xsrf.token=e4b92c1172d56d80e01877e5e590a7cc4aec3657_lin; cross.join.nudges.confluence.visited=true; tenant.session.token=eyJraWQiOiJzZXNzaW9uLXNlcnZpY2UvcHJvZC0xNTkyODU4Mzk0IiwiYWxnIjoiUlMyNTYifQ.eyJhc3NvY2lhdGlvbnMiOltdLCJzdWIiOiI3MTIwMjA6OTc3MzljMDMtNjdkMC00MjExLTlhM2QtNDNhYTdmNWVjYzAzIiwiZW1haWxEb21haW4iOiJnZW5lcml4Z3JvdXAuY29tIiwiaW1wZXJzb25hdGlvbiI6W10sImNyZWF0ZWQiOjE3MTQzNzQ4NDUsInJlZnJlc2hUaW1lb3V0IjoxNzE4MTE5NDUzLCJ2ZXJpZmllZCI6dHJ1ZSwiaXNzIjoic2Vzc2lvbi1zZXJ2aWNlIiwic2Vzc2lvbklkIjoiYWRmNTY0MTgtOGVlNC00Y2I3LTlhYzktNTM5YzgyZjE1MTlmIiwic3RlcFVwcyI6W10sImF1ZCI6ImF0bGFzc2lhbiIsIm5iZiI6MTcxODExODg1MywiZXhwIjoxNzIwNzEwODUzLCJpYXQiOjE3MTgxMTg4NTMsImVtYWlsIjoiYWJ2cmFiaWVsQGdlbmVyaXhncm91cC5jb20iLCJqdGkiOiJhZGY1NjQxOC04ZWU0LTRjYjctOWFjOS01MzljODJmMTUxOWYifQ.BW_OyiCo096Nb3K_j0HCIp-OalUoCvBy-YNP6-r25PPH1oYBFknBZ7zgA_k7KOeb6O9wi8WN4VU9cSLoqTFJfl1_CXL4cMhabaWqcLMkSewWWDeW5TirIEZGbmm_AtJ73EWMej-7I0ZmwC85HexfCitw45cawQmzfdu_sywXwZH3LhipXLb3XKBfQhRWkh2tVl3cg5POj0hW_foizmXDxGOhjLNov0bI71M5xE_UseQYKDCrL945cVvMDKqeFDp0xbZVX0zEcMpCmUdJwLc-7igZ2v-4m6fEVGTBEKKsgd_RsftL4FCvGGQyczjHQGkW5pRiC_sZaji61-A_Tw8tXA; JSESSIONID=F1906576917038203521A5A7F2E04500");
        httpURLConnection.connect();


        InputStream is = httpURLConnection.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int read = 0;
        while ((read = is.read(buffer, 0, buffer.length)) != -1) {
            baos.write(buffer, 0, read);
        }
        baos.flush();
        Base64.getEncoder().encodeToString()
        base64Output = Base64.getEncoder().encodeToString(baos.toByteArray());
    } catch (Exception e) {
        logger.error("CEVAAA  eerrrrrrrrrrrrrrrrrrr");
        logger.error("Error converting to Base 64 "+e.getMessage() +" "+attachment.get("self"));
    }
    //return null;
logger.debug("something")
logger.error("CEVAAA");
logger.error(attachment.get("self").toString());
//logger.error(attachment);
logger.error('OUTPUT:  '+base64Output);

    def issueManager = ComponentAccessor.getIssueManager();
def aM= ComponentAccessor.getAttachmentManager();
String attId = attachment.get("self").substring(attachment.get("self").lastIndexOf('/') + 1).trim();
logger.error(attId);
Object att = aM.getAttachment(Long.parseLong(attId));
logger.error(att);



// @WithPlugin("com.onresolve.scriptrunner.canned.jira.workflow.postfunctions.FireIssueEvent")
// void execute(IssueEvent event) {
//     def issue = event.issue

//     // Log the issue key and other details
//     log.info("Issue Created: ${issue.key}, Summary: ${issue.summary}, Project: ${issue.projectObject.key}")

//     // Display a message to the user (optional)
//     UserMessageUtil.success("Issue Created: ${issue.key}, Summary: ${issue.summary}, Project: ${issue.projectObject.key}")

//     // Additional actions can be performed here
// }






//ucon.setRequestProperty("Authorization","Basic ${base64Authorization}");
        // ucon.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        // ucon.setRequestProperty("User-Agent", "Mozilla/5.0");

//import com.onresolve.scriptrunner.runner.customisers.PluginModule
//import com.onresolve.scriptrunner.runner.customisers.WithPlugin
//import com.almworks.jira.structure.AllPublicStructureComponents

// Inject plugin module
//@PluginModule
//AllPublicStructureComponents structureComponents

// Specify that classes from this plugin should be available to this script
//@WithPlugin("com.almworks.jira.structure")

// This function will be triggered by an event
//def onIssueEvent(IssueEvent event) {
    // Retrieve the issue from the event
    //Issue issue = event.getIssue()
   
    // Get the issue ID
    //def issueId = issue.getId()
    //issue.id
    // Now you can use the issue ID as needed
   //println "Issue ID: $issueId"
//}

// Register the listener for issue events
//ComponentAccessor.getIssueManager().addListener(onIssueEvent)


serge calderara
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 14, 2024

You need to get your Issue object from the event context first as below :

Issue issue = event.getIssue()

def issueKey = issue.getKey()

Then you can get the issue key or any other issue properties

regarsd 

Like Vrabiel Attila Bela likes this
DEPLOYMENT TYPE
CLOUD
PRODUCT PLAN
STANDARD
PERMISSIONS LEVEL
Product Admin
TAGS
AUG Leaders

Atlassian Community Events