Tutorial - Writing JIRA event listeners with the atlassian-event library

Applicable:

This tutorial applies to JIRA 5.0 and later.

Level of experience:

This is an intermediate tutorial. You should have completed at least one beginner tutorial before working through this tutorial. See the list of developer tutorials.

Time estimate:

It should take you approximately half an hour to complete this tutorial.

On this page:

Overview of the tutorial

JIRA has supported a simple listener API for a long time, but that API has several problems. Installation and configuration are complex. Also, it's impossible (as of JIRA 4.0) to share code between listeners and plugins.

Fortunately, you can use the atlassian-event library to implement the same functionality and avoid these problems. This tutorial shows you how.

In this tutorial, you will create a plugin that listens for events generated when an issue is created or resolved. When the events occur, the plugin simply logs the event. Your completed plugin will consist of the following components:

  • Java classes encapsulating the plugin logic.
  • A plugin descriptor (XML file) to enable the plugin module in the Atlassian application.

When you have finished, all these components will be packaged in a single JAR file.

About these Instructions

You can use any supported combination of OS and IDE to create this plugin. These instructions were written using IntelliJ IDEA on Ubuntu Linux. If you are using another OS or IDE combination, you should use the equivalent operations for your specific environment.

This tutorial was last tested with JIRA 6.0.4.

Required knowledge

To complete this tutorial, you need to know the following: 

  • The basics of Java development: classes, interfaces, methods, how to use the compiler, and so on.
  • How to create an Atlassian plugin project using the Atlassian Plugin SDK.
  • The basics of using and administering JIRA.

Plugin source

We encourage you to work through this tutorial. If you want to skip ahead or check your work when you have finished, you can find the plugin source code on Atlassian Bitbucket. Bitbucket serves a public Git repository containing the tutorial's code. To clone the repository, issue the following command:

git clone https://bitbucket.org/atlassian_tutorial/jira-event-listener

Alternatively, you can download the source as a ZIP archive by choosing download here: https://bitbucket.org/atlassian_tutorial/jira-event-listener. 

Step 1. Create the plugin project

In this step, you'll use an atlas command to generate stub code for your plugin. The atlas commands are part of the Atlassian Plugin SDK, and automate much of the work of plugin development for you.

  1. If you have not already set up the Atlassian Plugin SDK, do that now: Set up the Atlassian Plugin SDK and Build a Project.
  2. Open a terminal and navigate to your project home directory.
  3. Enter the following command to create a plugin skeleton:

    atlas-create-jira-plugin
    
  4. When prompted for the version to create the plugin for, choose 1 for JIRA 5. 
  5. As prompted, enter the following information to identify your plugin:

    group-id

    com.example.tutorial.plugins

    artifact-id

    new-listener-plugin

    version

    1.0-SNAPSHOT

    package

    com.example.tutorial.plugins

  6. Confirm your entries when prompted.

Step 2. Modify the POM metadata and add a dependency

The POM (Project Object Model definition file) declares your plugin's dependencies, build settings, and metadata (information about your plugin). Modify the POM as follows:

  1. Change to the new-listener-plugin directory created by the SDK.
  2. Open the pom.xml file for editing.
  3. Add your company or organisation name and your website to the organization element:

    <organization>
        <name>Example Company</name>
        <url>http://www.example.com/</url>
    </organization>
    
  4. Update the description element:

    <description>This plugin implements a simple issue event listener for JIRA using atlassian-event.</description>
    
  5. Add the following dependency as a child of the dependencies element:

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>2.5.6.SEC02</version>
        <scope>provided</scope>
    </dependency> 

    The org.springframework version should match the version used by the UPM.

  6. We're going to use a custom log4j.properties file for this plugin. Add the following element as a child of the project.build.plugins.plugin.configuration element:

    <log4jProperties>src/aps/log4j.properties</log4jProperties>

    The complete plugin element should look like this:

    <plugin>
        <groupId>com.atlassian.maven.plugins</groupId>
        <artifactId>maven-jira-plugin</artifactId>
        <version>${amps.version}</version>
        <extensions>true</extensions>
        <configuration>
            <productVersion>${jira.version}</productVersion>
            <productDataVersion>${jira.version}</productDataVersion>
            <log4jProperties>src/aps/log4j.properties</log4jProperties>
        </configuration>
    </plugin> 
  7. Save the file.

Step 3. Register the plugin module in the plugin descriptor

The SDK can generate the code for many types of modules you can use in plugins. However, in the case of the event listener module, we'll need to add it by hand.

Let's start with the plugin descriptor. The plugin descriptor is an XML file that identifies the plugin to JIRA and defines the functionality that the plugin requires. Here's a basic plugin descriptor:

<atlassian-plugin key="${project.groupId}.${project.artifactId}" name="${project.name}" plugins-version="2">
    <plugin-info>
        <description>${project.description}</description>
        <version>${project.version}</version>
        <vendor name="${project.organization.name}" url="${project.organization.url}" />
        <param name="plugin-icon">images/pluginIcon.png</param>
        <param name="plugin-logo">images/pluginLogo.png</param>
    </plugin-info>

    <resource type="i18n" name="i18n" location="new-listener-plugin"/>
    
    <web-resource key="new-listener-plugin-resources" name="new-listener-plugin Web Resources">
        <dependency>com.atlassian.auiplugin:ajs</dependency>
        
        <resource type="download" name="new-listener-plugin.css" location="/css/new-listener-plugin.css"/>
        <resource type="download" name="new-listener-plugin.js" location="/js/new-listener-plugin.js"/>
        <resource type="download" name="images/" location="/images"/>

        <context>new-listener-plugin</context>
    </web-resource>
    
    <component key="myPluginComponent" class="com.example.tutorial.plugins.MyPluginComponentImpl" public="true">
        <interface>com.example.tutorial.plugins.MyPluginComponent</interface>
    </component>
    
    <component-import key="applicationProperties" interface="com.atlassian.sal.api.ApplicationProperties" />
    
