]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.init/src/org/argeo/init/osgi/ForeignModuleConnector.java
Improve runtime manager
[lgpl/argeo-commons.git] / org.argeo.init / src / org / argeo / init / osgi / ForeignModuleConnector.java
1 package org.argeo.init.osgi;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.util.List;
6 import java.util.Map;
7 import java.util.Optional;
8
9 import org.osgi.framework.Bundle;
10 import org.osgi.framework.BundleActivator;
11 import org.osgi.framework.BundleContext;
12 import org.osgi.framework.BundleException;
13 import org.osgi.framework.connect.ConnectContent;
14 import org.osgi.framework.connect.ConnectModule;
15 import org.osgi.framework.connect.ModuleConnector;
16
17 /**
18 * A {@link ModuleConnector} based on another OSGi runtime.
19 */
20 class ForeignModuleConnector implements ModuleConnector {
21 private final BundleContext foreignBundleContext;
22 private final List<String> foreignCategories;
23
24 private BundleContext localBundleContext;
25
26 public ForeignModuleConnector(BundleContext foreignBundleContext, List<String> foreignCategories) {
27 this.foreignBundleContext = foreignBundleContext;
28 this.foreignCategories = foreignCategories;
29 }
30
31 @Override
32 public Optional<BundleActivator> newBundleActivator() {
33 return Optional.of(new BundleActivator() {
34 @Override
35 public void start(BundleContext context) throws Exception {
36 ForeignModuleConnector.this.localBundleContext = context;
37 }
38
39 @Override
40 public void stop(BundleContext context) throws Exception {
41 ForeignModuleConnector.this.localBundleContext = null;
42 }
43
44 });
45 }
46
47 @Override
48 public void initialize(File storage, Map<String, String> configuration) {
49 }
50
51 @Override
52 public Optional<ConnectModule> connect(String location) throws BundleException {
53 // hacks
54 if (location.contains("org.eclipse.rap.rwt.osgi"))
55 return Optional.empty();
56
57 String category = categoryFromLocation(location);
58 if (category == null || !foreignCategories.contains(category))
59 return Optional.empty();
60 Bundle bundle = foreignBundleContext.getBundle(location);
61 if (bundle != null && bundle.getBundleId() != 0) {
62 // System.out.println("Foreign Bundle: " + bundle.getSymbolicName() + " " +
63 // location);
64 ConnectModule module = new ConnectModule() {
65
66 @Override
67 public ConnectContent getContent() throws IOException {
68 return new ForeignBundleConnectContent(localBundleContext, bundle);
69 }
70 };
71 return Optional.of(module);
72 }
73 return Optional.empty();
74 }
75
76 protected String categoryFromLocation(String location) {
77 // deal with Windows (sigh)
78 String regexp = File.separatorChar == '\\' ? "\\\\" : "/";
79 String[] arr = location.split(regexp);
80 if (arr.length < 2)
81 return null;
82 // TODO make it more robust
83 String category = arr[arr.length - 2];
84 return category;
85 }
86 }