aboutsummaryrefslogtreecommitdiffstats
path: root/jdisc_core/src/main/java/com/yahoo/jdisc/core/OsgiLogService.java
blob: bd908d77af52cf313b7195df4ca57b410c7ee414 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.core;

import org.osgi.framework.*;

/**
 * @author Simon Thoresen Hult
 */
class OsgiLogService {

    private ServiceRegistration<OsgiLogService> registration;

    public void start(BundleContext ctx) {
        if (registration != null) {
            throw new IllegalStateException();
        }
        ctx.addServiceListener(new ActivatorProxy(ctx));
        registration = ctx.registerService(OsgiLogService.class, this, null);
    }

    public void stop() {
        registration.unregister();
        registration = null;
    }

    private class ActivatorProxy implements ServiceListener {

        final BundleActivator activator = new org.apache.felix.log.Activator();
        final BundleContext ctx;

        ActivatorProxy(BundleContext ctx) {
            this.ctx = ctx;
        }

        @Override
        public void serviceChanged(ServiceEvent event) {
            if (ctx.getService(event.getServiceReference()) != OsgiLogService.this) {
                return;
            }
            switch (event.getType()) {
                case ServiceEvent.REGISTERED:
                    try {
                        activator.start(ctx);
                    } catch (Exception e) {
                        throw new RuntimeException("Exception thrown while starting " +
                                                   activator.getClass().getName() + ".", e);
                    }
                    break;
                case ServiceEvent.UNREGISTERING:
                    try {
                        activator.stop(ctx);
                    } catch (Exception e) {
                        throw new RuntimeException("Exception thrown while stopping " +
                                                   activator.getClass().getName() + ".", e);
                    }
                    break;
            }
        }
    }
}