</atlassian-plugin>

Notice that the SDK adds some ingredients that we won't pursue in this tutorial, such as plugin icons for the add-on management page. It doesn't hurt to leave these in, but this tutorial will leave icon customization as an exercise for you to explore later. Also note that some of the information from the POM is transferred to the plugin descriptor using variable names such as ${project.artifactId}.

Update the descriptor for the plugin as follows:

  1. Open the plugin descriptor file, atlassian-plugin.xml for editing. It is located at src/main/resources/.
  2. Add the following component declarations (as children of the atlassian-plugin element):

    <component-import key="eventPublisher" interface="com.atlassian.event.api.EventPublisher"/>
    <component key="eventListener" class="com.example.tutorial.plugins.IssueCreatedResolvedListener">
        <description>Class that processes the incoming JIRA issue events.</description>
    </component>
    

The first line imports the EventPublisher instance used to register for events. The second line instantiates the listener class that we will write. To be eligible for dependency injection, your classes must be registered as component plugin modules. We'll talk about this more later.

Now you are ready to write some code to make your plugin do something.

Step 4. Write the Java class

The recipe for creating an event listener is very simple:

  • Inject the EventPublisher implementation into your class.
  • Add an @EventListener annotation to any method that should receive events.
  • Handle events as they come in.

To demonstrate this, we'll create a listener that will log a notification whenever an issue is created, resolved, or closed. It's easy to imagine how this same approach could be used to send notifications, say to email or IRC, but we'll leave those as exercises for you to try later.

