Import a Groovy script from one to another

On this page

Still need help?

The Atlassian Community is here for you.

Ask the community

This is how you can import a Groovy script into another to be able to structure your code

InsightLogClass.groovy

import com.atlassian.jira.component.ComponentAccessor;
 
public Object getObject(String key) {
        Class objectFacadeClass = ComponentAccessor.getPluginAccessor().getClassLoader().
                                findClass("com.riadalabs.jira.plugins.insight.channel.external.api.facade.ObjectFacade");
        def objectFacade = ComponentAccessor.getOSGiComponentInstanceOfType(objectFacadeClass);
        return objectFacade.loadObjectBean(key);
}

Using an absolute path

LogObject.groovy

def PATH_TO_SCRIPTS = "/Users/.../groovy/";
 
File insightLogClassFile = new File(PATH_TO_SCRIPTS, "InsightLogClass.groovy");
Class insightLogClass = new GroovyClassLoader(getClass().getClassLoader()).parseClass(insightLogClassFile);
GroovyObject insightLogObject = (GroovyObject) insightLogClass.newInstance();
 
log.warn(insightLogObject.getObject(object.objectKey));

So if you execute the LogObject.groovy file in an automation rule, you will log out the affected object (which you already had, but anyway...)

Instead of using an absolute path for the scripts, one can use this instead:

def PATH_TO_SCRIPTS = new File(getClass().protectionDomain.codeSource.location.path).parent


This will provide a path to the directory in which the automation scripts is contained in JIRA. Groovy classes in this directory are now easy to access.

Another benefit is that it works on different JIRA instances right out of the box. Say, you have a production and QA/test/dev instances and they have different paths for where the scripts live. Finding the path dynamically means that the code works on all of those instances without any modification.

LogObject.groovy

def PATH_TO_SCRIPTS = new File(getClass().protectionDomain.codeSource.location.path).parent
 
File insightLogClassFile = new File(PATH_TO_SCRIPTS, "InsightLogClass.groovy");
Class insightLogClass = new GroovyClassLoader(getClass().getClassLoader()).parseClass(insightLogClassFile);
GroovyObject insightLogObject = (GroovyObject) insightLogClass.newInstance();
 
log.warn(insightLogObject.getObject(object.objectKey));

So if you execute the LogObject.groovy file in an automation rule, you will log out the affected object (which you already had, but anyway...)


Last modified on Mar 25, 2024

Was this helpful?

Yes
No
Provide feedback about this article
Powered by Confluence and Scroll Viewport.