1 package org
.argeo
.init
.osgi
;
3 import static org
.argeo
.init
.osgi
.OsgiBootUtils
.debug
;
4 import static org
.argeo
.init
.osgi
.OsgiBootUtils
.warn
;
7 import java
.net
.MalformedURLException
;
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
;
19 import java
.util
.Properties
;
21 import java
.util
.SortedMap
;
22 import java
.util
.StringTokenizer
;
23 import java
.util
.TreeMap
;
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
;
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.
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";
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";
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";
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";
59 public final static String DEFAULT_BASE_URL
= "reference:file:";
60 // public final static String EXCLUDES_SVN_PATTERN = "**/.svn/**";
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";
70 public final static String SYMBOLIC_NAME_OSGI_BOOT
= "org.argeo.osgi.boot";
71 public final static String SYMBOLIC_NAME_EQUINOX
= "org.eclipse.osgi";
73 /** Exclude svn metadata implicitely(a bit costly) */
74 // private boolean excludeSvn =
75 // Boolean.valueOf(System.getProperty(PROP_ARGEO_OSGI_BOOT_EXCLUDE_SVN,
79 // /** Default is 10s */
81 // private long defaultTimeout = 10000l;
83 private final BundleContext bundleContext
;
84 private final String localCache
;
86 private final ProvisioningManager provisioningManager
;
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/");
98 provisioningManager
= new ProvisioningManager(bundleContext
);
99 String sources
= getProperty(PROP_ARGEO_OSGI_SOURCES
);
100 if (sources
== null) {
101 provisioningManager
.registerDefaultSource();
103 for (String source
: sources
.split(",")) {
104 if (source
.trim().equals(A2Source
.DEFAULT_A2_URI
)) {
105 if (Files
.exists(homePath
))
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");
111 provisioningManager
.registerSource(source
);
117 ProvisioningManager
getProvisioningManager() {
118 return provisioningManager
;
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.
129 public void bootstrap(Map
<String
, String
> properties
) {
131 long begin
= System
.currentTimeMillis();
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
)) {
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
);
149 if (!value
.equals(bcValue
))
150 throw new IllegalArgumentException("Property " + property
+ "=" + value
151 + " is inconsistent with bundle context : " + bcValue
);
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.");
162 System
.out
.println();
163 String osgiInstancePath
= bundleContext
.getProperty(PROP_OSGI_INSTANCE_AREA
);
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
);
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
);
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());
199 System
.out
.println();
203 * Calls {@link #bootstrap(Map)} with <code>null</code>.
205 * @see #bootstrap(Map)
208 public void bootstrap() {
212 public void update() {
213 provisioningManager
.update();
219 /** Install a single url. Convenience method. */
220 public Bundle
installUrl(String url
) {
221 List
<String
> urls
= new ArrayList
<String
>();
224 return (Bundle
) getBundlesByLocation().get(url
);
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
);
237 /** Actually install the provided URL */
238 protected void installUrl(String url
, Map
<String
, Bundle
> installedBundles
) {
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())
250 Bundle bundle
= bundleContext
.installBundle(url
);
251 if (url
.startsWith("http"))
253 .info("Installed " + bundle
.getSymbolicName() + "-" + bundle
.getVersion() + " from " + url
);
254 else if (OsgiBootUtils
.isDebug())
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)
262 if (bundle
.getSymbolicName().equals(b
.getSymbolicName())) {
263 Version bundleV
= bundle
.getVersion();
264 Version bV
= b
.getVersion();
267 if (bundleV
.getMajor() == bV
.getMajor() && bundleV
.getMinor() == bV
.getMinor()) {
268 if (bundleV
.getMicro() > bV
.getMicro()) {
269 // uninstall older bundles
271 OsgiBootUtils
.debug("Uninstalled " + b
);
272 } else if (bundleV
.getMicro() < bV
.getMicro()) {
273 // uninstall just installed bundle if newer
275 OsgiBootUtils
.debug("Uninstalled " + bundle
);
278 // uninstall any other with same major/minor
279 if (!bundleV
.getQualifier().equals(bV
.getQualifier())) {
281 OsgiBootUtils
.debug("Uninstalled " + b
);
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...
297 if (message
.contains(ALREADY_INSTALLED
)) {
298 if (OsgiBootUtils
.isDebug())
299 OsgiBootUtils
.warn("Duplicate install from " + url
+ ": " + message
);
301 OsgiBootUtils
.warn("Could not install bundle from " + url
+ ": " + message
);
303 if (OsgiBootUtils
.isDebug() && !message
.contains(ALREADY_INSTALLED
))
312 * Start bundles based on system properties.
314 * @see OsgiBoot#startBundles(Map)
316 public void startBundles() {
317 Properties properties
= System
.getProperties();
318 startBundles(properties
);
322 * Start bundles based on these properties.
324 * @see OsgiBoot#startBundles(Map)
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
));
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);
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"));
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
);
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
);
362 } catch (BundleException e
) {
363 OsgiBootUtils
.error("Cannot mark " + bsn
+ " as started", e
);
365 if (OsgiBootUtils
.isDebug())
366 OsgiBootUtils
.debug(bsn
+ " starts at level " + level
);
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
+ ")");
379 private static void computeStartLevels(SortedMap
<Integer
, List
<String
>> startLevels
, Map
<String
, String
> properties
,
380 Integer defaultStartLevel
) {
382 // default (and previously, only behaviour)
383 appendToStartLevels(startLevels
, defaultStartLevel
, properties
.getOrDefault(PROP_ARGEO_OSGI_START
, ""));
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
)) {
392 String suffix
= key
.substring(prefix
.length());
393 String
[] tokens
= suffix
.split("\\.");
394 if (tokens
.length
> 0 && !tokens
[0].trim().equals(""))
396 // first token is start level
397 startLevel
= Integer
.parseInt(tokens
[0]);
398 } catch (NumberFormatException e
) {
399 startLevel
= defaultStartLevel
;
402 startLevel
= defaultStartLevel
;
404 // append bundle names
405 String bundleNames
= properties
.get(key
);
406 appendToStartLevels(startLevels
, startLevel
, bundleNames
);
411 /** Append a comma-separated list of bundles to the start levels. */
412 private static void appendToStartLevels(SortedMap
<Integer
, List
<String
>> startLevels
, Integer startLevel
,
414 if (str
== null || str
.trim().equals(""))
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
]);
427 // * Start the provided list of bundles
429 // * @return whether all bundles are now in active state
433 // public boolean startBundles(List<String> bundlesToStart) {
434 // if (bundlesToStart.size() == 0)
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);
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))
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);
458 // startedBundles.add(bundle);
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);
470 // for (int i = 0; i < notFoundBundles.size(); i++)
471 // OsgiBootUtils.warn("Bundle '" + notFoundBundles.get(i) + "' not started because it was not found.");
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());
489 // Thread.sleep(100);
490 // } catch (InterruptedException e) {
494 // long duration = System.currentTimeMillis() - beginMonitor;
497 // for (int i = 0; i < notStarted.size(); i++)
498 // OsgiBootUtils.warn("Bundle '" + notStarted.get(i) + "' not ACTIVE after " + (duration / 1000) + "s");
500 // return allStarted;
503 // /** Waits for a bundle to become active or resolved */
505 // private void waitForBundleResolvedOrActive(long startBegin, Bundle bundle) throws Exception {
506 // int originalState = bundle.getState();
507 // if ((originalState == Bundle.RESOLVED) || (originalState == Bundle.ACTIVE))
510 // String originalStateStr = OsgiBootUtils.stateAsString(originalState);
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) + ")");
521 // Thread.sleep(100l);
522 // } catch (InterruptedException e) {
525 // currentState = bundle.getState();
530 * BUNDLE PATTERNS INSTALLATION
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.
539 public List
<String
> getBundlesUrls() {
540 String bundlePatterns
= getProperty(PROP_ARGEO_OSGI_BUNDLES
);
541 return getBundlesUrls(bundlePatterns
);
545 * Compute a list of URLs to install based on the provided patterns, with
548 public List
<String
> getBundlesUrls(String bundlePatterns
) {
549 String baseUrl
= getProperty(PROP_ARGEO_OSGI_BASE_URL
, DEFAULT_BASE_URL
);
550 return getBundlesUrls(baseUrl
, bundlePatterns
);
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)
559 // bundlePatterns = SystemPropertyUtils.resolvePlaceholders(bundlePatterns);
560 if (OsgiBootUtils
.isDebug())
561 debug(PROP_ARGEO_OSGI_BUNDLES
+ "=" + bundlePatterns
);
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
);
571 bundlesSets
.add(new BundlesSet(token
));
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
);
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
);
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
));
606 * DISTRIBUTION JAR INSTALLATION
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
);
614 public List
<String
> getDistributionUrls(String distributionUrl
, String baseUrl
) {
615 List
<String
> urls
= new ArrayList
<String
>();
616 if (distributionUrl
== null)
619 DistributionBundle distributionBundle
;
620 if (distributionUrl
.startsWith("http") || distributionUrl
.startsWith("file")) {
621 distributionBundle
= new DistributionBundle(distributionUrl
);
623 distributionBundle
.setBaseUrl(baseUrl
);
626 if (baseUrl
== null) {
627 baseUrl
= localCache
;
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('/');
640 sb
.append(artifactId
).append('/');
641 sb
.append(version
).append('/');
642 sb
.append(artifactId
).append('-').append(version
).append(".jar");
643 distributionUrl
= sb
.toString();
646 distributionBundle
= new DistributionBundle(baseUrl
, distributionUrl
, localCache
);
648 // if (baseUrl != null && !(distributionUrl.startsWith("http") ||
649 // distributionUrl.startsWith("file"))) {
651 // distributionBundle = new DistributionBundle(baseUrl, distributionUrl,
654 // distributionBundle = new DistributionBundle(distributionUrl);
655 // if (baseUrl != null)
656 // distributionBundle.setBaseUrl(baseUrl);
658 distributionBundle
.processUrl();
659 return distributionBundle
.listUrls();
663 * HIGH LEVEL UTILITIES
665 /** Actually performs the matching logic. */
666 protected void match(List
<String
> matched
, String base
, String currentPath
, String pattern
) {
667 if (currentPath
== null) {
669 File baseDir
= new File(base
.replace('/', File
.separatorChar
));
670 File
[] files
= baseDir
.listFiles();
673 if (OsgiBootUtils
.isDebug())
674 OsgiBootUtils
.warn("Base dir " + baseDir
+ " has no children, exists=" + baseDir
.exists()
675 + ", isDirectory=" + baseDir
.isDirectory());
679 for (int i
= 0; i
< files
.length
; i
++)
680 match(matched
, base
, files
[i
].getName(), pattern
);
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
687 boolean ok
= matcher
.matches(Paths
.get(currentPath
));
689 // debug(currentPath + " " + (ok ? "" : " not ")
690 // + " matched with " + pattern);
692 matched
.add(fullPath
);
695 String newFullPath
= relativeToFullPath(base
, currentPath
);
696 File newFile
= new File(newFullPath
);
697 File
[] files
= newFile
.listFiles();
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
);
706 // if (OsgiBootUtils.isDebug())
707 // debug(newCurrentPath + " does not start match with " + pattern);
711 boolean nonDirectoryOk
= matcher
.matches(Paths
.get(newCurrentPath
));
712 if (OsgiBootUtils
.isDebug())
713 debug(currentPath
+ " " + (ok ?
"" : " not ") + " matched with " + pattern
);
715 matched
.add(relativeToFullPath(base
, newCurrentPath
));
723 protected void matchFile() {
728 * LOW LEVEL UTILITIES
731 * The bundles already installed. Key is location (String) , value is a
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
]);
740 return installedBundles
;
744 * The bundles already installed. Key is symbolic name (String) , value is a
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
]);
756 /** Creates an URL from a location */
757 protected String
locationToUrl(String baseUrl
, String location
) {
758 return baseUrl
+ location
;
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
);
766 private void refreshFramework() {
767 Bundle systemBundle
= bundleContext
.getBundle(0);
768 FrameworkWiring frameworkWiring
= systemBundle
.adapt(FrameworkWiring
.class);
769 frameworkWiring
.refreshBundles(null);
773 * Gets a property value
775 * @return null when defaultValue is ""
777 public String
getProperty(String name
, String defaultValue
) {
778 String value
= bundleContext
.getProperty(name
);
780 return defaultValue
; // may be null
785 public String
getProperty(String name
) {
786 return getProperty(name
, null);
793 // public boolean getDebug() {
794 // return OsgiBootUtils.debug;
797 // public void setDebug(boolean debug) {
798 // this.debug = debug;
801 public BundleContext
getBundleContext() {
802 return bundleContext
;
805 public String
getLocalCache() {
809 // public void setDefaultTimeout(long defaultTimeout) {
810 // this.defaultTimeout = defaultTimeout;
813 // public boolean isExcludeSvn() {
814 // return excludeSvn;
817 // public void setExcludeSvn(boolean excludeSvn) {
818 // this.excludeSvn = excludeSvn;