In the following steps, you'll create the class file and build on it little by little.

  1.  Create a file named IssueCreatedResolvedListener.java in the directory src/main/java/com/example/tutorial/plugins/, and give it the following contents:

    package com.example.tutorial.plugins;
    
    import com.atlassian.event.api.EventListener;
    import com.atlassian.event.api.EventPublisher;
    import com.atlassian.jira.event.issue.IssueEvent;
    import com.atlassian.jira.event.type.EventType;
    import com.atlassian.jira.issue.Issue;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    public class IssueCreatedResolvedListener {
             private static final Logger log = LoggerFactory.getLogger(IssueCreatedResolvedListener.class);
    
     }
    

    So far, all we've done is declared a few import statement and instantiated a logger. We'll use the logger to record our events as they happen. 

  2. Add a constructor that injects an EventPublisher instance into our plugin, which registers our IssueCreatedResolvedListener class with the EventPublisher:

    public IssueCreatedResolvedListener(EventPublisher eventPublisher) {
        eventPublisher.register(this);    // Demonstration only -- don't do this in real code!
    }
    

    You'll recall that we added a component-import statement to our plugin descriptor for EventPublisher, the entry point to the atlassian-event library. The EventPublisher object handles publication of events and registration of event listeners. While this works for a demonstration, it isn't what you want to do in your actual plugin. We'll explain why in a moment.

  3. Add a method to handle the event:

    @EventListener
    public void onIssueEvent(IssueEvent issueEvent) {
       Long eventTypeId = issueEvent.getEventTypeId();
       Issue issue = issueEvent.getIssue();
    
       if (eventTypeId.equals(EventType.ISSUE_CREATED_ID)) {
          log.info("Issue {} has been created at {}.", issue.getKey(), issue.getCreated());
       } else if (eventTypeId.equals(EventType.ISSUE_RESOLVED_ID)) {
          log.info("Issue {} has been resolved at {}.", issue.getKey(), issue.getResolutionDate());
       } else if (eventTypeId.equals(EventType.ISSUE_CLOSED_ID)) {
          log.info("Issue {} has been closed at {}.", issue.getKey(), issue.getUpdated());
       }
    }
    

    Notice that the method is annotated with EventListener. You can apply the EventListener annotation to any public method. The method must take a parameter corresponding to the event it should handle, IssueEvent in this case. JIRA provides several events, as described on JIRA-Specific Atlassian Events.

  4. Now create the custom log4j.properties file. This is the custom resource we added to the plugin's configuration in the POM. We need a custom log4j properties file because the JIRA log4j implementation doesn't know anything about our plugin's logger. And since our package name is com.example.tutorial.plugins, we don't inherit any of the com.atlassian hierarchical loggers.
    Add the following log4j.properties file in a new directory under your project home, src/aps.

    #####################################################
    # LOGGING LEVELS
    #####################################################
    
    # To turn more verbose logging on - change "WARN" to "DEBUG"
    
    log4j.rootLogger=WARN, console, filelog
    
    #####################################################
    # LOG FILE LOCATIONS
    #####################################################
    
    log4j.appender.console=org.apache.log4j.ConsoleAppender
    log4j.appender.console.Threshold=DEBUG
    log4j.appender.console.layout=org.apache.log4j.PatternLayout
    log4j.appender.console.layout.ConversionPattern=%d %t %p %X{jira.username} %X{jira.request.id} %X{jira.request.assession.id} %X{jira.request.ipaddr} %X{jira.request.url} [%c{4}] %m%n
    
    
    log4j.appender.nowarnconsole=org.apache.log4j.ConsoleAppender
    log4j.appender.nowarnconsole.Threshold=DEBUG
    log4j.appender.nowarnconsole.layout=org.apache.log4j.PatternLayout
    log4j.appender.nowarnconsole.layout.ConversionPattern=%d %t %p %X{jira.username} %X{jira.request.id} %X{jira.request.assession.id} %X{jira.request.ipaddr} %X{jira.request.url} [%c{4}] %m%n
    
    
    log4j.appender.filelog=com.atlassian.jira.logging.JiraHomeAppender
    log4j.appender.filelog.File=atlassian-jira.log
    log4j.appender.filelog.MaxFileSize=20480KB
    log4j.appender.filelog.MaxBackupIndex=5
    log4j.appender.filelog.layout=com.atlassian.logging.log4j.FilteredPatternLayout
    log4j.appender.filelog.layout.ConversionPattern=%d %t %p %X{jira.username} %X{jira.request.id} %X{jira.request.assession.id} %X{jira.request.ipaddr} %X{jira.request.url} [%c{4}] %m%n
    log4j.appender.filelog.layout.MinimumLines=6
    log4j.appender.filelog.layout.FilteringApplied=true
    log4j.appender.filelog.layout.ShowEludedSummary=true
    #
    # These are the Java stack frames that will be filtered out when an exception is logged.  This is to help reduce the
    # noise to information ratio in the JIRA logs.  Its a long comma seperated list with .properties line continuation
    # provided by the / character.
    #
    # It will always how the 'MinimumLines' value above regardless of these settings.  Also DEBUG level stack traces will always
    # be shown in their entirety.
    #
    # You can quickly revert to full stack traces by setting 'FilteringApplied'=false above or by removing the lines below
    # and restarting JIRA.
    #
    log4j.appender.filelog.layout.FilteredFrames=\
      sun.reflect, \
      \
      org.apache.catalina, \
      org.apache.coyote, \
      org.apache.tomcat.util.net, \
      org.apache.catalina.core.ApplicationFilterChain, \
      \
      webwork.interceptor, \
      webwork.dispatcher, \
      webwork.action.ActionSupport, \
      com.opensymphony.sitemesh, \
      \
      com.sun.jersey.server.impl, \
      com.sun.jersey.spi.container.servlet, \
      \
      com.atlassian.jira.web.dispatcher, \
      com.atlassian.jira.web.filters, \
      com.atlassian.jira.web.filters.steps, \
      com.atlassian.jira.startup.JiraStartupChecklistFilter, \
      com.atlassian.jira.security.xsrf.XsrfTokenAdditionRequestFilter, \
      \
      com.atlassian.seraph.filter, \
      com.atlassian.security.auth.trustedapps.filter, \
      com.atlassian.plugin.servlet.filter, \
      com.atlassian.plugins.rest.common, \
      com.atlassian.core.filters, \
      com.atlassian.util.profiling.filters, \
      com.atlassian.johnson.filters, \
      \
      com.atlassian.gzipfilter.GzipFilter, \
      com.atlassian.applinks.core.rest.context.ContextFilter, \
      com.atlassian.plugins.rest.module.servlet.RestServletUtilsUpdaterFilter, \
      com.atlassian.oauth.serviceprovider.internal.servlet.OAuthFilter, \
      \
      org.tuckey.web.filters.urlrewrite.UrlRewriteFilter, \
      com.sysbliss.jira.plugins.workflow.servlet.JWDSendRedirectFilter, \
    
    
    
    log4j.appender.soapaccesslog=com.atlassian.jira.logging.JiraHomeAppender
    log4j.appender.soapaccesslog.File=atlassian-jira-soap-access.log
    log4j.appender.soapaccesslog.MaxFileSize=20480KB
    log4j.appender.soapaccesslog.MaxBackupIndex=5
    log4j.appender.soapaccesslog.layout=org.apache.log4j.PatternLayout
    log4j.appender.soapaccesslog.layout.ConversionPattern=%m%n
    
    log4j.appender.soapdumplog=com.atlassian.jira.logging.JiraHomeAppender
    log4j.appender.soapdumplog.File=atlassian-jira-soap-dump.log
    log4j.appender.soapdumplog.MaxFileSize=20480KB
    log4j.appender.soapdumplog.MaxBackupIndex=5
    log4j.appender.soapdumplog.layout=org.apache.log4j.PatternLayout
    log4j.appender.soapdumplog.layout.ConversionPattern=%m%n
    
    log4j.appender.httpaccesslog=com.atlassian.jira.logging.JiraHomeAppender
    log4j.appender.httpaccesslog.File=atlassian-jira-http-access.log
    log4j.appender.httpaccesslog.MaxFileSize=20480KB
    log4j.appender.httpaccesslog.MaxBackupIndex=5
    log4j.appender.httpaccesslog.layout=org.apache.log4j.PatternLayout
    log4j.appender.httpaccesslog.layout.ConversionPattern=%m%n
    
    log4j.appender.httpdumplog=com.atlassian.jira.logging.JiraHomeAppender
    log4j.appender.httpdumplog.File=atlassian-jira-http-dump.log
    log4j.appender.httpdumplog.MaxFileSize=20480KB
    log4j.appender.httpdumplog.MaxBackupIndex=5
    log4j.appender.httpdumplog.layout=org.apache.log4j.PatternLayout
    log4j.appender.httpdumplog.layout.ConversionPattern=%m%n
    
    log4j.appender.sqllog=com.atlassian.jira.logging.JiraHomeAppender
    log4j.appender.sqllog.File=atlassian-jira-sql.log
    log4j.appender.sqllog.MaxFileSize=20480KB
    log4j.appender.sqllog.MaxBackupIndex=5
    log4j.appender.sqllog.layout=org.apache.log4j.PatternLayout
    log4j.appender.sqllog.layout.ConversionPattern=%d %t %X{jira.username} %X{jira.request.id} %X{jira.request.assession.id} %X{jira.request.url} %m%n
    
    log4j.appender.slowquerylog=com.atlassian.jira.logging.JiraHomeAppender
    log4j.appender.slowquerylog.File=atlassian-jira-slow-queries.log
    log4j.appender.slowquerylog.MaxFileSize=20480KB
    log4j.appender.slowquerylog.MaxBackupIndex=5
    log4j.appender.slowquerylog.layout=org.apache.log4j.PatternLayout
    log4j.appender.slowquerylog.layout.ConversionPattern=%d %t %p %X{jira.username} %X{jira.request.id} %X{jira.request.assession.id} %X{jira.request.url} [%c{4}] %m%n
    
    log4j.appender.xsrflog=com.atlassian.jira.logging.JiraHomeAppender
    log4j.appender.xsrflog.File=atlassian-jira-xsrf.log
    log4j.appender.xsrflog.MaxFileSize=20480KB
    log4j.appender.xsrflog.MaxBackupIndex=5
    log4j.appender.xsrflog.layout=org.apache.log4j.PatternLayout
    log4j.appender.xsrflog.layout.ConversionPattern=%d %t %X{jira.username} %X{jira.request.id} %X{jira.request.assession.id} %X{jira.request.url} %m%n
    
    log4j.appender.securitylog=com.atlassian.jira.logging.JiraHomeAppender
    log4j.appender.securitylog.File=atlassian-jira-security.log
    log4j.appender.securitylog.MaxFileSize=20480KB
    log4j.appender.securitylog.MaxBackupIndex=5
    log4j.appender.securitylog.layout=org.apache.log4j.PatternLayout
    log4j.appender.securitylog.layout.ConversionPattern=%d %t %X{jira.username} %X{jira.request.id} %X{jira.request.assession.id} %X{jira.request.ipaddr} %X{jira.request.url} %m%n
    
    log4j.appender.outgoingmaillog=com.atlassian.jira.logging.JiraHomeAppender
    log4j.appender.outgoingmaillog.File=atlassian-jira-outgoing-mail.log
    log4j.appender.outgoingmaillog.MaxFileSize=20480KB
    log4j.appender.outgoingmaillog.MaxBackupIndex=5
    log4j.appender.outgoingmaillog.layout=org.apache.log4j.PatternLayout
    log4j.appender.outgoingmaillog.layout.ConversionPattern=%d %p [%X{jira.mailserver}] %t %X{jira.username} %X{jira.request.id} %X{jira.request.assession.id} %X{jira.request.ipaddr} %X{jira.request.url} %m%n
    
    log4j.appender.incomingmaillog=com.atlassian.jira.logging.JiraHomeAppender
    log4j.appender.incomingmaillog.File=atlassian-jira-incoming-mail.log
    log4j.appender.incomingmaillog.MaxFileSize=20480KB
    log4j.appender.incomingmaillog.MaxBackupIndex=5
    log4j.appender.incomingmaillog.layout=org.apache.log4j.PatternLayout
    log4j.appender.incomingmaillog.layout.ConversionPattern=%d %p [%X{jira.mailserver}] %t %X{jira.username} %X{jira.request.id} %X{jira.request.assession.id} %X{jira.request.ipaddr} %X{jira.request.url} %m%n
    
    log4j.appender.remoteappssecurity=com.atlassian.jira.logging.JiraHomeAppender
    log4j.appender.remoteappssecurity.File=atlassian-remoteapps-security.log
    log4j.appender.remoteappssecurity.MaxFileSize=20480KB
    log4j.appender.remoteappssecurity.MaxBackupIndex=5
    log4j.appender.remoteappssecurity.layout=org.apache.log4j.PatternLayout
    log4j.appender.remoteappssecurity.layout.ConversionPattern=%d %t %p %X{jira.username} %X{jira.request.id} %X{jira.request.assession.id} %X{jira.request.ipaddr} %X{jira.request.url} [%c{4}] %m%n
    
    #####################################################
    # Log Marking
    #####################################################
    
    log4j.logger.com.atlassian.jira.util.log.LogMarker  = INFO, console, filelog, soapaccesslog, soapdumplog, httpaccesslog, httpdumplog, sqllog, slowquerylog, xsrflog, securitylog, outgoingmaillog, incomingmaillog, remoteappssecurity
    log4j.additivity.com.atlassian.jira.util.log.LogMarker = false
    
    
    #####################################################
    # Access logs
    #####################################################
    
    log4j.logger.com.atlassian.jira.soap.axis.JiraAxisSoapLog  = OFF, soapaccesslog
    log4j.additivity.com.atlassian.jira.soap.axis.JiraAxisSoapLog = false
    
    log4j.logger.com.atlassian.jira.soap.axis.JiraAxisSoapLogDump  = OFF, soapdumplog
    log4j.additivity.com.atlassian.jira.soap.axis.JiraAxisSoapLogDump = false
    
    log4j.logger.com.atlassian.jira.web.filters.accesslog.AccessLogFilter = OFF, httpaccesslog
    log4j.additivity.com.atlassian.jira.web.filters.accesslog.AccessLogFilter = false
    
    log4j.logger.com.atlassian.jira.web.filters.accesslog.AccessLogFilterIncludeImages = OFF, httpaccesslog
    log4j.additivity.com.atlassian.jira.web.filters.accesslog.AccessLogFilterIncludeImages = false
    
    log4j.logger.com.atlassian.jira.web.filters.accesslog.AccessLogFilterDump = OFF, httpdumplog
    log4j.additivity.com.atlassian.jira.web.filters.accesslog.AccessLogFilterDump = false
    
    #####################################################
    # SQL logs
    #####################################################
    #
    # Beware of turning this log level on.  At INFO level it will log every SQL statement
    # and at DEBUG level it will also log the calling stack trace.  Turning this on will DEGRADE your
    # JIRA database throughput.
    #
    log4j.logger.com.atlassian.jira.ofbiz.LoggingSQLInterceptor = OFF, sqllog
    log4j.additivity.com.atlassian.jira.ofbiz.LoggingSQLInterceptor = false
    
    log4j.logger.com.atlassian.jira.security.xsrf.XsrfVulnerabilityDetectionSQLInterceptor = OFF, xsrflog
    log4j.additivity.com.atlassian.jira.security.xsrf.XsrfVulnerabilityDetectionSQLInterceptor = false
    
    
    #####################################################
    # Security logs
    #####################################################
    
    log4j.logger.com.atlassian.jira.login.security = INFO, securitylog
    log4j.additivity.com.atlassian.jira.login.security = false
    
    #
    #
    # The following log levels can be useful to set when login problems occur within JIRA
    #
    log4j.logger.com.atlassian.jira.login = WARN, securitylog
    log4j.additivity.com.atlassian.jira.login = false
    
    log4j.logger.com.atlassian.jira.web.session.currentusers = WARN, securitylog
    log4j.additivity.com.atlassian.jira.web.session.currentusers = false
    
    #
    # BEWARE - Turning on Seraph debug logs will result in many logs lines per web request.  
    #
    log4j.logger.com.atlassian.seraph = WARN, securitylog
    log4j.additivity.com.atlassian.seraph = false
    
    #
    #---------------
    
    #####################################################
    # CLASS-SPECIFIC LOGGING LEVELS
    #####################################################
    # This stuff you may wish to debug, but it produces a high volume of logs.
    # Uncomment only if you want to debug something particular
    
    log4j.logger.com.atlassian = WARN, console, filelog
    log4j.additivity.com.atlassian = false
    
    log4j.logger.com.atlassian.jira = INFO, console, filelog
    log4j.additivity.com.atlassian.jira = false
    
    log4j.logger.com.atlassian.plugin = INFO, console, filelog
    log4j.additivity.com.atlassian.plugin = false
    
    log4j.logger.atlassian.plugin = INFO, console, filelog
    log4j.additivity.atlassian.plugin = false
    
    log4j.logger.org.twdata.pkgscanner = WARN, console, filelog
    log4j.additivity.org.twdata.pkgscanner = false
    
    log4j.logger.com.atlassian.plugin.osgi.factory = WARN, console, filelog
    log4j.additivity.com.atlassian.plugin.osgi.factory = false
    
    log4j.logger.com.atlassian.plugin.osgi.container = WARN, console, filelog
    log4j.additivity.com.atlassian.plugin.osgi.container = false
    
    log4j.logger.org.apache.shindig = ERROR, console, filelog
    log4j.additivity.org.apache.shindig = false
    
    log4j.logger.com.atlassian.gadgets = WARN, console, filelog
    log4j.additivity.com.atlassian.gadgets = false
    
    log4j.logger.com.atlassian.jira.gadgets.system.MarketingGadgetSpecProvider = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.gadgets.system.MarketingGadgetSpecProvider = false
    
    # The directory may produce errors of interest to admins when adding gadgets with features that aren't supported
    # (for example).
    log4j.logger.com.atlassian.gadgets.directory = INFO, console, filelog
    log4j.additivity.com.atlassian.gadgets.directory = false
    
    # Felix annoyingly dumps some pretty silly INFO level messages. So we have to set logging to WARN here.  Means
    # we miss out on some useful startup logging.  Should probably remove this if Felix ever fix this.
    log4j.logger.com.atlassian.plugin.osgi.container.felix.FelixOsgiContainerManager = WARN, console, filelog
    log4j.additivity.com.atlassian.plugin.osgi.container.felix.FelixOsgiContainerManager = false
    
    log4j.logger.com.atlassian.plugin.servlet = WARN, console, filelog
    log4j.additivity.com.atlassian.plugin.servlet = false
    
    log4j.logger.com.atlassian.plugin.classloader = WARN, console, filelog
    log4j.additivity.com.atlassian.plugin.classloader = false
    
    log4j.logger.com.atlassian.jira.util.system.JiraSystemRestarterImpl = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.util.system.JiraSystemRestarterImpl = false
    
    log4j.logger.com.atlassian.jira.upgrade = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.upgrade = false
    
    log4j.logger.com.atlassian.jira.startup = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.startup = false
    
    log4j.logger.com.atlassian.jira.config.database = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.config.database = false
    
    log4j.logger.com.atlassian.jira.web.action.util.LDAPConfigurer = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.web.action.util.LDAPConfigurer = false
    
    log4j.logger.com.atlassian.jira.imports  = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.imports = false
    
    log4j.logger.com.atlassian.jira.plugin  = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.plugin = false
    
    log4j.logger.com.atlassian.jira.bc.dataimport  = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.bc.dataimport = false
    
    log4j.logger.com.atlassian.jira.security = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.security = false
    
    log4j.logger.com.atlassian.jira.issue.index = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.issue.index = false
    
    # DefaultIndexManager should run at INFO level, because we want to see messages when we force an optimise etc.
    log4j.logger.com.atlassian.jira.issue.index.DefaultIndexManager = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.issue.index.DefaultIndexManager = false
    
    # Allow the optimise job to log at info level so that we can see the last time it ran
    log4j.logger.com.atlassian.jira.issue.index.job.OptimizeIndexJob = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.issue.index.job.OptimizeIndexJob = false
    
    # Allow the Composite IndexLifecycleManager to log info
    log4j.logger.com.atlassian.jira.util.index = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.util.index = false
    
    log4j.logger.com.atlassian.jira.project = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.project = false
    
    log4j.logger.com.atlassian.jira.project.version = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.project.version = false
    
    log4j.logger.com.atlassian.jira.user.job.RefreshActiveUserCountJob = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.user.job.RefreshActiveUserCountJob = false
    
    log4j.logger.com.atlassian.jira.issue.search.providers = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.issue.search.providers = false
    
    log4j.logger.com.atlassian.jira.issue.search.providers.LuceneSearchProvider_SLOW = INFO, slowquerylog
    log4j.additivity.com.atlassian.jira.issue.search.providers.LuceneSearchProvider_SLOW = false
    
    log4j.logger.com.atlassian.jira.action.admin = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.action.admin = false
    
    log4j.logger.com.opensymphony = WARN, console, filelog
    log4j.additivity.com.opensymphony = false
    
    log4j.logger.com.atlassian.jira.user = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.user = false
    
    log4j.logger.com.atlassian.jira.bc.user = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.bc.user = false
    
    log4j.logger.com.atlassian.jira.workflow = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.workflow = false
    
    log4j.logger.com.atlassian.jira.service = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.service = false
    
    log4j.logger.com.atlassian.jira.service.services.DebugService = DEBUG, console, filelog
    log4j.additivity.com.atlassian.jira.service.services.DebugService = false
    
    log4j.logger.com.atlassian.jira.web.dispatcher.JiraWebworkActionDispatcher = WARN, nowarnconsole, filelog
    log4j.additivity.com.atlassian.jira.web.dispatcher.JiraWebworkActionDispatcher = false
    log4j.logger.webwork = WARN, console, filelog
    log4j.additivity.webwork = false
    
    log4j.logger.webwork.util.ServletValueStack = WARN, console, filelog
    
    log4j.logger.org.ofbiz.core.entity.jdbc.DatabaseUtil = INFO, nowarnconsole, filelog
    log4j.additivity.org.ofbiz.core.entity.jdbc.DatabaseUtil = false
    log4j.logger.org.ofbiz = WARN, console, filelog
    log4j.additivity.org.ofbiz = false
    
    log4j.logger.com.atlassian.jira.web.servlet.rpc = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.web.servlet.rpc = false
    log4j.logger.com.atlassian.jira.soap = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.soap = false
    log4j.logger.com.atlassian.jira.rpc = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.rpc = false
    
    log4j.logger.com.atlassian.jira.plugin.ext.perforce = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.plugin.ext.perforce = false
    
    log4j.logger.jelly = INFO, console, filelog
    log4j.additivity.jelly = false
    
    log4j.logger.logMessage.jsp = INFO, console, filelog
    log4j.additivity.logMessage.jsp = false
    
    log4j.logger.com.atlassian.jira.issue.views = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.issue.views = false
    
    # Project Imports should be logged at INFO level so we can see the steps running.
    log4j.logger.com.atlassian.jira.imports.project = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.imports.project = false
    
    log4j.logger.com.atlassian.jira.plugin.userformat.DefaultUserFormats = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.plugin.userformat.DefaultUserFormats = false
    
    log4j.logger.com.atlassian.jira.scheduler.JiraSchedulerLauncher = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.scheduler.JiraSchedulerLauncher = false
    
    log4j.logger.com.atlassian.sal.jira.scheduling = INFO, console, filelog
    log4j.additivity.com.atlassian.sal.jira.scheduling = false
    
    #####################################################
    # Crowd Embedded
    #####################################################
    
    # We want to get INFO level logs about Directory events
    log4j.logger.com.atlassian.crowd.directory = INFO, console, filelog
    log4j.additivity.com.atlassian.crowd.directory = false
    
    #####################################################
    # REST
    #####################################################
    
    # only show WARN for WADL generation doclet
    log4j.logger.com.atlassian.plugins.rest.doclet = WARN, console, filelog
    log4j.additivity.com.atlassian.plugins.rest.doclet = false
    
    # JRADEV-12012: suppress irrelevant warnings.
    log4j.logger.com.sun.jersey.spi.container.servlet.WebComponent = ERROR, console, filelog
    log4j.additivity.com.sun.jersey.spi.container.servlet.WebComponent = false
    
    #####################################################
    # JQL
    #####################################################
    
    log4j.logger.com.atlassian.jira.jql  = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.jql = false
    
    log4j.logger.com.atlassian.jira.jql.resolver = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.jql.resolver = false
    
    #####################################################
    # UAL
    #####################################################
    
    log4j.logger.com.atlassian.applinks  = WARN, console, filelog
    log4j.additivity.com.atlassian.applinks = false
    
    #####################################################
    # ActiveObjects
    #####################################################
    
    log4j.logger.net.java.ao  = WARN, console, filelog
    log4j.additivity.net.java.ao = false
    
    log4j.logger.net.java.ao.sql  = WARN, console, filelog
    log4j.additivity.net.java.ao.sql = false
    
    #####################################################
    # Long Running Tasks
    #####################################################
    
    log4j.logger.com.atlassian.jira.workflow.migration  = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.workflow.migration = false
    
    log4j.logger.com.atlassian.jira.web.action.admin.index.IndexAdminImpl = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.web.action.admin.index.IndexAdminImpl = false
    
    #####################################################
    # PROFILING
    #####################################################
    
    log4j.logger.com.atlassian.util.profiling.filters = INFO, console, filelog
    log4j.additivity.com.atlassian.util.profiling.filters = false
    
    log4j.logger.com.atlassian.util.profiling = DEBUG, console, filelog
    log4j.additivity.com.atlassian.util.profiling = false
    
    log4j.logger.com.atlassian.jira.web.filters.ThreadLocalQueryProfiler = DEBUG, console, filelog
    log4j.additivity.com.atlassian.jira.web.filters.ThreadLocalQueryProfiler = false
    
    #
    # By default we ignore some usually harmless exception such as Client Abort Exceptions.  However
    # if this proves problematic then we can turn this to DEBUG log on.
    #
    log4j.logger.com.atlassian.jira.web.exception.WebExceptionChecker = OFF, console, filelog
    log4j.additivity.com.atlassian.jira.web.exception.WebExceptionChecker = false
    
    #
    # Errors in the logs occur at this logger if the user cancels a form upload. The actual exception
    # is rethrown and dealt with elsewhere so there is no need to keep these logs around.
    #
    log4j.logger.webwork.multipart.MultiPartRequestWrapper = OFF, console, filelog
    log4j.additivity.webwork.multipart.MultiPartRequestWrapper = false
    
    log4j.logger.com.atlassian.jira.plugins.monitor = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.plugins.monitor = false
    
    #####################################################
    # Mails
    #####################################################
    
    #
    # outgoing mail log includes also some logging information from classes which handle both incoming and outgoing mails
    # that's why the appender is configured at com.atlassian.mail level (not com.atlassian.mail.outgoing)
    #
    log4j.logger.com.atlassian.mail = INFO, console, outgoingmaillog
    log4j.additivity.com.atlassian.mail = false
    
    log4j.logger.com.atlassian.mail.incoming = INFO, console, incomingmaillog
    log4j.additivity.com.atlassian.mail.incoming = false
    
    # changes in mail settings need to be logged
    log4j.logger.com.atlassian.jira.mail.settings.MailSetting = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.mail.settings.MailSetting = false
    
    #
    # Need to ensure that the actual discovery of duplicates is logged
    #
    log4j.logger.com.atlassian.jira.upgrade.tasks.UpgradeTask_Build663 = INFO, console, filelog
    log4j.additivity.com.atlassian.jira.upgrade.tasks.UpgradeTask_Build663 = false
    
    # JRADEV-19240: Suppress useless warnings (will be fixed in atlassian-soy-templates-2.0.0, see SOY-18)
    log4j.logger.com.atlassian.soy.impl.GetTextFunction = ERROR, console, filelog
    log4j.additivity.com.atlassian.soy.impl.GetTextFunction = false
    
    # JRADEV-19613: Remote should log security messages to a separate log file
    log4j.logger.com.atlassian.plugin.remotable.plugin.module.oauth.OAuth2LOAuthenticator = INFO, console, remoteappssecurity
    log4j.additivity.com.atlassian.plugin.remotable.plugin.module.oauth.OAuth2LOAuthenticator = false
    
    log4j.logger.com.atlassian.plugin.remotable.plugin.module.permission.ApiScopingFilter = INFO, console, remoteappssecurity
    log4j.additivity.com.atlassian.plugin.remotable.plugin.module.permission.ApiScopingFilter = false
    
    log4j.logger.com.atlassian.plugin.remotable.plugin.OAuthLinkManager = INFO, console, remoteappssecurity
    log4j.additivity.com.atlassian.plugin.remotable.plugin.OAuthLinkManager = false
    
    log4j.logger.com.atlassian.plugin.remotable.plugin.util.http.CachingHttpContentRetriever = INFO, console, remoteappssecurity
    log4j.additivity.com.atlassian.plugin.remotable.plugin.util.http.CachingHttpContentRetriever = false
    
    log4j.logger.com.atlassian.plugin.remotable.plugin.service.LocalSignedRequestHandler = INFO, console, remoteappssecurity
    log4j.additivity.com.atlassian.plugin.remotable.plugin.service.LocalSignedRequestHandler = false
    
    log4j.logger.com.atlassian.plugin.remotable.host.common.service.http.bigpipe.DefaultBigPipeManager = INFO, console, remoteappssecurity
    log4j.additivity.com.atlassian.plugin.remotable.host.common.service.http.bigpipe.DefaultBigPipeManager = false
    
    log4j.logger.com.example.tutorial.plugins = DEBUG, console, filelog
    log4j.additivity.com.example.tutorial.plugins = false
    
    

    The key lines are the last two. Instead of adding this file as an alternative build resource for your plugin, you can simply add the last two lines to the log4j.properties file that comes with the version of JIRA you are using.

  5. Save any changed files, if you haven't already, since you'll try out your plugin next.

