]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.init/src/org/argeo/init/osgi/OsgiBoot.java
Disable OSGi configuration admin and LDIF-based deploy config.
[lgpl/argeo-commons.git] / org.argeo.init / src / org / argeo / init / osgi / OsgiBoot.java
1 package org.argeo.init.osgi;
2
3 import static org.argeo.init.osgi.OsgiBootUtils.debug;
4 import static org.argeo.init.osgi.OsgiBootUtils.warn;
5
6 import java.io.File;
7 import java.net.MalformedURLException;
8 import java.net.URL;
9 import java.nio.file.FileSystems;
10 import java.nio.file.Files;
11 import java.nio.file.Path;
12 import java.nio.file.PathMatcher;
13 import java.nio.file.Paths;
14 import java.util.ArrayList;
15 import java.util.HashMap;
16 import java.util.Iterator;
17 import java.util.List;
18 import java.util.Map;
19 import java.util.Properties;
20 import java.util.Set;
21 import java.util.SortedMap;
22 import java.util.StringTokenizer;
23 import java.util.TreeMap;
24
25 import org.argeo.init.a2.A2Source;
26 import org.argeo.init.a2.ProvisioningManager;
27 import org.osgi.framework.Bundle;
28 import org.osgi.framework.BundleContext;
29 import org.osgi.framework.BundleException;
30 import org.osgi.framework.FrameworkEvent;
31 import org.osgi.framework.Version;
32 import org.osgi.framework.startlevel.BundleStartLevel;
33 import org.osgi.framework.startlevel.FrameworkStartLevel;
34 import org.osgi.framework.wiring.FrameworkWiring;
35
36 /**
37 * Basic provisioning of an OSGi runtime via file path patterns and system
38 * properties. The approach is to generate list of URLs based on various
39 * methods, configured via properties.
40 */
41 public class OsgiBoot implements OsgiBootConstants {
42 public final static String PROP_ARGEO_OSGI_START = "argeo.osgi.start";
43 public final static String PROP_ARGEO_OSGI_SOURCES = "argeo.osgi.sources";
44
45 public final static String PROP_ARGEO_OSGI_BUNDLES = "argeo.osgi.bundles";
46 public final static String PROP_ARGEO_OSGI_BASE_URL = "argeo.osgi.baseUrl";
47 public final static String PROP_ARGEO_OSGI_LOCAL_CACHE = "argeo.osgi.localCache";
48 public final static String PROP_ARGEO_OSGI_DISTRIBUTION_URL = "argeo.osgi.distributionUrl";
49
50 // booleans
51 public final static String PROP_ARGEO_OSGI_BOOT_DEBUG = "argeo.osgi.boot.debug";
52 // public final static String PROP_ARGEO_OSGI_BOOT_EXCLUDE_SVN =
53 // "argeo.osgi.boot.excludeSvn";
54
55 public final static String PROP_ARGEO_OSGI_BOOT_SYSTEM_PROPERTIES_FILE = "argeo.osgi.boot.systemPropertiesFile";
56 public final static String PROP_ARGEO_OSGI_BOOT_APPCLASS = "argeo.osgi.boot.appclass";
57 public final static String PROP_ARGEO_OSGI_BOOT_APPARGS = "argeo.osgi.boot.appargs";
58
59 public final static String DEFAULT_BASE_URL = "reference:file:";
60 // public final static String EXCLUDES_SVN_PATTERN = "**/.svn/**";
61
62 // OSGi standard properties
63 final static String PROP_OSGI_BUNDLES_DEFAULTSTARTLEVEL = "osgi.bundles.defaultStartLevel";
64 final static String PROP_OSGI_STARTLEVEL = "osgi.startLevel";
65 final static String PROP_OSGI_INSTANCE_AREA = "osgi.instance.area";
66 final static String PROP_OSGI_CONFIGURATION_AREA = "osgi.configuration.area";
67 final static String PROP_OSGI_USE_SYSTEM_PROPERTIES = "osgi.framework.useSystemProperties";
68
69 // Symbolic names
70 public final static String SYMBOLIC_NAME_OSGI_BOOT = "org.argeo.osgi.boot";
71 public final static String SYMBOLIC_NAME_EQUINOX = "org.eclipse.osgi";
72
73 /** Exclude svn metadata implicitely(a bit costly) */
74 // private boolean excludeSvn =
75 // Boolean.valueOf(System.getProperty(PROP_ARGEO_OSGI_BOOT_EXCLUDE_SVN,
76 // "false"))
77 // .booleanValue();
78
79 // /** Default is 10s */
80 // @Deprecated
81 // private long defaultTimeout = 10000l;
82
83 private final BundleContext bundleContext;
84 private final String localCache;
85
86 private final ProvisioningManager provisioningManager;
87
88 /*
89 * INITIALIZATION
90 */
91 /** Constructor */
92 public OsgiBoot(BundleContext bundleContext) {
93 this.bundleContext = bundleContext;
94 Path homePath = Paths.get(System.getProperty("user.home")).toAbsolutePath();
95 String homeUri = homePath.toUri().toString();
96 localCache = getProperty(PROP_ARGEO_OSGI_LOCAL_CACHE, homeUri + ".m2/repository/");
97
98 provisioningManager = new ProvisioningManager(bundleContext);
99 String sources = getProperty(PROP_ARGEO_OSGI_SOURCES);
100 if (sources == null) {
101 provisioningManager.registerDefaultSource();
102 } else {
103 for (String source : sources.split(",")) {
104 if (source.trim().equals(A2Source.DEFAULT_A2_URI)) {
105 if (Files.exists(homePath))
106 provisioningManager
107 .registerSource(A2Source.SCHEME_A2 + "://" + homePath.toString() + "/.local/share/a2");
108 provisioningManager.registerSource(A2Source.SCHEME_A2 + ":///usr/local/share/a2");
109 provisioningManager.registerSource(A2Source.SCHEME_A2 + ":///usr/share/a2");
110 } else {
111 provisioningManager.registerSource(source);
112 }
113 }
114 }
115 }
116
117 ProvisioningManager getProvisioningManager() {
118 return provisioningManager;
119 }
120
121 /*
122 * HIGH-LEVEL METHODS
123 */
124 /**
125 * Bootstraps the OSGi runtime using these properties, which MUST be consistent
126 * with {@link BundleContext#getProperty(String)}. If these properties are
127 * <code>null</code>, system properties are used instead.
128 */
129 public void bootstrap(Map<String, String> properties) {
130 try {
131 long begin = System.currentTimeMillis();
132 // check properties
133 if (properties != null) {
134 for (String property : properties.keySet()) {
135 String value = properties.get(property);
136 String bcValue = bundleContext.getProperty(property);
137 if (PROP_OSGI_CONFIGURATION_AREA.equals(property) || PROP_OSGI_INSTANCE_AREA.equals(property)) {
138 try {
139 URL uri = new URL(value);
140 URL bcUri = new URL(bcValue);
141 if (!uri.equals(bcUri))
142 throw new IllegalArgumentException("Property " + property + "=" + uri
143 + " is inconsistent with bundle context : " + bcUri);
144 } catch (MalformedURLException e) {
145 throw new IllegalArgumentException("Malformed property " + property, e);
146 }
147
148 } else {
149 if (!value.equals(bcValue))
150 throw new IllegalArgumentException("Property " + property + "=" + value
151 + " is inconsistent with bundle context : " + bcValue);
152 }
153 }
154 } else {
155 String useSystemProperties = bundleContext.getProperty(PROP_OSGI_USE_SYSTEM_PROPERTIES);
156 if (useSystemProperties == null || !useSystemProperties.equals("true")) {
157 OsgiBootUtils.warn("No properties passed but " + PROP_OSGI_USE_SYSTEM_PROPERTIES + " is not set.");
158 }
159 }
160
161 // notify start
162 System.out.println();
163 String osgiInstancePath = bundleContext.getProperty(PROP_OSGI_INSTANCE_AREA);
164 OsgiBootUtils
165 .info("OSGi bootstrap starting" + (osgiInstancePath != null ? " (" + osgiInstancePath + ")" : ""));
166 installUrls(getBundlesUrls());
167 installUrls(getDistributionUrls());
168 provisioningManager.install(null);
169 if (properties != null)
170 startBundles(properties);
171 else
172 startBundles();
173 long duration = System.currentTimeMillis() - begin;
174 OsgiBootUtils.info("OSGi bootstrap completed in " + Math.round(((double) duration) / 1000) + "s ("
175 + duration + "ms), " + bundleContext.getBundles().length + " bundles");
176 } catch (RuntimeException e) {
177 OsgiBootUtils.error("OSGi bootstrap FAILED", e);
178 throw e;
179 }
180
181 // diagnostics
182 if (OsgiBootUtils.isDebug()) {
183 OsgiBootDiagnostics diagnostics = new OsgiBootDiagnostics(bundleContext);
184 diagnostics.checkUnresolved();
185 Map<String, Set<String>> duplicatePackages = diagnostics.findPackagesExportedTwice();
186 if (duplicatePackages.size() > 0) {
187 OsgiBootUtils.info("Packages exported twice:");
188 Iterator<String> it = duplicatePackages.keySet().iterator();
189 while (it.hasNext()) {
190 String pkgName = it.next();
191 OsgiBootUtils.info(pkgName);
192 Set<String> bdles = duplicatePackages.get(pkgName);
193 Iterator<String> bdlesIt = bdles.iterator();
194 while (bdlesIt.hasNext())
195 OsgiBootUtils.info(" " + bdlesIt.next());
196 }
197 }
198 }
199 System.out.println();
200 }
201
202 /**
203 * Calls {@link #bootstrap(Map)} with <code>null</code>.
204 *
205 * @see #bootstrap(Map)
206 */
207 @Deprecated
208 public void bootstrap() {
209 bootstrap(null);
210 }
211
212 public void update() {
213 provisioningManager.update();
214 }
215
216 /*
217 * INSTALLATION
218 */
219 /** Install a single url. Convenience method. */
220 public Bundle installUrl(String url) {
221 List<String> urls = new ArrayList<String>();
222 urls.add(url);
223 installUrls(urls);
224 return (Bundle) getBundlesByLocation().get(url);
225 }
226
227 /** Install the bundles at this URL list. */
228 public void installUrls(List<String> urls) {
229 Map<String, Bundle> installedBundles = getBundlesByLocation();
230 for (int i = 0; i < urls.size(); i++) {
231 String url = (String) urls.get(i);
232 installUrl(url, installedBundles);
233 }
234 refreshFramework();
235 }
236
237 /** Actually install the provided URL */
238 protected void installUrl(String url, Map<String, Bundle> installedBundles) {
239 try {
240 if (installedBundles.containsKey(url)) {
241 Bundle bundle = (Bundle) installedBundles.get(url);
242 if (OsgiBootUtils.isDebug())
243 debug("Bundle " + bundle.getSymbolicName() + " already installed from " + url);
244 } else if (url.contains("/" + SYMBOLIC_NAME_EQUINOX + "/")
245 || url.contains("/" + SYMBOLIC_NAME_OSGI_BOOT + "/")) {
246 if (OsgiBootUtils.isDebug())
247 warn("Skip " + url);
248 return;
249 } else {
250 Bundle bundle = bundleContext.installBundle(url);
251 if (url.startsWith("http"))
252 OsgiBootUtils
253 .info("Installed " + bundle.getSymbolicName() + "-" + bundle.getVersion() + " from " + url);
254 else if (OsgiBootUtils.isDebug())
255 OsgiBootUtils.debug(
256 "Installed " + bundle.getSymbolicName() + "-" + bundle.getVersion() + " from " + url);
257 assert bundle.getSymbolicName() != null;
258 // uninstall previous versions
259 bundles: for (Bundle b : bundleContext.getBundles()) {
260 if (b.getSymbolicName() == null)
261 continue bundles;
262 if (bundle.getSymbolicName().equals(b.getSymbolicName())) {
263 Version bundleV = bundle.getVersion();
264 Version bV = b.getVersion();
265 if (bV == null)
266 continue bundles;
267 if (bundleV.getMajor() == bV.getMajor() && bundleV.getMinor() == bV.getMinor()) {
268 if (bundleV.getMicro() > bV.getMicro()) {
269 // uninstall older bundles
270 b.uninstall();
271 OsgiBootUtils.debug("Uninstalled " + b);
272 } else if (bundleV.getMicro() < bV.getMicro()) {
273 // uninstall just installed bundle if newer
274 bundle.uninstall();
275 OsgiBootUtils.debug("Uninstalled " + bundle);
276 break bundles;
277 } else {
278 // uninstall any other with same major/minor
279 if (!bundleV.getQualifier().equals(bV.getQualifier())) {
280 b.uninstall();
281 OsgiBootUtils.debug("Uninstalled " + b);
282 }
283 }
284 }
285 }
286 }
287 }
288 } catch (BundleException e) {
289 final String ALREADY_INSTALLED = "is already installed";
290 String message = e.getMessage();
291 if ((message.contains("Bundle \"" + SYMBOLIC_NAME_OSGI_BOOT + "\"")
292 || message.contains("Bundle \"" + SYMBOLIC_NAME_EQUINOX + "\""))
293 && message.contains(ALREADY_INSTALLED)) {
294 // silent, in order to avoid warnings: we know that both
295 // have already been installed...
296 } else {
297 if (message.contains(ALREADY_INSTALLED)) {
298 if (OsgiBootUtils.isDebug())
299 OsgiBootUtils.warn("Duplicate install from " + url + ": " + message);
300 } else
301 OsgiBootUtils.warn("Could not install bundle from " + url + ": " + message);
302 }
303 if (OsgiBootUtils.isDebug() && !message.contains(ALREADY_INSTALLED))
304 e.printStackTrace();
305 }
306 }
307
308 /*
309 * START
310 */
311 /**
312 * Start bundles based on system properties.
313 *
314 * @see OsgiBoot#startBundles(Map)
315 */
316 public void startBundles() {
317 Properties properties = System.getProperties();
318 startBundles(properties);
319 }
320
321 /**
322 * Start bundles based on these properties.
323 *
324 * @see OsgiBoot#startBundles(Map)
325 */
326 public void startBundles(Properties properties) {
327 Map<String, String> map = new TreeMap<>();
328 for (Object key : properties.keySet()) {
329 String property = key.toString();
330 if (property.startsWith(PROP_ARGEO_OSGI_START)) {
331 map.put(property, properties.getProperty(property));
332 }
333 }
334 startBundles(map);
335 }
336
337 /** Start bundle based on keys starting with {@link #PROP_ARGEO_OSGI_START}. */
338 public void startBundles(Map<String, String> properties) {
339 FrameworkStartLevel frameworkStartLevel = bundleContext.getBundle(0).adapt(FrameworkStartLevel.class);
340
341 // default and active start levels from System properties
342 Integer defaultStartLevel = Integer.parseInt(getProperty(PROP_OSGI_BUNDLES_DEFAULTSTARTLEVEL, "4"));
343 Integer activeStartLevel = Integer.parseInt(getProperty(PROP_OSGI_STARTLEVEL, "6"));
344
345 SortedMap<Integer, List<String>> startLevels = new TreeMap<Integer, List<String>>();
346 computeStartLevels(startLevels, properties, defaultStartLevel);
347 // inverts the map for the time being, TODO optimise
348 Map<String, Integer> bundleStartLevels = new HashMap<>();
349 for (Integer level : startLevels.keySet()) {
350 for (String bsn : startLevels.get(level))
351 bundleStartLevels.put(bsn, level);
352 }
353 for (Bundle bundle : bundleContext.getBundles()) {
354 String bsn = bundle.getSymbolicName();
355 if (bundleStartLevels.containsKey(bsn)) {
356 BundleStartLevel bundleStartLevel = bundle.adapt(BundleStartLevel.class);
357 Integer level = bundleStartLevels.get(bsn);
358 if (bundleStartLevel.getStartLevel() != level || !bundleStartLevel.isPersistentlyStarted()) {
359 bundleStartLevel.setStartLevel(level);
360 try {
361 bundle.start();
362 } catch (BundleException e) {
363 OsgiBootUtils.error("Cannot mark " + bsn + " as started", e);
364 }
365 if (OsgiBootUtils.isDebug())
366 OsgiBootUtils.debug(bsn + " starts at level " + level);
367 }
368 }
369 }
370 frameworkStartLevel.setStartLevel(activeStartLevel, (FrameworkEvent event) -> {
371 if (OsgiBootUtils.isDebug())
372 OsgiBootUtils.debug("Framework event: " + event);
373 int initialStartLevel = frameworkStartLevel.getInitialBundleStartLevel();
374 int startLevel = frameworkStartLevel.getStartLevel();
375 OsgiBootUtils.debug("Framework start level: " + startLevel + " (initial: " + initialStartLevel + ")");
376 });
377 }
378
379 private static void computeStartLevels(SortedMap<Integer, List<String>> startLevels, Map<String, String> properties,
380 Integer defaultStartLevel) {
381
382 // default (and previously, only behaviour)
383 appendToStartLevels(startLevels, defaultStartLevel, properties.getOrDefault(PROP_ARGEO_OSGI_START, ""));
384
385 // list argeo.osgi.start.* system properties
386 Iterator<String> keys = properties.keySet().iterator();
387 final String prefix = PROP_ARGEO_OSGI_START + ".";
388 while (keys.hasNext()) {
389 String key = keys.next();
390 if (key.startsWith(prefix)) {
391 Integer startLevel;
392 String suffix = key.substring(prefix.length());
393 String[] tokens = suffix.split("\\.");
394 if (tokens.length > 0 && !tokens[0].trim().equals(""))
395 try {
396 // first token is start level
397 startLevel = Integer.parseInt(tokens[0]);
398 } catch (NumberFormatException e) {
399 startLevel = defaultStartLevel;
400 }
401 else
402 startLevel = defaultStartLevel;
403
404 // append bundle names
405 String bundleNames = properties.get(key);
406 appendToStartLevels(startLevels, startLevel, bundleNames);
407 }
408 }
409 }
410
411 /** Append a comma-separated list of bundles to the start levels. */
412 private static void appendToStartLevels(SortedMap<Integer, List<String>> startLevels, Integer startLevel,
413 String str) {
414 if (str == null || str.trim().equals(""))
415 return;
416
417 if (!startLevels.containsKey(startLevel))
418 startLevels.put(startLevel, new ArrayList<String>());
419 String[] bundleNames = str.split(",");
420 for (int i = 0; i < bundleNames.length; i++) {
421 if (bundleNames[i] != null && !bundleNames[i].trim().equals(""))
422 (startLevels.get(startLevel)).add(bundleNames[i]);
423 }
424 }
425
426 // /**
427 // * Start the provided list of bundles
428 // *
429 // * @return whether all bundles are now in active state
430 // * @deprecated
431 // */
432 // @Deprecated
433 // public boolean startBundles(List<String> bundlesToStart) {
434 // if (bundlesToStart.size() == 0)
435 // return true;
436 //
437 // // used to monitor ACTIVE states
438 // List<Bundle> startedBundles = new ArrayList<Bundle>();
439 // // used to log the bundles not found
440 // List<String> notFoundBundles = new ArrayList<String>(bundlesToStart);
441 //
442 // Bundle[] bundles = bundleContext.getBundles();
443 // long startBegin = System.currentTimeMillis();
444 // for (int i = 0; i < bundles.length; i++) {
445 // Bundle bundle = bundles[i];
446 // String symbolicName = bundle.getSymbolicName();
447 // if (bundlesToStart.contains(symbolicName))
448 // try {
449 // try {
450 // bundle.start();
451 // if (OsgiBootUtils.isDebug())
452 // debug("Bundle " + symbolicName + " started");
453 // } catch (Exception e) {
454 // OsgiBootUtils.warn("Start of bundle " + symbolicName + " failed because of " + e
455 // + ", maybe bundle is not yet resolved," + " waiting and trying again.");
456 // waitForBundleResolvedOrActive(startBegin, bundle);
457 // bundle.start();
458 // startedBundles.add(bundle);
459 // }
460 // notFoundBundles.remove(symbolicName);
461 // } catch (Exception e) {
462 // OsgiBootUtils.warn("Bundle " + symbolicName + " cannot be started: " + e.getMessage());
463 // if (OsgiBootUtils.isDebug())
464 // e.printStackTrace();
465 // // was found even if start failed
466 // notFoundBundles.remove(symbolicName);
467 // }
468 // }
469 //
470 // for (int i = 0; i < notFoundBundles.size(); i++)
471 // OsgiBootUtils.warn("Bundle '" + notFoundBundles.get(i) + "' not started because it was not found.");
472 //
473 // // monitors that all bundles are started
474 // long beginMonitor = System.currentTimeMillis();
475 // boolean allStarted = !(startedBundles.size() > 0);
476 // List<String> notStarted = new ArrayList<String>();
477 // while (!allStarted && (System.currentTimeMillis() - beginMonitor) < defaultTimeout) {
478 // notStarted = new ArrayList<String>();
479 // allStarted = true;
480 // for (int i = 0; i < startedBundles.size(); i++) {
481 // Bundle bundle = (Bundle) startedBundles.get(i);
482 // // TODO check behaviour of lazs bundles
483 // if (bundle.getState() != Bundle.ACTIVE) {
484 // allStarted = false;
485 // notStarted.add(bundle.getSymbolicName());
486 // }
487 // }
488 // try {
489 // Thread.sleep(100);
490 // } catch (InterruptedException e) {
491 // // silent
492 // }
493 // }
494 // long duration = System.currentTimeMillis() - beginMonitor;
495 //
496 // if (!allStarted)
497 // for (int i = 0; i < notStarted.size(); i++)
498 // OsgiBootUtils.warn("Bundle '" + notStarted.get(i) + "' not ACTIVE after " + (duration / 1000) + "s");
499 //
500 // return allStarted;
501 // }
502
503 // /** Waits for a bundle to become active or resolved */
504 // @Deprecated
505 // private void waitForBundleResolvedOrActive(long startBegin, Bundle bundle) throws Exception {
506 // int originalState = bundle.getState();
507 // if ((originalState == Bundle.RESOLVED) || (originalState == Bundle.ACTIVE))
508 // return;
509 //
510 // String originalStateStr = OsgiBootUtils.stateAsString(originalState);
511 //
512 // int currentState = bundle.getState();
513 // while (!(currentState == Bundle.RESOLVED || currentState == Bundle.ACTIVE)) {
514 // long now = System.currentTimeMillis();
515 // if ((now - startBegin) > defaultTimeout * 10)
516 // throw new Exception("Bundle " + bundle.getSymbolicName() + " was not RESOLVED or ACTIVE after "
517 // + (now - startBegin) + "ms (originalState=" + originalStateStr + ", currentState="
518 // + OsgiBootUtils.stateAsString(currentState) + ")");
519 //
520 // try {
521 // Thread.sleep(100l);
522 // } catch (InterruptedException e) {
523 // // silent
524 // }
525 // currentState = bundle.getState();
526 // }
527 // }
528
529 /*
530 * BUNDLE PATTERNS INSTALLATION
531 */
532 /**
533 * Computes a list of URLs based on Ant-like include/exclude patterns defined by
534 * ${argeo.osgi.bundles} with the following format:<br>
535 * <code>/base/directory;in=*.jar;in=**;ex=org.eclipse.osgi_*;jar</code><br>
536 * WARNING: <code>/base/directory;in=*.jar,\</code> at the end of a file,
537 * without a new line causes a '.' to be appended with unexpected side effects.
538 */
539 public List<String> getBundlesUrls() {
540 String bundlePatterns = getProperty(PROP_ARGEO_OSGI_BUNDLES);
541 return getBundlesUrls(bundlePatterns);
542 }
543
544 /**
545 * Compute a list of URLs to install based on the provided patterns, with
546 * default base url
547 */
548 public List<String> getBundlesUrls(String bundlePatterns) {
549 String baseUrl = getProperty(PROP_ARGEO_OSGI_BASE_URL, DEFAULT_BASE_URL);
550 return getBundlesUrls(baseUrl, bundlePatterns);
551 }
552
553 /** Implements the path matching logic */
554 public List<String> getBundlesUrls(String baseUrl, String bundlePatterns) {
555 List<String> urls = new ArrayList<String>();
556 if (bundlePatterns == null)
557 return urls;
558
559 // bundlePatterns = SystemPropertyUtils.resolvePlaceholders(bundlePatterns);
560 if (OsgiBootUtils.isDebug())
561 debug(PROP_ARGEO_OSGI_BUNDLES + "=" + bundlePatterns);
562
563 StringTokenizer st = new StringTokenizer(bundlePatterns, ",");
564 List<BundlesSet> bundlesSets = new ArrayList<BundlesSet>();
565 while (st.hasMoreTokens()) {
566 String token = st.nextToken();
567 if (new File(token).exists()) {
568 String url = locationToUrl(baseUrl, token);
569 urls.add(url);
570 } else
571 bundlesSets.add(new BundlesSet(token));
572 }
573
574 // find included
575 List<String> included = new ArrayList<String>();
576 // PathMatcher matcher = new AntPathMatcher();
577 for (int i = 0; i < bundlesSets.size(); i++) {
578 BundlesSet bundlesSet = (BundlesSet) bundlesSets.get(i);
579 for (int j = 0; j < bundlesSet.getIncludes().size(); j++) {
580 String pattern = (String) bundlesSet.getIncludes().get(j);
581 match(included, bundlesSet.getDir(), null, pattern);
582 }
583 }
584
585 // find excluded
586 List<String> excluded = new ArrayList<String>();
587 for (int i = 0; i < bundlesSets.size(); i++) {
588 BundlesSet bundlesSet = (BundlesSet) bundlesSets.get(i);
589 for (int j = 0; j < bundlesSet.getExcludes().size(); j++) {
590 String pattern = (String) bundlesSet.getExcludes().get(j);
591 match(excluded, bundlesSet.getDir(), null, pattern);
592 }
593 }
594
595 // construct list
596 for (int i = 0; i < included.size(); i++) {
597 String fullPath = (String) included.get(i);
598 if (!excluded.contains(fullPath))
599 urls.add(locationToUrl(baseUrl, fullPath));
600 }
601
602 return urls;
603 }
604
605 /*
606 * DISTRIBUTION JAR INSTALLATION
607 */
608 public List<String> getDistributionUrls() {
609 String distributionUrl = getProperty(PROP_ARGEO_OSGI_DISTRIBUTION_URL);
610 String baseUrl = getProperty(PROP_ARGEO_OSGI_BASE_URL);
611 return getDistributionUrls(distributionUrl, baseUrl);
612 }
613
614 public List<String> getDistributionUrls(String distributionUrl, String baseUrl) {
615 List<String> urls = new ArrayList<String>();
616 if (distributionUrl == null)
617 return urls;
618
619 DistributionBundle distributionBundle;
620 if (distributionUrl.startsWith("http") || distributionUrl.startsWith("file")) {
621 distributionBundle = new DistributionBundle(distributionUrl);
622 if (baseUrl != null)
623 distributionBundle.setBaseUrl(baseUrl);
624 } else {
625 // relative url
626 if (baseUrl == null) {
627 baseUrl = localCache;
628 }
629
630 if (distributionUrl.contains(":")) {
631 // TODO make it safer
632 String[] parts = distributionUrl.trim().split(":");
633 String[] categoryParts = parts[0].split("\\.");
634 String artifactId = parts[1];
635 String version = parts[2];
636 StringBuilder sb = new StringBuilder();
637 for (String categoryPart : categoryParts) {
638 sb.append(categoryPart).append('/');
639 }
640 sb.append(artifactId).append('/');
641 sb.append(version).append('/');
642 sb.append(artifactId).append('-').append(version).append(".jar");
643 distributionUrl = sb.toString();
644 }
645
646 distributionBundle = new DistributionBundle(baseUrl, distributionUrl, localCache);
647 }
648 // if (baseUrl != null && !(distributionUrl.startsWith("http") ||
649 // distributionUrl.startsWith("file"))) {
650 // // relative url
651 // distributionBundle = new DistributionBundle(baseUrl, distributionUrl,
652 // localCache);
653 // } else {
654 // distributionBundle = new DistributionBundle(distributionUrl);
655 // if (baseUrl != null)
656 // distributionBundle.setBaseUrl(baseUrl);
657 // }
658 distributionBundle.processUrl();
659 return distributionBundle.listUrls();
660 }
661
662 /*
663 * HIGH LEVEL UTILITIES
664 */
665 /** Actually performs the matching logic. */
666 protected void match(List<String> matched, String base, String currentPath, String pattern) {
667 if (currentPath == null) {
668 // Init
669 File baseDir = new File(base.replace('/', File.separatorChar));
670 File[] files = baseDir.listFiles();
671
672 if (files == null) {
673 if (OsgiBootUtils.isDebug())
674 OsgiBootUtils.warn("Base dir " + baseDir + " has no children, exists=" + baseDir.exists()
675 + ", isDirectory=" + baseDir.isDirectory());
676 return;
677 }
678
679 for (int i = 0; i < files.length; i++)
680 match(matched, base, files[i].getName(), pattern);
681 } else {
682 PathMatcher matcher = FileSystems.getDefault().getPathMatcher(pattern);
683 String fullPath = base + '/' + currentPath;
684 if (matched.contains(fullPath))
685 return;// don't try deeper if already matched
686
687 boolean ok = matcher.matches(Paths.get(currentPath));
688 // if (debug)
689 // debug(currentPath + " " + (ok ? "" : " not ")
690 // + " matched with " + pattern);
691 if (ok) {
692 matched.add(fullPath);
693 return;
694 } else {
695 String newFullPath = relativeToFullPath(base, currentPath);
696 File newFile = new File(newFullPath);
697 File[] files = newFile.listFiles();
698 if (files != null) {
699 for (int i = 0; i < files.length; i++) {
700 String newCurrentPath = currentPath + '/' + files[i].getName();
701 if (files[i].isDirectory()) {
702 // if (matcher.matchStart(pattern, newCurrentPath)) {
703 // FIXME recurse only if start matches ?
704 match(matched, base, newCurrentPath, pattern);
705 // } else {
706 // if (OsgiBootUtils.isDebug())
707 // debug(newCurrentPath + " does not start match with " + pattern);
708 //
709 // }
710 } else {
711 boolean nonDirectoryOk = matcher.matches(Paths.get(newCurrentPath));
712 if (OsgiBootUtils.isDebug())
713 debug(currentPath + " " + (ok ? "" : " not ") + " matched with " + pattern);
714 if (nonDirectoryOk)
715 matched.add(relativeToFullPath(base, newCurrentPath));
716 }
717 }
718 }
719 }
720 }
721 }
722
723 protected void matchFile() {
724
725 }
726
727 /*
728 * LOW LEVEL UTILITIES
729 */
730 /**
731 * The bundles already installed. Key is location (String) , value is a
732 * {@link Bundle}
733 */
734 public Map<String, Bundle> getBundlesByLocation() {
735 Map<String, Bundle> installedBundles = new HashMap<String, Bundle>();
736 Bundle[] bundles = bundleContext.getBundles();
737 for (int i = 0; i < bundles.length; i++) {
738 installedBundles.put(bundles[i].getLocation(), bundles[i]);
739 }
740 return installedBundles;
741 }
742
743 /**
744 * The bundles already installed. Key is symbolic name (String) , value is a
745 * {@link Bundle}
746 */
747 public Map<String, Bundle> getBundlesBySymbolicName() {
748 Map<String, Bundle> namedBundles = new HashMap<String, Bundle>();
749 Bundle[] bundles = bundleContext.getBundles();
750 for (int i = 0; i < bundles.length; i++) {
751 namedBundles.put(bundles[i].getSymbolicName(), bundles[i]);
752 }
753 return namedBundles;
754 }
755
756 /** Creates an URL from a location */
757 protected String locationToUrl(String baseUrl, String location) {
758 return baseUrl + location;
759 }
760
761 /** Transforms a relative path in a full system path. */
762 protected String relativeToFullPath(String basePath, String relativePath) {
763 return (basePath + '/' + relativePath).replace('/', File.separatorChar);
764 }
765
766 private void refreshFramework() {
767 Bundle systemBundle = bundleContext.getBundle(0);
768 FrameworkWiring frameworkWiring = systemBundle.adapt(FrameworkWiring.class);
769 frameworkWiring.refreshBundles(null);
770 }
771
772 /**
773 * Gets a property value
774 *
775 * @return null when defaultValue is ""
776 */
777 public String getProperty(String name, String defaultValue) {
778 String value = bundleContext.getProperty(name);
779 if (value == null)
780 return defaultValue; // may be null
781 else
782 return value;
783 }
784
785 public String getProperty(String name) {
786 return getProperty(name, null);
787 }
788
789 /*
790 * BEAN METHODS
791 */
792
793 // public boolean getDebug() {
794 // return OsgiBootUtils.debug;
795 // }
796
797 // public void setDebug(boolean debug) {
798 // this.debug = debug;
799 // }
800
801 public BundleContext getBundleContext() {
802 return bundleContext;
803 }
804
805 public String getLocalCache() {
806 return localCache;
807 }
808
809 // public void setDefaultTimeout(long defaultTimeout) {
810 // this.defaultTimeout = defaultTimeout;
811 // }
812
813 // public boolean isExcludeSvn() {
814 // return excludeSvn;
815 // }
816 //
817 // public void setExcludeSvn(boolean excludeSvn) {
818 // this.excludeSvn = excludeSvn;
819 // }
820
821 /*
822 * INTERNAL CLASSES
823 */
824
825 }