karaf-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From ioca...@apache.org
Subject svn commit: r1055528 - in /karaf/trunk/shell/dev/src/main: java/org/apache/karaf/shell/dev/Watch.java java/org/apache/karaf/shell/dev/watch/BundleWatcher.java resources/OSGI-INF/blueprint/shell-dev.xml
Date Wed, 05 Jan 2011 17:05:00 GMT
Author: iocanel
Date: Wed Jan  5 17:04:59 2011
New Revision: 1055528

URL: http://svn.apache.org/viewvc?rev=1055528&view=rev
Log:
[KARAF-317] Bundle resolution occurs in each interval, to affect new bundles too. Code cleanup
with the use of blueprint. In each interval the a new configuration object is created.

Modified:
    karaf/trunk/shell/dev/src/main/java/org/apache/karaf/shell/dev/Watch.java
    karaf/trunk/shell/dev/src/main/java/org/apache/karaf/shell/dev/watch/BundleWatcher.java
    karaf/trunk/shell/dev/src/main/resources/OSGI-INF/blueprint/shell-dev.xml

Modified: karaf/trunk/shell/dev/src/main/java/org/apache/karaf/shell/dev/Watch.java
URL: http://svn.apache.org/viewvc/karaf/trunk/shell/dev/src/main/java/org/apache/karaf/shell/dev/Watch.java?rev=1055528&r1=1055527&r2=1055528&view=diff
==============================================================================
--- karaf/trunk/shell/dev/src/main/java/org/apache/karaf/shell/dev/Watch.java (original)
+++ karaf/trunk/shell/dev/src/main/java/org/apache/karaf/shell/dev/Watch.java Wed Jan  5 17:04:59
2011
@@ -24,7 +24,6 @@ import org.apache.karaf.shell.dev.watch.
 import org.osgi.framework.Bundle;
 import org.osgi.framework.Constants;
 
-import java.util.ArrayList;
 import java.util.List;
 
 @Command(scope = "dev", name = "watch", description = "Watch and Update bundles")
@@ -36,6 +35,9 @@ public class Watch extends OsgiCommandSu
     @Option(name = "-i", aliases = {}, description = "Watch interval", required = false,
multiValued = false)
     private long interval;
 
+    @Option(name = "--start", description = "Starts watching the selcted bundles", required
= false, multiValued = false)
+    protected boolean start;
+
     @Option(name = "--stop", description = "Stops watching all bundles", required = false,
multiValued = false)
     protected boolean stop;
 
@@ -45,94 +47,53 @@ public class Watch extends OsgiCommandSu
     @Option(name = "--list", description = "Displays the watch list", required = false, multiValued
= false)
     protected boolean list;
 