Step 5. Try it out

Now you're ready to try out the plugin:

  1. Open a terminal and change to the project root directory (where the pom.xml file is located).
  2. Enter the following SDK command:

    atlas-run
  3. When JIRA finishes starting up, open the JIRA home page in a browser.
  4. Create a new project based on the Software Development project type. This gives us the workflow we need to try out each event type, that is, one that includes transitions for resolving and closing issues.  
  5. While keeping an eye on the terminal where you started JIRA, try creating an issue and then resolving it. You should see an event logged to the terminal output, like this:

    [INFO] [talledLocalContainer] 2013-07-24 12:52:42,347 http-2990-3 INFO admin 772x1164x1 slv00c 127.0.1.1 /secure/QuickCreateIssue.jspa [example.tutorial.plugins.IssueCreatedResolvedListener] Issue TST-1 has been created at 2013-07-24 12:52:42.105.
    [INFO] [talledLocalContainer] 2013-07-24 17:11:42,562 http-2990-8 INFO admin 1031x1858x1 slv00c 127.0.1.1 /secure/CommentAssignIssue.jspa [example.tutorial.plugins.IssueCreatedResolvedListener] Issue TST-1 has been resolved at 2013-07-24 17:11:42.512.

    If you miss the log message in the terminal output, you can check the log file on disk in the following directory: the target/container/tomcat6x/cargo-jira-home/logs.

