]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org/argeo/osgi/boot/OsgiBoot.java
Prepare next development cycle
[lgpl/argeo-commons.git] / org / argeo / osgi / boot / OsgiBoot.java
1 /*
2 * Copyright (C) 2007-2012 Argeo GmbH
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 static org.argeo.osgi.boot.OsgiBootUtils.debug;
19 import static org.argeo.osgi.boot.OsgiBootUtils.warn;
20
21 import java.io.File;
22 import java.io.IOException;
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
34 import org.argeo.osgi.boot.internal.springutil.AntPathMatcher;
35 import org.argeo.osgi.boot.internal.springutil.PathMatcher;
36 import org.argeo.osgi.boot.internal.springutil.SystemPropertyUtils;
37 import org.osgi.framework.Bundle;
38 import org.osgi.framework.BundleContext;
39 import org.osgi.framework.BundleException;
40 import org.osgi.framework.FrameworkEvent;
41 import org.osgi.framework.startlevel.BundleStartLevel;
42 import org.osgi.framework.startlevel.FrameworkStartLevel;
43
44 /**
45 * Basic provisioning of an OSGi runtime via file path patterns and system
46 * properties. The approach is to generate list of URLs based on various
47 * methods, configured via properties.
48 */
49 public class OsgiBoot implements OsgiBootConstants {
50 // public final static String PROP_ARGEO_OSGI_DATA_DIR =
51 // "argeo.osgi.data.dir";
52 public final static String PROP_ARGEO_OSGI_START = "argeo.osgi.start";
53 public final static String PROP_ARGEO_OSGI_BUNDLES = "argeo.osgi.bundles";
54 public final static String PROP_ARGEO_OSGI_BASE_URL = "argeo.osgi.baseUrl";
55 public final static String PROP_ARGEO_OSGI_DISTRIBUTION_URL = "argeo.osgi.distributionUrl";
56
57 // booleans
58 public final static String PROP_ARGEO_OSGI_BOOT_DEBUG = "argeo.osgi.boot.debug";
59 public final static String PROP_ARGEO_OSGI_BOOT_EXCLUDE_SVN = "argeo.osgi.boot.excludeSvn";
60
61 // public final static String PROP_ARGEO_OSGI_BOOT_DEFAULT_TIMEOUT =
62 // "argeo.osgi.boot.defaultTimeout";
63 public final static String PROP_ARGEO_OSGI_BOOT_SYSTEM_PROPERTIES_FILE = "argeo.osgi.boot.systemPropertiesFile";
64 public final static String PROP_ARGEO_OSGI_BOOT_APPCLASS = "argeo.osgi.boot.appclass";
65 public final static String PROP_ARGEO_OSGI_BOOT_APPARGS = "argeo.osgi.boot.appargs";
66
67 public final static String DEFAULT_BASE_URL = "reference:file:";
68 public final static String EXCLUDES_SVN_PATTERN = "**/.svn/**";
69
70 // OSGi system properties
71 public final static String PROP_OSGI_BUNDLES_DEFAULTSTARTLEVEL = "osgi.bundles.defaultStartLevel";
72 public final static String PROP_OSGI_STARTLEVEL = "osgi.startLevel";
73 public final static String INSTANCE_AREA_PROP = "osgi.instance.area";
74 // public final static String INSTANCE_AREA_DEFAULT_PROP =
75 // "osgi.instance.area.default";
76
77 // Symbolic names
78 public final static String SYMBOLIC_NAME_OSGI_BOOT = "org.argeo.osgi.boot";
79 public final static String SYMBOLIC_NAME_EQUINOX = "org.eclipse.osgi";
80
81 private boolean debug = Boolean.valueOf(System.getProperty(PROP_ARGEO_OSGI_BOOT_DEBUG, "false")).booleanValue();
82 /** Exclude svn metadata implicitely(a bit costly) */
83 private boolean excludeSvn = Boolean.valueOf(System.getProperty(PROP_ARGEO_OSGI_BOOT_EXCLUDE_SVN, "false"))
84 .booleanValue();
85
86 /** Default is 10s */
87 private long defaultTimeout = 10000l;
88
89 private final BundleContext bundleContext;
90
91 /*
92 * INITIALIZATION
93 */
94 /** Constructor */
95 public OsgiBoot(BundleContext bundleContext) {
96 this.bundleContext = bundleContext;
97 // defaultTimeout =
98 // Long.parseLong(OsgiBootUtils.getProperty(PROP_ARGEO_OSGI_BOOT_DEFAULT_TIMEOUT,
99 // "10000"));
100 // initSystemProperties();
101 }
102
103 // /**
104 // * Set additional system properties, especially ${argeo.osgi.data.dir} as
105 // an
106 // * OS file path (and not a file:// URL)
107 // */
108 // private void initSystemProperties() {
109 // String osgiInstanceArea = System.getProperty(INSTANCE_AREA_PROP);
110 // String osgiInstanceAreaDefault =
111 // System.getProperty(INSTANCE_AREA_DEFAULT_PROP);
112 // String tempDir = System.getProperty("java.io.tmpdir");
113 //
114 // File dataDir = null;
115 // if (osgiInstanceArea != null) {
116 // // within OSGi with -data specified
117 // osgiInstanceArea = removeFilePrefix(osgiInstanceArea);
118 // dataDir = new File(osgiInstanceArea);
119 // } else if (osgiInstanceAreaDefault != null) {
120 // // within OSGi without -data specified
121 // osgiInstanceAreaDefault = removeFilePrefix(osgiInstanceAreaDefault);
122 // dataDir = new File(osgiInstanceAreaDefault);
123 // } else {// outside OSGi
124 // dataDir = new File(tempDir + File.separator + "argeoOsgiData");
125 // }
126 // System.setProperty(PROP_ARGEO_OSGI_DATA_DIR, dataDir.getAbsolutePath());
127 // }
128
129 /*
130 * HIGH-LEVEL METHODS
131 */
132 /** Bootstraps the OSGi runtime */
133 public void bootstrap() {
134 try {
135 long begin = System.currentTimeMillis();
136 System.out.println();
137 String osgiInstancePath = bundleContext.getProperty(INSTANCE_AREA_PROP);
138 OsgiBootUtils
139 .info("OSGi bootstrap starting" + (osgiInstancePath != null ? " (" + osgiInstancePath + ")" : ""));
140 // OsgiBootUtils.info("Writable data directory : " +
141 // System.getProperty(PROP_ARGEO_OSGI_DATA_DIR)
142 // + " (set as system property " + PROP_ARGEO_OSGI_DATA_DIR + ")");
143 installUrls(getBundlesUrls());
144 installUrls(getDistributionUrls());
145 startBundles();
146 long duration = System.currentTimeMillis() - begin;
147 OsgiBootUtils.info("OSGi bootstrap completed in " + Math.round(((double) duration) / 1000) + "s ("
148 + duration + "ms), " + bundleContext.getBundles().length + " bundles");
149 } catch (RuntimeException e) {
150 OsgiBootUtils.error("OSGi bootstrap FAILED", e);
151 throw e;
152 }
153
154 // diagnostics
155 if (debug) {
156 OsgiBootDiagnostics diagnostics = new OsgiBootDiagnostics(bundleContext);
157 diagnostics.checkUnresolved();
158 Map<String, Set<String>> duplicatePackages = diagnostics.findPackagesExportedTwice();
159 if (duplicatePackages.size() > 0) {
160 OsgiBootUtils.info("Packages exported twice:");
161 Iterator<String> it = duplicatePackages.keySet().iterator();
162 while (it.hasNext()) {
163 String pkgName = it.next();
164 OsgiBootUtils.info(pkgName);
165 Set<String> bdles = duplicatePackages.get(pkgName);
166 Iterator<String> bdlesIt = bdles.iterator();
167 while (bdlesIt.hasNext())
168 OsgiBootUtils.info(" " + bdlesIt.next());
169 }
170 }
171 }
172 System.out.println();
173 }
174
175 /*
176 * INSTALLATION
177 */
178 /** Install a single url. Convenience method. */
179 public Bundle installUrl(String url) {
180 List<String> urls = new ArrayList<String>();
181 urls.add(url);
182 installUrls(urls);
183 return (Bundle) getBundlesByLocation().get(url);
184 }
185
186 /** Install the bundles at this URL list. */
187 public void installUrls(List<String> urls) {
188 Map<String, Bundle> installedBundles = getBundlesByLocation();
189 for (int i = 0; i < urls.size(); i++) {
190 String url = (String) urls.get(i);
191 installUrl(url, installedBundles);
192 }
193 }
194
195 /** Actually install the provided URL */
196 protected void installUrl(String url, Map<String, Bundle> installedBundles) {
197 try {
198 if (installedBundles.containsKey(url)) {
199 Bundle bundle = (Bundle) installedBundles.get(url);
200 if (debug)
201 debug("Bundle " + bundle.getSymbolicName() + " already installed from " + url);
202 } else if (url.contains("/" + SYMBOLIC_NAME_EQUINOX + "/")
203 || url.contains("/" + SYMBOLIC_NAME_OSGI_BOOT + "/")) {
204 if (debug)
205 warn("Skip " + url);
206 return;
207 } else {
208 Bundle bundle = bundleContext.installBundle(url);
209 if (url.startsWith("http"))
210 OsgiBootUtils
211 .info("Installed " + bundle.getSymbolicName() + "-" + bundle.getVersion() + " from " + url);
212 else if (debug)
213 OsgiBootUtils.debug(
214 "Installed " + bundle.getSymbolicName() + "-" + bundle.getVersion() + " from " + url);
215 }
216 } catch (BundleException e) {
217 String message = e.getMessage();
218 if ((message.contains("Bundle \"" + SYMBOLIC_NAME_OSGI_BOOT + "\"")
219 || message.contains("Bundle \"" + SYMBOLIC_NAME_EQUINOX + "\""))
220 && message.contains("is already installed")) {
221 // silent, in order to avoid warnings: we know that both
222 // have already been installed...
223 } else {
224 OsgiBootUtils.warn("Could not install bundle from " + url + ": " + message);
225 }
226 if (debug)
227 e.printStackTrace();
228 }
229 }
230
231 /*
232 * START
233 */
234 public void startBundles() {
235 FrameworkStartLevel frameworkStartLevel = bundleContext.getBundle(0).adapt(FrameworkStartLevel.class);
236
237 // default and active start levels from System properties
238 Integer defaultStartLevel = new Integer(
239 Integer.parseInt(OsgiBootUtils.getProperty(PROP_OSGI_BUNDLES_DEFAULTSTARTLEVEL, "4")));
240 Integer activeStartLevel = new Integer(OsgiBootUtils.getProperty(PROP_OSGI_STARTLEVEL, "6"));
241
242 SortedMap<Integer, List<String>> startLevels = new TreeMap<Integer, List<String>>();
243 computeStartLevels(startLevels, System.getProperties(), defaultStartLevel);
244 // inverts the map for the time being, TODO optimise
245 Map<String, Integer> bundleStartLevels = new HashMap<>();
246 for (Integer level : startLevels.keySet()) {
247 for (String bsn : startLevels.get(level))
248 bundleStartLevels.put(bsn, level);
249 }
250 for (Bundle bundle : bundleContext.getBundles()) {
251 String bsn = bundle.getSymbolicName();
252 if (bundleStartLevels.containsKey(bsn)) {
253 BundleStartLevel bundleStartLevel = bundle.adapt(BundleStartLevel.class);
254 Integer level = bundleStartLevels.get(bsn);
255 if (bundleStartLevel.getStartLevel() != level || !bundleStartLevel.isPersistentlyStarted()) {
256 bundleStartLevel.setStartLevel(level);
257 try {
258 bundle.start();
259 } catch (BundleException e) {
260 OsgiBootUtils.error("Cannot mark " + bsn + " as started", e);
261 }
262 if (getDebug())
263 OsgiBootUtils.debug(bsn + " starts at level " + level);
264 }
265 }
266 }
267 frameworkStartLevel.setStartLevel(activeStartLevel, (FrameworkEvent event) -> {
268 if (getDebug())
269 OsgiBootUtils.debug("Framework event: " + event);
270 int initialStartLevel = frameworkStartLevel.getInitialBundleStartLevel();
271 int startLevel = frameworkStartLevel.getStartLevel();
272 OsgiBootUtils.debug("Framework start level: " + startLevel + " (initial: " + initialStartLevel + ")");
273 });
274
275 // Iterator<Integer> levels = startLevels.keySet().iterator();
276 // while (levels.hasNext()) {
277 // Integer level = (Integer) levels.next();
278 // boolean allStarted = startBundles(startLevels.get(level));
279 // if (!allStarted)
280 // OsgiBootUtils.warn("Not all bundles started for level " + level);
281 // if (level.equals(activeStartLevel))
282 // break;// active start level reached
283 // }
284
285 }
286
287 public static void computeStartLevels(SortedMap<Integer, List<String>> startLevels, Properties properties,
288 Integer defaultStartLevel) {
289
290 // default (and previously, only behaviour)
291 appendToStartLevels(startLevels, defaultStartLevel, properties.getProperty(PROP_ARGEO_OSGI_START, ""));
292
293 // list argeo.osgi.start.* system properties
294 Iterator<Object> keys = properties.keySet().iterator();
295 final String prefix = PROP_ARGEO_OSGI_START + ".";
296 while (keys.hasNext()) {
297 String key = keys.next().toString();
298 if (key.startsWith(prefix)) {
299 Integer startLevel;
300 String suffix = key.substring(prefix.length());
301 String[] tokens = suffix.split("\\.");
302 if (tokens.length > 0 && !tokens[0].trim().equals(""))
303 try {
304 // first token is start level
305 startLevel = new Integer(tokens[0]);
306 } catch (NumberFormatException e) {
307 startLevel = defaultStartLevel;
308 }
309 else
310 startLevel = defaultStartLevel;
311
312 // append bundle names
313 String bundleNames = properties.getProperty(key);
314 appendToStartLevels(startLevels, startLevel, bundleNames);
315 }
316 }
317 }
318
319 /** Append a comma-separated list of bundles to the start levels. */
320 private static void appendToStartLevels(SortedMap<Integer, List<String>> startLevels, Integer startLevel,
321 String str) {
322 if (str == null || str.trim().equals(""))
323 return;
324
325 if (!startLevels.containsKey(startLevel))
326 startLevels.put(startLevel, new ArrayList<String>());
327 String[] bundleNames = str.split(",");
328 for (int i = 0; i < bundleNames.length; i++) {
329 if (bundleNames[i] != null && !bundleNames[i].trim().equals(""))
330 (startLevels.get(startLevel)).add(bundleNames[i]);
331 }
332 }
333
334 /**
335 * Start the provided list of bundles
336 *
337 * @return whether all bundles are now in active state
338 * @deprecated
339 */
340 @Deprecated
341 public boolean startBundles(List<String> bundlesToStart) {
342 if (bundlesToStart.size() == 0)
343 return true;
344
345 // used to monitor ACTIVE states
346 List<Bundle> startedBundles = new ArrayList<Bundle>();
347 // used to log the bundles not found
348 List<String> notFoundBundles = new ArrayList<String>(bundlesToStart);
349
350 Bundle[] bundles = bundleContext.getBundles();
351 long startBegin = System.currentTimeMillis();
352 for (int i = 0; i < bundles.length; i++) {
353 Bundle bundle = bundles[i];
354 String symbolicName = bundle.getSymbolicName();
355 if (bundlesToStart.contains(symbolicName))
356 try {
357 try {
358 bundle.start();
359 if (debug)
360 debug("Bundle " + symbolicName + " started");
361 } catch (Exception e) {
362 OsgiBootUtils.warn("Start of bundle " + symbolicName + " failed because of " + e
363 + ", maybe bundle is not yet resolved," + " waiting and trying again.");
364 waitForBundleResolvedOrActive(startBegin, bundle);
365 bundle.start();
366 startedBundles.add(bundle);
367 }
368 notFoundBundles.remove(symbolicName);
369 } catch (Exception e) {
370 OsgiBootUtils.warn("Bundle " + symbolicName + " cannot be started: " + e.getMessage());
371 if (debug)
372 e.printStackTrace();
373 // was found even if start failed
374 notFoundBundles.remove(symbolicName);
375 }
376 }
377
378 for (int i = 0; i < notFoundBundles.size(); i++)
379 OsgiBootUtils.warn("Bundle '" + notFoundBundles.get(i) + "' not started because it was not found.");
380
381 // monitors that all bundles are started
382 long beginMonitor = System.currentTimeMillis();
383 boolean allStarted = !(startedBundles.size() > 0);
384 List<String> notStarted = new ArrayList<String>();
385 while (!allStarted && (System.currentTimeMillis() - beginMonitor) < defaultTimeout) {
386 notStarted = new ArrayList<String>();
387 allStarted = true;
388 for (int i = 0; i < startedBundles.size(); i++) {
389 Bundle bundle = (Bundle) startedBundles.get(i);
390 // TODO check behaviour of lazs bundles
391 if (bundle.getState() != Bundle.ACTIVE) {
392 allStarted = false;
393 notStarted.add(bundle.getSymbolicName());
394 }
395 }
396 try {
397 Thread.sleep(100);
398 } catch (InterruptedException e) {
399 // silent
400 }
401 }
402 long duration = System.currentTimeMillis() - beginMonitor;
403
404 if (!allStarted)
405 for (int i = 0; i < notStarted.size(); i++)
406 OsgiBootUtils.warn("Bundle '" + notStarted.get(i) + "' not ACTIVE after " + (duration / 1000) + "s");
407
408 return allStarted;
409 }
410
411 /** Waits for a bundle to become active or resolved */
412 private void waitForBundleResolvedOrActive(long startBegin, Bundle bundle) throws Exception {
413 int originalState = bundle.getState();
414 if ((originalState == Bundle.RESOLVED) || (originalState == Bundle.ACTIVE))
415 return;
416
417 String originalStateStr = OsgiBootUtils.stateAsString(originalState);
418
419 int currentState = bundle.getState();
420 while (!(currentState == Bundle.RESOLVED || currentState == Bundle.ACTIVE)) {
421 long now = System.currentTimeMillis();
422 if ((now - startBegin) > defaultTimeout * 10)
423 throw new Exception("Bundle " + bundle.getSymbolicName() + " was not RESOLVED or ACTIVE after "
424 + (now - startBegin) + "ms (originalState=" + originalStateStr + ", currentState="
425 + OsgiBootUtils.stateAsString(currentState) + ")");
426
427 try {
428 Thread.sleep(100l);
429 } catch (InterruptedException e) {
430 // silent
431 }
432 currentState = bundle.getState();
433 }
434 }
435
436 /*
437 * BUNDLE PATTERNS INSTALLATION
438 */
439 /**
440 * Computes a list of URLs based on Ant-like include/exclude patterns
441 * defined by ${argeo.osgi.bundles} with the following format:<br>
442 * <code>/base/directory;in=*.jar;in=**;ex=org.eclipse.osgi_*;jar</code><br>
443 * WARNING: <code>/base/directory;in=*.jar,\</code> at the end of a file,
444 * without a new line causes a '.' to be appended with unexpected side
445 * effects.
446 */
447 public List<String> getBundlesUrls() {
448 String bundlePatterns = OsgiBootUtils.getProperty(PROP_ARGEO_OSGI_BUNDLES);
449 return getBundlesUrls(bundlePatterns);
450 }
451
452 /**
453 * Compute alist of URLs to install based on the provided patterns, with
454 * default base url
455 */
456 public List<String> getBundlesUrls(String bundlePatterns) {
457 String baseUrl = OsgiBootUtils.getProperty(PROP_ARGEO_OSGI_BASE_URL, DEFAULT_BASE_URL);
458 return getBundlesUrls(baseUrl, bundlePatterns);
459 }
460
461 /** Implements the path matching logic */
462 List<String> getBundlesUrls(String baseUrl, String bundlePatterns) {
463 List<String> urls = new ArrayList<String>();
464 if (bundlePatterns == null)
465 return urls;
466
467 bundlePatterns = SystemPropertyUtils.resolvePlaceholders(bundlePatterns);
468 if (debug)
469 debug(PROP_ARGEO_OSGI_BUNDLES + "=" + bundlePatterns + " (excludeSvn=" + excludeSvn + ")");
470
471 StringTokenizer st = new StringTokenizer(bundlePatterns, ",");
472 List<BundlesSet> bundlesSets = new ArrayList<BundlesSet>();
473 while (st.hasMoreTokens()) {
474 String token = st.nextToken();
475 if (new File(token).exists()) {
476 String url = locationToUrl(baseUrl, token);
477 urls.add(url);
478 } else
479 bundlesSets.add(new BundlesSet(token));
480 }
481
482 // find included
483 List<String> included = new ArrayList<String>();
484 PathMatcher matcher = new AntPathMatcher();
485 for (int i = 0; i < bundlesSets.size(); i++) {
486 BundlesSet bundlesSet = (BundlesSet) bundlesSets.get(i);
487 for (int j = 0; j < bundlesSet.getIncludes().size(); j++) {
488 String pattern = (String) bundlesSet.getIncludes().get(j);
489 match(matcher, included, bundlesSet.getDir(), null, pattern);
490 }
491 }
492
493 // find excluded
494 List<String> excluded = new ArrayList<String>();
495 for (int i = 0; i < bundlesSets.size(); i++) {
496 BundlesSet bundlesSet = (BundlesSet) bundlesSets.get(i);
497 for (int j = 0; j < bundlesSet.getExcludes().size(); j++) {
498 String pattern = (String) bundlesSet.getExcludes().get(j);
499 match(matcher, excluded, bundlesSet.getDir(), null, pattern);
500 }
501 }
502
503 // construct list
504 for (int i = 0; i < included.size(); i++) {
505 String fullPath = (String) included.get(i);
506 if (!excluded.contains(fullPath))
507 urls.add(locationToUrl(baseUrl, fullPath));
508 }
509
510 return urls;
511 }
512
513 /*
514 * DISTRIBUTION JAR INSTALLATION
515 */
516 public List<String> getDistributionUrls() {
517 List<String> urls = new ArrayList<String>();
518 String distributionUrl = OsgiBootUtils.getProperty(PROP_ARGEO_OSGI_DISTRIBUTION_URL);
519 if (distributionUrl == null)
520 return urls;
521 String baseUrl = OsgiBootUtils.getProperty(PROP_ARGEO_OSGI_BASE_URL);
522
523 DistributionBundle distributionBundle;
524 if (baseUrl != null && !(distributionUrl.startsWith("http") || distributionUrl.startsWith("file"))) {
525 // relative url
526 distributionBundle = new DistributionBundle(baseUrl, distributionUrl);
527 } else {
528 distributionBundle = new DistributionBundle(distributionUrl);
529 if (baseUrl != null)
530 distributionBundle.setBaseUrl(baseUrl);
531
532 }
533 distributionBundle.processUrl();
534 return distributionBundle.listUrls();
535 }
536
537 /*
538 * HIGH LEVEL UTILITIES
539 */
540 /** Actually performs the matching logic. */
541 protected void match(PathMatcher matcher, List<String> matched, String base, String currentPath, String pattern) {
542 if (currentPath == null) {
543 // Init
544 File baseDir = new File(base.replace('/', File.separatorChar));
545 File[] files = baseDir.listFiles();
546
547 if (files == null) {
548 if (debug)
549 OsgiBootUtils.warn("Base dir " + baseDir + " has no children, exists=" + baseDir.exists()
550 + ", isDirectory=" + baseDir.isDirectory());
551 return;
552 }
553
554 for (int i = 0; i < files.length; i++)
555 match(matcher, matched, base, files[i].getName(), pattern);
556 } else {
557 String fullPath = base + '/' + currentPath;
558 if (matched.contains(fullPath))
559 return;// don't try deeper if already matched
560
561 boolean ok = matcher.match(pattern, currentPath);
562 // if (debug)
563 // debug(currentPath + " " + (ok ? "" : " not ")
564 // + " matched with " + pattern);
565 if (ok) {
566 matched.add(fullPath);
567 return;
568 } else {
569 String newFullPath = relativeToFullPath(base, currentPath);
570 File newFile = new File(newFullPath);
571 File[] files = newFile.listFiles();
572 if (files != null) {
573 for (int i = 0; i < files.length; i++) {
574 String newCurrentPath = currentPath + '/' + files[i].getName();
575 if (files[i].isDirectory()) {
576 if (matcher.matchStart(pattern, newCurrentPath)) {
577 // recurse only if start matches
578 match(matcher, matched, base, newCurrentPath, pattern);
579 } else {
580 if (debug)
581 debug(newCurrentPath + " does not start match with " + pattern);
582
583 }
584 } else {
585 boolean nonDirectoryOk = matcher.match(pattern, newCurrentPath);
586 if (debug)
587 debug(currentPath + " " + (ok ? "" : " not ") + " matched with " + pattern);
588 if (nonDirectoryOk)
589 matched.add(relativeToFullPath(base, newCurrentPath));
590 }
591 }
592 }
593 }
594 }
595 }
596
597 protected void matchFile() {
598
599 }
600
601 /*
602 * LOW LEVEL UTILITIES
603 */
604 /**
605 * The bundles already installed. Key is location (String) , value is a
606 * {@link Bundle}
607 */
608 public Map<String, Bundle> getBundlesByLocation() {
609 Map<String, Bundle> installedBundles = new HashMap<String, Bundle>();
610 Bundle[] bundles = bundleContext.getBundles();
611 for (int i = 0; i < bundles.length; i++) {
612 installedBundles.put(bundles[i].getLocation(), bundles[i]);
613 }
614 return installedBundles;
615 }
616
617 /**
618 * The bundles already installed. Key is symbolic name (String) , value is a
619 * {@link Bundle}
620 */
621 public Map<String, Bundle> getBundlesBySymbolicName() {
622 Map<String, Bundle> namedBundles = new HashMap<String, Bundle>();
623 Bundle[] bundles = bundleContext.getBundles();
624 for (int i = 0; i < bundles.length; i++) {
625 namedBundles.put(bundles[i].getSymbolicName(), bundles[i]);
626 }
627 return namedBundles;
628 }
629
630 /** Creates an URL from a location */
631 protected String locationToUrl(String baseUrl, String location) {
632 return baseUrl + location;
633 }
634
635 /** Transforms a relative path in a full system path. */
636 protected String relativeToFullPath(String basePath, String relativePath) {
637 return (basePath + '/' + relativePath).replace('/', File.separatorChar);
638 }
639
640 // private String removeFilePrefix(String url) {
641 // if (url.startsWith("file:"))
642 // return url.substring("file:".length());
643 // else if (url.startsWith("reference:file:"))
644 // return url.substring("reference:file:".length());
645 // else
646 // return url;
647 // }
648
649 /*
650 * BEAN METHODS
651 */
652
653 public boolean getDebug() {
654 return debug;
655 }
656
657 public void setDebug(boolean debug) {
658 this.debug = debug;
659 }
660
661 public BundleContext getBundleContext() {
662 return bundleContext;
663 }
664
665 // public void setDefaultTimeout(long defaultTimeout) {
666 // this.defaultTimeout = defaultTimeout;
667 // }
668
669 public boolean isExcludeSvn() {
670 return excludeSvn;
671 }
672
673 public void setExcludeSvn(boolean excludeSvn) {
674 this.excludeSvn = excludeSvn;
675 }
676
677 /*
678 * INTERNAL CLASSES
679 */
680
681 /** Intermediary structure used by path matching */
682 protected class BundlesSet {
683 private String baseUrl = "reference:file";// not used yet
684 private final String dir;
685 private List<String> includes = new ArrayList<String>();
686 private List<String> excludes = new ArrayList<String>();
687
688 public BundlesSet(String def) {
689 StringTokenizer st = new StringTokenizer(def, ";");
690
691 if (!st.hasMoreTokens())
692 throw new RuntimeException("Base dir not defined.");
693 try {
694 String dirPath = st.nextToken();
695
696 if (dirPath.startsWith("file:"))
697 dirPath = dirPath.substring("file:".length());
698
699 dir = new File(dirPath.replace('/', File.separatorChar)).getCanonicalPath();
700 if (debug)
701 debug("Base dir: " + dir);
702 } catch (IOException e) {
703 throw new RuntimeException("Cannot convert to absolute path", e);
704 }
705
706 while (st.hasMoreTokens()) {
707 String tk = st.nextToken();
708 StringTokenizer stEq = new StringTokenizer(tk, "=");
709 String type = stEq.nextToken();
710 String pattern = stEq.nextToken();
711 if ("in".equals(type) || "include".equals(type)) {
712 includes.add(pattern);
713 } else if ("ex".equals(type) || "exclude".equals(type)) {
714 excludes.add(pattern);
715 } else if ("baseUrl".equals(type)) {
716 baseUrl = pattern;
717 } else {
718 System.err.println("Unkown bundles pattern type " + type);
719 }
720 }
721
722 if (excludeSvn && !excludes.contains(EXCLUDES_SVN_PATTERN)) {
723 excludes.add(EXCLUDES_SVN_PATTERN);
724 }
725 }
726
727 public String getDir() {
728 return dir;
729 }
730
731 public List<String> getIncludes() {
732 return includes;
733 }
734
735 public List<String> getExcludes() {
736 return excludes;
737 }
738
739 public String getBaseUrl() {
740 return baseUrl;
741 }
742
743 }
744 }