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