CJ F
CJ F

Reputation: 835

Hook in to plugin service call

I have a plugin that executes a service call as a background process. That is, it does some action on a timer that is not related directly to any user action.

What I need to do is execute some code in the "main" application every time this service call finishes. Is there a way to hook into that plugin code? I have access to the plugin code, so altering it isn't a huge obstacle.

Upvotes: 0

Views: 107

Answers (1)

chrislatimer
chrislatimer

Reputation: 3560

You can have your plugin service publish an event when it completes then listen for that event in your main application. I have used this pattern a few times and it has been a very convenient way to decouple various pieces of of my application. To do this, create an event class.

class PluginEvent extends ApplicationEvent {
   public PluginEvent(source) {
      super(source)
   }
}

Then, have your plugin service implement ApplicationContextAware. That gives your plugin a way to publish your events

class PluginService implements ApplicationContextAware {
  def applicationContext

  def serviceMethod() {
     //do stuff
     publishPluginEvent()  
  }

  private void publishPluginEvent() {
    def event = new PluginEvent(this)
    applicationContext.publishEvent(event)
  }
}

Then in your main application, create a listener service that will respond when the event is published:

class ApplicationService implements ApplicationListener<PluginEvent> {
   void onApplicationEvent(PluginEvent event) {
     //whatever you want to do in your app when 
     // the plugin service fires.
   }
}

This listener doesn't need to be a Grails Service, you can just use a POJO/POGO, but you'll need to configure it as a spring bean inside resources.groovy.

I have been using this approach recently and it has worked well for me. It's definitely a nice tool to have in your Grails toolbox.

Upvotes: 2

Related Questions