]> git.argeo.org Git - lgpl/argeo-commons.git/blob - OsgiBoot.java
276e13c79a0fe45cd9e19a4bdf86258ed354bbee
[lgpl/argeo-commons.git] / OsgiBoot.java
1 /*
2 * Copyright (C) 2010 Mathieu Baudier <mbaudier@argeo.org>
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
17 package org.argeo.osgi.boot;
18
19 import java.io.BufferedReader;
20 import java.io.File;
21 import java.io.IOException;
22 import java.io.InputStreamReader;
23 import java.net.URL;
24 import java.util.ArrayList;
25 import java.util.HashMap;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.Map;
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_ARGEO_OSGI_DATA_DIR = "argeo.osgi.data.dir";
57
58 public final static String PROP_ARGEO_OSGI_START = "argeo.osgi.start";
59 public final static String PROP_ARGEO_OSGI_BUNDLES = "argeo.osgi.bundles";
60 public final static String PROP_ARGEO_OSGI_LOCATIONS = "argeo.osgi.locations";
61 public final static String PROP_ARGEO_OSGI_BASE_URL = "argeo.osgi.baseUrl";
62 /** Use org.argeo.osgi */
63 public final static String PROP_ARGEO_OSGI_MODULES_URL = "argeo.osgi.modulesUrl";
64
65 // booleans
66 public final static String PROP_ARGEO_OSGI_BOOT_DEBUG = "argeo.osgi.boot.debug";
67 public final static String PROP_ARGEO_OSGI_BOOT_EXCLUDE_SVN = "argeo.osgi.boot.excludeSvn";
68 public final static String PROP_ARGEO_OSGI_BOOT_INSTALL_IN_LEXICOGRAPHIC_ORDER = "argeo.osgi.boot.installInLexicographicOrder";
69
70 public final static String PROP_ARGEO_OSGI_BOOT_DEFAULT_TIMEOUT = "argeo.osgi.boot.defaultTimeout";
71 public final static String PROP_ARGEO_OSGI_BOOT_MODULES_URL_SEPARATOR = "argeo.osgi.boot.modulesUrlSeparator";
72 public final static String PROP_ARGEO_OSGI_BOOT_SYSTEM_PROPERTIES_FILE = "argeo.osgi.boot.systemPropertiesFile";
73 public final static String PROP_ARGEO_OSGI_BOOT_APPCLASS = "argeo.osgi.boot.appclass";
74 public final static String PROP_ARGEO_OSGI_BOOT_APPARGS = "argeo.osgi.boot.appargs";
75
76 public final static String DEFAULT_BASE_URL = "reference:file:";
77 public final static String EXCLUDES_SVN_PATTERN = "**/.svn/**";
78
79 // OSGi system properties
80 public final static String INSTANCE_AREA_PROP = "osgi.instance.area";
81 public final static String INSTANCE_AREA_DEFAULT_PROP = "osgi.instance.area.default";
82
83 private boolean debug = Boolean.valueOf(
84 System.getProperty(PROP_ARGEO_OSGI_BOOT_DEBUG, "false"))
85 .booleanValue();
86 /** Exclude svn metadata implicitely(a bit costly) */
87 private boolean excludeSvn = Boolean.valueOf(
88 System.getProperty(PROP_ARGEO_OSGI_BOOT_EXCLUDE_SVN, "false"))
89 .booleanValue();
90
91 /**
92 * The {@link #installUrls(List)} methods won't follow the list order but
93 * order the urls according to the alphabetical order of the file names
94 * (last part of the URL). The goal is to stay closer from Eclipse PDE way
95 * of installing target platform bundles.
96 */
97 private boolean installInLexicographicOrder = Boolean
98 .valueOf(
99 System.getProperty(
100 PROP_ARGEO_OSGI_BOOT_INSTALL_IN_LEXICOGRAPHIC_ORDER,
101 "true")).booleanValue();;
102
103 /** Default is 10s (set in constructor) */
104 private long defaultTimeout;
105
106 /** Default is ',' (set in constructor) */
107 private String modulesUrlSeparator = ",";
108
109 private final BundleContext bundleContext;
110
111 /*
112 * INITIALIZATION
113 */
114 /** Constructor */
115 public OsgiBoot(BundleContext bundleContext) {
116 this.bundleContext = bundleContext;
117 defaultTimeout = Long.parseLong(OsgiBootUtils.getProperty(
118 PROP_ARGEO_OSGI_BOOT_DEFAULT_TIMEOUT, "10000"));
119 modulesUrlSeparator = OsgiBootUtils.getProperty(
120 PROP_ARGEO_OSGI_BOOT_MODULES_URL_SEPARATOR, ",");
121 initSystemProperties();
122 }
123
124 /**
125 * Set additional system properties, especially ${argeo.osgi.data.dir} as an
126 * OS file path (and not a file:// URL)
127 */
128 protected void initSystemProperties() {
129 String osgiInstanceArea = System.getProperty(INSTANCE_AREA_PROP);
130 String osgiInstanceAreaDefault = System
131 .getProperty(INSTANCE_AREA_DEFAULT_PROP);
132 String tempDir = System.getProperty("java.io.tmpdir");
133
134 File dataDir = null;
135 if (osgiInstanceArea != null) {
136 // within OSGi with -data specified
137 osgiInstanceArea = removeFilePrefix(osgiInstanceArea);
138 dataDir = new File(osgiInstanceArea);
139 } else if (osgiInstanceAreaDefault != null) {
140 // within OSGi without -data specified
141 osgiInstanceAreaDefault = removeFilePrefix(osgiInstanceAreaDefault);
142 dataDir = new File(osgiInstanceAreaDefault);
143 } else {// outside OSGi
144 dataDir = new File(tempDir + File.separator + "argeoOsgiData");
145 }
146 System.setProperty(PROP_ARGEO_OSGI_DATA_DIR, dataDir.getAbsolutePath());
147 }
148
149 /*
150 * HIGH-LEVEL METHODS
151 */
152 /** Bootstraps the OSGi runtime */
153 public void bootstrap() {
154 long begin = System.currentTimeMillis();
155 System.out.println();
156 OsgiBootUtils.info("OSGi bootstrap starting...");
157 OsgiBootUtils.info("Writable data directory : "
158 + System.getProperty(PROP_ARGEO_OSGI_DATA_DIR)
159 + " (set as system property " + PROP_ARGEO_OSGI_DATA_DIR + ")");
160 installUrls(getBundlesUrls());
161 installUrls(getLocationsUrls());
162 installUrls(getModulesUrls());
163 checkUnresolved();
164 startBundles();
165 long duration = System.currentTimeMillis() - begin;
166 OsgiBootUtils.info("OSGi bootstrap completed in "
167 + Math.round(((double) duration) / 1000) + "s (" + duration
168 + "ms), " + bundleContext.getBundles().length + " bundles");
169
170 // display packages exported twice
171 if (debug) {
172 Map /* <String,Set<String>> */duplicatePackages = findPackagesExportedTwice();
173 if (duplicatePackages.size() > 0) {
174 OsgiBootUtils.info("Packages exported twice:");
175 Iterator it = duplicatePackages.keySet().iterator();
176 while (it.hasNext()) {
177 String pkgName = it.next().toString();
178 OsgiBootUtils.info(pkgName);
179 Set bdles = (Set) duplicatePackages.get(pkgName);
180 Iterator bdlesIt = bdles.iterator();
181 while (bdlesIt.hasNext())
182 OsgiBootUtils.info(" " + bdlesIt.next());
183 }
184 }
185 }
186
187 System.out.println();
188 }
189
190 /*
191 * INSTALLATION
192 */
193 /** Install the bundles at this URL list. */
194 public void installUrls(List urls) {
195 Map installedBundles = getBundlesByLocation();
196
197 if (installInLexicographicOrder) {
198 SortedMap map = new TreeMap();
199 // reorder
200 for (int i = 0; i < urls.size(); i++) {
201 String url = (String) urls.get(i);
202 int index = url.lastIndexOf('/');
203 String fileName;
204 if (index >= 0)
205 fileName = url.substring(index + 1);
206 else
207 fileName = url;
208 map.put(fileName, url);
209 }
210
211 // install
212 Iterator keys = map.keySet().iterator();
213 while (keys.hasNext()) {
214 Object key = keys.next();
215 String url = map.get(key).toString();
216 installUrl(url, installedBundles);
217 }
218 } else {
219 for (int i = 0; i < urls.size(); i++) {
220 String url = (String) urls.get(i);
221 installUrl(url, installedBundles);
222 }
223 }
224
225 }
226
227 /** Actually install the provided URL */
228 protected void installUrl(String url, Map installedBundles) {
229 try {
230 if (installedBundles.containsKey(url)) {
231 Bundle bundle = (Bundle) installedBundles.get(url);
232 // bundle.update();
233 if (debug)
234 debug("Bundle " + bundle.getSymbolicName()
235 + " already installed from " + url);
236 } else {
237 Bundle bundle = bundleContext.installBundle(url);
238 if (debug)
239 debug("Installed bundle " + bundle.getSymbolicName()
240 + " from " + url);
241 }
242 } catch (BundleException e) {
243 String message = e.getMessage();
244 if ((message.contains("Bundle \"" + SYMBOLIC_NAME_OSGI_BOOT + "\"") || message
245 .contains("Bundle \"" + SYMBOLIC_NAME_EQUINOX + "\""))
246 && message.contains("has already been installed")) {
247 // silent, in order to avoid warnings: we know that both
248 // have already been installed...
249 } else {
250 OsgiBootUtils.warn("Could not install bundle from " + url
251 + ": " + message);
252 }
253 if (debug)
254 e.printStackTrace();
255 }
256 }
257
258 /* @deprecated Doesn't seem to be used anymore. */
259 // public void installOrUpdateUrls(Map urls) {
260 // Map installedBundles = getBundles();
261 //
262 // for (Iterator modules = urls.keySet().iterator(); modules.hasNext();) {
263 // String moduleName = (String) modules.next();
264 // String urlStr = (String) urls.get(moduleName);
265 // if (installedBundles.containsKey(moduleName)) {
266 // Bundle bundle = (Bundle) installedBundles.get(moduleName);
267 // InputStream in;
268 // try {
269 // URL url = new URL(urlStr);
270 // in = url.openStream();
271 // bundle.update(in);
272 // OsgiBootUtils.info("Updated bundle " + moduleName
273 // + " from " + urlStr);
274 // } catch (Exception e) {
275 // throw new RuntimeException("Cannot update " + moduleName
276 // + " from " + urlStr);
277 // }
278 // if (in != null)
279 // try {
280 // in.close();
281 // } catch (IOException e) {
282 // e.printStackTrace();
283 // }
284 // } else {
285 // try {
286 // Bundle bundle = bundleContext.installBundle(urlStr);
287 // if (debug)
288 // debug("Installed bundle " + bundle.getSymbolicName()
289 // + " from " + urlStr);
290 // } catch (BundleException e) {
291 // OsgiBootUtils.warn("Could not install bundle from "
292 // + urlStr + ": " + e.getMessage());
293 // }
294 // }
295 // }
296 //
297 // }
298
299 /*
300 * START
301 */
302 public void startBundles() {
303 String bundlesToStart = OsgiBootUtils
304 .getProperty(PROP_ARGEO_OSGI_START);
305 startBundles(bundlesToStart);
306 }
307
308 /** Convenience method accepting a comma-separated list of bundle to start */
309 public void startBundles(String bundlesToStartStr) {
310 if (bundlesToStartStr == null)
311 return;
312
313 StringTokenizer st = new StringTokenizer(bundlesToStartStr, ",");
314 List bundlesToStart = new ArrayList();
315 while (st.hasMoreTokens()) {
316 String name = st.nextToken().trim();
317 bundlesToStart.add(name);
318 }
319 startBundles(bundlesToStart);
320 }
321
322 /** Start the provided list of bundles */
323 public void startBundles(List bundlesToStart) {
324 if (bundlesToStart.size() == 0)
325 return;
326
327 // used to log the bundles not found
328 List notFoundBundles = new ArrayList(bundlesToStart);
329
330 Bundle[] bundles = bundleContext.getBundles();
331 long startBegin = System.currentTimeMillis();
332 for (int i = 0; i < bundles.length; i++) {
333 Bundle bundle = bundles[i];
334 String symbolicName = bundle.getSymbolicName();
335 if (bundlesToStart.contains(symbolicName))
336 try {
337 try {
338 bundle.start();
339 if (debug)
340 debug("Bundle " + symbolicName + " started");
341 } catch (Exception e) {
342 OsgiBootUtils.warn("Start of bundle " + symbolicName
343 + " failed because of " + e
344 + ", maybe bundle is not yet resolved,"
345 + " waiting and trying again.");
346 waitForBundleResolvedOrActive(startBegin, bundle);
347 bundle.start();
348 }
349 notFoundBundles.remove(symbolicName);
350 } catch (Exception e) {
351 OsgiBootUtils.warn("Bundle " + symbolicName
352 + " cannot be started: " + e.getMessage());
353 if (debug)
354 e.printStackTrace();
355 // was found even if start failed
356 notFoundBundles.remove(symbolicName);
357 }
358 }
359
360 for (int i = 0; i < notFoundBundles.size(); i++)
361 OsgiBootUtils.warn("Bundle " + notFoundBundles.get(i)
362 + " not started because it was not found.");
363 }
364
365 /*
366 * DIAGNOSTICS
367 */
368 /** Check unresolved bundles */
369 protected void checkUnresolved() {
370 // Refresh
371 ServiceReference packageAdminRef = bundleContext
372 .getServiceReference(PackageAdmin.class.getName());
373 PackageAdmin packageAdmin = (PackageAdmin) bundleContext
374 .getService(packageAdminRef);
375 packageAdmin.resolveBundles(null);
376
377 Bundle[] bundles = bundleContext.getBundles();
378 List /* Bundle */unresolvedBundles = new ArrayList();
379 for (int i = 0; i < bundles.length; i++) {
380 int bundleState = bundles[i].getState();
381 if (!(bundleState == Bundle.ACTIVE
382 || bundleState == Bundle.RESOLVED || bundleState == Bundle.STARTING))
383 unresolvedBundles.add(bundles[i]);
384 }
385
386 if (unresolvedBundles.size() != 0) {
387 OsgiBootUtils.warn("Unresolved bundles " + unresolvedBundles);
388 }
389 }
390
391 /** List packages exported twice. */
392 public Map findPackagesExportedTwice() {
393 ServiceReference paSr = bundleContext
394 .getServiceReference(PackageAdmin.class.getName());
395 PackageAdmin packageAdmin = (PackageAdmin) bundleContext
396 .getService(paSr);
397
398 // find packages exported twice
399 Bundle[] bundles = bundleContext.getBundles();
400 Map /* <String,Set<String>> */exportedPackages = new TreeMap();
401 for (int i = 0; i < bundles.length; i++) {
402 Bundle bundle = bundles[i];
403 ExportedPackage[] pkgs = packageAdmin.getExportedPackages(bundle);
404 if (pkgs != null)
405 for (int j = 0; j < pkgs.length; j++) {
406 String pkgName = pkgs[j].getName();
407 if (!exportedPackages.containsKey(pkgName)) {
408 exportedPackages.put(pkgName, new TreeSet());
409 }
410 ((Set) exportedPackages.get(pkgName)).add(bundle
411 .getSymbolicName() + "_" + bundle.getVersion());
412 }
413 }
414 Map /* <String,Set<String>> */duplicatePackages = new TreeMap();
415 Iterator it = exportedPackages.keySet().iterator();
416 while (it.hasNext()) {
417 String pkgName = it.next().toString();
418 Set bdles = (Set) exportedPackages.get(pkgName);
419 if (bdles.size() > 1)
420 duplicatePackages.put(pkgName, bdles);
421 }
422 return duplicatePackages;
423 }
424
425 /** Waits for a bundle to become active or resolved */
426 protected void waitForBundleResolvedOrActive(long startBegin, Bundle bundle)
427 throws Exception {
428 int originalState = bundle.getState();
429 if ((originalState == Bundle.RESOLVED)
430 || (originalState == Bundle.ACTIVE))
431 return;
432
433 String originalStateStr = OsgiBootUtils.stateAsString(originalState);
434
435 int currentState = bundle.getState();
436 while (!(currentState == Bundle.RESOLVED || currentState == Bundle.ACTIVE)) {
437 long now = System.currentTimeMillis();
438 if ((now - startBegin) > defaultTimeout)
439 throw new Exception("Bundle " + bundle.getSymbolicName()
440 + " was not RESOLVED or ACTIVE after "
441 + (now - startBegin) + "ms (originalState="
442 + originalStateStr + ", currentState="
443 + OsgiBootUtils.stateAsString(currentState) + ")");
444
445 try {
446 Thread.sleep(100l);
447 } catch (InterruptedException e) {
448 // silent
449 }
450 currentState = bundle.getState();
451 }
452 }
453
454 /*
455 * EXPLICIT LOCATIONS INSTALLATION
456 */
457 /** Gets the list of resolved explicit URL locations. */
458 public List getLocationsUrls() {
459 String baseUrl = OsgiBootUtils.getProperty(PROP_ARGEO_OSGI_BASE_URL,
460 DEFAULT_BASE_URL);
461 String bundleLocations = OsgiBootUtils
462 .getProperty(PROP_ARGEO_OSGI_LOCATIONS);
463 return getLocationsUrls(baseUrl, bundleLocations);
464 }
465
466 /**
467 * Gets a list of URLs based on explicit locations, resolving placeholder
468 * ${...} containing system properties, e.g. ${user.home}.
469 */
470 public List getLocationsUrls(String baseUrl, String bundleLocations) {
471 List urls = new ArrayList();
472
473 if (bundleLocations == null)
474 return urls;
475 bundleLocations = SystemPropertyUtils
476 .resolvePlaceholders(bundleLocations);
477 if (debug)
478 debug(PROP_ARGEO_OSGI_LOCATIONS + "=" + bundleLocations);
479
480 StringTokenizer st = new StringTokenizer(bundleLocations,
481 File.pathSeparator);
482 while (st.hasMoreTokens()) {
483 urls.add(locationToUrl(baseUrl, st.nextToken().trim()));
484 }
485 return urls;
486 }
487
488 /*
489 * BUNDLE PATTERNS INSTALLATION
490 */
491 /**
492 * Computes a list of URLs based on Ant-like incluide/exclude patterns
493 * defined by ${argeo.osgi.bundles} with the following format:<br>
494 * <code>/base/directory;in=*.jar;in=**;ex=org.eclipse.osgi_*;jar</code><br>
495 * WARNING: <code>/base/directory;in=*.jar,\</code> at the end of a file,
496 * without a new line causes a '.' to be appended with unexpected side
497 * effects.
498 */
499 public List getBundlesUrls() {
500 String baseUrl = OsgiBootUtils.getProperty(PROP_ARGEO_OSGI_BASE_URL,
501 DEFAULT_BASE_URL);
502 String bundlePatterns = OsgiBootUtils
503 .getProperty(PROP_ARGEO_OSGI_BUNDLES);
504 return getBundlesUrls(baseUrl, bundlePatterns);
505 }
506
507 /** Implements the path matching logic */
508 public List getBundlesUrls(String baseUrl, String bundlePatterns) {
509 List urls = new ArrayList();
510 if (bundlePatterns == null)
511 return urls;
512
513 bundlePatterns = SystemPropertyUtils
514 .resolvePlaceholders(bundlePatterns);
515 if (debug)
516 debug(PROP_ARGEO_OSGI_BUNDLES + "=" + bundlePatterns
517 + " (excludeSvn=" + excludeSvn + ")");
518
519 StringTokenizer st = new StringTokenizer(bundlePatterns, ",");
520 List bundlesSets = new ArrayList();
521 while (st.hasMoreTokens()) {
522 bundlesSets.add(new BundlesSet(st.nextToken()));
523 }
524
525 // find included
526 List included = new ArrayList();
527 PathMatcher matcher = new AntPathMatcher();
528 for (int i = 0; i < bundlesSets.size(); i++) {
529 BundlesSet bundlesSet = (BundlesSet) bundlesSets.get(i);
530 for (int j = 0; j < bundlesSet.getIncludes().size(); j++) {
531 String pattern = (String) bundlesSet.getIncludes().get(j);
532 match(matcher, included, bundlesSet.getDir(), null, pattern);
533 }
534 }
535
536 // find excluded
537 List excluded = new ArrayList();
538 for (int i = 0; i < bundlesSets.size(); i++) {
539 BundlesSet bundlesSet = (BundlesSet) bundlesSets.get(i);
540 for (int j = 0; j < bundlesSet.getExcludes().size(); j++) {
541 String pattern = (String) bundlesSet.getExcludes().get(j);
542 match(matcher, excluded, bundlesSet.getDir(), null, pattern);
543 }
544 }
545
546 // construct list
547 for (int i = 0; i < included.size(); i++) {
548 String fullPath = (String) included.get(i);
549 if (!excluded.contains(fullPath))
550 urls.add(locationToUrl(baseUrl, fullPath));
551 }
552
553 return urls;
554 }
555
556 /*
557 * MODULES LIST INSTALLATION (${argeo.osgi.modulesUrl})
558 */
559 /**
560 * Downloads a list of URLs in CSV format from ${argeo.osgi.modulesUrl}:<br>
561 * <code>Bundle-SymbolicName,Bundle-Version,url</code>)<br>
562 * If ${argeo.osgi.baseUrl} is set, URLs will be considered relative paths
563 * and be concatenated with the base URL, typically the root of a Maven
564 * repository.
565 */
566 public List getModulesUrls() {
567 List urls = new ArrayList();
568 String modulesUrlStr = OsgiBootUtils
569 .getProperty(PROP_ARGEO_OSGI_MODULES_URL);
570 if (modulesUrlStr == null)
571 return urls;
572
573 String baseUrl = OsgiBootUtils.getProperty(PROP_ARGEO_OSGI_BASE_URL);
574
575 Map installedBundles = getBundlesBySymbolicName();
576
577 BufferedReader reader = null;
578 try {
579 URL modulesUrl = new URL(modulesUrlStr);
580 reader = new BufferedReader(new InputStreamReader(
581 modulesUrl.openStream()));
582 String line = null;
583 while ((line = reader.readLine()) != null) {
584 StringTokenizer st = new StringTokenizer(line,
585 modulesUrlSeparator);
586 String moduleName = st.nextToken();
587 String moduleVersion = st.nextToken();
588 String url = st.nextToken();
589 if (baseUrl != null)
590 url = baseUrl + url;
591
592 if (installedBundles.containsKey(moduleName)) {
593 Bundle bundle = (Bundle) installedBundles.get(moduleName);
594 String bundleVersion = bundle.getHeaders()
595 .get(Constants.BUNDLE_VERSION).toString();
596 int comp = OsgiBootUtils.compareVersions(bundleVersion,
597 moduleVersion);
598 if (comp > 0) {
599 OsgiBootUtils.warn("Installed version " + bundleVersion
600 + " of bundle " + moduleName
601 + " is newer than provided version "
602 + moduleVersion);
603 } else if (comp < 0) {
604 urls.add(url);
605 OsgiBootUtils.info("Updated bundle " + moduleName
606 + " with version " + moduleVersion
607 + " (old version was " + bundleVersion + ")");
608 } else {
609 // do nothing
610 }
611 } else {
612 urls.add(url);
613 }
614 }
615 } catch (Exception e1) {
616 throw new RuntimeException("Cannot read url " + modulesUrlStr, e1);
617 } finally {
618 if (reader != null)
619 try {
620 reader.close();
621 } catch (IOException e) {
622 e.printStackTrace();
623 }
624 }
625 return urls;
626 }
627
628 /*
629 * HIGH LEVEL UTILITIES
630 */
631 /** Actually performs the matching logic. */
632 protected void match(PathMatcher matcher, List matched, String base,
633 String currentPath, String pattern) {
634 if (currentPath == null) {
635 // Init
636 File baseDir = new File(base.replace('/', File.separatorChar));
637 File[] files = baseDir.listFiles();
638
639 if (files == null) {
640 if (debug)
641 OsgiBootUtils.warn("Base dir " + baseDir
642 + " has no children, exists=" + baseDir.exists()
643 + ", isDirectory=" + baseDir.isDirectory());
644 return;
645 }
646
647 for (int i = 0; i < files.length; i++)
648 match(matcher, matched, base, files[i].getName(), pattern);
649 } else {
650 String fullPath = base + '/' + currentPath;
651 if (matched.contains(fullPath))
652 return;// don't try deeper if already matched
653
654 boolean ok = matcher.match(pattern, currentPath);
655 // if (debug)
656 // debug(currentPath + " " + (ok ? "" : " not ")
657 // + " matched with " + pattern);
658 if (ok) {
659 matched.add(fullPath);
660 return;
661 } else {
662 String newFullPath = relativeToFullPath(base, currentPath);
663 File newFile = new File(newFullPath);
664 File[] files = newFile.listFiles();
665 if (files != null) {
666 for (int i = 0; i < files.length; i++) {
667 String newCurrentPath = currentPath + '/'
668 + files[i].getName();
669 if (files[i].isDirectory()) {
670 if (matcher.matchStart(pattern, newCurrentPath)) {
671 // recurse only if start matches
672 match(matcher, matched, base, newCurrentPath,
673 pattern);
674 } else {
675 if (debug)
676 debug(newCurrentPath
677 + " does not start match with "
678 + pattern);
679
680 }
681 } else {
682 boolean nonDirectoryOk = matcher.match(pattern,
683 newCurrentPath);
684 if (debug)
685 debug(currentPath + " " + (ok ? "" : " not ")
686 + " matched with " + pattern);
687 if (nonDirectoryOk)
688 matched.add(relativeToFullPath(base,
689 newCurrentPath));
690 }
691 }
692 }
693 }
694 }
695 }
696
697 protected void matchFile() {
698
699 }
700
701 /*
702 * LOW LEVEL UTILITIES
703 */
704 /**
705 * The bundles already installed. Key is location (String) , value is a
706 * {@link Bundle}
707 */
708 public Map getBundlesByLocation() {
709 Map installedBundles = new HashMap();
710 Bundle[] bundles = bundleContext.getBundles();
711 for (int i = 0; i < bundles.length; i++) {
712 installedBundles.put(bundles[i].getLocation(), bundles[i]);
713 }
714 return installedBundles;
715 }
716
717 /**
718 * The bundles already installed. Key is symbolic name (String) , value is a
719 * {@link Bundle}
720 */
721 public Map getBundlesBySymbolicName() {
722 Map namedBundles = new HashMap();
723 Bundle[] bundles = bundleContext.getBundles();
724 for (int i = 0; i < bundles.length; i++) {
725 namedBundles.put(bundles[i].getSymbolicName(), bundles[i]);
726 }
727 return namedBundles;
728 }
729
730 /** Creates an URL from a location */
731 protected String locationToUrl(String baseUrl, String location) {
732 int extInd = location.lastIndexOf('.');
733 String ext = null;
734 if (extInd > 0)
735 ext = location.substring(extInd);
736
737 if (baseUrl.startsWith("reference:") && ".jar".equals(ext))
738 return "file:" + location;
739 else
740 return baseUrl + location;
741 }
742
743 /** Transforms a relative path in a full system path. */
744 protected String relativeToFullPath(String basePath, String relativePath) {
745 return (basePath + '/' + relativePath).replace('/', File.separatorChar);
746 }
747
748 private String removeFilePrefix(String url) {
749 if (url.startsWith("file:"))
750 return url.substring("file:".length());
751 else if (url.startsWith("reference:file:"))
752 return url.substring("reference:file:".length());
753 else
754 return url;
755 }
756
757 /**
758 * Convenience method to avoid cluttering the code with
759 * OsgiBootUtils.debug()
760 */
761 protected void debug(Object obj) {
762 OsgiBootUtils.debug(obj);
763 }
764
765 /*
766 * BEAN METHODS
767 */
768
769 public boolean getDebug() {
770 return debug;
771 }
772
773 public void setDebug(boolean debug) {
774 this.debug = debug;
775 }
776
777 public BundleContext getBundleContext() {
778 return bundleContext;
779 }
780
781 public void setInstallInLexicographicOrder(
782 boolean installInAlphabeticalOrder) {
783 this.installInLexicographicOrder = installInAlphabeticalOrder;
784 }
785
786 public boolean isInstallInLexicographicOrder() {
787 return installInLexicographicOrder;
788 }
789
790 public void setDefaultTimeout(long defaultTimeout) {
791 this.defaultTimeout = defaultTimeout;
792 }
793
794 public void setModulesUrlSeparator(String modulesUrlSeparator) {
795 this.modulesUrlSeparator = modulesUrlSeparator;
796 }
797
798 public boolean isExcludeSvn() {
799 return excludeSvn;
800 }
801
802 public void setExcludeSvn(boolean excludeSvn) {
803 this.excludeSvn = excludeSvn;
804 }
805
806 /*
807 * INTERNAL CLASSES
808 */
809
810 /** Intermediary structure used by path matching */
811 protected class BundlesSet {
812 private String baseUrl = "reference:file";// not used yet
813 private final String dir;
814 private List includes = new ArrayList();
815 private List excludes = new ArrayList();
816
817 public BundlesSet(String def) {
818 StringTokenizer st = new StringTokenizer(def, ";");
819
820 if (!st.hasMoreTokens())
821 throw new RuntimeException("Base dir not defined.");
822 try {
823 String dirPath = st.nextToken();
824
825 if (dirPath.startsWith("file:"))
826 dirPath = dirPath.substring("file:".length());
827
828 dir = new File(dirPath.replace('/', File.separatorChar))
829 .getCanonicalPath();
830 if (debug)
831 debug("Base dir: " + dir);
832 } catch (IOException e) {
833 throw new RuntimeException("Cannot convert to absolute path", e);
834 }
835
836 while (st.hasMoreTokens()) {
837 String tk = st.nextToken();
838 StringTokenizer stEq = new StringTokenizer(tk, "=");
839 String type = stEq.nextToken();
840 String pattern = stEq.nextToken();
841 if ("in".equals(type) || "include".equals(type)) {
842 includes.add(pattern);
843 } else if ("ex".equals(type) || "exclude".equals(type)) {
844 excludes.add(pattern);
845 } else if ("baseUrl".equals(type)) {
846 baseUrl = pattern;
847 } else {
848 System.err.println("Unkown bundles pattern type " + type);
849 }
850 }
851
852 if (excludeSvn && !excludes.contains(EXCLUDES_SVN_PATTERN)) {
853 excludes.add(EXCLUDES_SVN_PATTERN);
854 }
855 }
856
857 public String getDir() {
858 return dir;
859 }
860
861 public List getIncludes() {
862 return includes;
863 }
864
865 public List getExcludes() {
866 return excludes;
867 }
868
869 public String getBaseUrl() {
870 return baseUrl;
871 }
872
873 }
874
875 }