It works! However, it's not yet ready for prime time. We have a little more to do to make sure that our event listener plays well given the normal plugin lifecycle in a production deployment, as described next. You can keep JIRA running while you continue your work. 

Step 6. Mind the plugin lifecycle

More information about the plugin lifecycle is available in our guide to the JIRA Plugin Lifecycle

The code so far makes two naive assumptions about the plugin lifecycle:

  1. The constructor will only ever be called once, and
  2. The plugin will only shut down when the system itself shuts down

Neither is true. Plugins should expect to be enabled or disabled at any time. Since our plugin registers with an external service, this needs to be accounted for.

In the plugin system itself, Atlassian plugins are implemented as Spring dynamic modules, and the atlassian-plugin.xml is transformed into a Spring XML bean configuration before it is loaded by the product. In most cases, plugin developers don't need to worry about this. In our case, we do. As a <component>, IssueCreatedResolvedListener will become a Spring bean, so we can apply the Spring interfaces InitializingBean and DisposableBean. Spring guarantees that the bean – in this case, our listener class – will have a chance to get its act together before it's put into active service, or retired from it.

To coordinate our sample event listener with the plugin lifecyle, replace the IssueCreatedResolvedListener.java contents with the following:

package com.example.tutorial.plugins;

import com.atlassian.event.api.EventListener;
import com.atlassian.event.api.EventPublisher;
import com.atlassian.jira.event.issue.IssueEvent;
import com.atlassian.jira.event.type.EventType;
import com.atlassian.jira.issue.Issue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

