2 * Copyright (C) 2007-2012 Mathieu Baudier
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org
.argeo
.osgi
.boot
;
18 import java
.io
.BufferedReader
;
20 import java
.io
.IOException
;
21 import java
.io
.InputStreamReader
;
23 import java
.util
.ArrayList
;
24 import java
.util
.HashMap
;
25 import java
.util
.Iterator
;
26 import java
.util
.List
;
28 import java
.util
.Properties
;
30 import java
.util
.SortedMap
;
31 import java
.util
.StringTokenizer
;
32 import java
.util
.TreeMap
;
33 import java
.util
.TreeSet
;
35 import org
.argeo
.osgi
.boot
.internal
.springutil
.AntPathMatcher
;
36 import org
.argeo
.osgi
.boot
.internal
.springutil
.PathMatcher
;
37 import org
.argeo
.osgi
.boot
.internal
.springutil
.SystemPropertyUtils
;
38 import org
.osgi
.framework
.Bundle
;
39 import org
.osgi
.framework
.BundleContext
;
40 import org
.osgi
.framework
.BundleException
;
41 import org
.osgi
.framework
.Constants
;
42 import org
.osgi
.framework
.ServiceReference
;
43 import org
.osgi
.service
.packageadmin
.ExportedPackage
;
44 import org
.osgi
.service
.packageadmin
.PackageAdmin
;
47 * Basic provisioning of an OSGi runtime via file path patterns and system
48 * properties. Java 1.4 compatible.<br>
49 * The approach is to generate list of URLs based on various methods, configured
50 * via system properties.
52 public class OsgiBoot
{
53 public final static String SYMBOLIC_NAME_OSGI_BOOT
= "org.argeo.osgi.boot";
54 public final static String SYMBOLIC_NAME_EQUINOX
= "org.eclipse.osgi";
56 public final static String PROP_OSGI_STARTLEVEL
= "osgi.startLevel";
57 public final static String PROP_OSGI_BUNDLES_DEFAULTSTARTLEVEL
= "osgi.bundles.defaultStartLevel";
59 public final static String PROP_ARGEO_OSGI_DATA_DIR
= "argeo.osgi.data.dir";
61 public final static String PROP_ARGEO_OSGI_START
= "argeo.osgi.start";
62 public final static String PROP_ARGEO_OSGI_BUNDLES
= "argeo.osgi.bundles";
63 public final static String PROP_ARGEO_OSGI_LOCATIONS
= "argeo.osgi.locations";
64 public final static String PROP_ARGEO_OSGI_BASE_URL
= "argeo.osgi.baseUrl";
66 public final static String PROP_ARGEO_OSGI_MODULES_URL
= "argeo.osgi.modulesUrl";
67 public final static String PROP_ARGEO_OSGI_DISTRIBUTION_URL
= "argeo.osgi.distributionUrl";
70 public final static String PROP_ARGEO_OSGI_BOOT_DEBUG
= "argeo.osgi.boot.debug";
71 public final static String PROP_ARGEO_OSGI_BOOT_EXCLUDE_SVN
= "argeo.osgi.boot.excludeSvn";
72 public final static String PROP_ARGEO_OSGI_BOOT_INSTALL_IN_LEXICOGRAPHIC_ORDER
= "argeo.osgi.boot.installInLexicographicOrder";
74 public final static String PROP_ARGEO_OSGI_BOOT_DEFAULT_TIMEOUT
= "argeo.osgi.boot.defaultTimeout";
75 public final static String PROP_ARGEO_OSGI_BOOT_MODULES_URL_SEPARATOR
= "argeo.osgi.boot.modulesUrlSeparator";
76 public final static String PROP_ARGEO_OSGI_BOOT_SYSTEM_PROPERTIES_FILE
= "argeo.osgi.boot.systemPropertiesFile";
77 public final static String PROP_ARGEO_OSGI_BOOT_APPCLASS
= "argeo.osgi.boot.appclass";
78 public final static String PROP_ARGEO_OSGI_BOOT_APPARGS
= "argeo.osgi.boot.appargs";
80 public final static String DEFAULT_BASE_URL
= "reference:file:";
81 public final static String EXCLUDES_SVN_PATTERN
= "**/.svn/**";
83 // OSGi system properties
84 public final static String INSTANCE_AREA_PROP
= "osgi.instance.area";
85 public final static String INSTANCE_AREA_DEFAULT_PROP
= "osgi.instance.area.default";
87 private boolean debug
= Boolean
.valueOf(
88 System
.getProperty(PROP_ARGEO_OSGI_BOOT_DEBUG
, "false"))
90 /** Exclude svn metadata implicitely(a bit costly) */
91 private boolean excludeSvn
= Boolean
.valueOf(
92 System
.getProperty(PROP_ARGEO_OSGI_BOOT_EXCLUDE_SVN
, "false"))
96 * The {@link #installUrls(List)} methods won't follow the list order but
97 * order the urls according to the alphabetical order of the file names
98 * (last part of the URL). The goal is to stay closer from Eclipse PDE way
99 * of installing target platform bundles.
101 private boolean installInLexicographicOrder
= Boolean
104 PROP_ARGEO_OSGI_BOOT_INSTALL_IN_LEXICOGRAPHIC_ORDER
,
105 "true")).booleanValue();;
107 /** Default is 10s (set in constructor) */
108 private long defaultTimeout
;
110 /** Default is ',' (set in constructor) */
111 private String modulesUrlSeparator
= ",";
113 private final BundleContext bundleContext
;
119 public OsgiBoot(BundleContext bundleContext
) {
120 this.bundleContext
= bundleContext
;
121 defaultTimeout
= Long
.parseLong(OsgiBootUtils
.getProperty(
122 PROP_ARGEO_OSGI_BOOT_DEFAULT_TIMEOUT
, "10000"));
123 modulesUrlSeparator
= OsgiBootUtils
.getProperty(
124 PROP_ARGEO_OSGI_BOOT_MODULES_URL_SEPARATOR
, ",");
125 initSystemProperties();
129 * Set additional system properties, especially ${argeo.osgi.data.dir} as an
130 * OS file path (and not a file:// URL)
132 protected void initSystemProperties() {
133 String osgiInstanceArea
= System
.getProperty(INSTANCE_AREA_PROP
);
134 String osgiInstanceAreaDefault
= System
135 .getProperty(INSTANCE_AREA_DEFAULT_PROP
);
136 String tempDir
= System
.getProperty("java.io.tmpdir");
139 if (osgiInstanceArea
!= null) {
140 // within OSGi with -data specified
141 osgiInstanceArea
= removeFilePrefix(osgiInstanceArea
);
142 dataDir
= new File(osgiInstanceArea
);
143 } else if (osgiInstanceAreaDefault
!= null) {
144 // within OSGi without -data specified
145 osgiInstanceAreaDefault
= removeFilePrefix(osgiInstanceAreaDefault
);
146 dataDir
= new File(osgiInstanceAreaDefault
);
147 } else {// outside OSGi
148 dataDir
= new File(tempDir
+ File
.separator
+ "argeoOsgiData");
150 System
.setProperty(PROP_ARGEO_OSGI_DATA_DIR
, dataDir
.getAbsolutePath());
156 /** Bootstraps the OSGi runtime */
157 public void bootstrap() {
158 long begin
= System
.currentTimeMillis();
159 System
.out
.println();
160 OsgiBootUtils
.info("OSGi bootstrap starting...");
161 OsgiBootUtils
.info("Writable data directory : "
162 + System
.getProperty(PROP_ARGEO_OSGI_DATA_DIR
)
163 + " (set as system property " + PROP_ARGEO_OSGI_DATA_DIR
+ ")");
164 installUrls(getBundlesUrls());
165 installUrls(getLocationsUrls());
166 installUrls(getModulesUrls());
167 installUrls(getDistributionUrls());
170 long duration
= System
.currentTimeMillis() - begin
;
171 OsgiBootUtils
.info("OSGi bootstrap completed in "
172 + Math
.round(((double) duration
) / 1000) + "s (" + duration
173 + "ms), " + bundleContext
.getBundles().length
+ " bundles");
175 // display packages exported twice
177 Map
/* <String,Set<String>> */duplicatePackages
= findPackagesExportedTwice();
178 if (duplicatePackages
.size() > 0) {
179 OsgiBootUtils
.info("Packages exported twice:");
180 Iterator it
= duplicatePackages
.keySet().iterator();
181 while (it
.hasNext()) {
182 String pkgName
= it
.next().toString();
183 OsgiBootUtils
.info(pkgName
);
184 Set bdles
= (Set
) duplicatePackages
.get(pkgName
);
185 Iterator bdlesIt
= bdles
.iterator();
186 while (bdlesIt
.hasNext())
187 OsgiBootUtils
.info(" " + bdlesIt
.next());
192 System
.out
.println();
198 /** Install a single url. Convenience method. */
199 public Bundle
installUrl(String url
) {
200 List urls
= new ArrayList();
203 return (Bundle
) getBundlesByLocation().get(url
);
206 /** Install the bundles at this URL list. */
207 public void installUrls(List urls
) {
208 Map installedBundles
= getBundlesByLocation();
210 if (installInLexicographicOrder
) {
211 SortedMap map
= new TreeMap();
213 for (int i
= 0; i
< urls
.size(); i
++) {
214 String url
= (String
) urls
.get(i
);
215 int index
= url
.lastIndexOf('/');
218 fileName
= url
.substring(index
+ 1);
221 map
.put(fileName
, url
);
225 Iterator keys
= map
.keySet().iterator();
226 while (keys
.hasNext()) {
227 Object key
= keys
.next();
228 String url
= map
.get(key
).toString();
229 installUrl(url
, installedBundles
);
232 for (int i
= 0; i
< urls
.size(); i
++) {
233 String url
= (String
) urls
.get(i
);
234 installUrl(url
, installedBundles
);
240 /** Actually install the provided URL */
241 protected void installUrl(String url
, Map installedBundles
) {
243 if (installedBundles
.containsKey(url
)) {
244 Bundle bundle
= (Bundle
) installedBundles
.get(url
);
247 debug("Bundle " + bundle
.getSymbolicName()
248 + " already installed from " + url
);
250 Bundle bundle
= bundleContext
.installBundle(url
);
252 debug("Installed bundle " + bundle
.getSymbolicName()
255 } catch (BundleException e
) {
256 String message
= e
.getMessage();
257 if ((message
.contains("Bundle \"" + SYMBOLIC_NAME_OSGI_BOOT
+ "\"") || message
258 .contains("Bundle \"" + SYMBOLIC_NAME_EQUINOX
+ "\""))
259 && message
.contains("has already been installed")) {
260 // silent, in order to avoid warnings: we know that both
261 // have already been installed...
263 OsgiBootUtils
.warn("Could not install bundle from " + url
274 public void startBundles() {
275 // default and active start levels from System properties
276 Integer defaultStartLevel
= new Integer(Integer
.parseInt(OsgiBootUtils
277 .getProperty(PROP_OSGI_BUNDLES_DEFAULTSTARTLEVEL
)));
278 Integer activeStartLevel
= new Integer(
279 OsgiBootUtils
.getProperty(PROP_OSGI_STARTLEVEL
));
281 SortedMap
/* <Integer, List<String>> */startLevels
= new TreeMap();
282 computeStartLevels(startLevels
, System
.getProperties(),
285 Iterator
/* <Integer> */levels
= startLevels
.keySet().iterator();
286 while (levels
.hasNext()) {
287 Integer level
= (Integer
) levels
.next();
288 boolean allStarted
= startBundles((List
) startLevels
.get(level
));
291 .warn("Not all bundles started for level " + level
);
292 if (level
.equals(activeStartLevel
))
293 break;// active start level reached
298 public static void computeStartLevels(
299 SortedMap
/* <Integer, List<String>> */startLevels
,
300 Properties properties
, Integer defaultStartLevel
) {
302 // default (and previously, only behaviour)
303 appendToStartLevels(startLevels
, defaultStartLevel
,
304 properties
.getProperty(PROP_ARGEO_OSGI_START
, ""));
306 // list argeo.osgi.start.* system properties
307 Iterator
/* <String> */keys
= properties
.keySet().iterator();
308 final String prefix
= PROP_ARGEO_OSGI_START
+ ".";
309 while (keys
.hasNext()) {
310 String key
= (String
) keys
.next();
311 if (key
.startsWith(prefix
)) {
313 String suffix
= key
.substring(prefix
.length());
314 String
[] tokens
= suffix
.split("\\.");
315 if (tokens
.length
> 0 && !tokens
[0].trim().equals(""))
317 // first token is start level
318 startLevel
= new Integer(tokens
[0]);
319 } catch (NumberFormatException e
) {
320 startLevel
= defaultStartLevel
;
323 startLevel
= defaultStartLevel
;
325 // append bundle names
326 String bundleNames
= properties
.getProperty(key
);
327 appendToStartLevels(startLevels
, startLevel
, bundleNames
);
332 /** Append a comma-separated list of bundles to the start levels. */
333 private static void appendToStartLevels(
334 SortedMap
/* <Integer, List<String>> */startLevels
,
335 Integer startLevel
, String str
) {
336 if (str
== null || str
.trim().equals(""))
339 if (!startLevels
.containsKey(startLevel
))
340 startLevels
.put(startLevel
, new ArrayList());
341 String
[] bundleNames
= str
.split(",");
342 for (int i
= 0; i
< bundleNames
.length
; i
++) {
343 if (bundleNames
[i
] != null && !bundleNames
[i
].trim().equals(""))
344 ((List
) startLevels
.get(startLevel
)).add(bundleNames
[i
]);
349 * Convenience method accepting a comma-separated list of bundle to start
353 public void startBundles(String bundlesToStartStr
) {
354 if (bundlesToStartStr
== null)
357 StringTokenizer st
= new StringTokenizer(bundlesToStartStr
, ",");
358 List bundlesToStart
= new ArrayList();
359 while (st
.hasMoreTokens()) {
360 String name
= st
.nextToken().trim();
361 bundlesToStart
.add(name
);
363 startBundles(bundlesToStart
);
367 * Start the provided list of bundles
369 * @return whether all bundlesa are now in active state
371 public boolean startBundles(List bundlesToStart
) {
372 if (bundlesToStart
.size() == 0)
375 // used to monitor ACTIVE states
376 List
/* <Bundle> */startedBundles
= new ArrayList();
377 // used to log the bundles not found
378 List
/* <String> */notFoundBundles
= new ArrayList(bundlesToStart
);
380 Bundle
[] bundles
= bundleContext
.getBundles();
381 long startBegin
= System
.currentTimeMillis();
382 for (int i
= 0; i
< bundles
.length
; i
++) {
383 Bundle bundle
= bundles
[i
];
384 String symbolicName
= bundle
.getSymbolicName();
385 if (bundlesToStart
.contains(symbolicName
))
390 debug("Bundle " + symbolicName
+ " started");
391 } catch (Exception e
) {
392 OsgiBootUtils
.warn("Start of bundle " + symbolicName
393 + " failed because of " + e
394 + ", maybe bundle is not yet resolved,"
395 + " waiting and trying again.");
396 waitForBundleResolvedOrActive(startBegin
, bundle
);
398 startedBundles
.add(bundle
);
400 notFoundBundles
.remove(symbolicName
);
401 } catch (Exception e
) {
402 OsgiBootUtils
.warn("Bundle " + symbolicName
403 + " cannot be started: " + e
.getMessage());
406 // was found even if start failed
407 notFoundBundles
.remove(symbolicName
);
411 for (int i
= 0; i
< notFoundBundles
.size(); i
++)
412 OsgiBootUtils
.warn("Bundle '" + notFoundBundles
.get(i
)
413 + "' not started because it was not found.");
415 // monitors that all bundles are started
416 long beginMonitor
= System
.currentTimeMillis();
417 boolean allStarted
= false;
418 List
/* <String> */notStarted
= new ArrayList();
420 && (System
.currentTimeMillis() - beginMonitor
) > defaultTimeout
) {
421 notStarted
= new ArrayList();
422 for (int i
= 0; i
< startedBundles
.size(); i
++) {
423 Bundle bundle
= (Bundle
) startedBundles
.get(i
);
424 // TODO check behaviour of lazs bundles
425 if (bundle
.getState() != Bundle
.ACTIVE
) {
427 notStarted
.add(bundle
.getSymbolicName());
432 } catch (InterruptedException e
) {
436 long duration
= System
.currentTimeMillis() - beginMonitor
;
439 for (int i
= 0; i
< notStarted
.size(); i
++)
440 OsgiBootUtils
.warn("Bundle '" + notStarted
.get(i
)
441 + "' not ACTIVE after " + (duration
/ 1000) + "s");
449 /** Check unresolved bundles */
450 protected void checkUnresolved() {
452 ServiceReference packageAdminRef
= bundleContext
453 .getServiceReference(PackageAdmin
.class.getName());
454 PackageAdmin packageAdmin
= (PackageAdmin
) bundleContext
455 .getService(packageAdminRef
);
456 packageAdmin
.resolveBundles(null);
458 Bundle
[] bundles
= bundleContext
.getBundles();
459 List
/* Bundle */unresolvedBundles
= new ArrayList();
460 for (int i
= 0; i
< bundles
.length
; i
++) {
461 int bundleState
= bundles
[i
].getState();
462 if (!(bundleState
== Bundle
.ACTIVE
463 || bundleState
== Bundle
.RESOLVED
|| bundleState
== Bundle
.STARTING
))
464 unresolvedBundles
.add(bundles
[i
]);
467 if (unresolvedBundles
.size() != 0) {
468 OsgiBootUtils
.warn("Unresolved bundles " + unresolvedBundles
);
472 /** List packages exported twice. */
473 public Map
findPackagesExportedTwice() {
474 ServiceReference paSr
= bundleContext
475 .getServiceReference(PackageAdmin
.class.getName());
476 PackageAdmin packageAdmin
= (PackageAdmin
) bundleContext
479 // find packages exported twice
480 Bundle
[] bundles
= bundleContext
.getBundles();
481 Map
/* <String,Set<String>> */exportedPackages
= new TreeMap();
482 for (int i
= 0; i
< bundles
.length
; i
++) {
483 Bundle bundle
= bundles
[i
];
484 ExportedPackage
[] pkgs
= packageAdmin
.getExportedPackages(bundle
);
486 for (int j
= 0; j
< pkgs
.length
; j
++) {
487 String pkgName
= pkgs
[j
].getName();
488 if (!exportedPackages
.containsKey(pkgName
)) {
489 exportedPackages
.put(pkgName
, new TreeSet());
491 ((Set
) exportedPackages
.get(pkgName
)).add(bundle
492 .getSymbolicName() + "_" + bundle
.getVersion());
495 Map
/* <String,Set<String>> */duplicatePackages
= new TreeMap();
496 Iterator it
= exportedPackages
.keySet().iterator();
497 while (it
.hasNext()) {
498 String pkgName
= it
.next().toString();
499 Set bdles
= (Set
) exportedPackages
.get(pkgName
);
500 if (bdles
.size() > 1)
501 duplicatePackages
.put(pkgName
, bdles
);
503 return duplicatePackages
;
506 /** Waits for a bundle to become active or resolved */
507 protected void waitForBundleResolvedOrActive(long startBegin
, Bundle bundle
)
509 int originalState
= bundle
.getState();
510 if ((originalState
== Bundle
.RESOLVED
)
511 || (originalState
== Bundle
.ACTIVE
))
514 String originalStateStr
= OsgiBootUtils
.stateAsString(originalState
);
516 int currentState
= bundle
.getState();
517 while (!(currentState
== Bundle
.RESOLVED
|| currentState
== Bundle
.ACTIVE
)) {
518 long now
= System
.currentTimeMillis();
519 if ((now
- startBegin
) > defaultTimeout
)
520 throw new Exception("Bundle " + bundle
.getSymbolicName()
521 + " was not RESOLVED or ACTIVE after "
522 + (now
- startBegin
) + "ms (originalState="
523 + originalStateStr
+ ", currentState="
524 + OsgiBootUtils
.stateAsString(currentState
) + ")");
528 } catch (InterruptedException e
) {
531 currentState
= bundle
.getState();
536 * EXPLICIT LOCATIONS INSTALLATION
538 /** Gets the list of resolved explicit URL locations. */
539 public List
getLocationsUrls() {
540 String baseUrl
= OsgiBootUtils
.getProperty(PROP_ARGEO_OSGI_BASE_URL
,
542 String bundleLocations
= OsgiBootUtils
543 .getProperty(PROP_ARGEO_OSGI_LOCATIONS
);
544 return getLocationsUrls(baseUrl
, bundleLocations
);
548 * Gets a list of URLs based on explicit locations, resolving placeholder
549 * ${...} containing system properties, e.g. ${user.home}.
551 public List
getLocationsUrls(String baseUrl
, String bundleLocations
) {
552 List urls
= new ArrayList();
554 if (bundleLocations
== null)
556 bundleLocations
= SystemPropertyUtils
557 .resolvePlaceholders(bundleLocations
);
559 debug(PROP_ARGEO_OSGI_LOCATIONS
+ "=" + bundleLocations
);
561 StringTokenizer st
= new StringTokenizer(bundleLocations
,
563 while (st
.hasMoreTokens()) {
564 urls
.add(locationToUrl(baseUrl
, st
.nextToken().trim()));
570 * BUNDLE PATTERNS INSTALLATION
573 * Computes a list of URLs based on Ant-like incluide/exclude patterns
574 * defined by ${argeo.osgi.bundles} with the following format:<br>
575 * <code>/base/directory;in=*.jar;in=**;ex=org.eclipse.osgi_*;jar</code><br>
576 * WARNING: <code>/base/directory;in=*.jar,\</code> at the end of a file,
577 * without a new line causes a '.' to be appended with unexpected side
580 public List
getBundlesUrls() {
581 String bundlePatterns
= OsgiBootUtils
582 .getProperty(PROP_ARGEO_OSGI_BUNDLES
);
583 return getBundlesUrls(bundlePatterns
);
587 * Compute alist of URLs to install based on the provided patterns, with
590 public List
getBundlesUrls(String bundlePatterns
) {
591 String baseUrl
= OsgiBootUtils
.getProperty(PROP_ARGEO_OSGI_BASE_URL
,
593 return getBundlesUrls(baseUrl
, bundlePatterns
);
596 /** Implements the path matching logic */
597 List
getBundlesUrls(String baseUrl
, String bundlePatterns
) {
598 List urls
= new ArrayList();
599 if (bundlePatterns
== null)
602 bundlePatterns
= SystemPropertyUtils
603 .resolvePlaceholders(bundlePatterns
);
605 debug(PROP_ARGEO_OSGI_BUNDLES
+ "=" + bundlePatterns
606 + " (excludeSvn=" + excludeSvn
+ ")");
608 StringTokenizer st
= new StringTokenizer(bundlePatterns
, ",");
609 List bundlesSets
= new ArrayList();
610 while (st
.hasMoreTokens()) {
611 bundlesSets
.add(new BundlesSet(st
.nextToken()));
615 List included
= new ArrayList();
616 PathMatcher matcher
= new AntPathMatcher();
617 for (int i
= 0; i
< bundlesSets
.size(); i
++) {
618 BundlesSet bundlesSet
= (BundlesSet
) bundlesSets
.get(i
);
619 for (int j
= 0; j
< bundlesSet
.getIncludes().size(); j
++) {
620 String pattern
= (String
) bundlesSet
.getIncludes().get(j
);
621 match(matcher
, included
, bundlesSet
.getDir(), null, pattern
);
626 List excluded
= new ArrayList();
627 for (int i
= 0; i
< bundlesSets
.size(); i
++) {
628 BundlesSet bundlesSet
= (BundlesSet
) bundlesSets
.get(i
);
629 for (int j
= 0; j
< bundlesSet
.getExcludes().size(); j
++) {
630 String pattern
= (String
) bundlesSet
.getExcludes().get(j
);
631 match(matcher
, excluded
, bundlesSet
.getDir(), null, pattern
);
636 for (int i
= 0; i
< included
.size(); i
++) {
637 String fullPath
= (String
) included
.get(i
);
638 if (!excluded
.contains(fullPath
))
639 urls
.add(locationToUrl(baseUrl
, fullPath
));
646 * DISTRIBUTION JAR INSTALLATION
648 public List
getDistributionUrls() {
649 List urls
= new ArrayList();
650 String distributionUrl
= OsgiBootUtils
651 .getProperty(PROP_ARGEO_OSGI_DISTRIBUTION_URL
);
652 if (distributionUrl
== null)
654 String baseUrl
= OsgiBootUtils
.getProperty(PROP_ARGEO_OSGI_BASE_URL
);
656 DistributionBundle distributionBundle
;
658 && !(distributionUrl
.startsWith("http") || distributionUrl
659 .startsWith("file"))) {
661 distributionBundle
= new DistributionBundle(baseUrl
,
664 distributionBundle
= new DistributionBundle(distributionUrl
);
666 distributionBundle
.setBaseUrl(baseUrl
);
669 distributionBundle
.processUrl();
670 return distributionBundle
.listUrls();
674 * MODULES LIST INSTALLATION (${argeo.osgi.modulesUrl})
677 * Downloads a list of URLs in CSV format from ${argeo.osgi.modulesUrl}:<br>
678 * <code>Bundle-SymbolicName,Bundle-Version,url</code>)<br>
679 * If ${argeo.osgi.baseUrl} is set, URLs will be considered relative paths
680 * and be concatenated with the base URL, typically the root of a Maven
685 public List
getModulesUrls() {
686 List urls
= new ArrayList();
687 String modulesUrlStr
= OsgiBootUtils
688 .getProperty(PROP_ARGEO_OSGI_MODULES_URL
);
689 if (modulesUrlStr
== null)
692 String baseUrl
= OsgiBootUtils
.getProperty(PROP_ARGEO_OSGI_BASE_URL
);
694 Map installedBundles
= getBundlesBySymbolicName();
696 BufferedReader reader
= null;
698 URL modulesUrl
= new URL(modulesUrlStr
);
699 reader
= new BufferedReader(new InputStreamReader(
700 modulesUrl
.openStream()));
702 while ((line
= reader
.readLine()) != null) {
703 StringTokenizer st
= new StringTokenizer(line
,
704 modulesUrlSeparator
);
705 String moduleName
= st
.nextToken();
706 String moduleVersion
= st
.nextToken();
707 String url
= st
.nextToken();
711 if (installedBundles
.containsKey(moduleName
)) {
712 Bundle bundle
= (Bundle
) installedBundles
.get(moduleName
);
713 String bundleVersion
= bundle
.getHeaders()
714 .get(Constants
.BUNDLE_VERSION
).toString();
715 int comp
= OsgiBootUtils
.compareVersions(bundleVersion
,
718 OsgiBootUtils
.warn("Installed version " + bundleVersion
719 + " of bundle " + moduleName
720 + " is newer than provided version "
722 } else if (comp
< 0) {
724 OsgiBootUtils
.info("Updated bundle " + moduleName
725 + " with version " + moduleVersion
726 + " (old version was " + bundleVersion
+ ")");
734 } catch (Exception e1
) {
735 throw new RuntimeException("Cannot read url " + modulesUrlStr
, e1
);
740 } catch (IOException e
) {
748 * HIGH LEVEL UTILITIES
750 /** Actually performs the matching logic. */
751 protected void match(PathMatcher matcher
, List matched
, String base
,
752 String currentPath
, String pattern
) {
753 if (currentPath
== null) {
755 File baseDir
= new File(base
.replace('/', File
.separatorChar
));
756 File
[] files
= baseDir
.listFiles();
760 OsgiBootUtils
.warn("Base dir " + baseDir
761 + " has no children, exists=" + baseDir
.exists()
762 + ", isDirectory=" + baseDir
.isDirectory());
766 for (int i
= 0; i
< files
.length
; i
++)
767 match(matcher
, matched
, base
, files
[i
].getName(), pattern
);
769 String fullPath
= base
+ '/' + currentPath
;
770 if (matched
.contains(fullPath
))
771 return;// don't try deeper if already matched
773 boolean ok
= matcher
.match(pattern
, currentPath
);
775 // debug(currentPath + " " + (ok ? "" : " not ")
776 // + " matched with " + pattern);
778 matched
.add(fullPath
);
781 String newFullPath
= relativeToFullPath(base
, currentPath
);
782 File newFile
= new File(newFullPath
);
783 File
[] files
= newFile
.listFiles();
785 for (int i
= 0; i
< files
.length
; i
++) {
786 String newCurrentPath
= currentPath
+ '/'
787 + files
[i
].getName();
788 if (files
[i
].isDirectory()) {
789 if (matcher
.matchStart(pattern
, newCurrentPath
)) {
790 // recurse only if start matches
791 match(matcher
, matched
, base
, newCurrentPath
,
796 + " does not start match with "
801 boolean nonDirectoryOk
= matcher
.match(pattern
,
804 debug(currentPath
+ " " + (ok ?
"" : " not ")
805 + " matched with " + pattern
);
807 matched
.add(relativeToFullPath(base
,
816 protected void matchFile() {
821 * LOW LEVEL UTILITIES
824 * The bundles already installed. Key is location (String) , value is a
827 public Map
getBundlesByLocation() {
828 Map installedBundles
= new HashMap();
829 Bundle
[] bundles
= bundleContext
.getBundles();
830 for (int i
= 0; i
< bundles
.length
; i
++) {
831 installedBundles
.put(bundles
[i
].getLocation(), bundles
[i
]);
833 return installedBundles
;
837 * The bundles already installed. Key is symbolic name (String) , value is a
840 public Map
getBundlesBySymbolicName() {
841 Map namedBundles
= new HashMap();
842 Bundle
[] bundles
= bundleContext
.getBundles();
843 for (int i
= 0; i
< bundles
.length
; i
++) {
844 namedBundles
.put(bundles
[i
].getSymbolicName(), bundles
[i
]);
849 /** Creates an URL from a location */
850 protected String
locationToUrl(String baseUrl
, String location
) {
851 int extInd
= location
.lastIndexOf('.');
854 ext
= location
.substring(extInd
);
856 if (baseUrl
.startsWith("reference:") && ".jar".equals(ext
))
857 return "file:" + location
;
859 return baseUrl
+ location
;
862 /** Transforms a relative path in a full system path. */
863 protected String
relativeToFullPath(String basePath
, String relativePath
) {
864 return (basePath
+ '/' + relativePath
).replace('/', File
.separatorChar
);
867 private String
removeFilePrefix(String url
) {
868 if (url
.startsWith("file:"))
869 return url
.substring("file:".length());
870 else if (url
.startsWith("reference:file:"))
871 return url
.substring("reference:file:".length());
877 * Convenience method to avoid cluttering the code with
878 * OsgiBootUtils.debug()
880 protected void debug(Object obj
) {
881 OsgiBootUtils
.debug(obj
);
888 public boolean getDebug() {
892 public void setDebug(boolean debug
) {
896 public BundleContext
getBundleContext() {
897 return bundleContext
;
900 public void setInstallInLexicographicOrder(
901 boolean installInAlphabeticalOrder
) {
902 this.installInLexicographicOrder
= installInAlphabeticalOrder
;
905 public boolean isInstallInLexicographicOrder() {
906 return installInLexicographicOrder
;
909 public void setDefaultTimeout(long defaultTimeout
) {
910 this.defaultTimeout
= defaultTimeout
;
913 public void setModulesUrlSeparator(String modulesUrlSeparator
) {
914 this.modulesUrlSeparator
= modulesUrlSeparator
;
917 public boolean isExcludeSvn() {
921 public void setExcludeSvn(boolean excludeSvn
) {
922 this.excludeSvn
= excludeSvn
;
929 /** Intermediary structure used by path matching */
930 protected class BundlesSet
{
931 private String baseUrl
= "reference:file";// not used yet
932 private final String dir
;
933 private List includes
= new ArrayList();
934 private List excludes
= new ArrayList();
936 public BundlesSet(String def
) {
937 StringTokenizer st
= new StringTokenizer(def
, ";");
939 if (!st
.hasMoreTokens())
940 throw new RuntimeException("Base dir not defined.");
942 String dirPath
= st
.nextToken();
944 if (dirPath
.startsWith("file:"))
945 dirPath
= dirPath
.substring("file:".length());
947 dir
= new File(dirPath
.replace('/', File
.separatorChar
))
950 debug("Base dir: " + dir
);
951 } catch (IOException e
) {
952 throw new RuntimeException("Cannot convert to absolute path", e
);
955 while (st
.hasMoreTokens()) {
956 String tk
= st
.nextToken();
957 StringTokenizer stEq
= new StringTokenizer(tk
, "=");
958 String type
= stEq
.nextToken();
959 String pattern
= stEq
.nextToken();
960 if ("in".equals(type
) || "include".equals(type
)) {
961 includes
.add(pattern
);
962 } else if ("ex".equals(type
) || "exclude".equals(type
)) {
963 excludes
.add(pattern
);
964 } else if ("baseUrl".equals(type
)) {
967 System
.err
.println("Unkown bundles pattern type " + type
);
971 if (excludeSvn
&& !excludes
.contains(EXCLUDES_SVN_PATTERN
)) {
972 excludes
.add(EXCLUDES_SVN_PATTERN
);
976 public String
getDir() {
980 public List
getIncludes() {
984 public List
getExcludes() {
988 public String
getBaseUrl() {
994 /* @deprecated Doesn't seem to be used anymore. */
995 // public void installOrUpdateUrls(Map urls) {
996 // Map installedBundles = getBundles();
998 // for (Iterator modules = urls.keySet().iterator(); modules.hasNext();) {
999 // String moduleName = (String) modules.next();
1000 // String urlStr = (String) urls.get(moduleName);
1001 // if (installedBundles.containsKey(moduleName)) {
1002 // Bundle bundle = (Bundle) installedBundles.get(moduleName);
1005 // URL url = new URL(urlStr);
1006 // in = url.openStream();
1007 // bundle.update(in);
1008 // OsgiBootUtils.info("Updated bundle " + moduleName
1009 // + " from " + urlStr);
1010 // } catch (Exception e) {
1011 // throw new RuntimeException("Cannot update " + moduleName
1012 // + " from " + urlStr);
1017 // } catch (IOException e) {
1018 // e.printStackTrace();
1022 // Bundle bundle = bundleContext.installBundle(urlStr);
1024 // debug("Installed bundle " + bundle.getSymbolicName()
1025 // + " from " + urlStr);
1026 // } catch (BundleException e) {
1027 // OsgiBootUtils.warn("Could not install bundle from "
1028 // + urlStr + ": " + e.getMessage());