1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.logging.log4j.core.config.plugins.osgi;
19
20 import org.apache.logging.log4j.LogManager;
21 import org.apache.logging.log4j.Logger;
22 import org.apache.logging.log4j.core.config.plugins.util.PluginManager;
23 import org.apache.logging.log4j.core.impl.Log4jContextFactory;
24 import org.apache.logging.log4j.core.util.BundleResourceLoader;
25 import org.apache.logging.log4j.simple.SimpleLoggerContextFactory;
26 import org.apache.logging.log4j.spi.LoggerContextFactory;
27 import org.apache.logging.log4j.status.StatusLogger;
28 import org.osgi.framework.Bundle;
29 import org.osgi.framework.BundleContext;
30 import org.osgi.framework.BundleEvent;
31 import org.osgi.framework.BundleListener;
32
33
34
35
36 public final class Activator implements org.osgi.framework.BundleActivator {
37
38 private static final Logger LOGGER = StatusLogger.getLogger();
39
40 @Override
41 public void start(final BundleContext context) throws Exception {
42 registerLoggerContextFactory();
43 context.addBundleListener(new Listener());
44
45 scanInstalledBundlesForPlugins(context);
46 }
47
48 private void registerLoggerContextFactory() {
49 final LoggerContextFactory current = LogManager.getFactory();
50 if (!(current instanceof Log4jContextFactory)) {
51 LOGGER.debug("Replacing LogManager LoggerContextFactory.");
52 LogManager.setFactory(new Log4jContextFactory());
53 }
54 }
55
56 private void scanInstalledBundlesForPlugins(final BundleContext context) {
57 final Bundle[] bundles = context.getBundles();
58 for (final Bundle bundle : bundles) {
59 if (bundle.getState() == Bundle.ACTIVE) {
60
61 scanBundleForPlugins(bundle);
62 }
63 }
64 }
65
66 private static void scanBundleForPlugins(final Bundle bundle) {
67 LOGGER.debug("Scanning bundle [{}] for plugins.", bundle.getSymbolicName());
68 PluginManager.loadPlugins(new BundleResourceLoader(bundle));
69 }
70
71 @Override
72 public void stop(final BundleContext context) throws Exception {
73 unregisterLoggerContextFactory();
74 }
75
76 private void unregisterLoggerContextFactory() {
77 LogManager.setFactory(new SimpleLoggerContextFactory());
78 }
79
80 private static class Listener implements BundleListener {
81
82 @Override
83 public void bundleChanged(final BundleEvent event) {
84 switch (event.getType()) {
85 case BundleEvent.STARTED:
86 scanBundleForPlugins(event.getBundle());
87 break;
88
89 default:
90 break;
91 }
92 }
93 }
94 }