[Git][java-team/felix-gogo-command][upstream] 3 commits: New upstream version 0.16.0

Emmanuel Bourg (@ebourg) gitlab at salsa.debian.org
Fri Nov 20 08:19:32 GMT 2026



Emmanuel Bourg pushed to branch upstream at Debian Java Maintainers / felix-gogo-command


Commits:
330b49b8 by Emmanuel Bourg at 2026-11-19T18:03:07+01:00
New upstream version 0.16.0
- - - - -
29a057d7 by Emmanuel Bourg at 2026-11-19T18:03:07+01:00
New upstream version 1.1.0
- - - - -
c2baf491 by Emmanuel Bourg at 2026-11-19T18:03:08+01:00
New upstream version 1.1.2
- - - - -


12 changed files:

- doc/changelog.txt
- pom.xml
- src/main/java/org/apache/felix/gogo/command/Activator.java
- − src/main/java/org/apache/felix/gogo/command/Base64Encoder.java
- src/main/java/org/apache/felix/gogo/command/Basic.java
- src/main/java/org/apache/felix/gogo/command/Files.java
- src/main/java/org/apache/felix/gogo/command/Inspect.java
- − src/main/java/org/apache/felix/gogo/command/Inspect42.java
- − src/main/java/org/apache/felix/gogo/command/OBR.java
- src/main/java/org/apache/felix/gogo/command/Util.java
- + src/main/java/org/apache/felix/gogo/command/package-info.java
- + src/test/java/org/apache/felix/gogo/command/UtilTest.java


Changes:

=====================================
doc/changelog.txt
=====================================
@@ -1,4 +1,48 @@
-Changes from 0.10.0 to 0.12.0
+Changes from 1.1.0 to 1.1.2
+---------------------------
+Improvement
+    [FELIX-6038] - pull Java 7 support back in for gogo runtime,shell and console
+
+Changes from 1.0.2 to 1.1.0
+---------------------------
+Bug
+    [FELIX-5143] - Gogo Command bundle should not include org.osgi.service.log classes
+    [FELIX-5958] - gogo command exports org.osgi.service.log
+
+New Feature
+    [FELIX-5835] - Upgrade to JDK 8
+    [FELIX-5836] - Upgrade to OSGi r6
+
+Improvement
+    [FELIX-5969] - remove transitive dependencies from gogo command
+    [FELIX-5970] - Add requirement & capabilities model so gogo can be resolved
+    [FELIX-5999] - cleanup compiler warnings
+    [FELIX-6002] - Remove legacy code in Gogo Command
+    [FELIX-6003] - Add some resolver checks to make sure @RequireGogo annotation works for both jline and shell
+    [FELIX-6007] - create a gogo bom
+
+Changes from 1.0.0 to 1.0.2
+---------------------------
+** Bug
+    * [FELIX-5392] - Gogo-command has mandatory dependency on bundlerepository
+
+Changes from 0.16.0 to 1.0.0
+----------------------------
+** Task
+    * [FELIX-5378] - [gogo] Upgrade packages and bundle to 1.0.0
+
+Changes from 0.14.0 to 0.16.0
+-----------------------------
+** Improvement
+    * FELIX-5021 [GOGO] Use system bundle to find bundles
+    * FELIX-5009 Relative URIs would be nice for install and update
+    * FELIX-5008 gogo usage messages could be less confusing
+    * FELIX-3499 felix:cd command works only with relative paths
+
+** Bug
+    * FELIX-4969 cd refuses to leave initial directory
+
+Changes from 0.12.0 to 0.14.0
 -----------------------------
 
 * Fix a NPE with the obr:info command


=====================================
pom.xml
=====================================
@@ -1,98 +1,95 @@
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-
-  <!--
-   Licensed to the Apache Software Foundation (ASF) under one or more
-   contributor license agreements.  See the NOTICE file distributed with
-   this work for additional information regarding copyright ownership.
-   The ASF licenses this file to You under the Apache License, Version 2.0
-   (the "License"); you may not use this file except in compliance with
-   the License.  You may obtain a copy of the License at
-
-     http://www.apache.org/licenses/LICENSE-2.0
-
-   Unless required by applicable law or agreed to in writing, software
-   distributed under the License is distributed on an "AS IS" BASIS,
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-   See the License for the specific language governing permissions and
-   limitations under the License.
-  -->
-
-  <modelVersion>4.0.0</modelVersion>
+<?xml version="1.0"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements.  See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership.  The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License.  You may obtain a copy of the License at
 
-  <parent>
-    <groupId>org.apache.felix</groupId>
-    <artifactId>gogo-parent</artifactId>
-    <version>0.6.0</version>
-    <relativePath>../gogo-parent/pom.xml</relativePath>
-  </parent>
+    http://www.apache.org/licenses/LICENSE-2.0
 
-  <artifactId>org.apache.felix.gogo.command</artifactId>
-  <packaging>bundle</packaging>
-  <version>0.14.0</version>
-  <name>Apache Felix Gogo Command</name>
-
-  <description>
-    Provides basic shell commands for Gogo.
-  </description>
-
-  <dependencies>
-    <dependency>
-      <groupId>org.osgi</groupId>
-      <artifactId>org.osgi.core</artifactId>
-      <version>4.3.1</version>
-    </dependency>
-    <dependency>
-      <groupId>org.osgi</groupId>
-      <artifactId>org.osgi.compendium</artifactId>
-      <version>4.0.0</version>
-    </dependency>
-    <dependency>
-      <groupId>org.apache.felix</groupId>
-      <artifactId>org.apache.felix.gogo.runtime</artifactId>
-      <version>0.10.0</version>
-    </dependency>
-    <dependency>
-      <groupId>org.apache.felix</groupId>
-      <artifactId>org.apache.felix.bundlerepository</artifactId>
-      <version>1.6.0</version>
-    </dependency>
-  </dependencies>
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied.  See the License for the
+ specific language governing permissions and limitations
+ under the License.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 
-  <build>
-    <plugins>
-      <plugin>
-        <groupId>org.apache.maven.plugins</groupId>
-        <artifactId>maven-compiler-plugin</artifactId>
-        <configuration>
-          <target>1.5</target>
-          <source>1.5</source>
-        </configuration>
-      </plugin>
+    <modelVersion>4.0.0</modelVersion>
 
-      <plugin>
+    <parent>
         <groupId>org.apache.felix</groupId>
-        <artifactId>maven-bundle-plugin</artifactId>
-        <version>2.3.5</version>
+        <artifactId>gogo-parent</artifactId>
+        <version>6</version>
+        <relativePath>../gogo-parent/pom.xml</relativePath>
+    </parent>
 
-        <extensions>true</extensions>
-        <configuration>
-          <instructions>
-            <Export-Package>org.osgi.service.log</Export-Package>
-            <Bundle-SymbolicName>${artifactId}</Bundle-SymbolicName>
-            <Private-Package>${pom.artifactId}</Private-Package>
-            <Bundle-Activator>${pom.artifactId}.Activator</Bundle-Activator>
-            <Import-Package>org.apache.felix.service.command; status="provisional", org.osgi.framework; version="[1.5,2.0)", org.osgi.framework.wiring; resolution:=optional, *</Import-Package>
-            <Include-Resource>{maven-resources},META-INF/LICENSE=LICENSE,META-INF/NOTICE=NOTICE,META-INF/DEPENDENCIES=DEPENDENCIES</Include-Resource>
-            <DynamicImport-Package>org.apache.felix.bundlerepository, org.apache.felix.bundlerepository.*</DynamicImport-Package>
-          </instructions>
-        </configuration>
-      </plugin>
-    </plugins>
-  </build>
+    <artifactId>org.apache.felix.gogo.command</artifactId>
+    <packaging>bundle</packaging>
+    <version>1.1.2</version>
+    <name>Apache Felix Gogo Command</name>
 
-  <scm>
-    <connection>scm:svn:https://svn.apache.org/repos/asf/felix/releases/org.apache.felix.gogo.command-0.14.0</connection>
-    <developerConnection>scm:svn:https://svn.apache.org/repos/asf/felix/releases/org.apache.felix.gogo.command-0.14.0</developerConnection>
-    <url>scm:svn:https://svn.apache.org/repos/asf/felix/releases/org.apache.felix.gogo.command-0.14.0</url>
+    <description>
+        Provides basic shell commands for Gogo.
+    </description>
+    <url>http://felix.apache.org/</url>
+    <scm>
+        <connection>scm:git:https://github.com/apache/felix-dev.git</connection>
+        <developerConnection>scm:git:https://github.com/apache/felix-dev.git</developerConnection>
+        <url>https://gitbox.apache.org/repos/asf?p=felix-dev.git</url>
+      <tag>org.apache.felix.gogo.command-1.1.2</tag>
   </scm>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.osgi</groupId>
+            <artifactId>org.osgi.service.log</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.osgi</groupId>
+            <artifactId>osgi.annotation</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.osgi</groupId>
+            <artifactId>osgi.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.felix</groupId>
+            <artifactId>org.apache.felix.gogo.runtime</artifactId>
+            <version>1.1.4</version>
+        </dependency>
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.mockito</groupId>
+            <artifactId>mockito-core</artifactId>
+        </dependency>
+    </dependencies>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-bundle-plugin</artifactId>
+                <configuration>
+                    <instructions>
+                        <Import-Package>
+                            !org.osgi.service.log,
+                            org.apache.felix.service.command,
+                            *
+                        </Import-Package>
+                        <DynamicImport-Package>
+                            org.osgi.service.log
+                        </DynamicImport-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
 </project>


=====================================
src/main/java/org/apache/felix/gogo/command/Activator.java
=====================================
@@ -19,17 +19,18 @@
 package org.apache.felix.gogo.command;
 
 import java.util.Hashtable;
+
+import org.osgi.annotation.bundle.Header;
 import org.osgi.framework.BundleActivator;
 import org.osgi.framework.BundleContext;
-import org.osgi.util.tracker.ServiceTracker;
+import org.osgi.framework.Constants;
 
+ at Header(name = Constants.BUNDLE_ACTIVATOR, value = "${@class}")
 public class Activator implements BundleActivator
 {
-    private volatile ServiceTracker m_tracker = null;
-
-    public void start(BundleContext bc) throws Exception
-    {
-        Hashtable props = new Hashtable();
+    public void start(BundleContext bc) {
+        BundleContext systemBundleContext = bc.getBundle(0).getBundleContext();
+        Hashtable<String, Object> props = new Hashtable<>();
         props.put("osgi.command.scope", "felix");
         props.put("osgi.command.function", new String[] {
             "bundlelevel", "frameworklevel", "headers",
@@ -37,41 +38,19 @@ public class Activator implements BundleActivator
             "resolve", "start", "stop", "uninstall", "update",
             "which" });
         bc.registerService(
-            Basic.class.getName(), new Basic(bc), props);
+            Basic.class.getName(), new Basic(systemBundleContext), props);
 
-        // Register "inspect" command for R4.3 or R4.2 depending
-        // on the underlying framework.
         props.put("osgi.command.scope", "felix");
         props.put("osgi.command.function", new String[] { "inspect" });
-        try
-        {
-            getClass().getClassLoader().loadClass("org.osgi.framework.wiring.BundleWiring");
-            bc.registerService(
-                Inspect.class.getName(), new Inspect(bc), props);
-        }
-        catch (Throwable th)
-        {
-            bc.registerService(
-                Inspect42.class.getName(), new Inspect42(bc), props);
-        }
+        bc.registerService(
+            Inspect.class.getName(), new Inspect(systemBundleContext), props);
 
         props.put("osgi.command.scope", "felix");
         props.put("osgi.command.function", new String[] { "cd", "ls" });
         bc.registerService(
             Files.class.getName(), new Files(bc), props);
-
-        m_tracker = new ServiceTracker(
-            bc, "org.apache.felix.bundlerepository.RepositoryAdmin", null);
-        m_tracker.open();
-        props.put("osgi.command.scope", "obr");
-        props.put("osgi.command.function", new String[] {
-            "deploy", "info", "javadoc", "list", "repos", "source" });
-        bc.registerService(
-            OBR.class.getName(), new OBR(bc, m_tracker), props);
     }
 
-    public void stop(BundleContext bc) throws Exception
-    {
-        m_tracker.close();
+    public void stop(BundleContext bc) {
     }
 }
\ No newline at end of file


=====================================
src/main/java/org/apache/felix/gogo/command/Base64Encoder.java deleted
=====================================
@@ -1,131 +0,0 @@
-/* 
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.felix.gogo.command;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-public class Base64Encoder
-{
-    private static final byte encTab[] = { 0x41, 0x42, 0x43, 0x44, 0x45, 0x46,
-        0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52,
-        0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x61, 0x62, 0x63, 0x64,
-        0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70,
-        0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x30, 0x31,
-        0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x2b, 0x2f };
-
-    public static String base64Encode(String s) throws IOException
-    {
-        return encode(s.getBytes(), 0);
-    }
-
-    /**
-     * Encode a raw byte array to a Base64 String.
-     * 
-     * @param in Byte array to encode.
-     * @param len Length of Base64 lines. 0 means no line breaks.
-    **/
-    public static String encode(byte[] in, int len) throws IOException
-    {
-        ByteArrayOutputStream baos = null;
-        ByteArrayInputStream bais = null;
-        try
-        {
-            baos = new ByteArrayOutputStream();
-            bais = new ByteArrayInputStream(in);
-            encode(bais, baos, len);
-            // ASCII byte array to String
-            return (new String(baos.toByteArray()));
-        }
-        finally
-        {
-            if (baos != null)
-            {
-                baos.close();
-            }
-            if (bais != null)
-            {
-                bais.close();
-            }
-        }
-    }
-
-    public static void encode(InputStream in, OutputStream out, int len)
-        throws IOException
-    {
-
-        // Check that length is a multiple of 4 bytes
-        if (len % 4 != 0)
-        {
-            throw new IllegalArgumentException("Length must be a multiple of 4");
-        }
-
-        // Read input stream until end of file
-        int bits = 0;
-        int nbits = 0;
-        int nbytes = 0;
-        int b;
-
-        while ((b = in.read()) != -1)
-        {
-            bits = (bits << 8) | b;
-            nbits += 8;
-            while (nbits >= 6)
-            {
-                nbits -= 6;
-                out.write(encTab[0x3f & (bits >> nbits)]);
-                nbytes++;
-                // New line
-                if (len != 0 && nbytes >= len)
-                {
-                    out.write(0x0d);
-                    out.write(0x0a);
-                    nbytes -= len;
-                }
-            }
-        }
-
-        switch (nbits)
-        {
-            case 2:
-                out.write(encTab[0x3f & (bits << 4)]);
-                out.write(0x3d); // 0x3d = '='
-                out.write(0x3d);
-                break;
-            case 4:
-                out.write(encTab[0x3f & (bits << 2)]);
-                out.write(0x3d);
-                break;
-        }
-
-        if (len != 0)
-        {
-            if (nbytes != 0)
-            {
-                out.write(0x0d);
-                out.write(0x0a);
-            }
-            out.write(0x0d);
-            out.write(0x0a);
-        }
-    }
-}
\ No newline at end of file


