package com.almworks.jira.structure.util;
import com.atlassian.plugin.ModuleDescriptor;
import com.atlassian.plugin.Plugin;
import com.atlassian.plugin.event.PluginEventListener;
import com.atlassian.plugin.event.PluginEventManager;
import com.atlassian.plugin.event.events.*;
/**
* @author Igor Sereda
*/
public final class ModuleStopListener {
private final PluginEventManager myPluginEventManager;
private final String myModuleKey;
private final Runnable myStop;
private final String myPluginKey;
private ModuleStopListener(PluginEventManager pluginEventManager, String pluginKey, String moduleKey, Runnable stop) {
myPluginEventManager = pluginEventManager;
myModuleKey = moduleKey;
myStop = stop;
myPluginKey = pluginKey;
}
public static void install(PluginEventManager pluginEventManager, String pluginKey, String moduleKey, Runnable stop) {
pluginEventManager.register(new ModuleStopListener(pluginEventManager, pluginKey, moduleKey, stop));
}
public void stop() {
myPluginEventManager.unregister(this);
if (myStop != null) myStop.run();
}
@PluginEventListener
public void onShutdown(PluginFrameworkShutdownEvent event) {
stop();
}
@PluginEventListener
public void onPluginDisabled(PluginDisabledEvent event) {
if (event == null) return;
stopIfMe(event.getPlugin());
}
@PluginEventListener
public void onFrameworkRestarting(PluginFrameworkWarmRestartingEvent event) {
stop();
}
@PluginEventListener
public void onModuleDisabled(PluginModuleDisabledEvent event) {
if (event == null) return;
ModuleDescriptor module = event.getModule();
if (module == null) return;
Plugin plugin = module.getPlugin();
if (plugin == null) return;
if (myPluginKey.equals(plugin.getKey()) && myModuleKey.equals(module.getKey())) {
stop();
}
}
@PluginEventListener
public void onPluginUninstalledEvent(PluginUninstalledEvent event) {
if (event == null) return;
stopIfMe(event.getPlugin());
}
@PluginEventListener
public void onPluginRefreshedEvent(PluginRefreshedEvent event) {
if (event == null) return;
stopIfMe(event.getPlugin());
}
protected void stopIfMe(Plugin plugin) {
if (plugin == null) return;
if (myPluginKey.equals(plugin.getKey())) {
stop();
}
}
}