/**
 * Simple JIRA listener using the atlassian-event library and demonstrating
 * plugin lifecycle integration.
 */
public class IssueCreatedResolvedListener implements InitializingBean, DisposableBean {

    private static final Logger log = LoggerFactory.getLogger(IssueCreatedResolvedListener.class);

    private final EventPublisher eventPublisher;

    /**
     * Constructor.
     * @param eventPublisher injected {@code EventPublisher} implementation.
     */
    public IssueCreatedResolvedListener(EventPublisher eventPublisher) {
        this.eventPublisher = eventPublisher;
    }

    /**
     * Called when the plugin has been enabled.
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        // register ourselves with the EventPublisher
        eventPublisher.register(this);
    }

    /**
     * Called when the plugin is being disabled or removed.
     * @throws Exception
     */
    @Override
    public void destroy() throws Exception {
        // unregister ourselves with the EventPublisher
        eventPublisher.unregister(this);
    }

    /**
     * Receives any {@code IssueEvent}s sent by JIRA.
     * @param issueEvent the IssueEvent passed to us
     */
    @EventListener
    public void onIssueEvent(IssueEvent issueEvent) {
        Long eventTypeId = issueEvent.getEventTypeId();
        Issue issue = issueEvent.getIssue();
        // if it's an event we're interested in, log it
        if (eventTypeId.equals(EventType.ISSUE_CREATED_ID)) {
            log.info("Issue {} has been created at {}.", issue.getKey(), issue.getCreated());
        } else if (eventTypeId.equals(EventType.ISSUE_RESOLVED_ID)) {
            log.info("Issue {} has been resolved at {}.", issue.getKey(), issue.getResolutionDate());
        } else if (eventTypeId.equals(EventType.ISSUE_CLOSED_ID)) {
            log.info("Issue {} has been closed at {}.", issue.getKey(), issue.getUpdated());
        }
    }
}

Here, we've moved the EventPublisher reference to a member variable and bound the registration to the afterPropertiesSet()/destroy() methods, which come from InitializingBean and DisposableBean respectively. This guarantees the correct behaviour even when our plugin is disabled and later re-enabled, perhaps by an administrator using the Universal Plugin Manager.

Re-install the plugin using FastDev, the pi command, or by restarting JIRA, and try it out again. As before, make sure that your plugin logs issue created, resolved, and closed events as expected.

Next Steps

Although writing a listener as explained here has the advantage of working inside a fully-fledged plugin, it doesn't support the properties feature of legacy (pre-4.0) JIRA listeners. In those listeners, administrators could set properties to configure a listener. For example, a listener that forwarded issue events to IRC might have properties for the IRC server, username and password to use. Atlassian event listeners don't automatically integrate with the JIRA listener configuration screen.

To make your listener configurable by a JIRA administrator, implement your own administration page that can configure not only your listener but any other information your users might need to input. For guidance on how to do this, see Writing an Admin Configuration Screen.

Was this page helpful?

Have a question about this article?

See questions about this article

Powered by Confluence and Scroll Viewport