]> git.argeo.org Git - lgpl/argeo-commons.git/blob - OsgiBoot.java
effdcf3baf3bc7daf3e46d0692855a667e93001a
[lgpl/argeo-commons.git] / 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.nio.file.Paths;
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.Version;
42 import org.osgi.framework.startlevel.BundleStartLevel;
43 import org.osgi.framework.startlevel.FrameworkStartLevel;
44 import org.osgi.framework.wiring.FrameworkWiring;
45
46 /**
47 * Basic provisioning of an OSGi runtime via file path patterns and system
48 * properties. The approach is to generate list of URLs based on various
49 * methods, configured via properties.
50 */
51 public class OsgiBoot implements OsgiBootConstants {
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_LOCAL_CACHE = "argeo.osgi.localCache";
56 public final static String PROP_ARGEO_OSGI_DISTRIBUTION_URL = "argeo.osgi.distributionUrl";
57
58 // booleans
59 public final static String PROP_ARGEO_OSGI_BOOT_DEBUG = "argeo.osgi.boot.debug";
60 // public final static String PROP_ARGEO_OSGI_BOOT_EXCLUDE_SVN =
61 // "argeo.osgi.boot.excludeSvn";
62
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 final static String PROP_OSGI_BUNDLES_DEFAULTSTARTLEVEL = "osgi.bundles.defaultStartLevel";
72 final static String PROP_OSGI_STARTLEVEL = "osgi.startLevel";
73 final static String INSTANCE_AREA_PROP = "osgi.instance.area";
74 final static String CONFIGURATION_AREA_PROP = "osgi.configuration.area";
75
76 // Symbolic names
77 public final static String SYMBOLIC_NAME_OSGI_BOOT = "org.argeo.osgi.boot";
78 public final static String SYMBOLIC_NAME_EQUINOX = "org.eclipse.osgi";
79
80 /** Exclude svn metadata implicitely(a bit costly) */
81 // private boolean excludeSvn =
82 // Boolean.valueOf(System.getProperty(PROP_ARGEO_OSGI_BOOT_EXCLUDE_SVN,
83 // "false"))
84 // .booleanValue();
85
86 /** Default is 10s */
87 @Deprecated
88 private long defaultTimeout = 10000l;
89
90 private final BundleContext bundleContext;
91 private final String localCache;
92
93 /*
94 * INITIALIZATION
95 */
96 /** Constructor */
97 public OsgiBoot(BundleContext bundleContext) {
98 this.bundleContext = bundleContext;
99 String homeUri = Paths.get(System.getProperty("user.home")).toUri().toString();
100 localCache = getProperty(PROP_ARGEO_OSGI_LOCAL_CACHE, homeUri + ".m2/repository/");
101 }
102
103 /*
104 * HIGH-LEVEL METHODS
105 */
106 /** Bootstraps the OSGi runtime */
107 public void bootstrap() {
108 try {
109 long begin = System.currentTimeMillis();
110 System.out.println();
111 String osgiInstancePath = bundleContext.getProperty(INSTANCE_AREA_PROP);
112 OsgiBootUtils
113 .info("OSGi bootstrap starting" + (osgiInstancePath != null ? " (" + osgiInstancePath + ")" : ""));
114 installUrls(getBundlesUrls());
115 installUrls(getDistributionUrls());
116 startBundles();
117 long duration = System.currentTimeMillis() - begin;
118 OsgiBootUtils.info("OSGi bootstrap completed in " + Math.round(((double) duration) / 1000) + "s ("
119 + duration + "ms), " + bundleContext.getBundles().length + " bundles");
120 } catch (RuntimeException e) {
121 OsgiBootUtils.error("OSGi bootstrap FAILED", e);
122 throw e;
123 }
124
125 // diagnostics
126 if (OsgiBootUtils.debug) {
127 OsgiBootDiagnostics diagnostics = new OsgiBootDiagnostics(bundleContext);
128 diagnostics.checkUnresolved();
129 Map<String, Set<String>> duplicatePackages = diagnostics.findPackagesExportedTwice();
130 if (duplicatePackages.size() > 0) {
131 OsgiBootUtils.info("Packages exported twice:");
132 Iterator<String> it = duplicatePackages.keySet().iterator();
133 while (it.hasNext()) {
134 String pkgName = it.next();
135 OsgiBootUtils.info(pkgName);
136 Set<String> bdles = duplicatePackages.get(pkgName);
137 Iterator<String> bdlesIt = bdles.iterator();
138 while (bdlesIt.hasNext())
139 OsgiBootUtils.info(" " + bdlesIt.next());
140 }
141 }
142 }
143 System.out.println();
144 }
145
146 /*
147 * INSTALLATION
148 */
149 /** Install a single url. Convenience method. */
150 public Bundle installUrl(String url) {
151 List<String> urls = new ArrayList<String>();
152 urls.add(url);
153 installUrls(urls);
154 return (Bundle) getBundlesByLocation().get(url);
155 }
156
157 /** Install the bundles at this URL list. */
158 public void installUrls(List<String> urls) {
159 Map<String, Bundle> installedBundles = getBundlesByLocation();
160 for (int i = 0; i < urls.size(); i++) {
161 String url = (String) urls.get(i);
162 installUrl(url, installedBundles);
163 }
164 refreshFramework();
165 }
166
167 /** Actually install the provided URL */
168 protected void installUrl(String url, Map<String, Bundle> installedBundles) {
169 try {
170 if (installedBundles.containsKey(url)) {
171 Bundle bundle = (Bundle) installedBundles.get(url);
172 if (OsgiBootUtils.debug)
173 debug("Bundle " + bundle.getSymbolicName() + " already installed from " + url);
174 } else if (url.contains("/" + SYMBOLIC_NAME_EQUINOX + "/")
175 || url.contains("/" + SYMBOLIC_NAME_OSGI_BOOT + "/")) {
176 if (OsgiBootUtils.debug)
177 warn("Skip " + url);
178 return;
179 } else {
180 Bundle bundle = bundleContext.installBundle(url);
181 if (url.startsWith("http"))
182 OsgiBootUtils
183 .info("Installed " + bundle.getSymbolicName() + "-" + bundle.getVersion() + " from " + url);
184 else if (OsgiBootUtils.debug)
185 OsgiBootUtils.debug(
186 "Installed " + bundle.getSymbolicName() + "-" + bundle.getVersion() + " from " + url);
187 assert bundle.getSymbolicName() != null;
188 // uninstall previous versions
189 bundles: for (Bundle b : bundleContext.getBundles()) {
190 if (b.getSymbolicName() == null)
191 continue bundles;
192 if (bundle.getSymbolicName().equals(b.getSymbolicName())) {
193 Version bundleV = bundle.getVersion();
194 Version bV = b.getVersion();
195 if (bV == null)
196 continue bundles;
197 if (bundleV.getMajor() == bV.getMajor() && bundleV.getMinor() == bV.getMinor()) {
198 if (bundleV.getMicro() > bV.getMicro()) {
199 // uninstall older bundles
200 b.uninstall();
201 OsgiBootUtils.debug("Uninstalled " + b);
202 } else if (bundleV.getMicro() < bV.getMicro()) {
203 // uninstall just installed bundle if newer
204 bundle.uninstall();
205 OsgiBootUtils.debug("Uninstalled " + bundle);
206 break bundles;
207 } else {
208 // uninstall any other with same major/minor
209 if (!bundleV.getQualifier().equals(bV.getQualifier())) {
210 b.uninstall();
211 OsgiBootUtils.debug("Uninstalled " + b);
212 }
213 }
214 }
215 }
216 }
217 }
218 } catch (BundleException e) {
219 final String ALREADY_INSTALLED = "is already installed";
220 String message = e.getMessage();
221 if ((message.contains("Bundle \"" + SYMBOLIC_NAME_OSGI_BOOT + "\"")
222 || message.contains("Bundle \"" + SYMBOLIC_NAME_EQUINOX + "\""))
223 && message.contains(ALREADY_INSTALLED)) {
224 // silent, in order to avoid warnings: we know that both
225 // have already been installed...
226 } else {
227 if (message.contains(ALREADY_INSTALLED)) {
228 if (OsgiBootUtils.isDebug())
229 OsgiBootUtils.warn("Duplicate install from " + url + ": " + message);
230 } else
231 OsgiBootUtils.warn("Could not install bundle from " + url + ": " + message);
232 }
233 if (OsgiBootUtils.debug && !message.contains(ALREADY_INSTALLED))
234 e.printStackTrace();
235 }
236 }
237
238 /*
239 * START
240 */
241 public void startBundles() {
242 startBundles(System.getProperties());
243 }
244
245 public void startBundles(Properties properties) {
246 FrameworkStartLevel frameworkStartLevel = bundleContext.getBundle(0).adapt(FrameworkStartLevel.class);
247
248 // default and active start levels from System properties
249 Integer defaultStartLevel = new Integer(
250 Integer.parseInt(getProperty(PROP_OSGI_BUNDLES_DEFAULTSTARTLEVEL, "4")));
251 Integer activeStartLevel = new Integer(getProperty(PROP_OSGI_STARTLEVEL, "6"));
252
253 SortedMap<Integer, List<String>> startLevels = new TreeMap<Integer, List<String>>();
254 computeStartLevels(startLevels, properties, defaultStartLevel);
255 // inverts the map for the time being, TODO optimise
256 Map<String, Integer> bundleStartLevels = new HashMap<>();
257 for (Integer level : startLevels.keySet()) {
258 for (String bsn : startLevels.get(level))
259 bundleStartLevels.put(bsn, level);
260 }
261 for (Bundle bundle : bundleContext.getBundles()) {
262 String bsn = bundle.getSymbolicName();
263 if (bundleStartLevels.containsKey(bsn)) {
264 BundleStartLevel bundleStartLevel = bundle.adapt(BundleStartLevel.class);
265 Integer level = bundleStartLevels.get(bsn);
266 if (bundleStartLevel.getStartLevel() != level || !bundleStartLevel.isPersistentlyStarted()) {
267 bundleStartLevel.setStartLevel(level);
268 try {
269 bundle.start();
270 } catch (BundleException e) {
271 OsgiBootUtils.error("Cannot mark " + bsn + " as started", e);
272 }
273 if (getDebug())
274 OsgiBootUtils.debug(bsn + " starts at level " + level);
275 }
276 }
277 }
278 frameworkStartLevel.setStartLevel(activeStartLevel, (FrameworkEvent event) -> {
279 if (getDebug())
280 OsgiBootUtils.debug("Framework event: " + event);
281 int initialStartLevel = frameworkStartLevel.getInitialBundleStartLevel();
282 int startLevel = frameworkStartLevel.getStartLevel();
283 OsgiBootUtils.debug("Framework start level: " + startLevel + " (initial: " + initialStartLevel + ")");
284 });
285 }
286
287 private 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 (OsgiBootUtils.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 (OsgiBootUtils.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 @Deprecated
413 private void waitForBundleResolvedOrActive(long startBegin, Bundle bundle) throws Exception {
414 int originalState = bundle.getState();
415 if ((originalState == Bundle.RESOLVED) || (originalState == Bundle.ACTIVE))
416 return;
417
418 String originalStateStr = OsgiBootUtils.stateAsString(originalState);
419
420 int currentState = bundle.getState();
421 while (!(currentState == Bundle.RESOLVED || currentState == Bundle.ACTIVE)) {
422 long now = System.currentTimeMillis();
423 if ((now - startBegin) > defaultTimeout * 10)
424 throw new Exception("Bundle " + bundle.getSymbolicName() + " was not RESOLVED or ACTIVE after "
425 + (now - startBegin) + "ms (originalState=" + originalStateStr + ", currentState="
426 + OsgiBootUtils.stateAsString(currentState) + ")");
427
428 try {
429 Thread.sleep(100l);
430 } catch (InterruptedException e) {
431 // silent
432 }
433 currentState = bundle.getState();
434 }
435 }
436
437 /*
438 * BUNDLE PATTERNS INSTALLATION
439 */
440 /**
441 * Computes a list of URLs based on Ant-like include/exclude patterns defined by
442 * ${argeo.osgi.bundles} with the following format:<br>
443 * <code>/base/directory;in=*.jar;in=**;ex=org.eclipse.osgi_*;jar</code><br>
444 * WARNING: <code>/base/directory;in=*.jar,\</code> at the end of a file,
445 * without a new line causes a '.' to be appended with unexpected side effects.
446 */
447 public List<String> getBundlesUrls() {
448 String bundlePatterns = getProperty(PROP_ARGEO_OSGI_BUNDLES);
449 return getBundlesUrls(bundlePatterns);
450 }
451
452 /**
453 * Compute a list 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 = getProperty(PROP_ARGEO_OSGI_BASE_URL, DEFAULT_BASE_URL);
458 return getBundlesUrls(baseUrl, bundlePatterns);
459 }
460
461 /** Implements the path matching logic */
462 public 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 (OsgiBootUtils.debug)
469 debug(PROP_ARGEO_OSGI_BUNDLES + "=" + bundlePatterns);
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 String distributionUrl = getProperty(PROP_ARGEO_OSGI_DISTRIBUTION_URL);
518 String baseUrl = getProperty(PROP_ARGEO_OSGI_BASE_URL);
519 return getDistributionUrls(distributionUrl, baseUrl);
520 }
521
522 public List<String> getDistributionUrls(String distributionUrl, String baseUrl) {
523 List<String> urls = new ArrayList<String>();
524 if (distributionUrl == null)
525 return urls;
526
527 DistributionBundle distributionBundle;
528 if (distributionUrl.startsWith("http") || distributionUrl.startsWith("file")) {
529 distributionBundle = new DistributionBundle(distributionUrl);
530 if (baseUrl != null)
531 distributionBundle.setBaseUrl(baseUrl);
532 } else {
533 // relative url
534 if (baseUrl == null) {
535 baseUrl = localCache;
536 }
537
538 if (distributionUrl.contains(":")) {
539 // TODO make it safer
540 String[] parts = distributionUrl.trim().split(":");
541 String[] categoryParts = parts[0].split("\\.");
542 String artifactId = parts[1];
543 String version = parts[2];
544 StringBuilder sb = new StringBuilder();
545 for (String categoryPart : categoryParts) {
546 sb.append(categoryPart).append('/');
547 }
548 sb.append(artifactId).append('/');
549 sb.append(version).append('/');
550 sb.append(artifactId).append('-').append(version).append(".jar");
551 distributionUrl = sb.toString();
552 }
553
554 distributionBundle = new DistributionBundle(baseUrl, distributionUrl, localCache);
555 }
556 // if (baseUrl != null && !(distributionUrl.startsWith("http") ||
557 // distributionUrl.startsWith("file"))) {
558 // // relative url
559 // distributionBundle = new DistributionBundle(baseUrl, distributionUrl,
560 // localCache);
561 // } else {
562 // distributionBundle = new DistributionBundle(distributionUrl);
563 // if (baseUrl != null)
564 // distributionBundle.setBaseUrl(baseUrl);
565 // }
566 distributionBundle.processUrl();
567 return distributionBundle.listUrls();
568 }
569
570 /*
571 * HIGH LEVEL UTILITIES
572 */
573 /** Actually performs the matching logic. */
574 protected void match(PathMatcher matcher, List<String> matched, String base, String currentPath, String pattern) {
575 if (currentPath == null) {
576 // Init
577 File baseDir = new File(base.replace('/', File.separatorChar));
578 File[] files = baseDir.listFiles();
579
580 if (files == null) {
581 if (OsgiBootUtils.debug)
582 OsgiBootUtils.warn("Base dir " + baseDir + " has no children, exists=" + baseDir.exists()
583 + ", isDirectory=" + baseDir.isDirectory());
584 return;
585 }
586
587 for (int i = 0; i < files.length; i++)
588 match(matcher, matched, base, files[i].getName(), pattern);
589 } else {
590 String fullPath = base + '/' + currentPath;
591 if (matched.contains(fullPath))
592 return;// don't try deeper if already matched
593
594 boolean ok = matcher.match(pattern, currentPath);
595 // if (debug)
596 // debug(currentPath + " " + (ok ? "" : " not ")
597 // + " matched with " + pattern);
598 if (ok) {
599 matched.add(fullPath);
600 return;
601 } else {
602 String newFullPath = relativeToFullPath(base, currentPath);
603 File newFile = new File(newFullPath);
604 File[] files = newFile.listFiles();
605 if (files != null) {
606 for (int i = 0; i < files.length; i++) {
607 String newCurrentPath = currentPath + '/' + files[i].getName();
608 if (files[i].isDirectory()) {
609 if (matcher.matchStart(pattern, newCurrentPath)) {
610 // recurse only if start matches
611 match(matcher, matched, base, newCurrentPath, pattern);
612 } else {
613 if (OsgiBootUtils.debug)
614 debug(newCurrentPath + " does not start match with " + pattern);
615
616 }
617 } else {
618 boolean nonDirectoryOk = matcher.match(pattern, newCurrentPath);
619 if (OsgiBootUtils.debug)
620 debug(currentPath + " " + (ok ? "" : " not ") + " matched with " + pattern);
621 if (nonDirectoryOk)
622 matched.add(relativeToFullPath(base, newCurrentPath));
623 }
624 }
625 }
626 }
627 }
628 }
629
630 protected void matchFile() {
631
632 }
633
634 /*
635 * LOW LEVEL UTILITIES
636 */
637 /**
638 * The bundles already installed. Key is location (String) , value is a
639 * {@link Bundle}
640 */
641 public Map<String, Bundle> getBundlesByLocation() {
642 Map<String, Bundle> installedBundles = new HashMap<String, Bundle>();
643 Bundle[] bundles = bundleContext.getBundles();
644 for (int i = 0; i < bundles.length; i++) {
645 installedBundles.put(bundles[i].getLocation(), bundles[i]);
646 }
647 return installedBundles;
648 }
649
650 /**
651 * The bundles already installed. Key is symbolic name (String) , value is a
652 * {@link Bundle}
653 */
654 public Map<String, Bundle> getBundlesBySymbolicName() {
655 Map<String, Bundle> namedBundles = new HashMap<String, Bundle>();
656 Bundle[] bundles = bundleContext.getBundles();
657 for (int i = 0; i < bundles.length; i++) {
658 namedBundles.put(bundles[i].getSymbolicName(), bundles[i]);
659 }
660 return namedBundles;
661 }
662
663 /** Creates an URL from a location */
664 protected String locationToUrl(String baseUrl, String location) {
665 return baseUrl + location;
666 }
667
668 /** Transforms a relative path in a full system path. */
669 protected String relativeToFullPath(String basePath, String relativePath) {
670 return (basePath + '/' + relativePath).replace('/', File.separatorChar);
671 }
672
673 private void refreshFramework() {
674 Bundle systemBundle = bundleContext.getBundle(0);
675 FrameworkWiring frameworkWiring = systemBundle.adapt(FrameworkWiring.class);
676 frameworkWiring.refreshBundles(null);
677 }
678
679 /**
680 * Gets a property value
681 *
682 * @return null when defaultValue is ""
683 */
684 public String getProperty(String name, String defaultValue) {
685 String value = bundleContext.getProperty(name);
686 if (value == null)
687 return defaultValue; // may be null
688 else
689 return value;
690 }
691
692 public String getProperty(String name) {
693 return getProperty(name, null);
694 }
695
696 /*
697 * BEAN METHODS
698 */
699
700 public boolean getDebug() {
701 return OsgiBootUtils.debug;
702 }
703
704 // public void setDebug(boolean debug) {
705 // this.debug = debug;
706 // }
707
708 public BundleContext getBundleContext() {
709 return bundleContext;
710 }
711
712 public String getLocalCache() {
713 return localCache;
714 }
715
716 // public void setDefaultTimeout(long defaultTimeout) {
717 // this.defaultTimeout = defaultTimeout;
718 // }
719
720 // public boolean isExcludeSvn() {
721 // return excludeSvn;
722 // }
723 //
724 // public void setExcludeSvn(boolean excludeSvn) {
725 // this.excludeSvn = excludeSvn;
726 // }
727
728 /*
729 * INTERNAL CLASSES
730 */
731
732 }