1 package com.atlassian.plugin.osgi.spring;
2
3 import org.osgi.framework.BundleContext;
4 import org.osgi.framework.InvalidSyntaxException;
5 import org.osgi.framework.ServiceEvent;
6 import org.osgi.framework.ServiceListener;
7 import org.osgi.framework.ServiceReference;
8 import org.springframework.context.ApplicationEvent;
9 import org.springframework.context.ApplicationListener;
10 import org.springframework.context.event.SimpleApplicationEventMulticaster;
11 import org.springframework.context.event.ApplicationEventMulticaster;
12 import org.springframework.osgi.context.BundleContextAware;
13 import org.springframework.osgi.context.event.OsgiBundleApplicationContextEventMulticasterAdapter;
14 import org.springframework.osgi.context.event.OsgiBundleApplicationContextEvent;
15 import org.springframework.osgi.context.event.OsgiBundleApplicationContextListener;
16
17
18
19
20
21
22 public class PluginBridgeEventMulticaster extends OsgiBundleApplicationContextEventMulticasterAdapter implements BundleContextAware
23 {
24 private volatile OsgiBundleApplicationContextListener bridgeListener;
25
26 public PluginBridgeEventMulticaster()
27 {
28 super(new SimpleApplicationEventMulticaster());
29 }
30
31
32 @Override
33 public void multicastEvent(OsgiBundleApplicationContextEvent applicationEvent)
34 {
35 super.multicastEvent(applicationEvent);
36 if (bridgeListener != null)
37 bridgeListener.onOsgiApplicationEvent(applicationEvent);
38 }
39
40
41
42
43
44
45
46 public void setBundleContext(final BundleContext bundleContext)
47 {
48 String filter = "(&(objectClass=" + OsgiBundleApplicationContextListener.class.getName() + ")(plugin-bridge=true))";
49
50 ServiceReference[] refs;
51 try
52 {
53 refs = bundleContext.getAllServiceReferences(ApplicationListener.class.getName(), filter);
54 if (refs != null && refs.length == 1)
55 {
56 bridgeListener = (OsgiBundleApplicationContextListener) bundleContext.getService(refs[0]);
57 }
58
59
60 bundleContext.addServiceListener(new ServiceListener()
61 {
62
63 public void serviceChanged(ServiceEvent serviceEvent)
64 {
65 switch (serviceEvent.getType())
66 {
67 case ServiceEvent.REGISTERED :
68 bridgeListener = (OsgiBundleApplicationContextListener) bundleContext.getService(serviceEvent.getServiceReference());
69 break;
70 case ServiceEvent.UNREGISTERING :
71 bridgeListener = null;
72 break;
73 case ServiceEvent.MODIFIED :
74 bridgeListener = (OsgiBundleApplicationContextListener) bundleContext.getService(serviceEvent.getServiceReference());
75 break;
76 }
77 }
78 }, filter);
79 }
80 catch (InvalidSyntaxException e)
81 {
82
83 throw new RuntimeException("Invalid LDAP filter", e);
84 }
85 }
86 }