]> git.argeo.org Git - lgpl/argeo-commons.git/blobdiff - osgi/runtime/org.argeo.osgi.boot/src/main/java/org/argeo/osgi/boot/OsgiBoot.java
Use lexicographic order for OSGi Boot
[lgpl/argeo-commons.git] / osgi / runtime / org.argeo.osgi.boot / src / main / java / org / argeo / osgi / boot / OsgiBoot.java
index af28c8abacc845fe4f41b3061e80aaf35e50a0cc..d51c80b320a6c3e2f91d1fec285d6593da6e9d18 100644 (file)
@@ -27,7 +27,11 @@ import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
+import java.util.SortedMap;
 import java.util.StringTokenizer;
+import java.util.TreeMap;
+import java.util.TreeSet;
 
 import org.argeo.osgi.boot.internal.springutil.AntPathMatcher;
 import org.argeo.osgi.boot.internal.springutil.PathMatcher;
@@ -37,8 +41,10 @@ import org.osgi.framework.BundleContext;
 import org.osgi.framework.BundleException;
 import org.osgi.framework.Constants;
 import org.osgi.framework.ServiceReference;
+import org.osgi.service.packageadmin.ExportedPackage;
 import org.osgi.service.packageadmin.PackageAdmin;
 
+/** Core component, performing basic provisioning of an OSGi runtime. */
 public class OsgiBoot {
        public final static String SYMBOLIC_NAME_OSGI_BOOT = "org.argeo.osgi.boot";
        public final static String SYMBOLIC_NAME_EQUINOX = "org.eclipse.osgi";
@@ -49,47 +55,34 @@ public class OsgiBoot {
        public final static String PROP_ARGEO_OSGI_BUNDLES = "argeo.osgi.bundles";
        public final static String PROP_ARGEO_OSGI_LOCATIONS = "argeo.osgi.locations";
        public final static String PROP_ARGEO_OSGI_BASE_URL = "argeo.osgi.baseUrl";
+       /** Use org.argeo.osgi */
        public final static String PROP_ARGEO_OSGI_MODULES_URL = "argeo.osgi.modulesUrl";
 
        public final static String PROP_ARGEO_OSGI_BOOT_DEBUG = "argeo.osgi.boot.debug";
+       public final static String PROP_ARGEO_OSGI_BOOT_INSTALL_IN_LEXICOGRAPHIC_ORDER = "argeo.osgi.boot.installInLexicographicOrder";
        public final static String PROP_ARGEO_OSGI_BOOT_DEFAULT_TIMEOUT = "argeo.osgi.boot.defaultTimeout";
        public final static String PROP_ARGEO_OSGI_BOOT_MODULES_URL_SEPARATOR = "argeo.osgi.boot.modulesUrlSeparator";
        public final static String PROP_ARGEO_OSGI_BOOT_SYSTEM_PROPERTIES_FILE = "argeo.osgi.boot.systemPropertiesFile";
        public final static String PROP_ARGEO_OSGI_BOOT_APPCLASS = "argeo.osgi.boot.appclass";
        public final static String PROP_ARGEO_OSGI_BOOT_APPARGS = "argeo.osgi.boot.appargs";
-       
-       /** @deprecated */
-       public final static String PROP_SLC_OSGI_START = "slc.osgi.start";
-       /** @deprecated */
-       public final static String PROP_SLC_OSGI_BUNDLES = "slc.osgi.bundles";
-       /** @deprecated */
-       public final static String PROP_SLC_OSGI_LOCATIONS = "slc.osgi.locations";
-       /** @deprecated */
-       public final static String PROP_SLC_OSGI_BASE_URL = "slc.osgi.baseUrl";
-       /** @deprecated */
-       public final static String PROP_SLC_OSGI_MODULES_URL = "slc.osgi.modulesUrl";
-
-       /** @deprecated */
-       public final static String PROP_SLC_OSGIBOOT_DEBUG = "slc.osgiboot.debug";
-       /** @deprecated */
-       public final static String PROP_SLC_OSGIBOOT_DEFAULT_TIMEOUT = "slc.osgiboot.defaultTimeout";
-       /** @deprecated */
-       public final static String PROP_SLC_OSGIBOOT_MODULES_URL_SEPARATOR = "slc.osgiboot.modulesUrlSeparator";
-       /** @deprecated */
-       public final static String PROP_SLC_OSGIBOOT_SYSTEM_PROPERTIES_FILE = "slc.osgiboot.systemPropertiesFile";
-       /** @deprecated */
-       public final static String PROP_SLC_OSGIBOOT_APPCLASS = "slc.osgiboot.appclass";
-       /** @deprecated */
-       public final static String PROP_SLC_OSGIBOOT_APPARGS = "slc.osgiboot.appargs";
-
-       
-       
+
        public final static String DEFAULT_BASE_URL = "reference:file:";
        public final static String EXCLUDES_SVN_PATTERN = "**/.svn/**";
 
        private boolean debug = Boolean.valueOf(
-                       System.getProperty(PROP_ARGEO_OSGI_BOOT_DEBUG, System.getProperty(
-                                       PROP_SLC_OSGIBOOT_DEBUG, "false"))).booleanValue();
+                       System.getProperty(PROP_ARGEO_OSGI_BOOT_DEBUG, "false"))
+                       .booleanValue();
+
+       /**
+        * The {@link #installUrls(List)} methods won't follow the list order but
+        * order the urls according to teh alphabetical order of the file names
+        * (last part of the URL). The goal is to stay closer from Eclipse PDE way
+        * of installing target platform bundles.
+        */
+       private boolean installInLexicographicOrder = Boolean.valueOf(
+                       System.getProperty(PROP_ARGEO_OSGI_BOOT_DEBUG, "true"))
+                       .booleanValue();;
+
        /** Default is 10s (set in constructor) */
        private long defaultTimeout;
 
@@ -101,12 +94,10 @@ public class OsgiBoot {
 
        public OsgiBoot(BundleContext bundleContext) {
                this.bundleContext = bundleContext;
-               defaultTimeout = Long.parseLong(OsgiBootUtils.getPropertyCompat(
-                               PROP_ARGEO_OSGI_BOOT_DEFAULT_TIMEOUT,
-                               PROP_SLC_OSGIBOOT_DEFAULT_TIMEOUT, "10000"));
-               modulesUrlSeparator = OsgiBootUtils.getPropertyCompat(
-                               PROP_ARGEO_OSGI_BOOT_MODULES_URL_SEPARATOR,
-                               PROP_SLC_OSGIBOOT_MODULES_URL_SEPARATOR, ",");
+               defaultTimeout = Long.parseLong(OsgiBootUtils.getProperty(
+                               PROP_ARGEO_OSGI_BOOT_DEFAULT_TIMEOUT, "10000"));
+               modulesUrlSeparator = OsgiBootUtils.getProperty(
+                               PROP_ARGEO_OSGI_BOOT_MODULES_URL_SEPARATOR, ",");
                initSystemProperties();
        }
 
@@ -133,18 +124,10 @@ public class OsgiBoot {
 
                // TODO: Load additional system properties from file
                // Properties additionalSystemProperties = new Properties();
-               
-       }
 
-       public static String removeFilePrefix(String url) {
-               if (url.startsWith("file:"))
-                       return url.substring("file:".length());
-               else if (url.startsWith("reference:file:"))
-                       return url.substring("reference:file:".length());
-               else
-                       return url;
        }
 
+       /** Boot strap the OSGi runtime */
        public void bootstrap() {
                long begin = System.currentTimeMillis();
                System.out.println();
@@ -161,45 +144,92 @@ public class OsgiBoot {
                OsgiBootUtils.info("OSGi bootstrap completed in "
                                + Math.round(((double) duration) / 1000) + "s (" + duration
                                + "ms), " + bundleContext.getBundles().length + " bundles");
+
+               // display packages exported twice
+               if (debug) {
+                       Map /* <String,Set<String>> */duplicatePackages = findPackagesExportedTwice();
+                       if (duplicatePackages.size() > 0) {
+                               OsgiBootUtils.info("Packages exported twice:");
+                               Iterator it = duplicatePackages.keySet().iterator();
+                               while (it.hasNext()) {
+                                       String pkgName = it.next().toString();
+                                       OsgiBootUtils.info(pkgName);
+                                       Set bdles = (Set) duplicatePackages.get(pkgName);
+                                       Iterator bdlesIt = bdles.iterator();
+                                       while (bdlesIt.hasNext())
+                                               OsgiBootUtils.info("  " + bdlesIt.next());
+                               }
+                       }
+               }
+
                System.out.println();
        }
 
+       /** Install the bundles at this URL list. */
        public void installUrls(List urls) {
                Map installedBundles = getInstalledBundles();
-               for (int i = 0; i < urls.size(); i++) {
-                       String url = (String) urls.get(i);
-                       try {
-                               if (installedBundles.containsKey(url)) {
-                                       Bundle bundle = (Bundle) installedBundles.get(url);
-                                       // bundle.update();
-                                       if (debug)
-                                               debug("Bundle " + bundle.getSymbolicName()
-                                                               + " already installed from " + url);
-                               } else {
-                                       Bundle bundle = bundleContext.installBundle(url);
-                                       if (debug)
-                                               debug("Installed bundle " + bundle.getSymbolicName()
-                                                               + " from " + url);
-                               }
-                       } catch (BundleException e) {
-                               String message = e.getMessage();
-                               if ((message.contains("Bundle \"" + SYMBOLIC_NAME_OSGI_BOOT
-                                               + "\"") || message.contains("Bundle \""
-                                               + SYMBOLIC_NAME_EQUINOX + "\""))
-                                               && message.contains("has already been installed")) {
-                                       // silent, in order to avoid warnings: we know that both
-                                       // have already been installed...
-                               } else {
-                                       OsgiBootUtils.warn("Could not install bundle from " + url + ": "
-                                                       + message);
-                               }
-                               if (debug)
-                                       e.printStackTrace();
+
+               if (installInLexicographicOrder) {
+                       SortedMap map = new TreeMap();
+                       // reorder
+                       for (int i = 0; i < urls.size(); i++) {
+                               String url = (String) urls.get(i);
+                               int index = url.lastIndexOf('/');
+                               String fileName;
+                               if (index >= 0)
+                                       fileName = url.substring(index + 1);
+                               else
+                                       fileName = url;
+                               map.put(fileName, url);
+                       }
+
+                       // install
+                       Iterator keys = map.keySet().iterator();
+                       while (keys.hasNext()) {
+                               Object key = keys.next();
+                               String url = map.get(key).toString();
+                               installUrl(url, installedBundles);
+                       }
+               } else {
+                       for (int i = 0; i < urls.size(); i++) {
+                               String url = (String) urls.get(i);
+                               installUrl(url, installedBundles);
                        }
                }
 
        }
 
+       protected void installUrl(String url, Map installedBundles) {
+               try {
+                       if (installedBundles.containsKey(url)) {
+                               Bundle bundle = (Bundle) installedBundles.get(url);
+                               // bundle.update();
+                               if (debug)
+                                       debug("Bundle " + bundle.getSymbolicName()
+                                                       + " already installed from " + url);
+                       } else {
+                               Bundle bundle = bundleContext.installBundle(url);
+                               if (debug)
+                                       debug("Installed bundle " + bundle.getSymbolicName()
+                                                       + " from " + url);
+                       }
+               } catch (BundleException e) {
+                       String message = e.getMessage();
+                       if ((message.contains("Bundle \"" + SYMBOLIC_NAME_OSGI_BOOT + "\"") || message
+                                       .contains("Bundle \"" + SYMBOLIC_NAME_EQUINOX + "\""))
+                                       && message.contains("has already been installed")) {
+                               // silent, in order to avoid warnings: we know that both
+                               // have already been installed...
+                       } else {
+                               OsgiBootUtils.warn("Could not install bundle from " + url
+                                               + ": " + message);
+                       }
+                       if (debug)
+                               e.printStackTrace();
+               }
+       }
+
+       /** @deprecated Doesn't seem to be used anymore. */
        public void installOrUpdateUrls(Map urls) {
                Map installedBundles = getBundles();
 
@@ -213,7 +243,8 @@ public class OsgiBoot {
                                        URL url = new URL(urlStr);
                                        in = url.openStream();
                                        bundle.update(in);
-                                       OsgiBootUtils.info("Updated bundle " + moduleName + " from " + urlStr);
+                                       OsgiBootUtils.info("Updated bundle " + moduleName
+                                                       + " from " + urlStr);
                                } catch (Exception e) {
                                        throw new RuntimeException("Cannot update " + moduleName
                                                        + " from " + urlStr);
@@ -231,8 +262,8 @@ public class OsgiBoot {
                                                debug("Installed bundle " + bundle.getSymbolicName()
                                                                + " from " + urlStr);
                                } catch (BundleException e) {
-                                       OsgiBootUtils.warn("Could not install bundle from " + urlStr + ": "
-                                                       + e.getMessage());
+                                       OsgiBootUtils.warn("Could not install bundle from "
+                                                       + urlStr + ": " + e.getMessage());
                                }
                        }
                }
@@ -240,8 +271,8 @@ public class OsgiBoot {
        }
 
        public void startBundles() {
-               String bundlesToStart = OsgiBootUtils.getPropertyCompat(PROP_ARGEO_OSGI_START,
-                               PROP_SLC_OSGI_START);
+               String bundlesToStart = OsgiBootUtils
+                               .getProperty(PROP_ARGEO_OSGI_START);
                startBundles(bundlesToStart);
        }
 
@@ -274,6 +305,8 @@ public class OsgiBoot {
                                try {
                                        try {
                                                bundle.start();
+                                               if (debug)
+                                                       debug("Bundle " + symbolicName + " started");
                                        } catch (Exception e) {
                                                OsgiBootUtils.warn("Start of bundle " + symbolicName
                                                                + " failed because of " + e
@@ -284,8 +317,8 @@ public class OsgiBoot {
                                        }
                                        notFoundBundles.remove(symbolicName);
                                } catch (Exception e) {
-                                       OsgiBootUtils.warn("Bundle " + symbolicName + " cannot be started: "
-                                                       + e.getMessage());
+                                       OsgiBootUtils.warn("Bundle " + symbolicName
+                                                       + " cannot be started: " + e.getMessage());
                                        if (debug)
                                                e.printStackTrace();
                                        // was found even if start failed
@@ -320,6 +353,41 @@ public class OsgiBoot {
                }
        }
 
+       /** List packages exported twice. */
+       public Map findPackagesExportedTwice() {
+               ServiceReference paSr = bundleContext
+                               .getServiceReference(PackageAdmin.class.getName());
+               // TODO: make a cleaner referencing
+               PackageAdmin packageAdmin = (PackageAdmin) bundleContext
+                               .getService(paSr);
+
+               // find packages exported twice
+               Bundle[] bundles = bundleContext.getBundles();
+               Map /* <String,Set<String>> */exportedPackages = new TreeMap();
+               for (int i = 0; i < bundles.length; i++) {
+                       Bundle bundle = bundles[i];
+                       ExportedPackage[] pkgs = packageAdmin.getExportedPackages(bundle);
+                       if (pkgs != null)
+                               for (int j = 0; j < pkgs.length; j++) {
+                                       String pkgName = pkgs[j].getName();
+                                       if (!exportedPackages.containsKey(pkgName)) {
+                                               exportedPackages.put(pkgName, new TreeSet());
+                                       }
+                                       ((Set) exportedPackages.get(pkgName)).add(bundle
+                                                       .getSymbolicName() + "_" + bundle.getVersion());
+                               }
+               }
+               Map /* <String,Set<String>> */duplicatePackages = new TreeMap();
+               Iterator it = exportedPackages.keySet().iterator();
+               while (it.hasNext()) {
+                       String pkgName = it.next().toString();
+                       Set bdles = (Set) exportedPackages.get(pkgName);
+                       if (bdles.size() > 1)
+                               duplicatePackages.put(pkgName, bdles);
+               }
+               return duplicatePackages;
+       }
+
        protected void waitForBundleResolvedOrActive(long startBegin, Bundle bundle)
                        throws Exception {
                int originalState = bundle.getState();
@@ -389,30 +457,29 @@ public class OsgiBoot {
        }
 
        public List getLocationsUrls() {
-               String baseUrl = OsgiBootUtils.getPropertyCompat(PROP_ARGEO_OSGI_BASE_URL,
-                               PROP_SLC_OSGI_BASE_URL, DEFAULT_BASE_URL);
-               String bundleLocations = OsgiBootUtils.getPropertyCompat(PROP_ARGEO_OSGI_LOCATIONS,
-                               PROP_SLC_OSGI_LOCATIONS);
+               String baseUrl = OsgiBootUtils.getProperty(PROP_ARGEO_OSGI_BASE_URL,
+                               DEFAULT_BASE_URL);
+               String bundleLocations = OsgiBootUtils
+                               .getProperty(PROP_ARGEO_OSGI_LOCATIONS);
                return getLocationsUrls(baseUrl, bundleLocations);
        }
 
        public List getModulesUrls() {
                List urls = new ArrayList();
-               String modulesUrlStr = OsgiBootUtils.getPropertyCompat(PROP_ARGEO_OSGI_MODULES_URL,
-                               PROP_SLC_OSGI_MODULES_URL);
+               String modulesUrlStr = OsgiBootUtils
+                               .getProperty(PROP_ARGEO_OSGI_MODULES_URL);
                if (modulesUrlStr == null)
                        return urls;
 
-               String baseUrl = OsgiBootUtils.getPropertyCompat(PROP_ARGEO_OSGI_BASE_URL,
-                               PROP_SLC_OSGI_BASE_URL);
+               String baseUrl = OsgiBootUtils.getProperty(PROP_ARGEO_OSGI_BASE_URL);
 
                Map installedBundles = getBundles();
 
                BufferedReader reader = null;
                try {
                        URL modulesUrl = new URL(modulesUrlStr);
-                       reader = new BufferedReader(new InputStreamReader(modulesUrl
-                                       .openStream()));
+                       reader = new BufferedReader(new InputStreamReader(
+                                       modulesUrl.openStream()));
                        String line = null;
                        while ((line = reader.readLine()) != null) {
                                StringTokenizer st = new StringTokenizer(line,
@@ -425,8 +492,8 @@ public class OsgiBoot {
 
                                if (installedBundles.containsKey(moduleName)) {
                                        Bundle bundle = (Bundle) installedBundles.get(moduleName);
-                                       String bundleVersion = bundle.getHeaders().get(
-                                                       Constants.BUNDLE_VERSION).toString();
+                                       String bundleVersion = bundle.getHeaders()
+                                                       .get(Constants.BUNDLE_VERSION).toString();
                                        int comp = compareVersions(bundleVersion, moduleVersion);
                                        if (comp > 0) {
                                                OsgiBootUtils.warn("Installed version " + bundleVersion
@@ -435,9 +502,9 @@ public class OsgiBoot {
                                                                + moduleVersion);
                                        } else if (comp < 0) {
                                                urls.add(url);
-                                               OsgiBootUtils.info("Updated bundle " + moduleName + " with version "
-                                                               + moduleVersion + " (old version was "
-                                                               + bundleVersion + ")");
+                                               OsgiBootUtils.info("Updated bundle " + moduleName
+                                                               + " with version " + moduleVersion
+                                                               + " (old version was " + bundleVersion + ")");
                                        } else {
                                                // do nothing
                                        }
@@ -529,10 +596,10 @@ public class OsgiBoot {
        }
 
        public List getBundlesUrls() {
-               String baseUrl = OsgiBootUtils.getPropertyCompat(PROP_ARGEO_OSGI_BASE_URL,
-                               PROP_SLC_OSGI_BASE_URL, DEFAULT_BASE_URL);
-               String bundlePatterns = OsgiBootUtils.getPropertyCompat(PROP_ARGEO_OSGI_BUNDLES,
-                               PROP_SLC_OSGI_BUNDLES);
+               String baseUrl = OsgiBootUtils.getProperty(PROP_ARGEO_OSGI_BASE_URL,
+                               DEFAULT_BASE_URL);
+               String bundlePatterns = OsgiBootUtils
+                               .getProperty(PROP_ARGEO_OSGI_BUNDLES);
                return getBundlesUrls(baseUrl, bundlePatterns);
        }
 
@@ -581,6 +648,10 @@ public class OsgiBoot {
                return urls;
        }
 
+       /*
+        * HIGH LEVEL UTILITIES
+        */
+
        protected void match(PathMatcher matcher, List matched, String base,
                        String currentPath, String pattern) {
                if (currentPath == null) {
@@ -589,9 +660,9 @@ public class OsgiBoot {
                        File[] files = baseDir.listFiles();
 
                        if (files == null) {
-                               OsgiBootUtils.warn("Base dir " + baseDir + " has no children, exists="
-                                               + baseDir.exists() + ", isDirectory="
-                                               + baseDir.isDirectory());
+                               OsgiBootUtils.warn("Base dir " + baseDir
+                                               + " has no children, exists=" + baseDir.exists()
+                                               + ", isDirectory=" + baseDir.isDirectory());
                                return;
                        }
 
@@ -603,9 +674,9 @@ public class OsgiBoot {
                                return;// don't try deeper if already matched
 
                        boolean ok = matcher.match(pattern, currentPath);
-                       if (debug)
-                               debug(currentPath + " " + (ok ? "" : " not ")
-                                               + " matched with " + pattern);
+                       // if (debug)
+                       // debug(currentPath + " " + (ok ? "" : " not ")
+                       // + " matched with " + pattern);
                        if (ok) {
                                matched.add(fullPath);
                                return;
@@ -645,6 +716,11 @@ public class OsgiBoot {
                }
        }
 
+       /*
+        * LOW LEVEL UTILITIES
+        */
+
+       /** Creates an URL from a location */
        protected String locationToUrl(String baseUrl, String location) {
                int extInd = location.lastIndexOf('.');
                String ext = null;
@@ -662,6 +738,15 @@ public class OsgiBoot {
                return (basePath + '/' + relativePath).replace('/', File.separatorChar);
        }
 
+       private String removeFilePrefix(String url) {
+               if (url.startsWith("file:"))
+                       return url.substring("file:".length());
+               else if (url.startsWith("reference:file:"))
+                       return url.substring("reference:file:".length());
+               else
+                       return url;
+       }
+
        protected void debug(Object obj) {
                if (debug)
                        OsgiBootUtils.debug(obj);
@@ -679,6 +764,15 @@ public class OsgiBoot {
                return bundleContext;
        }
 
+       public void setInstallInLexicographicOrder(
+                       boolean installInAlphabeticalOrder) {
+               this.installInLexicographicOrder = installInAlphabeticalOrder;
+       }
+
+       public boolean isInstallInLexicographicOrder() {
+               return installInLexicographicOrder;
+       }
+
        /** Whether to exclude Subversion directories (true by default) */
        public boolean isExcludeSvn() {
                return excludeSvn;