2 * Copyright (C) 2007-2012 Argeo GmbH
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org
.argeo
.osgi
.boot
;
18 import static org
.argeo
.osgi
.boot
.OsgiBootUtils
.debug
;
19 import static org
.argeo
.osgi
.boot
.OsgiBootUtils
.warn
;
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
;
29 import java
.util
.Properties
;
31 import java
.util
.SortedMap
;
32 import java
.util
.StringTokenizer
;
33 import java
.util
.TreeMap
;
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
;
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.
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";
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";
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";
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";
72 public final static String DEFAULT_BASE_URL
= "reference:file:";
73 // public final static String EXCLUDES_SVN_PATTERN = "**/.svn/**";
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";
82 public final static String SYMBOLIC_NAME_OSGI_BOOT
= "org.argeo.osgi.boot";
83 public final static String SYMBOLIC_NAME_EQUINOX
= "org.eclipse.osgi";
85 /** Exclude svn metadata implicitely(a bit costly) */
86 // private boolean excludeSvn =
87 // Boolean.valueOf(System.getProperty(PROP_ARGEO_OSGI_BOOT_EXCLUDE_SVN,
93 private long defaultTimeout
= 10000l;
95 private final BundleContext bundleContext
;
96 private final String localCache
;
98 private final ProvisioningManager provisioningManager
;
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/");
110 provisioningManager
= new ProvisioningManager(bundleContext
);
111 String sources
= getProperty(PROP_ARGEO_OSGI_SOURCES
);
112 if (sources
== null) {
113 provisioningManager
.registerDefaultSource();
115 for (String source
: sources
.split(",")) {
116 if (source
.trim().equals(A2Source
.DEFAULT_A2_URI
)) {
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");
122 provisioningManager
.registerSource(source
);
128 ProvisioningManager
getProvisioningManager() {
129 return provisioningManager
;
135 /** Bootstraps the OSGi runtime */
136 public void bootstrap() {
138 long begin
= System
.currentTimeMillis();
139 System
.out
.println();
140 String osgiInstancePath
= bundleContext
.getProperty(INSTANCE_AREA_PROP
);
142 .info("OSGi bootstrap starting" + (osgiInstancePath
!= null ?
" (" + osgiInstancePath
+ ")" : ""));
143 installUrls(getBundlesUrls());
144 installUrls(getDistributionUrls());
145 provisioningManager
.install(null);
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
);
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());
173 System
.out
.println();
176 public void update() {
177 provisioningManager
.update();
183 /** Install a single url. Convenience method. */
184 public Bundle
installUrl(String url
) {
185 List
<String
> urls
= new ArrayList
<String
>();
188 return (Bundle
) getBundlesByLocation().get(url
);
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
);
201 /** Actually install the provided URL */
202 protected void installUrl(String url
, Map
<String
, Bundle
> installedBundles
) {
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
)
214 Bundle bundle
= bundleContext
.installBundle(url
);
215 if (url
.startsWith("http"))
217 .info("Installed " + bundle
.getSymbolicName() + "-" + bundle
.getVersion() + " from " + url
);
218 else if (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)
226 if (bundle
.getSymbolicName().equals(b
.getSymbolicName())) {
227 Version bundleV
= bundle
.getVersion();
228 Version bV
= b
.getVersion();
231 if (bundleV
.getMajor() == bV
.getMajor() && bundleV
.getMinor() == bV
.getMinor()) {
232 if (bundleV
.getMicro() > bV
.getMicro()) {
233 // uninstall older bundles
235 OsgiBootUtils
.debug("Uninstalled " + b
);
236 } else if (bundleV
.getMicro() < bV
.getMicro()) {
237 // uninstall just installed bundle if newer
239 OsgiBootUtils
.debug("Uninstalled " + bundle
);
242 // uninstall any other with same major/minor
243 if (!bundleV
.getQualifier().equals(bV
.getQualifier())) {
245 OsgiBootUtils
.debug("Uninstalled " + b
);
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...
261 if (message
.contains(ALREADY_INSTALLED
)) {
262 if (OsgiBootUtils
.isDebug())
263 OsgiBootUtils
.warn("Duplicate install from " + url
+ ": " + message
);
265 OsgiBootUtils
.warn("Could not install bundle from " + url
+ ": " + message
);
267 if (OsgiBootUtils
.debug
&& !message
.contains(ALREADY_INSTALLED
))
275 public void startBundles() {
276 startBundles(System
.getProperties());
279 public void startBundles(Properties properties
) {
280 FrameworkStartLevel frameworkStartLevel
= bundleContext
.getBundle(0).adapt(FrameworkStartLevel
.class);
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"));
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
);
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
);
304 } catch (BundleException e
) {
305 OsgiBootUtils
.error("Cannot mark " + bsn
+ " as started", e
);
308 OsgiBootUtils
.debug(bsn
+ " starts at level " + level
);
312 frameworkStartLevel
.setStartLevel(activeStartLevel
, (FrameworkEvent event
) -> {
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
+ ")");
321 private static void computeStartLevels(SortedMap
<Integer
, List
<String
>> startLevels
, Properties properties
,
322 Integer defaultStartLevel
) {
324 // default (and previously, only behaviour)
325 appendToStartLevels(startLevels
, defaultStartLevel
, properties
.getProperty(PROP_ARGEO_OSGI_START
, ""));
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
)) {
334 String suffix
= key
.substring(prefix
.length());
335 String
[] tokens
= suffix
.split("\\.");
336 if (tokens
.length
> 0 && !tokens
[0].trim().equals(""))
338 // first token is start level
339 startLevel
= new Integer(tokens
[0]);
340 } catch (NumberFormatException e
) {
341 startLevel
= defaultStartLevel
;
344 startLevel
= defaultStartLevel
;
346 // append bundle names
347 String bundleNames
= properties
.getProperty(key
);
348 appendToStartLevels(startLevels
, startLevel
, bundleNames
);
353 /** Append a comma-separated list of bundles to the start levels. */
354 private static void appendToStartLevels(SortedMap
<Integer
, List
<String
>> startLevels
, Integer startLevel
,
356 if (str
== null || str
.trim().equals(""))
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
]);
369 * Start the provided list of bundles
371 * @return whether all bundles are now in active state
375 public boolean startBundles(List
<String
> bundlesToStart
) {
376 if (bundlesToStart
.size() == 0)
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
);
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
))
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
);
400 startedBundles
.add(bundle
);
402 notFoundBundles
.remove(symbolicName
);
403 } catch (Exception e
) {
404 OsgiBootUtils
.warn("Bundle " + symbolicName
+ " cannot be started: " + e
.getMessage());
405 if (OsgiBootUtils
.debug
)
407 // was found even if start failed
408 notFoundBundles
.remove(symbolicName
);
412 for (int i
= 0; i
< notFoundBundles
.size(); i
++)
413 OsgiBootUtils
.warn("Bundle '" + notFoundBundles
.get(i
) + "' not started because it was not found.");
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
>();
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
) {
427 notStarted
.add(bundle
.getSymbolicName());
432 } catch (InterruptedException e
) {
436 long duration
= System
.currentTimeMillis() - beginMonitor
;
439 for (int i
= 0; i
< notStarted
.size(); i
++)
440 OsgiBootUtils
.warn("Bundle '" + notStarted
.get(i
) + "' not ACTIVE after " + (duration
/ 1000) + "s");
445 /** Waits for a bundle to become active or resolved */
447 private void waitForBundleResolvedOrActive(long startBegin
, Bundle bundle
) throws Exception
{
448 int originalState
= bundle
.getState();
449 if ((originalState
== Bundle
.RESOLVED
) || (originalState
== Bundle
.ACTIVE
))
452 String originalStateStr
= OsgiBootUtils
.stateAsString(originalState
);
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
) + ")");
464 } catch (InterruptedException e
) {
467 currentState
= bundle
.getState();
472 * BUNDLE PATTERNS INSTALLATION
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.
481 public List
<String
> getBundlesUrls() {
482 String bundlePatterns
= getProperty(PROP_ARGEO_OSGI_BUNDLES
);
483 return getBundlesUrls(bundlePatterns
);
487 * Compute a list of URLs to install based on the provided patterns, with
490 public List
<String
> getBundlesUrls(String bundlePatterns
) {
491 String baseUrl
= getProperty(PROP_ARGEO_OSGI_BASE_URL
, DEFAULT_BASE_URL
);
492 return getBundlesUrls(baseUrl
, bundlePatterns
);
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)
501 bundlePatterns
= SystemPropertyUtils
.resolvePlaceholders(bundlePatterns
);
502 if (OsgiBootUtils
.debug
)
503 debug(PROP_ARGEO_OSGI_BUNDLES
+ "=" + bundlePatterns
);
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
);
513 bundlesSets
.add(new BundlesSet(token
));
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
);
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
);
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
));
548 * DISTRIBUTION JAR INSTALLATION
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
);
556 public List
<String
> getDistributionUrls(String distributionUrl
, String baseUrl
) {
557 List
<String
> urls
= new ArrayList
<String
>();
558 if (distributionUrl
== null)
561 DistributionBundle distributionBundle
;
562 if (distributionUrl
.startsWith("http") || distributionUrl
.startsWith("file")) {
563 distributionBundle
= new DistributionBundle(distributionUrl
);
565 distributionBundle
.setBaseUrl(baseUrl
);
568 if (baseUrl
== null) {
569 baseUrl
= localCache
;
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('/');
582 sb
.append(artifactId
).append('/');
583 sb
.append(version
).append('/');
584 sb
.append(artifactId
).append('-').append(version
).append(".jar");
585 distributionUrl
= sb
.toString();
588 distributionBundle
= new DistributionBundle(baseUrl
, distributionUrl
, localCache
);
590 // if (baseUrl != null && !(distributionUrl.startsWith("http") ||
591 // distributionUrl.startsWith("file"))) {
593 // distributionBundle = new DistributionBundle(baseUrl, distributionUrl,
596 // distributionBundle = new DistributionBundle(distributionUrl);
597 // if (baseUrl != null)
598 // distributionBundle.setBaseUrl(baseUrl);
600 distributionBundle
.processUrl();
601 return distributionBundle
.listUrls();
605 * HIGH LEVEL UTILITIES
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) {
611 File baseDir
= new File(base
.replace('/', File
.separatorChar
));
612 File
[] files
= baseDir
.listFiles();
615 if (OsgiBootUtils
.debug
)
616 OsgiBootUtils
.warn("Base dir " + baseDir
+ " has no children, exists=" + baseDir
.exists()
617 + ", isDirectory=" + baseDir
.isDirectory());
621 for (int i
= 0; i
< files
.length
; i
++)
622 match(matcher
, matched
, base
, files
[i
].getName(), pattern
);
624 String fullPath
= base
+ '/' + currentPath
;
625 if (matched
.contains(fullPath
))
626 return;// don't try deeper if already matched
628 boolean ok
= matcher
.match(pattern
, currentPath
);
630 // debug(currentPath + " " + (ok ? "" : " not ")
631 // + " matched with " + pattern);
633 matched
.add(fullPath
);
636 String newFullPath
= relativeToFullPath(base
, currentPath
);
637 File newFile
= new File(newFullPath
);
638 File
[] files
= newFile
.listFiles();
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
);
647 if (OsgiBootUtils
.debug
)
648 debug(newCurrentPath
+ " does not start match with " + pattern
);
652 boolean nonDirectoryOk
= matcher
.match(pattern
, newCurrentPath
);
653 if (OsgiBootUtils
.debug
)
654 debug(currentPath
+ " " + (ok ?
"" : " not ") + " matched with " + pattern
);
656 matched
.add(relativeToFullPath(base
, newCurrentPath
));
664 protected void matchFile() {
669 * LOW LEVEL UTILITIES
672 * The bundles already installed. Key is location (String) , value is a
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
]);
681 return installedBundles
;
685 * The bundles already installed. Key is symbolic name (String) , value is a
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
]);
697 /** Creates an URL from a location */
698 protected String
locationToUrl(String baseUrl
, String location
) {
699 return baseUrl
+ location
;
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
);
707 private void refreshFramework() {
708 Bundle systemBundle
= bundleContext
.getBundle(0);
709 FrameworkWiring frameworkWiring
= systemBundle
.adapt(FrameworkWiring
.class);
710 frameworkWiring
.refreshBundles(null);
714 * Gets a property value
716 * @return null when defaultValue is ""
718 public String
getProperty(String name
, String defaultValue
) {
719 String value
= bundleContext
.getProperty(name
);
721 return defaultValue
; // may be null
726 public String
getProperty(String name
) {
727 return getProperty(name
, null);
734 public boolean getDebug() {
735 return OsgiBootUtils
.debug
;
738 // public void setDebug(boolean debug) {
739 // this.debug = debug;
742 public BundleContext
getBundleContext() {
743 return bundleContext
;
746 public String
getLocalCache() {
750 // public void setDefaultTimeout(long defaultTimeout) {
751 // this.defaultTimeout = defaultTimeout;
754 // public boolean isExcludeSvn() {
755 // return excludeSvn;
758 // public void setExcludeSvn(boolean excludeSvn) {
759 // this.excludeSvn = excludeSvn;