--- /dev/null
+package org.argeo.eclipse.spring;\r
+\r
+import static java.text.MessageFormat.format;\r
+\r
+import org.osgi.framework.Bundle;\r
+import org.osgi.framework.BundleContext;\r
+import org.osgi.framework.FrameworkUtil;\r
+import org.osgi.framework.InvalidSyntaxException;\r
+import org.osgi.util.tracker.ServiceTracker;\r
+import org.springframework.context.ApplicationContext;\r
+\r
+/**\r
+ * @author Heiko Seeberger\r
+ */\r
+public class ApplicationContextTracker {\r
+\r
+ private static final String FILTER = "(&(objectClass=org.springframework.context.ApplicationContext)" //$NON-NLS-1$\r
+ + "(org.springframework.context.service.name={0}))"; //$NON-NLS-1$\r
+\r
+ private ServiceTracker applicationContextServiceTracker;\r
+\r
+ /**\r
+ * @param contributorBundle\r
+ * OSGi bundle for which the Spring application context is to be\r
+ * tracked. Must not be null!\r
+ * @param factoryBundleContext\r
+ * BundleContext object which can be used to track services\r
+ * @throws IllegalArgumentException\r
+ * if the given bundle is null.\r
+ */\r
+ public ApplicationContextTracker(final Bundle contributorBundle, final BundleContext factoryBundleContext) {\r
+ final String filter = format(FILTER, contributorBundle.getSymbolicName());\r
+ try {\r
+ applicationContextServiceTracker = new ServiceTracker(\r
+ factoryBundleContext, FrameworkUtil.createFilter(filter), null);\r
+ applicationContextServiceTracker.open();\r
+ } catch (final InvalidSyntaxException e) {\r
+ e.printStackTrace();\r
+ }\r
+ }\r
+\r
+ public void close() {\r
+ if (applicationContextServiceTracker != null) {\r
+ applicationContextServiceTracker.close();\r
+ }\r
+ }\r
+\r
+ public ApplicationContext getApplicationContext() {\r
+ ApplicationContext applicationContext = null;\r
+ if (applicationContextServiceTracker != null) {\r
+ try {\r
+ applicationContext = (ApplicationContext) applicationContextServiceTracker\r
+ .waitForService(5000);\r
+ } catch (InterruptedException e) {\r
+ e.printStackTrace();\r
+ }\r
+ }\r
+ return applicationContext;\r
+ }\r
+\r
+ @Override\r
+ protected void finalize() throws Throwable {\r
+ close();\r
+ super.finalize();\r
+ }\r
+}\r