]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.util/src/org/argeo/osgi/util/OsgiRegister.java
Rename into CMS Context
[lgpl/argeo-commons.git] / org.argeo.util / src / org / argeo / osgi / util / OsgiRegister.java
1 package org.argeo.osgi.util;
2
3 import java.util.ArrayList;
4 import java.util.Hashtable;
5 import java.util.List;
6 import java.util.Map;
7 import java.util.concurrent.CompletableFuture;
8 import java.util.concurrent.ExecutionException;
9 import java.util.concurrent.Executor;
10 import java.util.concurrent.ForkJoinPool;
11
12 import org.argeo.util.register.Register;
13 import org.argeo.util.register.Singleton;
14 import org.osgi.framework.BundleContext;
15 import org.osgi.framework.ServiceRegistration;
16
17 public class OsgiRegister implements Register {
18 private final BundleContext bundleContext;
19 private Executor executor;
20
21 private CompletableFuture<Void> shutdownStarting = new CompletableFuture<Void>();
22
23 public OsgiRegister(BundleContext bundleContext) {
24 this.bundleContext = bundleContext;
25 // TODO experiment with dedicated executors
26 this.executor = ForkJoinPool.commonPool();
27 }
28
29 @Override
30 public <T> Singleton<T> set(T obj, Class<T> clss, Map<String, Object> attributes, Class<?>... classes) {
31 CompletableFuture<ServiceRegistration<?>> srf = new CompletableFuture<ServiceRegistration<?>>();
32 CompletableFuture<T> postRegistration = CompletableFuture.supplyAsync(() -> {
33 List<String> lst = new ArrayList<>();
34 lst.add(clss.getName());
35 for (Class<?> c : classes) {
36 lst.add(c.getName());
37 }
38 ServiceRegistration<?> sr = bundleContext.registerService(lst.toArray(new String[lst.size()]), obj,
39 new Hashtable<String, Object>(attributes));
40 srf.complete(sr);
41 return obj;
42 }, executor);
43 Singleton<T> singleton = new Singleton<T>(clss, postRegistration);
44
45 shutdownStarting. //
46 thenCompose(singleton::prepareUnregistration). //
47 thenRunAsync(() -> {
48 try {
49 srf.get().unregister();
50 } catch (InterruptedException | ExecutionException e) {
51 e.printStackTrace();
52 }
53 }, executor);
54 return singleton;
55 }
56
57 public void shutdown() {
58 shutdownStarting.complete(null);
59 }
60 }