]> git.argeo.org Git - lgpl/argeo-commons.git/blob - base/runtime/org.argeo.osgi.boot/src/main/java/org/argeo/osgi/boot/OsgiBoot.java
8d07219dfb9d29cbcc8662d16b0055822bc60282
[lgpl/argeo-commons.git] / base / runtime / org.argeo.osgi.boot / src / main / java / org / argeo / osgi / boot / OsgiBoot.java
1 /*
2 * Copyright (C) 2007-2012 Mathieu Baudier
3 *
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
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16 package org.argeo.osgi.boot;
17
18 import java.io.BufferedReader;
19 import java.io.File;
20 import java.io.IOException;
21 import java.io.InputStreamReader;
22 import java.net.URL;
23 import java.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.Iterator;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Properties;
29 import java.util.Set;
30 import java.util.SortedMap;
31 import java.util.StringTokenizer;
32 import java.util.TreeMap;
33 import java.util.TreeSet;
34
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;
45
46 /**
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.
51 */
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";
55
56 public final static String PROP_OSGI_STARTLEVEL = "osgi.startLevel";
57 public final static String PROP_OSGI_BUNDLES_DEFAULTSTARTLEVEL = "osgi.bundles.defaultStartLevel";
58
59 public final static String PROP_ARGEO_OSGI_DATA_DIR = "argeo.osgi.data.dir";
60
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";
65 /** @deprecated */
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";
68
69 // booleans
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";
73
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";
79
80 public final static String DEFAULT_BASE_URL = "reference:file:";
81 public final static String EXCLUDES_SVN_PATTERN = "**/.svn/**";
82
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";
86
87 private boolean debug = Boolean.valueOf(
88 System.getProperty(PROP_ARGEO_OSGI_BOOT_DEBUG, "false"))
89 .booleanValue();
90 /** Exclude svn metadata implicitely(a bit costly) */
91 private boolean excludeSvn = Boolean.valueOf(
92 System.getProperty(PROP_ARGEO_OSGI_BOOT_EXCLUDE_SVN, "false"))
93 .booleanValue();
94
95 /**
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.
100 */
101 private boolean installInLexicographicOrder = Boolean
102 .valueOf(
103 System.getProperty(
104 PROP_ARGEO_OSGI_BOOT_INSTALL_IN_LEXICOGRAPHIC_ORDER,
105 "true")).booleanValue();;
106
107 /** Default is 10s (set in constructor) */
108 private long defaultTimeout;
109
110 /** Default is ',' (set in constructor) */
111 private String modulesUrlSeparator = ",";
112
113 private final BundleContext bundleContext;
114
115 /*
116 * INITIALIZATION
117 */
118 /** Constructor */
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();
126 }
127
128 /**
129 * Set additional system properties, especially ${argeo.osgi.data.dir} as an
130 * OS file path (and not a file:// URL)
131 */
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");
137
138 File dataDir = null;
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");
149 }
150 System.setProperty(PROP_ARGEO_OSGI_DATA_DIR, dataDir.getAbsolutePath());
151 }
152
153 /*
154 * HIGH-LEVEL METHODS
155 */
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());
168 checkUnresolved();
169 startBundles();
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");
174
175 // display packages exported twice
176 if (debug) {
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());
188 }
189 }
190 }
191
192 System.out.println();
193 }
194
195 /*
196 * INSTALLATION
197 */
198 /** Install a single url. Convenience method. */
199 public Bundle installUrl(String url) {
200 List urls = new ArrayList();
201 urls.add(url);
202 installUrls(urls);
203 return (Bundle) getBundlesByLocation().get(url);
204 }
205
206 /** Install the bundles at this URL list. */
207 public void installUrls(List urls) {
208 Map installedBundles = getBundlesByLocation();
209
210 if (installInLexicographicOrder) {
211 SortedMap map = new TreeMap();
212 // reorder
213 for (int i = 0; i < urls.size(); i++) {
214 String url = (String) urls.get(i);
215 int index = url.lastIndexOf('/');
216 String fileName;
217 if (index >= 0)
218 fileName = url.substring(index + 1);
219 else
220 fileName = url;
221 map.put(fileName, url);
222 }
223
224 // install
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);
230 }
231 } else {
232 for (int i = 0; i < urls.size(); i++) {
233 String url = (String) urls.get(i);
234 installUrl(url, installedBundles);
235 }
236 }
237
238 }
239
240 /** Actually install the provided URL */
241 protected void installUrl(String url, Map installedBundles) {
242 try {
243 if (installedBundles.containsKey(url)) {
244 Bundle bundle = (Bundle) installedBundles.get(url);
245 // bundle.update();
246 if (debug)
247 debug("Bundle " + bundle.getSymbolicName()
248 + " already installed from " + url);
249 } else {
250 Bundle bundle = bundleContext.installBundle(url);
251 if (debug)
252 debug("Installed bundle " + bundle.getSymbolicName()
253 + " from " + url);
254 }
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...
262 } else {
263 OsgiBootUtils.warn("Could not install bundle from " + url
264 + ": " + message);
265 }
266 if (debug)
267 e.printStackTrace();
268 }
269 }
270
271 /*
272 * START
273 */
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));
280
281 SortedMap/* <Integer, List<String>> */startLevels = new TreeMap();
282 computeStartLevels(startLevels, System.getProperties(),
283 defaultStartLevel);
284
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));
289 if (!allStarted)
290 OsgiBootUtils
291 .warn("Not all bundles started for level " + level);
292 if (level.equals(activeStartLevel))
293 break;// active start level reached
294 }
295
296 }
297
298 public static void computeStartLevels(
299 SortedMap/* <Integer, List<String>> */startLevels,
300 Properties properties, Integer defaultStartLevel) {
301
302 // default (and previously, only behaviour)
303 appendToStartLevels(startLevels, defaultStartLevel,
304 properties.getProperty(PROP_ARGEO_OSGI_START, ""));
305
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)) {
312 Integer startLevel;
313 String suffix = key.substring(prefix.length());
314 String[] tokens = suffix.split("\\.");
315 if (tokens.length > 0 && !tokens[0].trim().equals(""))
316 try {
317 // first token is start level
318 startLevel = new Integer(tokens[0]);
319 } catch (NumberFormatException e) {
320 startLevel = defaultStartLevel;
321 }
322 else
323 startLevel = defaultStartLevel;
324
325 // append bundle names
326 String bundleNames = properties.getProperty(key);
327 appendToStartLevels(startLevels, startLevel, bundleNames);
328 }
329 }
330 }
331
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(""))
337 return;
338
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]);
345 }
346 }
347
348 /**
349 * Convenience method accepting a comma-separated list of bundle to start
350 *
351 * @deprecated
352 */
353 public void startBundles(String bundlesToStartStr) {
354 if (bundlesToStartStr == null)
355 return;
356
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);
362 }
363 startBundles(bundlesToStart);
364 }
365
366 /**
367 * Start the provided list of bundles
368 *
369 * @return whether all bundlesa are now in active state
370 */
371 public boolean startBundles(List bundlesToStart) {
372 if (bundlesToStart.size() == 0)
373 return true;
374
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);
379
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))
386 try {
387 try {
388 bundle.start();
389 if (debug)
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);
397 bundle.start();
398 startedBundles.add(bundle);
399 }
400 notFoundBundles.remove(symbolicName);
401 } catch (Exception e) {
402 OsgiBootUtils.warn("Bundle " + symbolicName
403 + " cannot be started: " + e.getMessage());
404 if (debug)
405 e.printStackTrace();
406 // was found even if start failed
407 notFoundBundles.remove(symbolicName);
408 }
409 }
410
411 for (int i = 0; i < notFoundBundles.size(); i++)
412 OsgiBootUtils.warn("Bundle '" + notFoundBundles.get(i)
413 + "' not started because it was not found.");
414
415 // monitors that all bundles are started
416 long beginMonitor = System.currentTimeMillis();
417 boolean allStarted = false;
418 List/* <String> */notStarted = new ArrayList();
419 while (allStarted
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) {
426 allStarted = false;
427 notStarted.add(bundle.getSymbolicName());
428 }
429 }
430 try {
431 Thread.sleep(100);
432 } catch (InterruptedException e) {
433 // silent
434 }
435 }
436 long duration = System.currentTimeMillis() - beginMonitor;
437
438 if (!allStarted)
439 for (int i = 0; i < notStarted.size(); i++)
440 OsgiBootUtils.warn("Bundle '" + notStarted.get(i)
441 + "' not ACTIVE after " + (duration / 1000) + "s");
442
443 return allStarted;
444 }
445
446 /*
447 * DIAGNOSTICS
448 */
449 /** Check unresolved bundles */
450 protected void checkUnresolved() {
451 // Refresh
452 ServiceReference packageAdminRef = bundleContext
453 .getServiceReference(PackageAdmin.class.getName());
454 PackageAdmin packageAdmin = (PackageAdmin) bundleContext
455 .getService(packageAdminRef);
456 packageAdmin.resolveBundles(null);
457
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]);
465 }
466
467 if (unresolvedBundles.size() != 0) {
468 OsgiBootUtils.warn("Unresolved bundles " + unresolvedBundles);
469 }
470 }
471
472 /** List packages exported twice. */
473 public Map findPackagesExportedTwice() {
474 ServiceReference paSr = bundleContext
475 .getServiceReference(PackageAdmin.class.getName());
476 PackageAdmin packageAdmin = (PackageAdmin) bundleContext
477 .getService(paSr);
478
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);
485 if (pkgs != null)
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());
490 }
491 ((Set) exportedPackages.get(pkgName)).add(bundle
492 .getSymbolicName() + "_" + bundle.getVersion());
493 }
494 }
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);
502 }
503 return duplicatePackages;
504 }
505
506 /** Waits for a bundle to become active or resolved */
507 protected void waitForBundleResolvedOrActive(long startBegin, Bundle bundle)
508 throws Exception {
509 int originalState = bundle.getState();
510 if ((originalState == Bundle.RESOLVED)
511 || (originalState == Bundle.ACTIVE))
512 return;
513
514 String originalStateStr = OsgiBootUtils.stateAsString(originalState);
515
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) + ")");
525
526 try {
527 Thread.sleep(100l);
528 } catch (InterruptedException e) {
529 // silent
530 }
531 currentState = bundle.getState();
532 }
533 }
534
535 /*
536 * EXPLICIT LOCATIONS INSTALLATION
537 */
538 /** Gets the list of resolved explicit URL locations. */
539 public List getLocationsUrls() {
540 String baseUrl = OsgiBootUtils.getProperty(PROP_ARGEO_OSGI_BASE_URL,
541 DEFAULT_BASE_URL);
542 String bundleLocations = OsgiBootUtils
543 .getProperty(PROP_ARGEO_OSGI_LOCATIONS);
544 return getLocationsUrls(baseUrl, bundleLocations);
545 }
546
547 /**
548 * Gets a list of URLs based on explicit locations, resolving placeholder
549 * ${...} containing system properties, e.g. ${user.home}.
550 */
551 public List getLocationsUrls(String baseUrl, String bundleLocations) {
552 List urls = new ArrayList();
553
554 if (bundleLocations == null)
555 return urls;
556 bundleLocations = SystemPropertyUtils
557 .resolvePlaceholders(bundleLocations);
558 if (debug)
559 debug(PROP_ARGEO_OSGI_LOCATIONS + "=" + bundleLocations);
560
561 StringTokenizer st = new StringTokenizer(bundleLocations,
562 File.pathSeparator);
563 while (st.hasMoreTokens()) {
564 urls.add(locationToUrl(baseUrl, st.nextToken().trim()));
565 }
566 return urls;
567 }
568
569 /*
570 * BUNDLE PATTERNS INSTALLATION
571 */
572 /**
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
578 * effects.
579 */
580 public List getBundlesUrls() {
581 String bundlePatterns = OsgiBootUtils
582 .getProperty(PROP_ARGEO_OSGI_BUNDLES);
583 return getBundlesUrls(bundlePatterns);
584 }
585
586 /**
587 * Compute alist of URLs to install based on the provided patterns, with
588 * default base url
589 */
590 public List getBundlesUrls(String bundlePatterns) {
591 String baseUrl = OsgiBootUtils.getProperty(PROP_ARGEO_OSGI_BASE_URL,
592 DEFAULT_BASE_URL);
593 return getBundlesUrls(baseUrl, bundlePatterns);
594 }
595
596 /** Implements the path matching logic */
597 List getBundlesUrls(String baseUrl, String bundlePatterns) {
598 List urls = new ArrayList();
599 if (bundlePatterns == null)
600 return urls;
601
602 bundlePatterns = SystemPropertyUtils
603 .resolvePlaceholders(bundlePatterns);
604 if (debug)
605 debug(PROP_ARGEO_OSGI_BUNDLES + "=" + bundlePatterns
606 + " (excludeSvn=" + excludeSvn + ")");
607
608 StringTokenizer st = new StringTokenizer(bundlePatterns, ",");
609 List bundlesSets = new ArrayList();
610 while (st.hasMoreTokens()) {
611 bundlesSets.add(new BundlesSet(st.nextToken()));
612 }
613
614 // find included
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);
622 }
623 }
624
625 // find excluded
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);
632 }
633 }
634
635 // construct list
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));
640 }
641
642 return urls;
643 }
644
645 /*
646 * DISTRIBUTION JAR INSTALLATION
647 */
648 public List getDistributionUrls() {
649 List urls = new ArrayList();
650 String distributionUrl = OsgiBootUtils
651 .getProperty(PROP_ARGEO_OSGI_DISTRIBUTION_URL);
652 if (distributionUrl == null)
653 return urls;
654 String baseUrl = OsgiBootUtils.getProperty(PROP_ARGEO_OSGI_BASE_URL);
655
656 DistributionBundle distributionBundle;
657 if (baseUrl != null
658 && !(distributionUrl.startsWith("http") || distributionUrl
659 .startsWith("file"))) {
660 // relative url
661 distributionBundle = new DistributionBundle(baseUrl,
662 distributionUrl);
663 } else {
664 distributionBundle = new DistributionBundle(distributionUrl);
665 if (baseUrl != null)
666 distributionBundle.setBaseUrl(baseUrl);
667
668 }
669 distributionBundle.processUrl();
670 return distributionBundle.listUrls();
671 }
672
673 /*
674 * MODULES LIST INSTALLATION (${argeo.osgi.modulesUrl})
675 */
676 /**
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
681 * repository.
682 *
683 * @deprecated
684 */
685 public List getModulesUrls() {
686 List urls = new ArrayList();
687 String modulesUrlStr = OsgiBootUtils
688 .getProperty(PROP_ARGEO_OSGI_MODULES_URL);
689 if (modulesUrlStr == null)
690 return urls;
691
692 String baseUrl = OsgiBootUtils.getProperty(PROP_ARGEO_OSGI_BASE_URL);
693
694 Map installedBundles = getBundlesBySymbolicName();
695
696 BufferedReader reader = null;
697 try {
698 URL modulesUrl = new URL(modulesUrlStr);
699 reader = new BufferedReader(new InputStreamReader(
700 modulesUrl.openStream()));
701 String line = null;
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();
708 if (baseUrl != null)
709 url = baseUrl + url;
710
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,
716 moduleVersion);
717 if (comp > 0) {
718 OsgiBootUtils.warn("Installed version " + bundleVersion
719 + " of bundle " + moduleName
720 + " is newer than provided version "
721 + moduleVersion);
722 } else if (comp < 0) {
723 urls.add(url);
724 OsgiBootUtils.info("Updated bundle " + moduleName
725 + " with version " + moduleVersion
726 + " (old version was " + bundleVersion + ")");
727 } else {
728 // do nothing
729 }
730 } else {
731 urls.add(url);
732 }
733 }
734 } catch (Exception e1) {
735 throw new RuntimeException("Cannot read url " + modulesUrlStr, e1);
736 } finally {
737 if (reader != null)
738 try {
739 reader.close();
740 } catch (IOException e) {
741 e.printStackTrace();
742 }
743 }
744 return urls;
745 }
746
747 /*
748 * HIGH LEVEL UTILITIES
749 */
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) {
754 // Init
755 File baseDir = new File(base.replace('/', File.separatorChar));
756 File[] files = baseDir.listFiles();
757
758 if (files == null) {
759 if (debug)
760 OsgiBootUtils.warn("Base dir " + baseDir
761 + " has no children, exists=" + baseDir.exists()
762 + ", isDirectory=" + baseDir.isDirectory());
763 return;
764 }
765
766 for (int i = 0; i < files.length; i++)
767 match(matcher, matched, base, files[i].getName(), pattern);
768 } else {
769 String fullPath = base + '/' + currentPath;
770 if (matched.contains(fullPath))
771 return;// don't try deeper if already matched
772
773 boolean ok = matcher.match(pattern, currentPath);
774 // if (debug)
775 // debug(currentPath + " " + (ok ? "" : " not ")
776 // + " matched with " + pattern);
777 if (ok) {
778 matched.add(fullPath);
779 return;
780 } else {
781 String newFullPath = relativeToFullPath(base, currentPath);
782 File newFile = new File(newFullPath);
783 File[] files = newFile.listFiles();
784 if (files != null) {
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,
792 pattern);
793 } else {
794 if (debug)
795 debug(newCurrentPath
796 + " does not start match with "
797 + pattern);
798
799 }
800 } else {
801 boolean nonDirectoryOk = matcher.match(pattern,
802 newCurrentPath);
803 if (debug)
804 debug(currentPath + " " + (ok ? "" : " not ")
805 + " matched with " + pattern);
806 if (nonDirectoryOk)
807 matched.add(relativeToFullPath(base,
808 newCurrentPath));
809 }
810 }
811 }
812 }
813 }
814 }
815
816 protected void matchFile() {
817
818 }
819
820 /*
821 * LOW LEVEL UTILITIES
822 */
823 /**
824 * The bundles already installed. Key is location (String) , value is a
825 * {@link Bundle}
826 */
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]);
832 }
833 return installedBundles;
834 }
835
836 /**
837 * The bundles already installed. Key is symbolic name (String) , value is a
838 * {@link Bundle}
839 */
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]);
845 }
846 return namedBundles;
847 }
848
849 /** Creates an URL from a location */
850 protected String locationToUrl(String baseUrl, String location) {
851 int extInd = location.lastIndexOf('.');
852 String ext = null;
853 if (extInd > 0)
854 ext = location.substring(extInd);
855
856 if (baseUrl.startsWith("reference:") && ".jar".equals(ext))
857 return "file:" + location;
858 else
859 return baseUrl + location;
860 }
861
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);
865 }
866
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());
872 else
873 return url;
874 }
875
876 /**
877 * Convenience method to avoid cluttering the code with
878 * OsgiBootUtils.debug()
879 */
880 protected void debug(Object obj) {
881 OsgiBootUtils.debug(obj);
882 }
883
884 /*
885 * BEAN METHODS
886 */
887
888 public boolean getDebug() {
889 return debug;
890 }
891
892 public void setDebug(boolean debug) {
893 this.debug = debug;
894 }
895
896 public BundleContext getBundleContext() {
897 return bundleContext;
898 }
899
900 public void setInstallInLexicographicOrder(
901 boolean installInAlphabeticalOrder) {
902 this.installInLexicographicOrder = installInAlphabeticalOrder;
903 }
904
905 public boolean isInstallInLexicographicOrder() {
906 return installInLexicographicOrder;
907 }
908
909 public void setDefaultTimeout(long defaultTimeout) {
910 this.defaultTimeout = defaultTimeout;
911 }
912
913 public void setModulesUrlSeparator(String modulesUrlSeparator) {
914 this.modulesUrlSeparator = modulesUrlSeparator;
915 }
916
917 public boolean isExcludeSvn() {
918 return excludeSvn;
919 }
920
921 public void setExcludeSvn(boolean excludeSvn) {
922 this.excludeSvn = excludeSvn;
923 }
924
925 /*
926 * INTERNAL CLASSES
927 */
928
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();
935
936 public BundlesSet(String def) {
937 StringTokenizer st = new StringTokenizer(def, ";");
938
939 if (!st.hasMoreTokens())
940 throw new RuntimeException("Base dir not defined.");
941 try {
942 String dirPath = st.nextToken();
943
944 if (dirPath.startsWith("file:"))
945 dirPath = dirPath.substring("file:".length());
946
947 dir = new File(dirPath.replace('/', File.separatorChar))
948 .getCanonicalPath();
949 if (debug)
950 debug("Base dir: " + dir);
951 } catch (IOException e) {
952 throw new RuntimeException("Cannot convert to absolute path", e);
953 }
954
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)) {
965 baseUrl = pattern;
966 } else {
967 System.err.println("Unkown bundles pattern type " + type);
968 }
969 }
970
971 if (excludeSvn && !excludes.contains(EXCLUDES_SVN_PATTERN)) {
972 excludes.add(EXCLUDES_SVN_PATTERN);
973 }
974 }
975
976 public String getDir() {
977 return dir;
978 }
979
980 public List getIncludes() {
981 return includes;
982 }
983
984 public List getExcludes() {
985 return excludes;
986 }
987
988 public String getBaseUrl() {
989 return baseUrl;
990 }
991
992 }
993
994 /* @deprecated Doesn't seem to be used anymore. */
995 // public void installOrUpdateUrls(Map urls) {
996 // Map installedBundles = getBundles();
997 //
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);
1003 // InputStream in;
1004 // try {
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);
1013 // }
1014 // if (in != null)
1015 // try {
1016 // in.close();
1017 // } catch (IOException e) {
1018 // e.printStackTrace();
1019 // }
1020 // } else {
1021 // try {
1022 // Bundle bundle = bundleContext.installBundle(urlStr);
1023 // if (debug)
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());
1029 // }
1030 // }
1031 // }
1032 //
1033 // }
1034
1035 }