=====================================
src/main/java/org/apache/felix/gogo/command/Basic.java
=====================================
@@ -32,11 +32,14 @@ import java.util.Arrays;
 import java.util.Date;
 import java.util.Dictionary;
 import java.util.Enumeration;
+import java.util.Formatter;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
 import java.util.TreeMap;
+
+import org.apache.felix.service.command.CommandSession;
 import org.apache.felix.service.command.Descriptor;
 import org.apache.felix.service.command.Parameter;
 import org.osgi.framework.Bundle;
@@ -46,47 +49,32 @@ import org.osgi.framework.BundleReference;
 import org.osgi.framework.Constants;
 import org.osgi.framework.InvalidSyntaxException;
 import org.osgi.framework.ServiceReference;
+import org.osgi.framework.startlevel.BundleStartLevel;
+import org.osgi.framework.startlevel.FrameworkStartLevel;
+import org.osgi.framework.wiring.FrameworkWiring;
 import org.osgi.service.log.LogEntry;
 import org.osgi.service.log.LogReaderService;
 import org.osgi.service.log.LogService;
-import org.osgi.service.packageadmin.PackageAdmin;
-import org.osgi.service.startlevel.StartLevel;
 
 public class Basic
 {
     private final BundleContext m_bc;
+    private final Bundle m_b0;
 
     public Basic(BundleContext bc)
     {
         m_bc = bc;
+        m_b0 = m_bc.getBundle(0);
     }
 
     @Descriptor("query bundle start level")
-    public void bundlelevel(@Descriptor("bundle to query") Bundle bundle)
+    public String bundlelevel(@Descriptor("bundle to query") Bundle bundle)
     {
-        // Keep track of service references.
-        List<ServiceReference> refs = new ArrayList();
-
-        // Get start level service.
-        StartLevel sl = Util.getService(m_bc, StartLevel.class, refs);
-        if (sl == null)
-        {
-            System.out.println("Start Level service is unavailable.");
-        }
-        // Get the bundle start level.
-        else
-        {
-            if (bundle != null)
-            {
-                System.out.println(bundle + " is level " + sl.getBundleStartLevel(bundle));
-            }
-        }
-
-        Util.ungetServices(m_bc, refs);
+        return bundle + " is level " + bundle.adapt(BundleStartLevel.class).getStartLevel();
     }
 
     @Descriptor("set bundle start level or initial bundle start level")
-    public void bundlelevel(
+    public String bundlelevel(
         @Descriptor("set the bundle's start level") @Parameter(names = { "-s",
                 "--setlevel" }, presentValue = "true", absentValue = "false") boolean set,
         @Descriptor("set the initial bundle start level") @Parameter(names = { "-i",
@@ -94,37 +82,29 @@ public class Basic
         @Descriptor("target level") int level,
         @Descriptor("target identifiers") Bundle[] bundles)
     {
-        // Keep track of service references.
-        List<ServiceReference> refs = new ArrayList();
 
-        // Get start level service.
-        StartLevel sl = Util.getService(m_bc, StartLevel.class, refs);
-        if (sl == null)
+        if (set && initial)
         {
-            System.out.println("Start Level service is unavailable.");
-        }
-        else if (set && initial)
-        {
-            System.out.println("Cannot specify '-s' and '-i' at the same time.");
+            return "Cannot specify '-s' and '-i' at the same time.";
         }
         else if (!set && !initial)
         {
-            System.out.println("Must specify either '-s' or '-i'.");
+            return "Must specify either '-s' or '-i'.";
         }
         else if (level <= 0)
         {
-            System.out.println("Specified start level must be greater than zero.");
+            return "Specified start level must be greater than zero.";
         }
         // Set the initial bundle start level.
         else if (initial)
         {
             if ((bundles != null) && (bundles.length == 0))
             {
-                sl.setInitialBundleStartLevel(level);
+                m_b0.adapt(FrameworkStartLevel.class).setInitialBundleStartLevel(level);
             }
             else
             {
-                System.out.println("Cannot specify bundles when setting initial start level.");
+                return "Cannot specify bundles when setting initial start level.";
             }
         }
         // Set the bundle start level.
@@ -134,83 +114,70 @@ public class Basic
             {
                 for (Bundle bundle : bundles)
                 {
-                    sl.setBundleStartLevel(bundle, level);
+                    bundle.adapt(BundleStartLevel.class).setStartLevel(level);
                 }
             }
             else
             {
-                System.out.println("Must specify target bundles.");
+                return "Must specify target bundles.";
             }
         }
-
-        Util.ungetServices(m_bc, refs);
+        return null;
     }
 
     @Descriptor("query framework active start level")
-    public void frameworklevel()
+    public String frameworklevel()
     {
-        // Keep track of service references.
-        List<ServiceReference> refs = new ArrayList();
-
-        // Get start level service.
-        StartLevel sl = Util.getService(m_bc, StartLevel.class, refs);
-        if (sl == null)
-        {
-            System.out.println("Start Level service is unavailable.");
-        }
-        System.out.println("Level is " + sl.getStartLevel());
-        Util.ungetServices(m_bc, refs);
+        return "Level is " + m_b0.adapt(FrameworkStartLevel.class).getStartLevel();
     }
 
     @Descriptor("set framework active start level")
     public void frameworklevel(@Descriptor("target start level") int level)
     {
-        // Keep track of service references.
-        List<ServiceReference> refs = new ArrayList();
-
-        // Get start level service.
-        StartLevel sl = Util.getService(m_bc, StartLevel.class, refs);
-        if (sl == null)
-        {
-            System.out.println("Start Level service is unavailable.");
-        }
-        sl.setStartLevel(level);
-        Util.ungetServices(m_bc, refs);
+        m_b0.adapt(FrameworkStartLevel.class).setStartLevel(level);
     }
 
     @Descriptor("display bundle headers")
-    public void headers(@Descriptor("target bundles") Bundle[] bundles)
+    public String headers(@Descriptor("target bundles") Bundle[] bundles)
     {
-        bundles = ((bundles == null) || (bundles.length == 0)) ? m_bc.getBundles()
-            : bundles;
-        for (Bundle bundle : bundles)
-        {
-            String title = Util.getBundleName(bundle);
-            System.out.println("\n" + title);
-            System.out.println(Util.getUnderlineString(title.length()));
-            Dictionary dict = bundle.getHeaders();
-            Enumeration keys = dict.keys();
-            while (keys.hasMoreElements())
+        try (Formatter f = new Formatter()) {
+            bundles = ((bundles == null) || (bundles.length == 0)) ? m_bc.getBundles()
+                : bundles;
+            String prefix = "";
+            for (Bundle bundle : bundles)
             {
-                Object k = (String) keys.nextElement();
-                Object v = dict.get(k);
-                System.out.println(k + " = " + Util.getValueString(v));
+                String title = Util.getBundleName(bundle);
+                f.format("%s%s%n", prefix, title);
+                f.format("%s%n", Util.getUnderlineString(title.length()));
+                Dictionary<String, String> dict = bundle.getHeaders();
+                Enumeration<String> keys = dict.keys();
+                while (keys.hasMoreElements())
+                {
+                    String k = keys.nextElement();
+                    String v = dict.get(k);
+                    f.format("%s = %s%n", k, v);
+                }
+                prefix = "\n";
             }
+            return f.toString();
         }
     }
 
     @Descriptor("displays available commands")
-    public void help()
+    public String help()
     {
-        Map<String, List<Method>> commands = getCommands();
-        for (String name : commands.keySet())
-        {
-            System.out.println(name);
+        try (Formatter f = new Formatter()) {
+            Map<String, List<Method>> commands = getCommands();
+            for (String name : commands.keySet())
+            {
+                f.format("%s%n", name);
+            }
+            return f.toString();
         }
     }
 
     @Descriptor("displays information about a specific command")
-    public void help(@Descriptor("target command") String name)
+    public String help(@Descriptor("target command") String name)
     {
         Map<String, List<Method>> commands = getCommands();
 
@@ -238,32 +205,42 @@ public class Basic
             methods = commands.get(name);
         }
 
-        if ((methods != null) && (methods.size() > 0))
+        if ((methods == null) || (methods.size() <= 0))
         {
+            return "No methods found matching: " + name;
+        }
+
+        try (Formatter f = new Formatter()) {
+            String prefix = "";
             for (Method m : methods)
             {
                 Descriptor d = m.getAnnotation(Descriptor.class);
                 if (d == null)
                 {
-                    System.out.println("\n" + m.getName());
+                    f.format("%s%s%n", prefix, m.getName());
                 }
                 else
                 {
-                    System.out.println("\n" + m.getName() + " - " + d.value());
+                    f.format("%s%s - %s%n", prefix, m.getName(), d.value());
                 }
 
-                System.out.println("   scope: " + name.substring(0, name.indexOf(':')));
+                f.format("   scope: %s%n", name.substring(0, name.indexOf(':')));
 
                 // Get flags and options.
-                Class[] paramTypes = m.getParameterTypes();
-                Map<String, Parameter> flags = new TreeMap();
-                Map<String, String> flagDescs = new TreeMap();
-                Map<String, Parameter> options = new TreeMap();
-                Map<String, String> optionDescs = new TreeMap();
-                List<String> params = new ArrayList();
+                Class<?>[] paramTypes = m.getParameterTypes();
+                Map<String, Parameter> flags = new TreeMap<>();
+                Map<String, String> flagDescs = new TreeMap<>();
+                Map<String, Parameter> options = new TreeMap<>();
+                Map<String, String> optionDescs = new TreeMap<>();
+                List<String> params = new ArrayList<>();
                 Annotation[][] anns = m.getParameterAnnotations();
                 for (int paramIdx = 0; paramIdx < anns.length; paramIdx++)
                 {
+                    Class<?> paramType = m.getParameterTypes()[paramIdx];
+                    if (paramType == CommandSession.class) {
+                        /* Do not bother the user with a CommandSession. */
+                        continue;
+                    }
                     Parameter p = findAnnotation(anns[paramIdx], Parameter.class);
                     d = findAnnotation(anns[paramIdx], Descriptor.class);
                     if (p != null)
@@ -300,46 +277,47 @@ public class Basic
                 // Print flags and options.
                 if (flags.size() > 0)
                 {
-                    System.out.println("   flags:");
+                    f.format("   flags:%n");
                     for (Entry<String, Parameter> entry : flags.entrySet())
                     {
                         // Print all aliases.
                         String[] names = entry.getValue().names();
-                        System.out.print("      " + names[0]);
+                        f.format("      %s", names[0]);
                         for (int aliasIdx = 1; aliasIdx < names.length; aliasIdx++)
                         {
-                            System.out.print(", " + names[aliasIdx]);
+                            f.format(", %s", names[aliasIdx]);
                         }
-                        System.out.println("   " + flagDescs.get(entry.getKey()));
+                        f.format("   %s%n", flagDescs.get(entry.getKey()));
                     }
                 }
                 if (options.size() > 0)
                 {
-                    System.out.println("   options:");
+                    f.format("   options:%n");
                     for (Entry<String, Parameter> entry : options.entrySet())
                     {
                         // Print all aliases.
                         String[] names = entry.getValue().names();
-                        System.out.print("      " + names[0]);
+                        f.format("      %s", names[0]);
                         for (int aliasIdx = 1; aliasIdx < names.length; aliasIdx++)
                         {
-                            System.out.print(", " + names[aliasIdx]);
+                            f.format(", %s", names[aliasIdx]);
                         }
-                        System.out.println("   "
-                            + optionDescs.get(entry.getKey())
-                            + ((entry.getValue().absentValue() == null) ? ""
-                                : " [optional]"));
+                        f.format("   %s%s%n",
+                            optionDescs.get(entry.getKey()),
+                            ((entry.getValue().absentValue() == null) ? "" : " [optional]"));
                     }
                 }
                 if (params.size() > 0)
                 {
-                    System.out.println("   parameters:");
+                    f.format("   parameters:%n");
                     for (Iterator<String> it = params.iterator(); it.hasNext();)
                     {
-                        System.out.println("      " + it.next() + "   " + it.next());
+                        f.format("      %s   %s%n", it.next(), it.next());
                     }
                 }
+                prefix = "\n";
             }
+            return f.toString();
         }
     }
 
@@ -358,7 +336,7 @@ public class Basic
 
     private Map<String, List<Method>> getCommands()
     {
-        ServiceReference[] refs = null;
+        ServiceReference<?>[] refs = null;
         try
         {
             refs = m_bc.getAllServiceReferences(null, "(osgi.command.scope=*)");
@@ -368,9 +346,9 @@ public class Basic
             // This should never happen.
         }
 
-        Map<String, List<Method>> commands = new TreeMap();
+        Map<String, List<Method>> commands = new TreeMap<>();
 
-        for (ServiceReference ref : refs)
+        for (ServiceReference<?> ref : refs)
         {
             Object svc = m_bc.getService(ref);
             if (svc != null)
@@ -382,7 +360,7 @@ public class Basic
 
                 for (String func : funcs)
                 {
-                    commands.put(scope + ":" + func, new ArrayList());
+                    commands.put(scope + ":" + func, new ArrayList<Method>());
                 }
 
                 if (!commands.isEmpty())
@@ -415,83 +393,84 @@ public class Basic
     }
 
     @Descriptor("install bundle using URLs")
-    public void install(@Descriptor("target URLs") String[] urls)
+    public String install(@Descriptor("command session")CommandSession session,
+                        @Descriptor("target URLs") String[] urls) throws IOException
     {
-        StringBuffer sb = new StringBuffer();
+        try (Formatter f = new Formatter()) {
 
-        for (String url : urls)
-        {
-            String location = url.trim();
-            Bundle bundle = null;
-            try
-            {
-                bundle = m_bc.installBundle(location, null);
-            }
-            catch (IllegalStateException ex)
-            {
-                System.err.println(ex.toString());
-            }
-            catch (BundleException ex)
+            StringBuilder sb = new StringBuilder();
+
+            for (String url : urls)
             {
-                if (ex.getNestedException() != null)
+                String location = Util.resolveUri(session, url.trim());
+                Bundle bundle = null;
+                try
                 {
-                    System.err.println(ex.getNestedException().toString());
+                    bundle = m_bc.installBundle(location, null);
                 }
-                else
+                catch (IllegalStateException ex)
+                {
+                    f.format("%s%n", ex.toString());
+                }
+                catch (BundleException ex)
+                {
+                    if (ex.getNestedException() != null)
+                    {
+                        f.format("%s%n", ex.getNestedException().toString());
+                    }
+                    else
+                    {
+                        f.format("%s%n", ex.toString());
+                    }
+                }
+                catch (Exception ex)
+                {
+                    f.format("%s%n", ex.toString());
+                }
+                if (bundle != null)
                 {
-                    System.err.println(ex.toString());
+                    if (sb.length() > 0)
+                    {
+                        sb.append(", ");
+                    }
+                    sb.append(bundle.getBundleId());
                 }
             }
-            catch (Exception ex)
+            if (sb.toString().indexOf(',') > 0)
             {
-                System.err.println(ex.toString());
+                return "Bundle IDs: " + sb.toString();
             }
-            if (bundle != null)
+            else if (sb.length() > 0)
             {
-                if (sb.length() > 0)
-                {
-                    sb.append(", ");
-                }
-                sb.append(bundle.getBundleId());
+                return "Bundle ID: " + sb.toString();
             }
-        }
-        if (sb.toString().indexOf(',') > 0)
-        {
-            System.out.println("Bundle IDs: " + sb.toString());
-        }
-        else if (sb.length() > 0)
-        {
-            System.out.println("Bundle ID: " + sb.toString());
+            return f.toString();
         }
     }
 
     @Descriptor("list all installed bundles")
-    public void lb(
+    public String lb(
         @Descriptor("show location") @Parameter(names = { "-l", "--location" }, presentValue = "true", absentValue = "false") boolean showLoc,
         @Descriptor("show symbolic name") @Parameter(names = { "-s", "--symbolicname" }, presentValue = "true", absentValue = "false") boolean showSymbolic,
         @Descriptor("show update location") @Parameter(names = { "-u", "--updatelocation" }, presentValue = "true", absentValue = "false") boolean showUpdate)
     {
-        lb(showLoc, showSymbolic, showUpdate, null);
+        return lb(showLoc, showSymbolic, showUpdate, null);
     }
 
     @Descriptor("list installed bundles matching a substring")
-    public void lb(
+    public String lb(
         @Descriptor("show location") @Parameter(names = { "-l", "--location" }, presentValue = "true", absentValue = "false") boolean showLoc,
         @Descriptor("show symbolic name") @Parameter(names = { "-s", "--symbolicname" }, presentValue = "true", absentValue = "false") boolean showSymbolic,
         @Descriptor("show update location") @Parameter(names = { "-u", "--updatelocation" }, presentValue = "true", absentValue = "false") boolean showUpdate,
         @Descriptor("subtring matched against name or symbolic name") String pattern)
     {
-        // Keep track of service references.
-        List<ServiceReference> refs = new ArrayList();
-
-        // Get start level service.
-        StartLevel sl = Util.getService(m_bc, StartLevel.class, refs);
-        if (sl == null)
-        {
-            System.out.println("Start Level service is unavailable.");
+        if ((showLoc && showSymbolic && showUpdate) ||
+            (showLoc && showSymbolic) ||
+            (showSymbolic && showUpdate) ||
+            (showLoc && showUpdate)) {
+            return "Only one of -l, -s, -u should be used.";
         }
-
-        List<Bundle> found = new ArrayList();
+        List<Bundle> found = new ArrayList<>();
 
         if (pattern == null)
         {
@@ -500,14 +479,10 @@ public class Basic
         else
         {
             Bundle[] bundles = m_bc.getBundles();
-
-            for (int i = 0; i < bundles.length; i++)
-            {
-                Bundle bundle = bundles[i];
-                String name = (String) bundle.getHeaders().get(Constants.BUNDLE_NAME);
+            for (Bundle bundle : bundles) {
+                String name = bundle.getHeaders().get(Constants.BUNDLE_NAME);
                 if (matchBundleName(bundle.getSymbolicName(), pattern)
-                    || matchBundleName(name, pattern))
-                {
+                        || matchBundleName(name, pattern)) {
                     found.add(bundle);
                 }
             }
@@ -515,15 +490,16 @@ public class Basic
 
         if (found.size() > 0)
         {
-            printBundleList((Bundle[]) found.toArray(new Bundle[found.size()]), sl,
-                showLoc, showSymbolic, showUpdate);
+            try (Formatter f = new Formatter()) {
+                printBundleList(found.toArray(new Bundle[found.size()]),
+                    showLoc, showSymbolic, showUpdate, m_b0, f);
+                return f.toString();
+            }
         }
         else
         {
-            System.out.println("No matching bundles found");
+            return "No matching bundles found.";
         }
-
-        Util.ungetServices(m_bc, refs);
     }
 
     private boolean matchBundleName(String name, String pattern)
@@ -532,51 +508,64 @@ public class Basic
     }
 
     @Descriptor("display all matching log entries")
-    public void log(
+    public String log(
         @Descriptor("minimum log level [ debug | info | warn | error ]") String logLevel)
     {
-        log(-1, logLevel);
+        return log(-1, logLevel);
     }
 
     @Descriptor("display some matching log entries")
-    public void log(@Descriptor("maximum number of entries") int maxEntries,
+    public String log(@Descriptor("maximum number of entries") int maxEntries,
         @Descriptor("minimum log level [ debug | info | warn | error ]") String logLevel)
     {
         // Keep track of service references.
-        List<ServiceReference> refs = new ArrayList();
+        List<ServiceReference<?>> refs = new ArrayList<>();
 
         // Get start level service.
-        LogReaderService lrs = Util.getService(m_bc, LogReaderService.class, refs);
-        if (lrs == null)
-        {
-            System.out.println("Log reader service is unavailable.");
-        }
-        else
-        {
-            Enumeration entries = lrs.getLog();
+        try {
+            LogReaderService lrs = Util.getService(m_bc, LogReaderService.class, refs);
+            if (lrs == null)
+            {
+                return "Log reader service is unavailable.";
+            }
+            else
+            {
+                try (Formatter f = new Formatter()) {
+                    @SuppressWarnings("unchecked")
+                    Enumeration<LogEntry> entries = lrs.getLog();
+                    List<LogEntry> select = new ArrayList<>();
 
-            int minLevel = logLevelAsInt(logLevel);
+                    int minLevel = logLevelAsInt(logLevel);
 
-            int index = 0;
-            while (entries.hasMoreElements() && (maxEntries < 0 || index < maxEntries))
-            {
-                LogEntry entry = (LogEntry) entries.nextElement();
-                if (entry.getLevel() <= minLevel)
-                {
-                    display(entry);
-                    index++;
+                    int index = 0;
+                    while (entries.hasMoreElements() && (maxEntries < 0 || index < maxEntries))
+                    {
+                        LogEntry entry = entries.nextElement();
+                        if (entry.getLevel() <= minLevel)
+                        {
+                            select.add(0, entry);
+                            index++;
+                        }
+                    }
+
+                    for (LogEntry e : select) {
+                        display(e,f);
+                    }
+                    Util.ungetServices(m_bc, refs);
+                    return f.toString();
                 }
             }
-
-            Util.ungetServices(m_bc, refs);
+        }
+        catch (NoClassDefFoundError ncdfe) {
+            return "Log reader service is unavailable.";
         }
     }
 
-    private void display(LogEntry entry)
+    private void display(LogEntry entry, Formatter f)
     {
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
 
-        StringBuffer buffer = new StringBuffer();
+        StringBuilder buffer = new StringBuilder();
         buffer.append(sdf.format(new Date(entry.getTime()))).append(" ");
         buffer.append(logLevelAsString(entry.getLevel())).append(" - ");
         buffer.append("Bundle: ").append(entry.getBundle().getSymbolicName());
@@ -595,7 +584,7 @@ public class Basic
             buffer.append(writer.toString());
         }
 
-        System.out.println(buffer.toString());
+        f.format("%s%n", buffer.toString());
     }
 
     private static int logLevelAsInt(String logLevel)
@@ -639,55 +628,31 @@ public class Basic
             bundles = null;
         }
 
-        // Keep track of service references.
-        List<ServiceReference> refs = new ArrayList();
-
-        // Get package admin service.
-        PackageAdmin pa = Util.getService(m_bc, PackageAdmin.class, refs);
-        if (pa == null)
-        {
-            System.out.println("Package Admin service is unavailable.");
-        }
-
-        pa.refreshPackages((bundles == null) ? null : bundles);
-
-        Util.ungetServices(m_bc, refs);
+        m_b0.adapt(FrameworkWiring.class).refreshBundles(Arrays.asList(bundles));
     }
 
     @Descriptor("resolve bundles")
-    public void resolve(
+    public String resolve(
         @Descriptor("target bundles (can be null or empty)") Bundle[] bundles)
     {
-        if ((bundles != null) && (bundles.length == 0))
-        {
-            bundles = null;
-        }
-
-        // Keep track of service references.
-        List<ServiceReference> refs = new ArrayList();
-
-        // Get package admin service.
-        PackageAdmin pa = Util.getService(m_bc, PackageAdmin.class, refs);
-        if (pa == null)
+        if (m_b0.adapt(FrameworkWiring.class).resolveBundles(bundles != null ? Arrays.asList(bundles) : null))
         {
-            System.out.println("Package Admin service is unavailable.");
+            return "Not all bundles could be resolved.";
         }
-
-        if (!pa.resolveBundles(bundles))
-        {
-            System.out.println("Not all bundles could be resolved.");
-        }
-
-        Util.ungetServices(m_bc, refs);
+        return null;
     }
 
     @Descriptor("start bundles")
-    public void start(
+    public String start(
         @Descriptor("start bundle transiently") @Parameter(names = { "-t", "--transient" }, presentValue = "true", absentValue = "false") boolean trans,
         @Descriptor("use declared activation policy") @Parameter(names = { "-p",
                 "--policy" }, presentValue = "true", absentValue = "false") boolean policy,
         @Descriptor("target bundle identifiers or URLs") String[] ss)
     {
+        if ((ss == null) || (ss.length < 1)) {
+            return "Please specify the bundles to start.";
+        }
+
         int options = 0;
 
         // Check for "transient" switch.
@@ -702,9 +667,7 @@ public class Basic
             options |= Bundle.START_ACTIVATION_POLICY;
         }
 
-        // There should be at least one bundle id.
-        if ((ss != null) && (ss.length >= 1))
-        {
+        try (Formatter f = new Formatter()) {
             for (String s : ss)
             {
                 String id = s.trim();
@@ -730,45 +693,41 @@ public class Basic
                     }
                     else
                     {
-                        System.err.println("Bundle ID " + id + " is invalid.");
+                        f.format("Bundle ID '%s'  is invalid.%n", id);
                     }
                 }
                 catch (NumberFormatException ex)
                 {
-                    System.err.println("Unable to parse id '" + id + "'.");
+                    f.format("Unable to parse id '%s'.%n", id);
                 }
                 catch (BundleException ex)
                 {
                     if (ex.getNestedException() != null)
                     {
-                        ex.printStackTrace();
-                        System.err.println(ex.getNestedException().toString());
+                        f.format("%s%n", ex.getNestedException().toString());
                     }
                     else
                     {
-                        System.err.println(ex.toString());
+                        f.format("%s%n", ex.toString());
                     }
                 }
                 catch (Exception ex)
                 {
-                    System.err.println(ex.toString());
+                    f.format("%s%n", ex.toString());
                 }
             }
-        }
-        else
-        {
-            System.err.println("Incorrect number of arguments");
+            return f.toString();
         }
     }
 
     @Descriptor("stop bundles")
-    public void stop(@Descriptor("stop bundle transiently") @Parameter(names = { "-t",
+    public String stop(@Descriptor("stop bundle transiently") @Parameter(names = { "-t",
             "--transient" }, presentValue = "true", absentValue = "false") boolean trans,
         @Descriptor("target bundles") Bundle[] bundles)
     {
         if ((bundles == null) || (bundles.length == 0))
         {
-            System.out.println("Please specify the bundles to stop.");
+            return "Please specify the bundles to stop.";
         }
 
         int options = 0;
@@ -779,185 +738,176 @@ public class Basic
             options |= Bundle.STOP_TRANSIENT;
         }
 
-        for (Bundle bundle : bundles)
-        {
-            try
+        try (Formatter f = new Formatter()) {
+            for (Bundle bundle : bundles)
             {
-                bundle.stop(options);
-            }
-            catch (BundleException ex)
-            {
-                if (ex.getNestedException() != null)
+                try
                 {
-                    System.err.println(ex.getNestedException().toString());
+                    bundle.stop(options);
                 }
-                else
+                catch (BundleException ex)
                 {
-                    System.err.println(ex.toString());
+                    if (ex.getNestedException() != null)
+                    {
+                        f.format("%s%n", ex.getNestedException().toString());
+                    }
+                    else
+                    {
+                        f.format("%s%n", ex.toString());
+                    }
+                }
+                catch (Exception ex)
+                {
+                    f.format("%s%n", ex.toString());
                 }
             }
-            catch (Exception ex)
-            {
-                System.err.println(ex.toString());
-            }
+            return f.toString();
         }
     }
 
     @Descriptor("uninstall bundles")
-    public void uninstall(@Descriptor("target bundles") Bundle[] bundles)
+    public String uninstall(@Descriptor("target bundles") Bundle[] bundles)
     {
         if ((bundles == null) || (bundles.length == 0))
         {
-            System.out.println("Please specify the bundles to uninstall.");
+            return "Please specify the bundles to uninstall.";
         }
-        else
-        {
-            try
+
+        try (Formatter f = new Formatter()) {
+            for (Bundle bundle : bundles)
             {
-                for (Bundle bundle : bundles)
+                try
                 {
                     bundle.uninstall();
                 }
-            }
-            catch (BundleException ex)
-            {
-                if (ex.getNestedException() != null)
+                catch (BundleException ex)
                 {
-                    ex.printStackTrace();
-                    System.err.println(ex.getNestedException().toString());
+                    if (ex.getNestedException() != null)
+                    {
+                        f.format("%s%n", ex.getNestedException().toString());
+                    }
+                    else {
+                        f.format("%s%n", ex.toString());
+                    }
                 }
-                else
+                catch (Exception ex)
                 {
-                    System.err.println(ex.toString());
+                    f.format("%s%n", ex.toString());
                 }
             }
-            catch (Exception ex)
-            {
-                System.err.println(ex.toString());
-            }
+            return f.toString();
         }
     }
 
     @Descriptor("update bundle")
-    public void update(@Descriptor("target bundle") Bundle bundle)
+    public String update(@Descriptor("target bundle") Bundle bundle)
     {
+        if (bundle == null)
+        {
+            return "Must specify a bundle.";
+        }
+
         try
         {
-            // Get the bundle.
-            if (bundle != null)
-            {
-                bundle.update();
-            }
+            bundle.update();
+            return null;
         }
         catch (BundleException ex)
         {
             if (ex.getNestedException() != null)
             {
-                System.err.println(ex.getNestedException().toString());
-            }
-            else
-            {
-                System.err.println(ex.toString());
+                return ex.getNestedException().toString();
             }
+
+            return ex.toString();
         }
         catch (Exception ex)
         {
-            System.err.println(ex.toString());
+            return ex.toString();
         }
     }
 
     @Descriptor("update bundle from URL")
-    public void update(@Descriptor("target bundle") Bundle bundle,
-        @Descriptor("URL from where to retrieve bundle") String location)
-    {
-        if (location != null)
+    public String update(
+            @Descriptor("command session") CommandSession session,
+            @Descriptor("target bundle") Bundle bundle,
+        @Descriptor("URL from where to retrieve bundle") String location) throws IOException {
+        if (bundle == null)
         {
-            try
-            {
-                // Get the bundle.
-                if (bundle != null)
-                {
-                    InputStream is = new URL(location).openStream();
-                    bundle.update(is);
-                }
-                else
-                {
-                    System.err.println("Please specify a bundle to update");
-                }
-            }
-            catch (MalformedURLException ex)
-            {
-                System.err.println("Unable to parse URL");
-            }
-            catch (IOException ex)
-            {
-                System.err.println("Unable to open input stream: " + ex);
-            }
-            catch (BundleException ex)
-            {
-                if (ex.getNestedException() != null)
-                {
-                    System.err.println(ex.getNestedException().toString());
-                }
-                else
-                {
-                    System.err.println(ex.toString());
-                }
-            }
-            catch (Exception ex)
+            return "Must specify a bundle.";
+        }
+        if (location == null)
+        {
+            return "Must specify a location.";
+        }
+
+        try
+        {
+            location = Util.resolveUri(session, location.trim());
+            InputStream is = new URL(location).openStream();
+            bundle.update(is);
+            return null;
+        }
+        catch (MalformedURLException ex)
+        {
+            return "Unable to parse URL";
+        }
+        catch (IOException ex)
+        {
+            return "Unable to open input stream: " + ex;
+        }
+        catch (BundleException ex)
+        {
+            if (ex.getNestedException() != null)
             {
-                System.err.println(ex.toString());
+                return ex.getNestedException().toString();
             }
+
+            return ex.toString();
         }
-        else
+        catch (Exception ex)
         {
-            System.err.println("Must specify a location.");
+            return ex.toString();
         }
     }
 
     @Descriptor("determines from where a bundle loads a class")
-    public void which(@Descriptor("target bundle") Bundle bundle,
+    public String which(@Descriptor("target bundle") Bundle bundle,
         @Descriptor("target class name") String className)
     {
         if (bundle == null)
         {
-            System.err.println("Please specify a bundle");
+            return "Please specify a bundle";
         }
-        else
+
+        Class<?> clazz = null;
+        try
         {
-            Class clazz = null;
-            try
+            clazz = bundle.loadClass(className);
+            if (clazz.getClassLoader() == null)
             {
-                clazz = bundle.loadClass(className);
-                if (clazz.getClassLoader() == null)
-                {
-                    System.out.println("Loaded from: boot class loader");
-                }
-                else if (clazz.getClassLoader() instanceof BundleReference)
-                {
-                    Bundle p = ((BundleReference) clazz.getClassLoader()).getBundle();
-                    System.out.println("Loaded from: " + p);
-                }
-                else
-                {
-                    System.out.println("Loaded from: " + clazz.getClassLoader());
-                }
+                return "Loaded from: boot class loader";
             }
-            catch (ClassNotFoundException ex)
+            else if (clazz.getClassLoader() instanceof BundleReference)
+            {
+                Bundle p = ((BundleReference) clazz.getClassLoader()).getBundle();
+                return "Loaded from: " + p;
+            }
+            else
             {
-                System.out.println("Class not found");
+                return "Loaded from: " + clazz.getClassLoader();
             }
         }
+        catch (ClassNotFoundException ex)
+        {
+            return "Class not found";
+        }
     }
 
-    private static void printBundleList(Bundle[] bundles, StartLevel startLevel,
-        boolean showLoc, boolean showSymbolic, boolean showUpdate)
+    private static void printBundleList(Bundle[] bundles,
+        boolean showLoc, boolean showSymbolic, boolean showUpdate, Bundle b0, Formatter f)
     {
-        // Display active start level.
-        if (startLevel != null)
-        {
-            System.out.println("START LEVEL " + startLevel.getStartLevel());
-        }
+        f.format("START LEVEL %s%n", b0.adapt(FrameworkStartLevel.class).getStartLevel());
 
         // Determine last column.
         String lastColumn = "Name";
@@ -974,20 +924,11 @@ public class Basic
             lastColumn = "Update location";
         }
 
-        // Print column headers.
-        if (startLevel != null)
-        {
-            System.out.println(String.format("%5s|%-11s|%5s|%s", "ID", "State", "Level",
-                lastColumn));
-        }
-        else
-        {
-            System.out.println(String.format("%5s|%-11s|%s", "ID", "State", lastColumn));
-        }
+        f.format("%5s|%-11s|%5s|%s%n", "ID", "State", "Level", lastColumn);
         for (Bundle bundle : bundles)
         {
             // Get the bundle name or location.
-            String name = (String) bundle.getHeaders().get(Constants.BUNDLE_NAME);
+            String name = bundle.getHeaders().get(Constants.BUNDLE_NAME);
             // If there is no name, then default to symbolic name.
             name = (name == null) ? bundle.getSymbolicName() : name;
             // If there is no symbolic name, resort to location.
@@ -1006,7 +947,7 @@ public class Basic
             }
             else if (showUpdate)
             {
-                name = (String) bundle.getHeaders().get(Constants.BUNDLE_UPDATELOCATION);
+                name = bundle.getHeaders().get(Constants.BUNDLE_UPDATELOCATION);
                 name = (name == null) ? bundle.getLocation() : name;
             }
 
@@ -1015,20 +956,11 @@ public class Basic
                 : name;
 
             // Get the bundle's start level.
-            int level = (startLevel == null) ? -1
-                : startLevel.getBundleStartLevel(bundle);
+            int level = bundle.adapt(BundleStartLevel.class).getStartLevel();
 
-            if (level < 0)
-            {
-                System.out.println(String.format("%5d|%-11s|%s", bundle.getBundleId(),
-                    getStateString(bundle), name, bundle.getVersion()));
-            }
-            else
-            {
-                System.out.println(String.format("%5d|%-11s|%5d|%s",
-                    bundle.getBundleId(), getStateString(bundle), level, name,
-                    bundle.getVersion()));
-            }
+            f.format("%5d|%-11s|%5d|%s|%s%n",
+                bundle.getBundleId(), getStateString(bundle), level, name,
+                bundle.getVersion());
         }
     }
 
@@ -1060,4 +992,4 @@ public class Basic
             return "Unknown    ";
         }
     }
-}
\ No newline at end of file
+}


=====================================
src/main/java/org/apache/felix/gogo/command/Files.java
=====================================
@@ -6,9 +6,9 @@
  * to you under the Apache License, Version 2.0 (the
  * "License"); you may not use this file except in compliance
  * with the License.  You may obtain a copy of the License at
- * 
+ *
  *   http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing,
  * software distributed under the License is distributed on an
  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@@ -21,16 +21,17 @@ package org.apache.felix.gogo.command;
 import java.io.File;
 import java.io.FileFilter;
 import java.io.IOException;
+import java.net.URI;
 import java.util.ArrayList;
 import java.util.List;
 import org.apache.felix.service.command.CommandSession;
 import org.apache.felix.service.command.Descriptor;
 import org.osgi.framework.BundleContext;
+import static org.apache.felix.gogo.command.Util.CWD;
 
 public class Files
 {
-    private static final String CWD = "_cwd";
-
+    @SuppressWarnings("unused")
     private final BundleContext m_bc;
 
     public Files(BundleContext bc)
@@ -68,7 +69,11 @@ public class Files
         {
             return cwd;
         }
-        cwd = new File(cwd, dir);
+
+        URI curUri = cwd.toURI();
+        URI newUri = curUri.resolve(dir);
+
+        cwd = new File(newUri);
         if (!cwd.exists())
         {
             throw new IOException("Directory does not exist");
@@ -143,8 +148,8 @@ public class Files
 
     public static List<String> parseSubstring(String value)
     {
-        List<String> pieces = new ArrayList();
-        StringBuffer ss = new StringBuffer();
+        List<String> pieces = new ArrayList<>();
+        StringBuilder ss = new StringBuilder();
         // int kind = SIMPLE; // assume until proven otherwise
         boolean wasStar = false; // indicates last piece was a star
         boolean leftstar = false; // track if the initial piece is a star
@@ -261,14 +266,7 @@ loop:   for (int i = 0; i < len; i++)
             // string ends with it.
             if (i == len - 1)
             {
-                if (s.endsWith(piece))
-                {
-                    result = true;
-                }
-                else
-                {
-                    result = false;
-                }
+                result = s.endsWith(piece);
                 break loop;
             }
 
@@ -290,4 +288,4 @@ loop:   for (int i = 0; i < len; i++)
 
         return result;
     }
-}
\ No newline at end of file
+}


=====================================
src/main/java/org/apache/felix/gogo/command/Inspect.java
=====================================
@@ -19,10 +19,16 @@
 package org.apache.felix.gogo.command;
 
 import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Formatter;
 import java.util.HashMap;
 import java.util.List;
-
 import java.util.Map;
+import java.util.Map.Entry;
+
 import org.apache.felix.service.command.Descriptor;
 import org.osgi.framework.Bundle;
 import org.osgi.framework.BundleContext;
@@ -32,9 +38,6 @@ import org.osgi.framework.wiring.BundleCapability;
 import org.osgi.framework.wiring.BundleRequirement;
 import org.osgi.framework.wiring.BundleWire;
 import org.osgi.framework.wiring.BundleWiring;
-import org.osgi.service.packageadmin.ExportedPackage;
-import org.osgi.service.packageadmin.PackageAdmin;
-import org.osgi.service.packageadmin.RequiredBundle;
 
 public class Inspect
 {
@@ -55,15 +58,15 @@ public class Inspect
     }
 
     @Descriptor("inspects bundle capabilities and requirements")
-    public void inspect(
+    public String inspect(
         @Descriptor("('capability' | 'requirement')") String direction,
         @Descriptor("(<namespace> | 'service')") String namespace,
         @Descriptor("target bundles") Bundle[] bundles)
     {
-        inspect(m_bc, direction, namespace, bundles);
+        return inspect(m_bc, direction, namespace, bundles);
     }
 
-    private static void inspect(
+    private static String inspect(
         BundleContext bc, String direction, String namespace, Bundle[] bundles)
     {
         // Verify arguments.
@@ -74,69 +77,58 @@ public class Inspect
 
             if (CAPABILITY.startsWith(direction))
             {
-                printCapabilities(bc, Util.parseSubstring(namespace), bundles);
+                return printCapabilities(bc, Util.parseSubstring(namespace), bundles);
             }
             else
             {
-                printRequirements(bc, Util.parseSubstring(namespace), bundles);
-            }
-        }
-        else
-        {
-            if (!isValidDirection(direction))
-            {
-                System.out.println("Invalid argument: " + direction);
+                return printRequirements(bc, Util.parseSubstring(namespace), bundles);
             }
         }
+
+        return "Invalid argument: " + direction;
     }
 
-    public static void printCapabilities(
+    public static String printCapabilities(
         BundleContext bc, List<String> namespace, Bundle[] bundles)
     {
-        boolean separatorNeeded = false;
-        for (Bundle b : bundles)
-        {
-            if (separatorNeeded)
+        try (Formatter f = new Formatter()) {
+            for (Bundle b : bundles)
             {
-                System.out.println("");
-            }
+                // Print out any matching generic capabilities.
+                BundleWiring wiring = b.adapt(BundleWiring.class);
+                if (wiring != null)
+                {
+                    String title = b + " provides:";
+                    f.format("%s%n%s%n", title, Util.getUnderlineString(title.length()));
 
-            // Print out any matching generic capabilities.
-            BundleWiring wiring = b.adapt(BundleWiring.class);
-            if (wiring != null)
-            {
-                String title = b + " provides:";
-                System.out.println(title);
-                System.out.println(Util.getUnderlineString(title.length()));
+                    // Print generic capabilities for matching namespaces.
+                    boolean matches = printMatchingCapabilities(wiring, namespace, f);
 
-                // Print generic capabilities for matching namespaces.
-                boolean matches = printMatchingCapabilities(wiring, namespace);
+                    // Handle service capabilities separately, since they aren't part
+                    // of the generic model in OSGi.
+                    if (matchNamespace(namespace, NONSTANDARD_SERVICE_NAMESPACE))
+                    {
+                        matches |= printServiceCapabilities(b, f);
+                    }
 
-                // Handle service capabilities separately, since they aren't part
-                // of the generic model in OSGi.
-                if (matchNamespace(namespace, NONSTANDARD_SERVICE_NAMESPACE))
-                {
-                    matches |= printServiceCapabilities(b);
+                    // If there were no capabilities for the specified namespace,
+                    // then say so.
+                    if (!matches)
+                    {
+                        f.format("%s %s%n", Util.unparseSubstring(namespace), EMPTY_MESSAGE);
+                    }
                 }
-
-                // If there were no capabilities for the specified namespace,
-                // then say so.
-                if (!matches)
+                else
                 {
-                    System.out.println(Util.unparseSubstring(namespace) + " " + EMPTY_MESSAGE);
+                    f.format("Bundle %s is not resolved.",
+                        b.getBundleId());
                 }
             }
-            else
-            {
-                System.out.println("Bundle "
-                    + b.getBundleId()
-                    + " is not resolved.");
-            }
-            separatorNeeded = true;
+            return f.toString();
         }
     }
 
-    private static boolean printMatchingCapabilities(BundleWiring wiring, List<String> namespace)
+    private static boolean printMatchingCapabilities(BundleWiring wiring, List<String> namespace, Formatter f)
     {
         List<BundleWire> wires = wiring.getProvidedWires(null);
         Map<BundleCapability, List<BundleWire>> aggregateCaps =
@@ -147,57 +139,101 @@ public class Inspect
         {
             if (matchNamespace(namespace, cap.getNamespace()))
             {
+                if ("osgi.service".equals(cap.getNamespace())) {
+                    continue;
+                }
                 matches = true;
                 List<BundleWire> dependents = aggregateCaps.get(cap);
                 Object keyAttr =
                     cap.getAttributes().get(cap.getNamespace());
-                if (dependents != null)
+                if ("osgi.native".equals(cap.getNamespace()))
+                {
+                    f.format("%s with properties:%n", cap.getNamespace());
+                    List<Entry<String, Object>> sortedEntries = 
+                            new ArrayList<Entry<String, Object>>(cap.getAttributes().entrySet());
+                    Collections.sort(sortedEntries, new Comparator<Entry<String, Object>>() {
+                        @Override
+                        public int compare(Entry<String, Object> o1, Entry<String, Object> o2) {
+                            return o1.getKey().compareTo(o2.getKey());
+                        }});
+                    
+                    for (Entry<String, Object> e : sortedEntries) {
+                        f.format("   %s = %s%n", e.getKey(), e.getValue());
+                    }
+                    
+                    if (dependents != null)
+                    {
+                        f.format("   required by:%n");
+                        for (BundleWire wire : dependents) {
+                            f.format("      %s%n", wire.getRequirerWiring().getBundle());
+                        }
+                    }
+                    else
+                    {
+                        f.format("   %s%n", UNUSED_MESSAGE);
+                    }
+                }
+                else if (dependents != null)
                 {
-                    String msg;
                     if (keyAttr != null)
                     {
-                        msg = cap.getNamespace()
-                            + "; "
-                            + keyAttr
-                            + " "
-                            + getVersionFromCapability(cap);
+                        f.format("%s; %s %s required by:%n",
+                            cap.getNamespace(),
+                            format(keyAttr),
+                            getVersionFromCapability(cap));
                     }
                     else
                     {
-                        msg = cap.toString();
+                        f.format("%s required by:%n", cap.toString());
                     }
-                    msg = msg + " required by:";
-                    System.out.println(msg);
                     for (BundleWire wire : dependents)
                     {
-                        System.out.println("   " + wire.getRequirerWiring().getBundle());
+                        f.format("   %s%n", wire.getRequirerWiring().getBundle());
                     }
                 }
                 else if (keyAttr != null)
                 {
-                    System.out.println(cap.getNamespace()
-                        + "; "
-                        + cap.getAttributes().get(cap.getNamespace())
-                        + " "
-                        + getVersionFromCapability(cap)
-                        + " "
-                        + UNUSED_MESSAGE);
+                    f.format("%s; %s %s %s%n",
+                        cap.getNamespace(),
+                        format(keyAttr),
+                        getVersionFromCapability(cap),
+                        UNUSED_MESSAGE);
                 }
                 else
                 {
-                    System.out.println(cap + " " + UNUSED_MESSAGE);
+                    f.format("%s %s%n", cap, UNUSED_MESSAGE);
                 }
             }
         }
         return matches;
     }
 
+    private static String format(Object object) {
+        String retVal;
+        if (object.getClass().isArray() || object instanceof Collection) {        	
+            StringBuffer buffer = new StringBuffer();
+            @SuppressWarnings("rawtypes")
+            Iterable formatTarget = object.getClass().isArray() ? Arrays.asList(object) : (Iterable) object;
+            for (Object elem : formatTarget) {
+                if (buffer.length()>0) {
+                    buffer.append(',');
+                }
+                buffer.append(elem.toString());
+            }
+            retVal = buffer.toString();
+        }
+        else {
+            retVal = String.valueOf(object);
+        }
+        return retVal;
+    }
+    
     private static Map<BundleCapability, List<BundleWire>> aggregateCapabilities(
         List<String> namespace, List<BundleWire> wires)
     {
         // Aggregate matching capabilities.
         Map<BundleCapability, List<BundleWire>> map =
-            new HashMap<BundleCapability, List<BundleWire>>();
+                new HashMap<>();
         for (BundleWire wire : wires)
         {
             if (matchNamespace(namespace, wire.getCapability().getNamespace()))
@@ -205,7 +241,7 @@ public class Inspect
                 List<BundleWire> dependents = map.get(wire.getCapability());
                 if (dependents == null)
                 {
-                    dependents = new ArrayList<BundleWire>();
+                    dependents = new ArrayList<>();
                     map.put(wire.getCapability(), dependents);
                 }
                 dependents.add(wire);
@@ -214,26 +250,24 @@ public class Inspect
         return map;
     }
 
-    static boolean printServiceCapabilities(Bundle b)
+    static boolean printServiceCapabilities(Bundle b, Formatter f)
     {
         boolean matches = false;
 
         try
         {
-            ServiceReference[] refs = b.getRegisteredServices();
+            ServiceReference<?>[] refs = b.getRegisteredServices();
 
             if ((refs != null) && (refs.length > 0))
             {
                 matches = true;
                 // Print properties for each service.
-                for (ServiceReference ref : refs)
+                for (ServiceReference<?> ref : refs)
                 {
                     // Print object class with "namespace".
-                    System.out.println(
-                        NONSTANDARD_SERVICE_NAMESPACE
-                        + "; "
-                        + Util.getValueString(ref.getProperty("objectClass"))
-                        + " with properties:");
+                    f.format("%s; %s with properties:%n",
+                        NONSTANDARD_SERVICE_NAMESPACE,
+                        Util.getValueString(ref.getProperty("objectClass")));
                     // Print service properties.
                     String[] keys = ref.getPropertyKeys();
                     for (String key : keys)
@@ -241,17 +275,16 @@ public class Inspect
                         if (!key.equalsIgnoreCase(Constants.OBJECTCLASS))
                         {
                             Object v = ref.getProperty(key);
-                            System.out.println("   "
-                                + key + " = " + Util.getValueString(v));
+                            f.format("   %s = %s%n", key, Util.getValueString(v));
                         }
                     }
                     Bundle[] users = ref.getUsingBundles();
                     if ((users != null) && (users.length > 0))
                     {
-                        System.out.println("   Used by:");
+                        f.format("   Used by:%n");
                         for (Bundle user : users)
                         {
-                            System.out.println("      " + user);
+                            f.format("      %s%n", user);
                         }
                     }
                 }
@@ -259,58 +292,51 @@ public class Inspect
         }
         catch (Exception ex)
         {
-            System.err.println(ex.toString());
+            f.format("%s%n", ex.toString());
         }
 
         return matches;
     }
 
-    public static void printRequirements(
+    public static String printRequirements(
         BundleContext bc, List<String> namespace, Bundle[] bundles)
     {
-        boolean separatorNeeded = false;
-        for (Bundle b : bundles)
-        {
-            if (separatorNeeded)
+        try (Formatter f = new Formatter()) {
+            for (Bundle b : bundles)
             {
-                System.out.println("");
-            }
-
-            // Print out any matching generic requirements.
-            BundleWiring wiring = b.adapt(BundleWiring.class);
-            if (wiring != null)
-            {
-                String title = b + " requires:";
-                System.out.println(title);
-                System.out.println(Util.getUnderlineString(title.length()));
-                boolean matches = printMatchingRequirements(wiring, namespace);
-
-                // Handle service requirements separately, since they aren't part
-                // of the generic model in OSGi.
-                if (matchNamespace(namespace, NONSTANDARD_SERVICE_NAMESPACE))
+                // Print out any matching generic requirements.
+                BundleWiring wiring = b.adapt(BundleWiring.class);
+                if (wiring != null)
                 {
-                    matches |= printServiceRequirements(b);
-                }
+                    String title = b + " requires:";
+                    f.format("%s%n%s%n", title, Util.getUnderlineString(title.length()));
+                    boolean matches = printMatchingRequirements(wiring, namespace, f);
 
-                // If there were no requirements for the specified namespace,
-                // then say so.
-                if (!matches)
+                    // Handle service requirements separately, since they aren't part
+                    // of the generic model in OSGi.
+                    if (matchNamespace(namespace, NONSTANDARD_SERVICE_NAMESPACE))
+                    {
+                        matches |= printServiceRequirements(b, f);
+                    }
+
+                    // If there were no requirements for the specified namespace,
+                    // then say so.
+                    if (!matches)
+                    {
+                        f.format("%s %s%n", Util.unparseSubstring(namespace), EMPTY_MESSAGE);
+                    }
+                }
+                else
                 {
-                    System.out.println(Util.unparseSubstring(namespace) + " " + EMPTY_MESSAGE);
+                    f.format("Bundle %s is not resolved.%n",
+                        b.getBundleId());
                 }
             }
-            else
-            {
-                System.out.println("Bundle "
-                    + b.getBundleId()
-                    + " is not resolved.");
-            }
-
-            separatorNeeded = true;
+            return f.toString();
         }
     }
 
-    private static boolean printMatchingRequirements(BundleWiring wiring, List<String> namespace)
+    private static boolean printMatchingRequirements(BundleWiring wiring, List<String> namespace, Formatter f)
     {
         List<BundleWire> wires = wiring.getRequiredWires(null);
         Map<BundleRequirement, List<BundleWire>> aggregateReqs =
@@ -325,11 +351,9 @@ public class Inspect
                 List<BundleWire> providers = aggregateReqs.get(req);
                 if (providers != null)
                 {
-                    System.out.println(
-                        req.getNamespace()
-                        + "; "
-                        + req.getDirectives().get(Constants.FILTER_DIRECTIVE)
-                        + " resolved by:");
+                    f.format("%s; %s resolved by:%n",
+                        req.getNamespace(),
+                        req.getDirectives().get(Constants.FILTER_DIRECTIVE));
                     for (BundleWire wire : providers)
                     {
                         String msg;
@@ -348,19 +372,15 @@ public class Inspect
                         {
                             msg = wire.getCapability().toString();
                         }
-                        msg = "   " + msg + " from "
-                            + wire.getProviderWiring().getBundle();
-                        System.out.println(msg);
+                        f.format("   %s from %s%n", msg, wire.getProviderWiring().getBundle());
                     }
                 }
                 else
                 {
-                    System.out.println(
-                        req.getNamespace()
-                        + "; "
-                        + req.getDirectives().get(Constants.FILTER_DIRECTIVE)
-                        + " "
-                        + UNRESOLVED_MESSAGE);
+                    f.format("%s; %s %s%n",
+                        req.getNamespace(),
+                        req.getDirectives().get(Constants.FILTER_DIRECTIVE),
+                        UNRESOLVED_MESSAGE);
                 }
             }
         }
@@ -372,7 +392,7 @@ public class Inspect
     {
         // Aggregate matching capabilities.
         Map<BundleRequirement, List<BundleWire>> map =
-            new HashMap<BundleRequirement, List<BundleWire>>();
+                new HashMap<>();
         for (BundleWire wire : wires)
         {
             if (matchNamespace(namespace, wire.getRequirement().getNamespace()))
@@ -380,7 +400,7 @@ public class Inspect
                 List<BundleWire> providers = map.get(wire.getRequirement());
                 if (providers == null)
                 {
-                    providers = new ArrayList<BundleWire>();
+                    providers = new ArrayList<>();
                     map.put(wire.getRequirement(), providers);
                 }
                 providers.add(wire);
@@ -389,27 +409,25 @@ public class Inspect
         return map;
     }
 
-    static boolean printServiceRequirements(Bundle b)
+    static boolean printServiceRequirements(Bundle b, Formatter f)
     {
         boolean matches = false;
 
         try
         {
-            ServiceReference[] refs = b.getServicesInUse();
+            ServiceReference<?>[] refs = b.getServicesInUse();
 
             if ((refs != null) && (refs.length > 0))
             {
                 matches = true;
                 // Print properties for each service.
-                for (ServiceReference ref : refs)
+                for (ServiceReference<?> ref : refs)
                 {
                     // Print object class with "namespace".
-                    System.out.println(
-                        NONSTANDARD_SERVICE_NAMESPACE
-                        + "; "
-                        + Util.getValueString(ref.getProperty("objectClass"))
-                        + " provided by:");
-                    System.out.println("   " + ref.getBundle());
+                    f.format("%s; %s provided by:%n   %s%n",
+                        NONSTANDARD_SERVICE_NAMESPACE,
+                        Util.getValueString(ref.getProperty("objectClass")),
+                        ref.getBundle());
                 }
             }
         }
@@ -440,9 +458,4 @@ public class Inspect
     {
         return (CAPABILITY.startsWith(direction) || REQUIREMENT.startsWith(direction));
     }
-
-    private static boolean isFragment(Bundle bundle)
-    {
-        return bundle.getHeaders().get(Constants.FRAGMENT_HOST) != null;
-    }
 }
\ No newline at end of file


=====================================
src/main/java/org/apache/felix/gogo/command/Inspect42.java deleted
=====================================
@@ -1,548 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.felix.gogo.command;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.felix.service.command.Descriptor;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Constants;
-import org.osgi.framework.ServiceReference;
-import org.osgi.service.packageadmin.ExportedPackage;
-import org.osgi.service.packageadmin.PackageAdmin;
-import org.osgi.service.packageadmin.RequiredBundle;
-
-public class Inspect42
-{
-    public static final String LEGACY_PACKAGE_NAMESPACE = "package";
-    public static final String LEGACY_BUNDLE_NAMESPACE = "bundle";
-    public static final String LEGACY_HOST_NAMESPACE = "host";
-    public static final String NONSTANDARD_SERVICE_NAMESPACE = "service";
-
-    public static final String CAPABILITY = "capability";
-    public static final String REQUIREMENT = "requirement";
-
-    private static final String EMPTY_MESSAGE = "[EMPTY]";
-    private static final String UNUSED_MESSAGE = "[UNUSED]";
-    private static final String UNRESOLVED_MESSAGE = "[UNRESOLVED]";
-
-    private final BundleContext m_bc;
-
-    public Inspect42(BundleContext bc)
-    {
-        m_bc = bc;
-    }
-
-    @Descriptor("inspects bundle capabilities and requirements")
-    public void inspect(
-        @Descriptor("('capability' | 'requirement')") String direction,
-        @Descriptor("('package' | 'bundle' | 'host' | 'service')") String namespace,
-        @Descriptor("target bundles") Bundle[] bundles)
-    {
-        inspect(m_bc, direction, namespace, bundles);
-    }
-
-    private static void inspect(
-        BundleContext bc, String direction, String namespace, Bundle[] bundles)
-    {
-        // Verify arguments.
-        if (isValidDirection(direction))
-        {
-            bundles = ((bundles == null) || (bundles.length == 0))
-                ? bc.getBundles() : bundles;
-
-            if (CAPABILITY.startsWith(direction))
-            {
-                printNonstandardCapabilities(bc, Util.parseSubstring(namespace), bundles);
-            }
-            else
-            {
-                printNonstandardRequirements(bc, Util.parseSubstring(namespace), bundles);
-            }
-        }
-        else
-        {
-            if (!isValidDirection(direction))
-            {
-                System.out.println("Invalid argument: " + direction);
-            }
-        }
-    }
-
-    private static void printNonstandardCapabilities(
-        BundleContext bc, List<String> namespace, Bundle[] bundles)
-    {
-        boolean separatorNeeded = false;
-        for (Bundle b : bundles)
-        {
-            if (separatorNeeded)
-            {
-                System.out.println("");
-            }
-            String title = b + " provides:";
-            System.out.println(title);
-            System.out.println(Util.getUnderlineString(title.length()));
-            boolean matches = false;
-
-            if (matchNamespace(namespace, LEGACY_BUNDLE_NAMESPACE))
-            {
-                matches |= printRequiringBundles(bc, b);
-            }
-            if (matchNamespace(namespace, LEGACY_HOST_NAMESPACE))
-            {
-                matches |= printHostedFragments(bc, b);
-            }
-            if (matchNamespace(namespace, LEGACY_PACKAGE_NAMESPACE))
-            {
-                matches |= printExportedPackages(bc, b);
-            }
-            if (matchNamespace(namespace, NONSTANDARD_SERVICE_NAMESPACE))
-            {
-                matches |= Inspect.printServiceCapabilities(b);
-            }
-
-            // If there were no capabilities for the specified namespace,
-            // then say so.
-            if (!matches)
-            {
-                System.out.println(Util.unparseSubstring(namespace) + " " + EMPTY_MESSAGE);
-            }
-            separatorNeeded = true;
-        }
-    }
-
-    private static void printNonstandardRequirements(
-        BundleContext bc, List<String> namespace, Bundle[] bundles)
-    {
-        boolean separatorNeeded = false;
-        for (Bundle b : bundles)
-        {
-            if (separatorNeeded)
-            {
-                System.out.println("");
-            }
-            String title = b + " requires:";
-            System.out.println(title);
-            System.out.println(Util.getUnderlineString(title.length()));
-            boolean matches = false;
-            if (matchNamespace(namespace, LEGACY_BUNDLE_NAMESPACE))
-            {
-                matches |= printRequiredBundles(bc, b);
-            }
-            if (matchNamespace(namespace, LEGACY_HOST_NAMESPACE))
-            {
-                matches |= printFragmentHosts(bc, b);
-            }
-            if (matchNamespace(namespace, LEGACY_PACKAGE_NAMESPACE))
-            {
-                matches |= printImportedPackages(bc, b);
-            }
-            if (matchNamespace(namespace, NONSTANDARD_SERVICE_NAMESPACE))
-            {
-                matches |= Inspect.printServiceRequirements(b);
-            }
-
-            // If there were no capabilities for the specified namespace,
-            // then say so.
-            if (!matches)
-            {
-                System.out.println(Util.unparseSubstring(namespace) + " " + EMPTY_MESSAGE);
-            }
-            separatorNeeded = true;
-        }
-    }
-
-    public static boolean printExportedPackages(BundleContext bc, Bundle b)
-    {
-        boolean matches = false;
-
-        // Keep track of service references.
-        List<ServiceReference> refs = new ArrayList();
-
-        // Fragments cannot export packages.
-        if (!isFragment(b))
-        {
-            // Get package admin service.
-            PackageAdmin pa = Util.getService(bc, PackageAdmin.class, refs);
-            if (pa == null)
-            {
-                System.out.println("PackageAdmin service is unavailable.");
-            }
-            else
-            {
-                try
-                {
-                    ExportedPackage[] exports = pa.getExportedPackages(b);
-                    if (exports != null)
-                    {
-                        for (ExportedPackage ep : exports)
-                        {
-                            matches = true;
-                            Bundle[] importers = ep.getImportingBundles();
-                            if ((importers != null) && (importers.length > 0))
-                            {
-                                String msg = LEGACY_PACKAGE_NAMESPACE
-                                    + "; "
-                                    + ep.getName()
-                                    + "; "
-                                    + ep.getVersion().toString()
-                                    + " required by:";
-                                System.out.println(msg);
-                                for (Bundle importer : importers)
-                                {
-                                    System.out.println("   " + importer);
-                                }
-                            }
-                            else
-                            {
-                                System.out.println(
-                                    LEGACY_PACKAGE_NAMESPACE
-                                    + "; "
-                                    + ep.getName()
-                                    + "; "
-                                    + ep.getVersion().toString()
-                                    + " "
-                                    + UNUSED_MESSAGE);
-                            }
-                        }
-                    }
-                }
-                catch (Exception ex)
-                {
-                    System.err.println(ex.toString());
-                }
-            }
-        }
-
-        Util.ungetServices(bc, refs);
-
-        return matches;
-    }
-
-    private static boolean printImportedPackages(BundleContext bc, Bundle b)
-    {
-        boolean matches = false;
-
-        // Keep track of service references.
-        List<ServiceReference> refs = new ArrayList();
-
-        // Fragments cannot import packages.
-        if (!isFragment(b))
-        {
-            // Get package admin service.
-            PackageAdmin pa = Util.getService(bc, PackageAdmin.class, refs);
-            if (pa == null)
-            {
-                System.out.println("PackageAdmin service is unavailable.");
-            }
-            else
-            {
-                ExportedPackage[] exports = pa.getExportedPackages((Bundle) null);
-                if (exports != null)
-                {
-                    for (ExportedPackage ep : exports)
-                    {
-                        Bundle[] importers = ep.getImportingBundles();
-                        if (importers != null)
-                        {
-                            for (Bundle importer : importers)
-                            {
-                                if (importer == b)
-                                {
-                                    matches = true;
-                                    System.out.println(
-                                        LEGACY_PACKAGE_NAMESPACE
-                                        + "; "
-                                        + ep.getName()
-                                        + " resolved by:");
-                                    System.out.println(
-                                        "   "
-                                        + ep.getName()
-                                        + "; "
-                                        + ep.getVersion().toString()
-                                        + " from "
-                                        + ep.getExportingBundle());
-                                }
-                            }
-                        }
-                    }
-                }
-            }
-        }
-
-        Util.ungetServices(bc, refs);
-
-        return matches;
-    }
-
-    public static boolean printRequiringBundles(BundleContext bc, Bundle b)
-    {
-        boolean matches = false;
-
-        // Keep track of service references.
-        List<ServiceReference> refs = new ArrayList();
-
-        // Fragments cannot be required.
-        if (!isFragment(b))
-        {
-            // Get package admin service.
-            PackageAdmin pa = Util.getService(bc, PackageAdmin.class, refs);
-            if (pa == null)
-            {
-                System.out.println("PackageAdmin service is unavailable.");
-            }
-            else
-            {
-                try
-                {
-                    RequiredBundle[] rbs = pa.getRequiredBundles(b.getSymbolicName());
-                    if (rbs != null)
-                    {
-                        for (RequiredBundle rb : rbs)
-                        {
-                            if (rb.getBundle() == b)
-                            {
-                                Bundle[] requires = rb.getRequiringBundles();
-                                if ((requires != null) && (requires.length > 0))
-                                {
-                                    matches = true;
-                                    System.out.println(
-                                        LEGACY_BUNDLE_NAMESPACE
-                                        + "; "
-                                        + b.getSymbolicName()
-                                        + "; "
-                                        + b.getVersion().toString()
-                                        + " required by:");
-                                    for (Bundle requirer : requires)
-                                    {
-                                        System.out.println("   " + requirer);
-                                    }
-                                }
-                            }
-                        }
-                    }
-
-                    if (!matches)
-                    {
-                        matches = true;
-                        System.out.println(
-                            LEGACY_BUNDLE_NAMESPACE
-                            + "; "
-                            + b.getSymbolicName()
-                            + "; "
-                            + b.getVersion().toString()
-                            + " "
-                            + UNUSED_MESSAGE);
-                    }
-
-                }
-                catch (Exception ex)
-                {
-                    System.err.println(ex.toString());
-                }
-            }
-        }
-
-        Util.ungetServices(bc, refs);
-
-        return matches;
-    }
-
-    private static boolean printRequiredBundles(BundleContext bc, Bundle b)
-    {
-        boolean matches = false;
-
-        // Keep track of service references.
-        List<ServiceReference> refs = new ArrayList();
-
-        // Fragments cannot require bundles.
-        if (!isFragment(b))
-        {
-            // Get package admin service.
-            PackageAdmin pa = Util.getService(bc, PackageAdmin.class, refs);
-            if (pa == null)
-            {
-                System.out.println("PackageAdmin service is unavailable.");
-            }
-            else
-            {
-                RequiredBundle[] rbs = pa.getRequiredBundles(null);
-                if (rbs != null)
-                {
-                    for (RequiredBundle rb : rbs)
-                    {
-                        Bundle[] requirers = rb.getRequiringBundles();
-                        if (requirers != null)
-                        {
-                            for (Bundle requirer : requirers)
-                            {
-                                if (requirer == b)
-                                {
-                                    matches = true;
-                                    System.out.println(
-                                        LEGACY_BUNDLE_NAMESPACE
-                                        + "; "
-                                        + rb.getSymbolicName()
-                                        + " resolved by:");
-                                    System.out.println("   " + rb.getBundle());
-                                }
-                            }
-                        }
-                    }
-                }
-            }
-        }
-
-        Util.ungetServices(bc, refs);
-
-        return matches;
-    }
-
-    public static boolean printHostedFragments(BundleContext bc, Bundle b)
-    {
-        boolean matches = false;
-
-        // Keep track of service references.
-        List<ServiceReference> refs = new ArrayList();
-
-        // Get package admin service.
-        PackageAdmin pa = Util.getService(bc, PackageAdmin.class, refs);
-        if (pa == null)
-        {
-            System.out.println("PackageAdmin service is unavailable.");
-        }
-        else
-        {
-            try
-            {
-                if (!isFragment(b))
-                {
-                    matches = true;
-                    Bundle[] fragments = pa.getFragments(b);
-                    if ((fragments != null) && (fragments.length > 0))
-                    {
-                        System.out.println(
-                            LEGACY_HOST_NAMESPACE
-                            + "; "
-                            + b.getSymbolicName()
-                            + "; "
-                            + b.getVersion().toString()
-                            + " required by:");
-                        for (Bundle fragment : fragments)
-                        {
-                            System.out.println("   " + fragment);
-                        }
-                    }
-                    else
-                    {
-                        System.out.println(
-                            LEGACY_HOST_NAMESPACE
-                            + "; "
-                            + b.getSymbolicName()
-                            + "; "
-                            + b.getVersion().toString()
-                            + " "
-                            + UNUSED_MESSAGE);
-                    }
-                }
-            }
-            catch (Exception ex)
-            {
-                System.err.println(ex.toString());
-            }
-
-            Util.ungetServices(bc, refs);
-        }
-
-        return matches;
-    }
-
-    public static boolean printFragmentHosts(BundleContext bc, Bundle b)
-    {
-        boolean matches = false;
-
-        // Keep track of service references.
-        List<ServiceReference> refs = new ArrayList();
-
-        // Get package admin service.
-        PackageAdmin pa = Util.getService(bc, PackageAdmin.class, refs);
-        if (pa == null)
-        {
-            System.out.println("PackageAdmin service is unavailable.");
-        }
-        else
-        {
-            try
-            {
-                if (isFragment(b))
-                {
-                    matches = true;
-
-                    Bundle[] hosts = pa.getHosts(b);
-                    if ((hosts != null) && (hosts.length > 0))
-                    {
-                        System.out.println(
-                            LEGACY_HOST_NAMESPACE
-                            + "; "
-                            + b.getHeaders().get(Constants.FRAGMENT_HOST)
-                            + " resolved by:");
-                        for (Bundle host : hosts)
-                        {
-                            System.out.println("   " + host);
-                        }
-                    }
-                    else
-                    {
-                        System.out.println(
-                            LEGACY_HOST_NAMESPACE
-                            + "; "
-                            + b.getHeaders().get(Constants.FRAGMENT_HOST)
-                            + " "
-                            + UNRESOLVED_MESSAGE);
-                    }
-                }
-            }
-            catch (Exception ex)
-            {
-                System.err.println(ex.toString());
-            }
-
-            Util.ungetServices(bc, refs);
-        }
-
-        return matches;
-    }
-
-    private static boolean matchNamespace(List<String> namespace, String actual)
-    {
-        return Util.compareSubstring(namespace, actual);
-    }
-
-    private static boolean isValidDirection(String direction)
-    {
-        return (CAPABILITY.startsWith(direction) || REQUIREMENT.startsWith(direction));
-    }
-
-    private static boolean isFragment(Bundle bundle)
-    {
-        return bundle.getHeaders().get(Constants.FRAGMENT_HOST) != null;
-    }
-}
\ No newline at end of file


=====================================
src/main/java/org/apache/felix/gogo/command/OBR.java deleted
=====================================
@@ -1,679 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.felix.gogo.command;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.PrintStream;
-import java.lang.reflect.Array;
-import java.net.URL;
-import java.util.Comparator;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.TreeMap;
-
-import org.apache.felix.bundlerepository.Capability;
-import org.apache.felix.bundlerepository.Reason;
-import org.apache.felix.bundlerepository.RepositoryAdmin;
-import org.apache.felix.bundlerepository.Requirement;
-import org.apache.felix.bundlerepository.Resolver;
-import org.apache.felix.bundlerepository.Resource;
-import org.apache.felix.service.command.Descriptor;
-import org.apache.felix.service.command.Parameter;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.framework.Version;
-import org.osgi.util.tracker.ServiceTracker;
-
-public class OBR
-{
-    private static final String REPO_ADD = "add";
-    private static final String REPO_REMOVE = "remove";
-    private static final String REPO_LIST = "list";
-    private static final String REPO_REFRESH = "refresh";
-
-    private static final char VERSION_SEPARATOR = '@';
-
-    private final BundleContext m_bc;
-    private final ServiceTracker m_tracker;
-
-    public OBR(BundleContext bc, ServiceTracker tracker)
-    {
-        m_bc = bc;
-        m_tracker = tracker;
-    }
-
-    private RepositoryAdmin getRepositoryAdmin()
-    {
-        Object svcObj;
-        try
-        {
-            svcObj = m_tracker.getService();
-        }
-        catch (Exception ex)
-        {
-            svcObj = null;
-        }
-        if (svcObj == null)
-        {
-            System.out.println("No repository admin service available");
-        }
-        return (RepositoryAdmin) svcObj;
-    }
-
-    @Descriptor("manage repositories")
-    public void repos(
-        @Descriptor("( add | list | refresh | remove )") String action,
-        @Descriptor("space-delimited list of repository URLs") String[] args)
-        throws IOException
-    {
-        Object svcObj = getRepositoryAdmin();
-        if (svcObj == null)
-        {
-            return;
-        }
-        RepositoryAdmin ra = (RepositoryAdmin) svcObj;
-
-        if (args.length > 0)
-        {
-            for (int i = 0; i < args.length; i++)
-            {
-                try
-                {
-                    if (action.equals(REPO_ADD))
-                    {
-                        ra.addRepository(args[i]);
-                    }
-                    else if (action.equals(REPO_REFRESH))
-                    {
-                        ra.removeRepository(args[i]);
-                        ra.addRepository(args[i]);
-                    }
-                    else if (action.equals(REPO_REMOVE))
-                    {
-                        ra.removeRepository(args[i]);
-                    }
-                    else
-                    {
-                        System.out.println("Unknown repository operation: " + action);
-                    }
-                }
-                catch (Exception ex)
-                {
-                    ex.printStackTrace(System.err);
-                }
-            }
-        }
-        else
-        {
-            org.apache.felix.bundlerepository.Repository[] repos =
-                ra.listRepositories();
-            if ((repos != null) && (repos.length > 0))
-            {
-                for (int i = 0; i < repos.length; i++)
-                {
-                    System.out.println(repos[i].getURI());
-                }
-            }
-            else
-            {
-                System.out.println("No repository URLs are set.");
-            }
-        }
-    }
-
-    @Descriptor("list repository resources")
-    public void list(
-        @Descriptor("display all versions")
-        @Parameter(names={ "-v", "--verbose" }, presentValue="true",
-            absentValue="false") boolean verbose,
-        @Descriptor("optional strings used for name matching") String[] args)
-        throws IOException, InvalidSyntaxException
-    {
-        Object svcObj = getRepositoryAdmin();
-        if (svcObj == null)
-        {
-            return;
-        }
-        RepositoryAdmin ra = (RepositoryAdmin) svcObj;
-
-        // Create a filter that will match presentation name or symbolic name.
-        StringBuffer sb = new StringBuffer();
-        if ((args == null) || (args.length == 0))
-        {
-            sb.append("(|(presentationname=*)(symbolicname=*))");
-        }
-        else
-        {
-            StringBuffer value = new StringBuffer();
-            for (int i = 0; i < args.length; i++)
-            {
-                if (i > 0)
-                {
-                    value.append(" ");
-                }
-                value.append(args[i]);
-            }
-            sb.append("(|(presentationname=*");
-            sb.append(value);
-            sb.append("*)(symbolicname=*");
-            sb.append(value);
-            sb.append("*))");
-        }
-        // Use filter to get matching resources.
-        Resource[] resources = ra.discoverResources(sb.toString());
-
-        // Group the resources by symbolic name in descending version order,
-        // but keep them in overall sorted order by presentation name.
-        Map revisionMap = new TreeMap(new Comparator() {
-            public int compare(Object o1, Object o2)
-            {
-                Resource r1 = (Resource) o1;
-                Resource r2 = (Resource) o2;
-                // Assume if the symbolic name is equal, then the two are equal,
-                // since we are trying to aggregate by symbolic name.
-                int symCompare = r1.getSymbolicName().compareTo(r2.getSymbolicName());
-                if (symCompare == 0)
-                {
-                    return 0;
-                }
-                // Otherwise, compare the presentation name to keep them sorted
-                // by presentation name. If the presentation names are equal, then
-                // use the symbolic name to differentiate.
-                int compare = (r1.getPresentationName() == null)
-                    ? -1
-                    : (r2.getPresentationName() == null)
-                        ? 1
-                        : r1.getPresentationName().compareToIgnoreCase(
-                            r2.getPresentationName());
-                if (compare == 0)
-                {
-                    return symCompare;
-                }
-                return compare;
-            }
-        });
-        for (int resIdx = 0; (resources != null) && (resIdx < resources.length); resIdx++)
-        {
-            Resource[] revisions = (Resource[]) revisionMap.get(resources[resIdx]);
-            revisionMap.put(resources[resIdx], addResourceByVersion(revisions, resources[resIdx]));
-        }
-
-        // Print any matching resources.
-        for (Iterator i = revisionMap.entrySet().iterator(); i.hasNext(); )
-        {
-            Map.Entry entry = (Map.Entry) i.next();
-            Resource[] revisions = (Resource[]) entry.getValue();
-            String name = revisions[0].getPresentationName();
-            name = (name == null) ? revisions[0].getSymbolicName() : name;
-            System.out.print(name);
-
-            if (verbose && revisions[0].getPresentationName() != null)
-            {
-                System.out.print(" [" + revisions[0].getSymbolicName() + "]");
-            }
-
-            System.out.print(" (");
-            int revIdx = 0;
-            do
-            {
-                if (revIdx > 0)
-                {
-                    System.out.print(", ");
-                }
-                System.out.print(revisions[revIdx].getVersion());
-                revIdx++;
-            }
-            while (verbose && (revIdx < revisions.length));
-            if (!verbose && (revisions.length > 1))
-            {
-                System.out.print(", ...");
-            }
-            System.out.println(")");
-        }
-
-        if ((resources == null) || (resources.length == 0))
-        {
-            System.out.println("No matching bundles.");
-        }
-    }
-
-    @Descriptor("retrieve resource description from repository")
-    public void info(
-        @Descriptor("( <bundle-name> | <symbolic-name> | <bundle-id> )[@<version>] ...")
-            String[] args)
-        throws IOException, InvalidSyntaxException
-    {
-        Object svcObj = getRepositoryAdmin();
-        if (svcObj == null)
-        {
-            return;
-        }
-        RepositoryAdmin ra = (RepositoryAdmin) svcObj;
-
-        for (int argIdx = 0; (args != null) && (argIdx < args.length); argIdx++)
-        {
-            // Find the target's bundle resource.
-            String targetName = args[argIdx];
-            String targetVersion = null;
-            int idx = args[argIdx].indexOf(VERSION_SEPARATOR);
-            if (idx > 0)
-            {
-                targetName = args[argIdx].substring(0, idx);
-                targetVersion = args[argIdx].substring(idx + 1);
-            }
-            Resource[] resources = searchRepository(ra, targetName, targetVersion);
-            if ((resources == null) || (resources.length == 0))
-            {
-                System.err.println("Unknown bundle and/or version: " + args[argIdx]);
-            }
-            else
-            {
-                for (int resIdx = 0; resIdx < resources.length; resIdx++)
-                {
-                    if (resIdx > 0)
-                    {
-                        System.out.println("");
-                    }
-                    printResource(System.out, resources[resIdx]);
-                }
-            }
-        }
-    }
-
-    @Descriptor("deploy resource from repository")
-    public void deploy(
-        @Descriptor("start deployed bundles")
-        @Parameter(names={ "-s", "--start" }, presentValue="true",
-            absentValue="false") boolean start,
-        @Descriptor("deploy required bundles only")
-        @Parameter(names={ "-ro", "--required-only" }, presentValue="true",
-            absentValue="false") boolean requiredOnly,
-        @Descriptor("( <bundle-name> | <symbolic-name> | <bundle-id> )[@<version>] ...")
-            String[] args)
-        throws IOException, InvalidSyntaxException
-    {
-        Object svcObj = getRepositoryAdmin();
-        if (svcObj == null)
-        {
-            return;
-        }
-        RepositoryAdmin ra = (RepositoryAdmin) svcObj;
-
-        Resolver resolver = ra.resolver();
-        for (int argIdx = 0; (args != null) && (argIdx < args.length); argIdx++)
-        {
-            // Find the target's bundle resource.
-            String targetName = args[argIdx];
-            String targetVersion = null;
-            int idx = args[argIdx].indexOf(VERSION_SEPARATOR);
-            if (idx > 0)
-            {
-                targetName = args[argIdx].substring(0, idx);
-                targetVersion = args[argIdx].substring(idx + 1);
-            }
-            Resource resource = selectNewestVersion(
-                searchRepository(ra, targetName, targetVersion));
-            if (resource != null)
-            {
-                resolver.add(resource);
-            }
-            else
-            {
-                System.err.println("Unknown bundle - " + args[argIdx]);
-            }
-        }
-
-        if ((resolver.getAddedResources() != null) &&
-            (resolver.getAddedResources().length > 0))
-        {
-            if (resolver.resolve())
-            {
-                System.out.println("Target resource(s):");
-                System.out.println(Util.getUnderlineString(19));
-                Resource[] resources = resolver.getAddedResources();
-                for (int resIdx = 0; (resources != null) && (resIdx < resources.length); resIdx++)
-                {
-                    System.out.println("   " + resources[resIdx].getPresentationName()
-                        + " (" + resources[resIdx].getVersion() + ")");
-                }
-                resources = resolver.getRequiredResources();
-                if ((resources != null) && (resources.length > 0))
-                {
-                    System.out.println("\nRequired resource(s):");
-                    System.out.println(Util.getUnderlineString(21));
-                    for (int resIdx = 0; resIdx < resources.length; resIdx++)
-                    {
-                        System.out.println("   " + resources[resIdx].getPresentationName()
-                            + " (" + resources[resIdx].getVersion() + ")");
-                    }
-                }
-                if (!requiredOnly)
-                {
-                    resources = resolver.getOptionalResources();
-                    if ((resources != null) && (resources.length > 0))
-                    {
-                        System.out.println("\nOptional resource(s):");
-                        System.out.println(Util.getUnderlineString(21));
-                        for (int resIdx = 0; resIdx < resources.length; resIdx++)
-                        {
-                            System.out.println("   " + resources[resIdx].getPresentationName()
-                                + " (" + resources[resIdx].getVersion() + ")");
-                        }
-                    }
-                }
-
-                try
-                {
-                    System.out.print("\nDeploying...\n");
-                    int options = 0;
-                    if (start)
-                    {
-                        options |= Resolver.START;
-                    }
-                    if (requiredOnly)
-                    {
-                        options |= Resolver.NO_OPTIONAL_RESOURCES;
-                    }
-                    resolver.deploy(options);
-                    System.out.println("done.");
-                }
-                catch (IllegalStateException ex)
-                {
-                    System.err.println(ex);
-                }
-            }
-            else
-            {
-                Reason[] reqs = resolver.getUnsatisfiedRequirements();
-                if ((reqs != null) && (reqs.length > 0))
-                {
-                    System.out.println("Unsatisfied requirement(s):");
-                    System.out.println(Util.getUnderlineString(27));
-                    for (int reqIdx = 0; reqIdx < reqs.length; reqIdx++)
-                    {
-                        System.out.println("   " + reqs[reqIdx].getRequirement().getFilter());
-                        System.out.println("      " + reqs[reqIdx].getResource().getPresentationName());
-                    }
-                }
-                else
-                {
-                    System.out.println("Could not resolve targets.");
-                }
-            }
-        }
-    }
-
-    @Descriptor("retrieve resource source code from repository")
-    public void source(
-        @Descriptor("extract source code")
-        @Parameter(names={ "-x", "--extract" }, presentValue="true",
-            absentValue="false") boolean extract,
-        @Descriptor("local target directory") File localDir,
-        @Descriptor("( <bundle-name> | <symbolic-name> | <bundle-id> )[@<version>] ...")
-            String[] args)
-        throws IOException, InvalidSyntaxException
-    {
-        Object svcObj = getRepositoryAdmin();
-        if (svcObj == null)
-        {
-            return;
-        }
-        RepositoryAdmin ra = (RepositoryAdmin) svcObj;
-
-        for (int argIdx = 0; argIdx < args.length; argIdx++)
-        {
-            // Find the target's bundle resource.
-            String targetName = args[argIdx];
-            String targetVersion = null;
-            int idx = args[argIdx].indexOf(VERSION_SEPARATOR);
-            if (idx > 0)
-            {
-                targetName = args[argIdx].substring(0, idx);
-                targetVersion = args[argIdx].substring(idx + 1);
-            }
-            Resource resource = selectNewestVersion(
-                searchRepository(ra, targetName, targetVersion));
-            if (resource == null)
-            {
-                System.err.println("Unknown bundle and/or version: " + args[argIdx]);
-            }
-            else
-            {
-                String srcURI = (String) resource.getProperties().get(Resource.SOURCE_URI);
-                if (srcURI != null)
-                {
-                    Util.downloadSource(
-                        System.out, System.err, new URL(srcURI),
-                        localDir, extract);
-                }
-                else
-                {
-                    System.err.println("Missing source URL: " + args[argIdx]);
-                }
-            }
-        }
-    }
-
-    @Descriptor("retrieve resource JavaDoc from repository")
-    public void javadoc(
-        @Descriptor("extract documentation")
-        @Parameter(names={"-x", "--extract" }, presentValue="true",
-            absentValue="false") boolean extract,
-        @Descriptor("local target directory") File localDir,
-        @Descriptor("( <bundle-name> | <symbolic-name> | <bundle-id> )[@<version>] ...")
-            String[] args)
-        throws IOException, InvalidSyntaxException
-    {
-        Object svcObj = getRepositoryAdmin();
-        if (svcObj == null)
-        {
-            return;
-        }
-        RepositoryAdmin ra = (RepositoryAdmin) svcObj;
-
-        for (int argIdx = 0; argIdx < args.length; argIdx++)
-        {
-            // Find the target's bundle resource.
-            String targetName = args[argIdx];
-            String targetVersion = null;
-            int idx = args[argIdx].indexOf(VERSION_SEPARATOR);
-            if (idx > 0)
-            {
-                targetName = args[argIdx].substring(0, idx);
-                targetVersion = args[argIdx].substring(idx + 1);
-            }
-            Resource resource = selectNewestVersion(
-                searchRepository(ra, targetName, targetVersion));
-            if (resource == null)
-            {
-                System.err.println("Unknown bundle and/or version: " + args[argIdx]);
-            }
-            else
-            {
-                URL docURL = (URL) resource.getProperties().get("javadoc");
-                if (docURL != null)
-                {
-                    Util.downloadSource(
-                        System.out, System.err, docURL, localDir, extract);
-                }
-                else
-                {
-                    System.err.println("Missing javadoc URL: " + args[argIdx]);
-                }
-            }
-        }
-    }
-
-    private Resource[] searchRepository(
-        RepositoryAdmin ra, String targetId, String targetVersion)
-        throws InvalidSyntaxException
-    {
-        // Try to see if the targetId is a bundle ID.
-        try
-        {
-            Bundle bundle = m_bc.getBundle(Long.parseLong(targetId));
-            if (bundle != null)
-            {
-                targetId = bundle.getSymbolicName();
-            }
-            else
-            {
-                return null;
-            }
-        }
-        catch (NumberFormatException ex)
-        {
-            // It was not a number, so ignore.
-        }
-
-        // The targetId may be a bundle name or a bundle symbolic name,
-        // so create the appropriate LDAP query.
-        StringBuffer sb = new StringBuffer("(|(presentationname=");
-        sb.append(targetId);
-        sb.append(")(symbolicname=");
-        sb.append(targetId);
-        sb.append("))");
-        if (targetVersion != null)
-        {
-            sb.insert(0, "(&");
-            sb.append("(version=");
-            sb.append(targetVersion);
-            sb.append("))");
-        }
-        return ra.discoverResources(sb.toString());
-    }
-
-    private Resource selectNewestVersion(Resource[] resources)
-    {
-        int idx = -1;
-        Version v = null;
-        for (int i = 0; (resources != null) && (i < resources.length); i++)
-        {
-            if (i == 0)
-            {
-                idx = 0;
-                v = resources[i].getVersion();
-            }
-            else
-            {
-                Version vtmp = resources[i].getVersion();
-                if (vtmp.compareTo(v) > 0)
-                {
-                    idx = i;
-                    v = vtmp;
-                }
-            }
-        }
-
-        return (idx < 0) ? null : resources[idx];
-    }
-
-    private void printResource(PrintStream out, Resource resource)
-    {
-        String presentationName = resource.getPresentationName();
-        if (presentationName == null)
-            presentationName = resource.getSymbolicName();
-
-        System.out.println(Util.getUnderlineString(presentationName.length()));
-        out.println(presentationName);
-        System.out.println(Util.getUnderlineString(presentationName.length()));
-
-        Map map = resource.getProperties();
-        for (Iterator iter = map.entrySet().iterator(); iter.hasNext(); )
-        {
-            Map.Entry entry = (Map.Entry) iter.next();
-            if (entry.getValue().getClass().isArray())
-            {
-                out.println(entry.getKey() + ":");
-                for (int j = 0; j < Array.getLength(entry.getValue()); j++)
-                {
-                    out.println("   " + Array.get(entry.getValue(), j));
-                }
-            }
-            else
-            {
-                out.println(entry.getKey() + ": " + entry.getValue());
-            }
-        }
-
-        Requirement[] reqs = resource.getRequirements();
-        if ((reqs != null) && (reqs.length > 0))
-        {
-            out.println("Requires:");
-            for (int i = 0; i < reqs.length; i++)
-            {
-                out.println("   " + reqs[i].getFilter());
-            }
-        }
-
-        Capability[] caps = resource.getCapabilities();
-        if ((caps != null) && (caps.length > 0))
-        {
-            out.println("Capabilities:");
-            for (int i = 0; i < caps.length; i++)
-            {
-                out.println("   " + caps[i].getPropertiesAsMap());
-            }
-        }
-    }
-
-    private static Resource[] addResourceByVersion(Resource[] revisions, Resource resource)
-    {
-        // We want to add the resource into the array of revisions
-        // in descending version sorted order (i.e., newest first)
-        Resource[] sorted = null;
-        if (revisions == null)
-        {
-            sorted = new Resource[] { resource };
-        }
-        else
-        {
-            Version version = resource.getVersion();
-            Version middleVersion = null;
-            int top = 0, bottom = revisions.length - 1, middle = 0;
-            while (top <= bottom)
-            {
-                middle = (bottom - top) / 2 + top;
-                middleVersion = revisions[middle].getVersion();
-                // Sort in reverse version order.
-                int cmp = middleVersion.compareTo(version);
-                if (cmp < 0)
-                {
-                    bottom = middle - 1;
-                }
-                else
-                {
-                    top = middle + 1;
-                }
-            }
-
-            // Ignore duplicates.
-            if ((top >= revisions.length) || (revisions[top] != resource))
-            {
-                sorted = new Resource[revisions.length + 1];
-                System.arraycopy(revisions, 0, sorted, 0, top);
-                System.arraycopy(revisions, top, sorted, top + 1, revisions.length - top);
-                sorted[top] = resource;
-            }
-        }
-        return sorted;
-    }
-}


=====================================
src/main/java/org/apache/felix/gogo/command/Util.java
=====================================
@@ -20,18 +20,16 @@ package org.apache.felix.gogo.command;
 
 import java.io.BufferedOutputStream;
 import java.io.File;
-import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.PrintStream;
-import java.net.URL;
-import java.net.URLConnection;
+import java.net.URI;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.jar.JarEntry;
 import java.util.jar.JarInputStream;
+
+import org.apache.felix.service.command.CommandSession;
 import org.osgi.framework.Bundle;
 import org.osgi.framework.BundleContext;
 import org.osgi.framework.Constants;
@@ -39,11 +37,15 @@ import org.osgi.framework.ServiceReference;
 
 public class Util
 {
+
+
+    static final String CWD = "_cwd";
+
     public static String getBundleName(Bundle bundle)
     {
         if (bundle != null)
         {
-            String name = (String) bundle.getHeaders().get(Constants.BUNDLE_NAME);
+            String name = bundle.getHeaders().get(Constants.BUNDLE_NAME);
             return (name == null)
                 ? "Bundle " + Long.toString(bundle.getBundleId())
                 : name + " (" + Long.toString(bundle.getBundleId()) + ")";
@@ -83,7 +85,7 @@ public class Util
                     {
                         m_sb.append(", ");
                     }
-                    m_sb.append(array[i].toString());
+                    m_sb.append(array[i]);
                 }
                 return m_sb.toString();
             }
@@ -105,11 +107,11 @@ public class Util
             }
             else if (obj instanceof Double)
             {
-                return ((Double) obj).toString();
+                return obj.toString();
             }
             else if (obj instanceof Float)
             {
-                return ((Float) obj).toString();
+                return obj.toString();
             }
             else if (obj == null)
             {
@@ -123,14 +125,15 @@ public class Util
     }
 
     public static <T> T getService(
-        BundleContext bc, Class<T> clazz, List<ServiceReference> refs)
+        BundleContext bc, Class<T> clazz, List<ServiceReference<?>> refs)
     {
-        ServiceReference ref = bc.getServiceReference(clazz.getName());
+        @SuppressWarnings("unchecked")
+        ServiceReference<T> ref = (ServiceReference<T>) bc.getServiceReference(clazz.getName());
         if (ref == null)
         {
             return null;
         }
-        T t = (T) bc.getService(ref);
+        T t = bc.getService(ref);
         if (t != null)
         {
             refs.add(ref);
@@ -138,7 +141,7 @@ public class Util
         return t;
     }
 
-    public static void ungetServices(BundleContext bc, List<ServiceReference> refs)
+    public static void ungetServices(BundleContext bc, List<ServiceReference<?>> refs)
     {
         while (refs.size() > 0)
         {
@@ -146,67 +149,6 @@ public class Util
         }
     }
 
-    public static void downloadSource(
-        PrintStream out, PrintStream err,
-        URL srcURL, File localDir, boolean extract)
-    {
-        // Get the file name from the URL.
-        String fileName = (srcURL.getFile().lastIndexOf('/') > 0)
-            ? srcURL.getFile().substring(srcURL.getFile().lastIndexOf('/') + 1)
-            : srcURL.getFile();
-
-        try
-        {
-            out.println("Connecting...");
-
-            if (!localDir.exists())
-            {
-                err.println("Destination directory does not exist.");
-            }
-            File file = new File(localDir, fileName);
-
-            OutputStream os = new FileOutputStream(file);
-            URLConnection conn = srcURL.openConnection();
-            Util.setProxyAuth(conn);
-            int total = conn.getContentLength();
-            InputStream is = conn.getInputStream();
-
-            if (total > 0)
-            {
-                out.println("Downloading " + fileName
-                    + " ( " + total + " bytes ).");
-            }
-            else
-            {
-                out.println("Downloading " + fileName + ".");
-            }
-            byte[] buffer = new byte[4096];
-            int count = 0;
-            for (int len = is.read(buffer); len > 0; len = is.read(buffer))
-            {
-                count += len;
-                os.write(buffer, 0, len);
-            }
-
-            os.close();
-            is.close();
-
-            if (extract)
-            {
-                is = new FileInputStream(file);
-                JarInputStream jis = new JarInputStream(is);
-                out.println("Extracting...");
-                unjar(jis, localDir);
-                jis.close();
-                file.delete();
-            }
-        }
-        catch (Exception ex)
-        {
-            err.println(ex);
-        }
-    }
-
     public static void unjar(JarInputStream jis, File dir)
         throws IOException
     {
@@ -288,40 +230,10 @@ public class Util
         bos.close();
     }
 
-    public static void setProxyAuth(URLConnection conn) throws IOException
-    {
-        // Support for http proxy authentication
-        String auth = System.getProperty("http.proxyAuth");
-        if ((auth != null) && (auth.length() > 0))
-        {
-            if ("http".equals(conn.getURL().getProtocol())
-                || "https".equals(conn.getURL().getProtocol()))
-            {
-                String base64 = Base64Encoder.base64Encode(auth);
-                conn.setRequestProperty("Proxy-Authorization", "Basic " + base64);
-            }
-        }
-    }
-
-    public static InputStream openURL(final URL url) throws IOException
-    {
-        // Do it the manual way to have a chance to
-        // set request properties as proxy auth (EW).
-        return openURL(url.openConnection());
-    }
-
-    public static InputStream openURL(final URLConnection conn) throws IOException
-    {
-        // Do it the manual way to have a chance to
-        // set request properties as proxy auth (EW).
-        setProxyAuth(conn);
-        return conn.getInputStream();
-    }
-
     public static List<String> parseSubstring(String value)
     {
-        List<String> pieces = new ArrayList();
-        StringBuffer ss = new StringBuffer();
+        List<String> pieces = new ArrayList<>();
+        StringBuilder ss = new StringBuilder();
         // int kind = SIMPLE; // assume until proven otherwise
         boolean wasStar = false; // indicates last piece was a star
         boolean leftstar = false; // track if the initial piece is a star
@@ -408,7 +320,7 @@ loop:   for (;;)
 
     public static String unparseSubstring(List<String> pieces)
     {
-        StringBuffer sb = new StringBuffer();
+        StringBuilder sb = new StringBuilder();
         for (int i = 0; i < pieces.size(); i++)
         {
             if (i > 0)
@@ -462,14 +374,7 @@ loop:   for (int i = 0; i < len; i++)
             // string ends with it.
             if (i == len - 1)
             {
-                if (s.endsWith(piece))
-                {
-                    result = true;
-                }
-                else
-                {
-                    result = false;
-                }
+                result = s.endsWith(piece);
                 break loop;
             }
 
@@ -491,4 +396,29 @@ loop:   for (int i = 0; i < len; i++)
 
         return result;
     }
-}
\ No newline at end of file
+
+    /**
+     * Intepret a string as a URI relative to the current working directory.
+     * @param session the session (where the CWD is stored)
+     * @param relativeUri the input URI
+     * @return the resulting URI as a string
+     * @throws IOException
+     */
+    public static String resolveUri(CommandSession session, String relativeUri) throws IOException
+    {
+        File cwd = (File) session.get(CWD);
+        if (cwd == null)
+        {
+            cwd = new File("").getCanonicalFile();
+            session.put(CWD, cwd);
+        }
+        if ((relativeUri == null) || (relativeUri.length() == 0))
+        {
+            return relativeUri;
+        }
+
+        URI curUri = cwd.toURI();
+        URI newUri = curUri.resolve(relativeUri);
+        return newUri.toString();
+    }
+}


=====================================
src/main/java/org/apache/felix/gogo/command/package-info.java
=====================================
@@ -0,0 +1,32 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+ at org.osgi.annotation.bundle.Capability(
+    namespace = "org.apache.felix.gogo",
+    name = "command.implementation",
+    version = "1.0.0"
+)
+ at org.osgi.annotation.bundle.Requirement(
+    effective = "active",
+    namespace = "org.apache.felix.gogo",
+    name = "runtime.implementation",
+    version = "1.0.0"
+)
+package org.apache.felix.gogo.command;
+


=====================================
src/test/java/org/apache/felix/gogo/command/UtilTest.java
=====================================
@@ -0,0 +1,49 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.felix.gogo.command;
+
+import org.apache.felix.service.command.CommandSession;
+import org.junit.Test;
+
+import java.io.File;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ *
+ */
+public class UtilTest {
+
+    @Test
+    public void relativeUri() throws Exception {
+        CommandSession session = mock(CommandSession.class);
+        when(session.get(Util.CWD)).thenReturn(null); // start with no CWD
+        String u = Util.resolveUri(session, "three");
+        assertEquals(new File(new File("").getAbsoluteFile(), "three").toURI().toString(), u);
+
+        when(session.get(Util.CWD)).thenReturn(new File(".").getCanonicalFile());
+        u = Util.resolveUri(session, "file:/a/b/c");
+        assertEquals("file:/a/b/c", u);
+        u = Util.resolveUri(session, "three");
+        assertEquals(new File("./three").getCanonicalFile().toURI().toString(), u);
+    }
+}



View it on GitLab: https://salsa.debian.org/java-team/felix-gogo-command/-/compare/b2c7c62a3dbf7b57e81e69b241d64c558c093711...c2baf491c064b39fc22c633cac658855e0d8191d

-- 
View it on GitLab: https://salsa.debian.org/java-team/felix-gogo-command/-/compare/b2c7c62a3dbf7b57e81e69b241d64c558c093711...c2baf491c064b39fc22c633cac658855e0d8191d
You're receiving this email because of your account on salsa.debian.org. Manage all notifications: https://salsa.debian.org/-/profile/notifications | Help: https://salsa.debian.org/help


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://alioth-lists.debian.net/pipermail/pkg-java-commits/attachments/20261120/6db87a16/attachment.htm>


More information about the pkg-java-commits mailing list