+    private BundleWatcher watcher;
 
     @Override
     protected Object doExecute() throws Exception {
-        //Set the interval if exists.
-        if (interval > 0) {
-            BundleWatcher.getInstance().setInterval(interval);
-        }
-
-        if (stop || list) {
-            doExecute(null);
+        if (urls == null && (interval == 0 && !stop && !start &&
!list)) {
+            System.out.println("No option specified. Bundle id/url is required.");
             return null;
-        } else if (urls != null && urls.trim().length() > 0) {
+        }
 
-            List<Bundle> bundleList = new ArrayList<Bundle>();
-            //Check if an id is passed instead of URLs
-            try {
-                Long id = Long.parseLong(urls);
-                Bundle bundle = getBundleContext().getBundle(id);
-                if (bundle != null) {
-                    bundleList.add(bundle);
-                }
-            } catch (NumberFormatException e) {
+        if (interval > 0) { //Set the interval if exists.
+            watcher.setInterval(interval);
+        }
 
-                for (int i = 0; i < getBundleContext().getBundles().length; i++) {
-                    Bundle bundle = getBundleContext().getBundles()[i];
-                    if (wildCardMatch(bundle.getLocation(), urls)) {
-                        bundleList.add(bundle);
+        if (list) { //List the watched bundles.
+            String format = "%-40s %6s %-80s";
+            System.out.println(String.format(format, "URL", "ID", "Bundle Name"));
+            for (String url : watcher.getWatchURLs()) {
+
+                List<Bundle> bundleList = watcher.getBundlesByURL(url);
+                if (bundleList != null && bundleList.size() > 0) {
+                    for (Bundle bundle : bundleList) {
+                        System.out.println(String.format(format, url, bundle.getBundleId(),
(String) bundle.getHeaders().get(Constants.BUNDLE_NAME)));
                     }
+                } else {
+                    System.out.println(String.format(format, url, "", ""));
                 }
             }
-            if (bundleList.size() > 0) {
-                doExecute(bundleList);
-            }
-            return null;
-        } else {
-            return null;
-        }
-    }
-
-    /**
-     * Exectues watch/stop watching the passed bundles.
-     *
-     * @param bundleList
-     */
-    public void doExecute(List<Bundle> bundleList) {
-        BundleWatcher watcher = BundleWatcher.getInstance();
-        if (stop) {
+        } else if (start) {
+            watcher.start();
+        } else if (stop) {
             watcher.stop();
-        } else if (list) {
-            List<Bundle> watchList = watcher.getWatchList();
-            if (watchList != null && watchList.size() > 0) {
-                String format = "%6s %-40s";
-                System.out.println(String.format(format, "ID", "Name"));
-                for (Bundle bundle : watcher.getWatchList()) {
-                    System.out.println(String.format(format, bundle.getBundleId(), (String)
bundle.getHeaders().get(Constants.BUNDLE_NAME)));
-                }
-            } else System.out.println("No bundle is being watched.");
+        } else if (remove) {
+            watcher.remove(urls);
         } else {
-            if (remove) {
-                watcher.remove(bundleList);
-            } else {
-                watcher.add(bundleList);
-            }
+            watcher.start();
+            watcher.add(urls);
         }
-    }
 
+        return null;
+    }
 
-    /**
-     * Matches text using a pattern containing wildchards.
-     *
-     * @param text
-     * @param pattern
-     * @return
-     */
-    public static boolean wildCardMatch(String text, String pattern) {
-        String[] cards = pattern.split("\\*");
-        // Iterate over the cards.
-        for (String card : cards) {
-            int idx = text.indexOf(card);
-            // Card not detected in the text.
-            if (idx == -1) {
-                return false;
-            }
+    public BundleWatcher getWatcher() {
+        return watcher;
+    }
 
-            // Move ahead, towards the right of the text.
-            text = text.substring(idx + card.length());
-        }
-        return true;
+    public void setWatcher(BundleWatcher watcher) {
+        this.watcher = watcher;
     }
 }
 

Modified: karaf/trunk/shell/dev/src/main/java/org/apache/karaf/shell/dev/watch/BundleWatcher.java
URL: http://svn.apache.org/viewvc/karaf/trunk/shell/dev/src/main/java/org/apache/karaf/shell/dev/watch/BundleWatcher.java?rev=1055528&r1=1055527&r2=1055528&view=diff
==============================================================================
--- karaf/trunk/shell/dev/src/main/java/org/apache/karaf/shell/dev/watch/BundleWatcher.java
(original)
+++ karaf/trunk/shell/dev/src/main/java/org/apache/karaf/shell/dev/watch/BundleWatcher.java
Wed Jan  5 17:04:59 2011
@@ -19,6 +19,7 @@ package org.apache.karaf.shell.dev.watch
 
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
+import org.ops4j.pax.url.maven.commons.MavenConfiguration;
 import org.ops4j.pax.url.maven.commons.MavenConfigurationImpl;
 import org.ops4j.pax.url.maven.commons.MavenRepositoryURL;
 import org.ops4j.pax.url.mvn.ServiceConstants;
@@ -28,15 +29,17 @@ import org.osgi.framework.Bundle;
 import org.osgi.framework.BundleContext;
 import org.osgi.framework.BundleException;
 import org.osgi.framework.BundleReference;
-import org.osgi.framework.ServiceReference;
+import org.osgi.framework.Constants;
 import org.osgi.service.cm.Configuration;
 import org.osgi.service.cm.ConfigurationAdmin;
+import org.osgi.service.cm.ConfigurationException;
+import org.osgi.service.cm.ManagedService;
 
 import java.io.File;
+import java.io.FileInputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.net.MalformedURLException;
-import java.net.URL;
 import java.util.ArrayList;
 import java.util.Dictionary;
 import java.util.HashMap;
@@ -50,54 +53,45 @@ public class BundleWatcher implements Ru
 
     private static Log logger = LogFactory.getLog(BundleWatcher.class);
 
-    private static BundleWatcher instance = null;
-
     private ConfigurationAdmin configurationAdmin;
 
-    private Boolean running = true;
+    private Boolean running = false;
     private Long interval = 10000L;
+    private List<String> watchURLs = new ArrayList<String>();
     private Map<Bundle, Long> lastModificationTimes = new HashMap<Bundle, Long>();
 
-    /**
-     * Construcotr
-     */
-    private BundleWatcher() {
-        Thread thread = new Thread(this);
-        thread.start();
-    }
 
     /**
-     * Returns the singleton instance.
-     *
-     * @return
+     * Construcotr
      */
-    public static synchronized BundleWatcher getInstance() {
-        if (instance == null)
-            instance = new BundleWatcher();
-        return instance;
+    public BundleWatcher() {
     }
 
     public void run() {
         if (logger.isDebugEnabled()) {
             logger.debug("Bundle watcher thread started");
         }
-        running = true;
         while (running) {
-            for (Bundle bundle : lastModificationTimes.keySet()) {
-                try {
-                    Long lastModifiedTime = getBundleLastModifiedTime(bundle);
-                    Long oldLastModifiedTime = lastModificationTimes.get(bundle);
-                    if (!lastModifiedTime.equals(oldLastModifiedTime)) {
-                        URL bundleLocation = new URL(bundle.getLocation());
-                        InputStream is = bundleLocation.openStream();
-                        bundle.update(is);
-                        is.close();
-                        lastModificationTimes.put(bundle, lastModifiedTime);
+            for (String bundleURL : watchURLs) {
+                for (Bundle bundle : getBundlesByURL(bundleURL)) {
+                    try {
+                        Long lastModifiedTime = getBundleLastModifiedTime(bundle);
+                        Long oldLastModifiedTime = lastModificationTimes.get(bundle);
+                        if (!lastModifiedTime.equals(oldLastModifiedTime)) {
+                            String externalLocation = getBundleExternalLocation(bundle);
+                            if (externalLocation != null) {
+                                File f = new File(externalLocation);
+                                InputStream is = new FileInputStream(f);
+                                bundle.update(is);
+                                is.close();
+                                lastModificationTimes.put(bundle, lastModifiedTime);
+                            }
+                        }
+                    } catch (IOException ex) {
+                        logger.error("Error watching bundle.", ex);
+                    } catch (BundleException ex) {
+                        logger.error("Error updating bundle.", ex);
                     }
-                } catch (IOException ex) {
-                    logger.error("Error watching bundle.", ex);
-                } catch (BundleException ex) {
-                    logger.error("Error updating bundle.", ex);
                 }
             }
             try {
@@ -112,99 +106,175 @@ public class BundleWatcher implements Ru
         }
     }
 
-
     /**
-     * Adds a Bundle to the watch list.
-     *
-     * @param bundleList
+     * Adds a Bundle URLs to the watch list.
+     * @param urls
      */
-    public void add(List<Bundle> bundleList) {
-        for (Bundle bundle : bundleList) {
+    public void add(String urls) {
+        watchURLs.add(urls);
+        for (Bundle bundle : getBundlesByURL(urls)) {
             lastModificationTimes.put(bundle, getBundleLastModifiedTime(bundle));
         }
     }
 
     /**
-     * Removes a bundle from the watch list.
-     *
-     * @param bundleList
+     * Removes a bundle URLs from the watch list.
+     * @param urls
      */
-    public void remove(List<Bundle> bundleList) {
-        for (Bundle bundle : bundleList) {
+    public void remove(String urls) {
+        watchURLs.remove(urls);
+        for (Bundle bundle : getBundlesByURL(urls)) {
             lastModificationTimes.remove(bundle);
         }
     }
 
     /**
      * Returns the last modification time of the bundle artifact as Long.
-     *
      * @param bundle
      * @return
      */
     private Long getBundleLastModifiedTime(Bundle bundle) {
-        BundleContext bundleContext = null;
-        ServiceReference ref = null;
+        Long lastModificationTime = 0L;
+        String bundleExternalLocation = getBundleExternalLocation(bundle);
+        if (bundleExternalLocation != null) {
+            File bundleFile = new File(bundleExternalLocation);
+            lastModificationTime = bundleFile.lastModified();
+        }
+        return lastModificationTime;
+    }
 
+    /**
+     * Returns the location of the Bundle inside the local maven repository.
+     * @param bundle
+     * @return
+     */
+    public String getBundleExternalLocation(Bundle bundle) {
+        Parser p = null;
+        String bundleExternalLocation = null;
         String localRepository = null;
-        Long lastModificationTime = 0L;
+
+        //Attempt to retrieve local repository location from MavenConfiguration
+        MavenConfiguration configuration = retrieveMavenConfiguration();
+        if (configuration != null) {
+            MavenRepositoryURL localRepositoryURL = configuration.getLocalRepository();
+            if (localRepositoryURL != null) {
+                localRepository = localRepositoryURL.getFile().getAbsolutePath();
+            }
+        }
+
+        //If local repository not found assume default.
+        if (localRepository == null) {
+            localRepository = System.getProperty("user.home") + File.separator + ".m2" +
File.separator + "repository";
+        }
 
         try {
-            bundleContext = ((BundleReference) getClass().getClassLoader()).getBundle().getBundleContext();
-            //Get a reference to the configuration admin.
-            ref = bundleContext.getServiceReference(ConfigurationAdmin.class.getName());
-            configurationAdmin = (ConfigurationAdmin) bundleContext.getService(ref);
+            p = new Parser(bundle.getLocation().substring(4));
+            bundleExternalLocation = localRepository + File.separator + p.getArtifactPath();
+        } catch (MalformedURLException e) {
+            logger.error("Could not parse artifact path for bundle" + bundle.getSymbolicName(),
e);
+        }
+        return bundleExternalLocation;
+    }
 
+
+    public MavenConfiguration retrieveMavenConfiguration() {
+        MavenConfiguration mavenConfiguration=null;
+
+        try {
             Configuration configuration = configurationAdmin.getConfiguration(ServiceConstants.PID);
+            if(configuration != null){
+              Dictionary dictonary = configuration.getProperties();
+              if(dictonary != null) {
+                  DictionaryPropertyResolver resolver = new DictionaryPropertyResolver(dictonary);
+                  mavenConfiguration = new MavenConfigurationImpl(resolver,ServiceConstants.PID);
+              }
+            }
 
-            //Attempt to retrieve local repository location from MavenConfiguration
-            if (configuration != null) {
-                Dictionary dictionary = configuration.getProperties();
-                MavenConfigurationImpl config = new MavenConfigurationImpl(new DictionaryPropertyResolver(dictionary),
ServiceConstants.PID);
-
-                MavenRepositoryURL localRepositoryURL = config.getLocalRepository();
-                if (localRepositoryURL != null) {
-                    localRepository = localRepositoryURL.getFile().getAbsolutePath();
+        } catch (IOException e) {
+            logger.error("Error retrieving maven configuration",e);
+        }
+        return mavenConfiguration;
+    }
+
+    /**
+     * Returns the bundles that match
+     * @param url
+     * @return
+     */
+    public List<Bundle> getBundlesByURL(String url) {
+        BundleContext bundleContext = ((BundleReference) getClass().getClassLoader()).getBundle().getBundleContext();
+        List<Bundle> bundleList = new ArrayList<Bundle>();
+        try {
+            Long id = Long.parseLong(url);
+            Bundle bundle = bundleContext.getBundle(id);
+            if (bundle != null) {
+                bundleList.add(bundle);
+            }
+        } catch (NumberFormatException e) {
+
+            for (int i = 0; i < bundleContext.getBundles().length; i++) {
+                Bundle bundle = bundleContext.getBundles()[i];
+                if (wildCardMatch(bundle.getLocation(), url)) {
+                    bundleList.add(bundle);
                 }
             }
+        }
+        return bundleList;
+    }
 
-            //If local repository not found assume default.
-            if (localRepository == null) {
-                localRepository = System.getProperty("user.home") + File.separator + ".m2"
+ File.separator + "repository";
+    /**
+     * Matches text using a pattern containing wildchards.
+     *
+     * @param text
+     * @param pattern
+     * @return
+     */
+    protected boolean wildCardMatch(String text, String pattern) {
+        String[] cards = pattern.split("\\*");
+        // Iterate over the cards.
+        for (String card : cards) {
+            int idx = text.indexOf(card);
+            // Card not detected in the text.
+            if (idx == -1) {
+                return false;
             }
 
-            Parser p = new Parser(bundle.getLocation().substring(4));
-            p.getArtifactPath();
+            // Move ahead, towards the right of the text.
+            text = text.substring(idx + card.length());
+        }
+        return true;
+    }
 
-            String bundlePath = localRepository + File.separator + p.getArtifactPath();
-            File bundleFile = new File(bundlePath);
-            lastModificationTime = bundleFile.lastModified();
 
-        } catch (MalformedURLException e) {
-            logger.warn("ConfigAdmin service is unavailable.");
-        } catch (IOException e) {
-            logger.warn("ConfigAdmin service is unavailable.");
-        } finally {
-            bundleContext.ungetService(ref);
+    public void start() {
+        if (!running) {
+            Thread thread = new Thread(this);
+            setRunning(true);
+            thread.start();
         }
-        return lastModificationTime;
     }
 
-
     /**
      * Stops the execution of the thread and releases the singleton instance
      */
     public void stop() {
         setRunning(false);
-        this.instance = null;
     }
 
-    /**
-     * Returns the list of bundles that are being watched.
-     *
-     * @return
-     */
-    public List<Bundle> getWatchList() {
-        return new ArrayList(lastModificationTimes.keySet());
+    public ConfigurationAdmin getConfigurationAdmin() {
+        return configurationAdmin;
+    }
+
+    public void setConfigurationAdmin(ConfigurationAdmin configurationAdmin) {
+        this.configurationAdmin = configurationAdmin;
+    }
+
+    public List<String> getWatchURLs() {
+        return watchURLs;
+    }
+
+    public void setWatchURLs(List<String> watchURLs) {
+        this.watchURLs = watchURLs;
     }
 
     public Long getInterval() {

Modified: karaf/trunk/shell/dev/src/main/resources/OSGI-INF/blueprint/shell-dev.xml
URL: http://svn.apache.org/viewvc/karaf/trunk/shell/dev/src/main/resources/OSGI-INF/blueprint/shell-dev.xml?rev=1055528&r1=1055527&r2=1055528&view=diff
==============================================================================
--- karaf/trunk/shell/dev/src/main/resources/OSGI-INF/blueprint/shell-dev.xml (original)
+++ karaf/trunk/shell/dev/src/main/resources/OSGI-INF/blueprint/shell-dev.xml Wed Jan  5 17:04:59
2011
@@ -17,7 +17,9 @@
     limitations under the License.
 
 -->
-<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">
+<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
+           xmlns:cm="http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.0.0"
+           xmlns:ext="http://aries.apache.org/blueprint/xmlns/blueprint-ext/v1.0.0">
 
     <command-bundle xmlns="http://karaf.apache.org/xmlns/shell/v1.0.0">
         <command name="dev/show-tree">
@@ -36,8 +38,17 @@
             <action class="org.apache.karaf.shell.dev.Restart" />
         </command>
         <command name="dev/watch">
-            <action class="org.apache.karaf.shell.dev.Watch" />
+            <action class="org.apache.karaf.shell.dev.Watch" >
+                <property name="watcher" ref="watcher"/>
+            </action>
         </command>
     </command-bundle>
 
+    <!-- Referenace to the Configuration Admin Service -->
+    <reference id="configurationAdmin" interface="org.osgi.service.cm.ConfigurationAdmin"/>
+
+    <bean id="watcher" class="org.apache.karaf.shell.dev.watch.BundleWatcher">
+        <property name="configurationAdmin" ref="configurationAdmin"/>
+    </bean>
+
 </blueprint>



Mime
View raw message