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