1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.logging.log4j.core.osgi;
19
20 import java.util.concurrent.atomic.AtomicReference;
21
22 import org.apache.logging.log4j.LogManager;
23 import org.apache.logging.log4j.Logger;
24 import org.apache.logging.log4j.core.config.plugins.util.PluginRegistry;
25 import org.apache.logging.log4j.core.util.Constants;
26 import org.apache.logging.log4j.status.StatusLogger;
27 import org.apache.logging.log4j.util.PropertiesUtil;
28 import org.osgi.framework.Bundle;
29 import org.osgi.framework.BundleActivator;
30 import org.osgi.framework.BundleContext;
31 import org.osgi.framework.BundleEvent;
32 import org.osgi.framework.SynchronousBundleListener;
33 import org.osgi.framework.wiring.BundleWiring;
34
35
36
37
38 public final class Activator implements BundleActivator, SynchronousBundleListener {
39
40 private static final Logger LOGGER = StatusLogger.getLogger();
41
42 private final AtomicReference<BundleContext> contextRef = new AtomicReference<>();
43
44 @Override
45 public void start(final BundleContext context) throws Exception {
46
47 if (PropertiesUtil.getProperties().getStringProperty(Constants.LOG4J_CONTEXT_SELECTOR) == null) {
48 System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, BundleContextSelector.class.getName());
49 }
50 if (this.contextRef.compareAndSet(null, context)) {
51 context.addBundleListener(this);
52
53 scanInstalledBundlesForPlugins(context);
54 }
55 }
56
57 private static void scanInstalledBundlesForPlugins(final BundleContext context) {
58 final Bundle[] bundles = context.getBundles();
59 for (final Bundle bundle : bundles) {
60
61 if (bundle.getState() == Bundle.ACTIVE && bundle.getBundleId() != 0) {
62
63 scanBundleForPlugins(bundle);
64 }
65 }
66 }
67
68 private static void scanBundleForPlugins(final Bundle bundle) {
69 LOGGER.trace("Scanning bundle [{}] for plugins.", bundle.getSymbolicName());
70 PluginRegistry.getInstance().loadFromBundle(bundle.getBundleId(),
71 bundle.adapt(BundleWiring.class).getClassLoader());
72 }
73
74 private static void stopBundlePlugins(final Bundle bundle) {
75 LOGGER.trace("Stopping bundle [{}] plugins.", bundle.getSymbolicName());
76
77 PluginRegistry.getInstance().clearBundlePlugins(bundle.getBundleId());
78 }
79
80 @Override
81 public void stop(final BundleContext context) throws Exception {
82 this.contextRef.compareAndSet(context, null);
83 LogManager.shutdown();
84 }
85
86 @Override
87 public void bundleChanged(final BundleEvent event) {
88 switch (event.getType()) {
89
90 case BundleEvent.STARTED:
91 scanBundleForPlugins(event.getBundle());
92 break;
93
94 case BundleEvent.STOPPING:
95 stopBundlePlugins(event.getBundle());
96 break;
97
98 default:
99 break;
100 }
101 }
102 }