You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@karaf.apache.org by cs...@apache.org on 2014/02/24 11:28:07 UTC

[09/11] KARAF-2772 Extracting command-api

http://git-wip-us.apache.org/repos/asf/karaf/blob/1ee78df9/shell/command-api/src/main/java/org/apache/karaf/shell/commands/converter/DefaultConverter.java
----------------------------------------------------------------------
diff --git a/shell/command-api/src/main/java/org/apache/karaf/shell/commands/converter/DefaultConverter.java b/shell/command-api/src/main/java/org/apache/karaf/shell/commands/converter/DefaultConverter.java
new file mode 100644
index 0000000..54fe81a
--- /dev/null
+++ b/shell/command-api/src/main/java/org/apache/karaf/shell/commands/converter/DefaultConverter.java
@@ -0,0 +1,401 @@
+/*
+ * 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.karaf.shell.commands.converter;
+
+import java.util.Collection;
+import java.util.Map;
+import java.util.Dictionary;
+import java.util.Locale;
+import java.util.Properties;
+import java.util.Hashtable;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.SortedMap;
+import java.util.TreeMap;
+import java.util.LinkedHashMap;
+import java.util.SortedSet;
+import java.util.TreeSet;
+import java.util.Set;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.ArrayList;
+import java.util.Queue;
+import java.util.LinkedList;
+import java.util.regex.Pattern;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.ConcurrentHashMap;
+import java.math.BigInteger;
+import java.math.BigDecimal;
+import java.io.ByteArrayInputStream;
+import java.lang.reflect.Modifier;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Array;
+import java.lang.reflect.Type;
+import java.lang.reflect.InvocationTargetException;
+
+public class DefaultConverter
+{
+
+    private Object loader;
+
+    public DefaultConverter(Object loader) {
+        this.loader = loader;
+    }
+
+    public Object convert(Object source, Type target) throws Exception {
+        return convert( source, new GenericType(target));
+    }
+
+    public Object convert(Object fromValue, ReifiedType type) throws Exception {
+        // Discard null values
+        if (fromValue == null) {
+            return null;
+        }
+        // If the object is an instance of the type, just return it
+        if (isAssignable(fromValue, type)) {
+            return fromValue;
+        }
+        Object value = convertWithConverters(fromValue, type);
+        if (value == null) {
+            if (fromValue instanceof Number && Number.class.isAssignableFrom(unwrap(toClass(type)))) {
+                return convertToNumber((Number) fromValue, toClass(type));
+            } else if (fromValue instanceof String) {
+                return convertFromString((String) fromValue, toClass(type), loader);
+            } else if (toClass(type).isArray() && (fromValue instanceof Collection || fromValue.getClass().isArray())) {
+                return convertToArray(fromValue, type);
+            } else if (Map.class.isAssignableFrom(toClass(type)) && (fromValue instanceof Map || fromValue instanceof Dictionary)) {
+                return convertToMap(fromValue, type);
+            } else if (Dictionary.class.isAssignableFrom(toClass(type)) && (fromValue instanceof Map || fromValue instanceof Dictionary)) {
+                return convertToDictionary(fromValue, type);
+            } else if (Collection.class.isAssignableFrom(toClass(type)) && (fromValue instanceof Collection || fromValue.getClass().isArray())) {
+                return convertToCollection(fromValue, type);
+            } else {
+                throw new Exception("Unable to convert value " + fromValue + " to type " + type);
+            }
+        }
+        return value;
+    }
+
+    private Object convertWithConverters(Object source, ReifiedType type) throws Exception {
+        Object value = null;
+//        for (Converter converter : converters) {
+//            if (converter.canConvert(source, type)) {
+//                value = converter.convert(source, type);
+//                if (value != null) {
+//                    return value;
+//                }
+//            }
+//        }
+        return value;
+    }
+
+    public Object convertToNumber(Number value, Class toType) throws Exception {
+        toType = unwrap(toType);
+        if (AtomicInteger.class == toType) {
+            return new AtomicInteger((Integer) convertToNumber(value, Integer.class));
+        } else if (AtomicLong.class == toType) {
+            return new AtomicLong((Long) convertToNumber(value, Long.class));
+        } else if (Integer.class == toType) {
+            return value.intValue();
+        } else if (Short.class == toType) {
+            return value.shortValue();
+        } else if (Long.class == toType) {
+            return value.longValue();
+        } else if (Float.class == toType) {
+            return value.floatValue();
+        } else if (Double.class == toType) {
+            return value.doubleValue();
+        } else if (Byte.class == toType) {
+            return value.byteValue();
+        } else if (BigInteger.class == toType) {
+            return new BigInteger(value.toString());
+        } else if (BigDecimal.class == toType) {
+            return new BigDecimal(value.toString());
+        } else {
+            throw new Exception("Unable to convert number " + value + " to " + toType);
+        }
+    }
+
+    public Object convertFromString(String value, Class toType, Object loader) throws Exception {
+        toType = unwrap(toType);
+        if (ReifiedType.class == toType) {
+            try {
+                return GenericType.parse(value, loader);
+            } catch (ClassNotFoundException e) {
+                throw new Exception("Unable to convert", e);
+            }
+        } else if (Class.class == toType) {
+            try {
+                return GenericType.parse(value, loader).getRawClass();
+            } catch (ClassNotFoundException e) {
+                throw new Exception("Unable to convert", e);
+            }
+        } else if (Locale.class == toType) {
+            String[] tokens = value.split("_");
+            if (tokens.length == 1) {
+                return new Locale(tokens[0]);
+            } else if (tokens.length == 2) {
+                return new Locale(tokens[0], tokens[1]);
+            } else if (tokens.length == 3) {
+                return new Locale(tokens[0], tokens[1], tokens[2]);
+            } else {
+                throw new Exception("Invalid locale string:" + value);
+            }
+        } else if (Pattern.class == toType) {
+            return Pattern.compile(value);
+        } else if (Properties.class == toType) {
+            Properties props = new Properties();
+            ByteArrayInputStream in = new ByteArrayInputStream(value.getBytes("UTF8"));
+            props.load(in);
+            return props;
+        } else if (Boolean.class == toType) {
+            if ("yes".equalsIgnoreCase(value) || "true".equalsIgnoreCase(value) || "on".equalsIgnoreCase(value)) {
+                return Boolean.TRUE;
+            } else if ("no".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value) || "off".equalsIgnoreCase(value)) {
+                return Boolean.FALSE;
+            } else {
+                throw new RuntimeException("Invalid boolean value: " + value);
+            }
+        } else if (Integer.class == toType) {
+            return Integer.valueOf(value);
+        } else if (Short.class == toType) {
+            return Short.valueOf(value);
+        } else if (Long.class == toType) {
+            return Long.valueOf(value);
+        } else if (Float.class == toType) {
+            return Float.valueOf(value);
+        } else if (Double.class == toType) {
+            return Double.valueOf(value);
+        } else if (Character.class == toType) {
+            if (value.length() == 6 && value.startsWith("\\u")) {
+                int code = Integer.parseInt(value.substring(2), 16);
+                return (char)code;
+            } else if (value.length() == 1) {
+                return value.charAt(0);
+            } else {
+                throw new Exception("Invalid value for character type: " + value);
+            }
+        } else if (Byte.class == toType) {
+            return Byte.valueOf(value);
+        } else if (Enum.class.isAssignableFrom(toType)) {
+            return Enum.valueOf((Class<Enum>) toType, value);
+        } else {
+            return createObject(value, toType);
+        }
+    }
+
+    private static Object createObject(String value, Class type) throws Exception {
+        if (type.isInterface() || Modifier.isAbstract(type.getModifiers())) {
+            throw new Exception("Unable to convert value " + value + " to type " + type + ". Type " + type + " is an interface or an abstract class");
+        }
+        Constructor constructor = null;
+        try {
+            constructor = type.getConstructor(String.class);
+        } catch (NoSuchMethodException e) {
+            throw new RuntimeException("Unable to convert to " + type);
+        }
+        try {
+            return constructor.newInstance(value);
+        } catch (Exception e) {
+            throw new Exception("Unable to convert ", getRealCause(e));
+        }
+    }
+
+    private static Throwable getRealCause(Throwable t) {
+        if (t instanceof InvocationTargetException && t.getCause() != null) {
+            return t.getCause();
+        }
+        return t;
+    }
+
+    private Object convertToCollection(Object obj, ReifiedType type) throws Exception {
+        ReifiedType valueType = type.getActualTypeArgument(0);
+        Collection newCol = (Collection) getCollection(toClass(type)).newInstance();
+        if (obj.getClass().isArray()) {
+            for (int i = 0; i < Array.getLength(obj); i++) {
+                try {
+                    newCol.add(convert(Array.get(obj, i), valueType));
+                } catch (Exception t) {
+                    throw new Exception("Unable to convert from " + obj + " to " + type + "(error converting array element)", t);
+                }
+            }
+        } else {
+            for (Object item : (Collection) obj) {
+                try {
+                    newCol.add(convert(item, valueType));
+                } catch (Exception t) {
+                    throw new Exception("Unable to convert from " + obj + " to " + type + "(error converting collection entry)", t);
+                }
+            }
+        }
+        return newCol;
+    }
+
+    private Object convertToDictionary(Object obj, ReifiedType type) throws Exception {
+        ReifiedType keyType = type.getActualTypeArgument(0);
+        ReifiedType valueType = type.getActualTypeArgument(1);
+        Dictionary newDic = new Hashtable();
+        if (obj instanceof Dictionary) {
+            Dictionary dic = (Dictionary) obj;
+            for (Enumeration keyEnum = dic.keys(); keyEnum.hasMoreElements();) {
+                Object key = keyEnum.nextElement();
+                try {
+                    newDic.put(convert(key, keyType), convert(dic.get(key), valueType));
+                } catch (Exception t) {
+                    throw new Exception("Unable to convert from " + obj + " to " + type + "(error converting map entry)", t);
+                }
+            }
+        } else {
+            for (Map.Entry e : ((Map<Object,Object>) obj).entrySet()) {
+                try {
+                    newDic.put(convert(e.getKey(), keyType), convert(e.getValue(), valueType));
+                } catch (Exception t) {
+                    throw new Exception("Unable to convert from " + obj + " to " + type + "(error converting map entry)", t);
+                }
+            }
+        }
+        return newDic;
+    }
+
+    private Object convertToMap(Object obj, ReifiedType type) throws Exception {
+        ReifiedType keyType = type.getActualTypeArgument(0);
+        ReifiedType valueType = type.getActualTypeArgument(1);
+        Map newMap = (Map) getMap(toClass(type)).newInstance();
+        if (obj instanceof Dictionary) {
+            Dictionary dic = (Dictionary) obj;
+            for (Enumeration keyEnum = dic.keys(); keyEnum.hasMoreElements();) {
+                Object key = keyEnum.nextElement();
+                try {
+                    newMap.put(convert(key, keyType), convert(dic.get(key), valueType));
+                } catch (Exception t) {
+                    throw new Exception("Unable to convert from " + obj + " to " + type + "(error converting map entry)", t);
+                }
+            }
+        } else {
+            for (Map.Entry e : ((Map<Object,Object>) obj).entrySet()) {
+                try {
+                    newMap.put(convert(e.getKey(), keyType), convert(e.getValue(), valueType));
+                } catch (Exception t) {
+                    throw new Exception("Unable to convert from " + obj + " to " + type + "(error converting map entry)", t);
+                }
+            }
+        }
+        return newMap;
+    }
+
+    private Object convertToArray(Object obj, ReifiedType type) throws Exception {
+        if (obj instanceof Collection) {
+            obj = ((Collection) obj).toArray();
+        }
+        if (!obj.getClass().isArray()) {
+            throw new Exception("Unable to convert from " + obj + " to " + type);
+        }
+        ReifiedType componentType;
+        if (type.size() > 0) {
+            componentType = type.getActualTypeArgument(0);
+        } else {
+            componentType = new GenericType(type.getRawClass().getComponentType());
+        }
+        Object array = Array.newInstance(toClass(componentType), Array.getLength(obj));
+        for (int i = 0; i < Array.getLength(obj); i++) {
+            try {
+                Array.set(array, i, convert(Array.get(obj, i), componentType));
+            } catch (Exception t) {
+                throw new Exception("Unable to convert from " + obj + " to " + type + "(error converting array element)", t);
+            }
+        }
+        return array;
+    }
+
+    public static boolean isAssignable(Object source, ReifiedType target) {
+        return source == null
+                || (target.size() == 0
+                    && unwrap(target.getRawClass()).isAssignableFrom(unwrap(source.getClass())));
+    }
+
+    private static Class unwrap(Class c) {
+        Class u = primitives.get(c);
+        return u != null ? u : c;
+    }
+
+    private static Class getMap(Class type) {
+        if (hasDefaultConstructor(type)) {
+            return type;
+        } else if (SortedMap.class.isAssignableFrom(type)) {
+            return TreeMap.class;
+        } else if (ConcurrentMap.class.isAssignableFrom(type)) {
+            return ConcurrentHashMap.class;
+        } else {
+            return LinkedHashMap.class;
+        }
+    }
+
+    private static Class getCollection(Class type) {
+        if (hasDefaultConstructor(type)) {
+            return type;
+        } else if (SortedSet.class.isAssignableFrom(type)) {
+            return TreeSet.class;
+        } else if (Set.class.isAssignableFrom(type)) {
+            return LinkedHashSet.class;
+        } else if (List.class.isAssignableFrom(type)) {
+            return ArrayList.class;
+        } else if (Queue.class.isAssignableFrom(type)) {
+            return LinkedList.class;
+        } else {
+            return ArrayList.class;
+        }
+    }
+
+    private static boolean hasDefaultConstructor(Class type) {
+        if (!Modifier.isPublic(type.getModifiers())) {
+            return false;
+        }
+        if (Modifier.isAbstract(type.getModifiers())) {
+            return false;
+        }
+        Constructor[] constructors = type.getConstructors();
+        for (Constructor constructor : constructors) {
+            if (Modifier.isPublic(constructor.getModifiers()) &&
+                    constructor.getParameterTypes().length == 0) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private static final Map<Class, Class> primitives;
+    static {
+        primitives = new HashMap<Class, Class>();
+        primitives.put(byte.class, Byte.class);
+        primitives.put(short.class, Short.class);
+        primitives.put(char.class, Character.class);
+        primitives.put(int.class, Integer.class);
+        primitives.put(long.class, Long.class);
+        primitives.put(float.class, Float.class);
+        primitives.put(double.class, Double.class);
+        primitives.put(boolean.class, Boolean.class);
+    }
+
+    private Class toClass(ReifiedType type) {
+        return type.getRawClass();
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/karaf/blob/1ee78df9/shell/command-api/src/main/java/org/apache/karaf/shell/commands/converter/GenericType.java
----------------------------------------------------------------------
diff --git a/shell/command-api/src/main/java/org/apache/karaf/shell/commands/converter/GenericType.java b/shell/command-api/src/main/java/org/apache/karaf/shell/commands/converter/GenericType.java
new file mode 100644
index 0000000..2f2b5e0
--- /dev/null
+++ b/shell/command-api/src/main/java/org/apache/karaf/shell/commands/converter/GenericType.java
@@ -0,0 +1,195 @@
+/*
+ * 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.karaf.shell.commands.converter;
+
+import java.lang.reflect.Array;
+import java.lang.reflect.GenericArrayType;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.lang.reflect.TypeVariable;
+import java.lang.reflect.WildcardType;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.osgi.framework.Bundle;
+
+public class GenericType extends ReifiedType {
+
+	private static final GenericType[] EMPTY = new GenericType[0];
+
+    private static final Map<String, Class> primitiveClasses = new HashMap<String, Class>();
+
+    static {
+        primitiveClasses.put("int", int.class);
+        primitiveClasses.put("short", short.class);
+        primitiveClasses.put("long", long.class);
+        primitiveClasses.put("byte", byte.class);
+        primitiveClasses.put("char", char.class);
+        primitiveClasses.put("float", float.class);
+        primitiveClasses.put("double", double.class);
+        primitiveClasses.put("boolean", boolean.class);
+    }
+
+    private GenericType[] parameters;
+
+	public GenericType(Type type) {
+		this(getConcreteClass(type), parametersOf(type));
+	}
+
+    public GenericType(Class clazz, GenericType... parameters) {
+        super(clazz);
+        this.parameters = parameters;
+    }
+
+    public static GenericType parse(String type, Object loader) throws ClassNotFoundException, IllegalArgumentException {
+        type = type.trim();
+        // Check if this is an array
+        if (type.endsWith("[]")) {
+            GenericType t = parse(type.substring(0, type.length() - 2), loader);
+            return new GenericType(Array.newInstance(t.getRawClass(), 0).getClass(), t);
+        }
+        // Check if this is a generic
+        int genericIndex = type.indexOf('<');
+        if (genericIndex > 0) {
+            if (!type.endsWith(">")) {
+                throw new IllegalArgumentException("Can not load type: " + type);
+            }
+            GenericType base = parse(type.substring(0, genericIndex), loader);
+            String[] params = type.substring(genericIndex + 1, type.length() - 1).split(",");
+            GenericType[] types = new GenericType[params.length];
+            for (int i = 0; i < params.length; i++) {
+                types[i] = parse(params[i], loader);
+            }
+            return new GenericType(base.getRawClass(), types);
+        }
+        // Primitive
+        if (primitiveClasses.containsKey(type)) {
+            return new GenericType(primitiveClasses.get(type));
+        }
+        // Class
+        if (loader instanceof ClassLoader) {
+            return new GenericType(((ClassLoader) loader).loadClass(type));
+        } else if (loader instanceof Bundle) {
+            return new GenericType(((Bundle) loader).loadClass(type));
+        } else {
+            throw new IllegalArgumentException("Unsupported loader: " + loader);
+        }
+    }
+
+    @Override
+    public ReifiedType getActualTypeArgument(int i) {
+        if (parameters.length == 0) {
+            return super.getActualTypeArgument(i);
+        }
+        return parameters[i];
+    }
+
+    @Override
+    public int size() {
+        return parameters.length;
+    }
+
+    @Override
+    public String toString() {
+        Class cl = getRawClass();
+        if (cl.isArray()) {
+            if (parameters.length > 0) {
+                return parameters[0].toString() + "[]";
+            } else {
+                return cl.getComponentType().getName() + "[]";
+            }
+        }
+        if (parameters.length > 0) {
+            StringBuilder sb = new StringBuilder();
+            sb.append(cl.getName());
+            sb.append("<");
+            for (int i = 0; i < parameters.length; i++) {
+                if (i > 0) {
+                    sb.append(",");
+                }
+                sb.append(parameters[i].toString());
+            }
+            sb.append(">");
+            return sb.toString();
+        }
+        return cl.getName();
+    }
+
+    static GenericType[] parametersOf(Type type ) {
+		if ( type instanceof Class ) {
+		    Class clazz = (Class) type;
+		    if (clazz.isArray()) {
+                GenericType t = new GenericType(clazz.getComponentType());
+                if (t.size() > 0) {
+		            return new GenericType[] { t };
+                } else {
+                    return EMPTY;
+                }
+		    } else {
+		        return EMPTY;
+		    }
+		}
+        if ( type instanceof ParameterizedType ) {
+            ParameterizedType pt = (ParameterizedType) type;
+            Type [] parameters = pt.getActualTypeArguments();
+            GenericType[] gts = new GenericType[parameters.length];
+            for ( int i =0; i<gts.length; i++) {
+                gts[i] = new GenericType(parameters[i]);
+            }
+            return gts;
+        }
+        if ( type instanceof GenericArrayType ) {
+            return new GenericType[] { new GenericType(((GenericArrayType) type).getGenericComponentType()) };
+        }
+        throw new IllegalStateException();
+	}
+
+	static Class<?> getConcreteClass(Type type) {
+		Type ntype = collapse(type);
+		if ( ntype instanceof Class )
+			return (Class<?>) ntype;
+
+		if ( ntype instanceof ParameterizedType )
+			return getConcreteClass(collapse(((ParameterizedType)ntype).getRawType()));
+
+		throw new RuntimeException("Unknown type " + type );
+	}
+
+	static Type collapse(Type target) {
+		if (target instanceof Class || target instanceof ParameterizedType ) {
+			return target;
+		} else if (target instanceof TypeVariable) {
+			return collapse(((TypeVariable<?>) target).getBounds()[0]);
+		} else if (target instanceof GenericArrayType) {
+			Type t = collapse(((GenericArrayType) target)
+					.getGenericComponentType());
+			while ( t instanceof ParameterizedType )
+				t = collapse(((ParameterizedType)t).getRawType());
+			return Array.newInstance((Class<?>)t, 0).getClass();
+		} else if (target instanceof WildcardType) {
+			WildcardType wct = (WildcardType) target;
+			if (wct.getLowerBounds().length == 0)
+				return collapse(wct.getUpperBounds()[0]);
+			else
+				return collapse(wct.getLowerBounds()[0]);
+		}
+		throw new RuntimeException("Huh? " + target);
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/karaf/blob/1ee78df9/shell/command-api/src/main/java/org/apache/karaf/shell/commands/converter/ReifiedType.java
----------------------------------------------------------------------
diff --git a/shell/command-api/src/main/java/org/apache/karaf/shell/commands/converter/ReifiedType.java b/shell/command-api/src/main/java/org/apache/karaf/shell/commands/converter/ReifiedType.java
new file mode 100644
index 0000000..dda4477
--- /dev/null
+++ b/shell/command-api/src/main/java/org/apache/karaf/shell/commands/converter/ReifiedType.java
@@ -0,0 +1,116 @@
+/*
+ * Copyright (c) OSGi Alliance (2008, 2009). All Rights Reserved.
+ *
+ * Licensed 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.karaf.shell.commands.converter;
+
+/**
+ * Provides access to a concrete type and its optional generic type arguments.
+ *
+ * Java 5 and later support generic types. These types consist of a raw class
+ * with type arguments. This class models such a <code>Type</code> class but
+ * ensures that the type is <em>reified</em>. Reification means that the Type
+ * graph associated with a Java 5 <code>Type</code> instance is traversed
+ * until the type becomes a concrete class. In Java 1.4 a class has no
+ * arguments. This concrete class implements the Reified Type for Java 1.4.
+ *
+ * In Java 1.4, this class works with non-generic types. In that cases, a
+ * Reified Type provides access to the class and has zero type arguments, though
+ * a subclass that provide type arguments should be respected. Blueprint
+ * extender implementations can subclass this class and provide access to the
+ * generics type graph if used in a conversion. Such a subclass must
+ * <em>reify<em> the different Java 5 <code>Type</code> instances into the
+ * reified form. That is, a form where the raw Class is available with its optional type arguments as Reified Types.
+ *
+ * @Immutable
+ */
+public class ReifiedType {
+	final static ReifiedType ALL = new ReifiedType(Object.class);
+
+	private final Class clazz;
+
+	/**
+	 * Create a Reified Type for a raw Java class without any generic arguments.
+	 * Subclasses can provide the optional generic argument information. Without
+	 * subclassing, this instance has no type arguments.
+	 *
+	 * @param clazz
+	 *            The raw class of the Reified Type.
+	 */
+	public ReifiedType(Class clazz) {
+		this.clazz = clazz;
+	}
+
+	/**
+	 * Access to the raw class.
+	 *
+	 * The raw class represents the concrete class that is associated with a
+	 * type declaration. This class could have been deduced from the generics
+	 * type graph of the declaration. For example, in the following example:
+	 *
+	 * <pre>
+	 * Map&lt;String, Object&gt; map;
+	 * </pre>
+	 *
+	 * The raw class is the Map class.
+	 *
+	 * @return the collapsed raw class that represents this type.
+	 */
+	public Class getRawClass() {
+		return clazz;
+	}
+
+	/**
+	 * Access to a type argument.
+	 *
+	 * The type argument refers to a argument in a generic type declaration
+	 * given by index <code>i</code>. This method returns a Reified Type that
+	 * has Object as class when no generic type information is available. Any
+	 * object is assignable to Object and therefore no conversion is then
+	 * necessary, this is compatible with older Javas than 5. For this reason,
+	 * the implementation in this class always returns the
+	 * <code>Object<code> class, regardless of the given index.
+	 *
+	 * This method should be overridden by a subclass that provides access to
+	 * the generic information.
+	 *
+	 * For example, in the following example:
+	 *
+	 * <pre>
+	 * Map&lt;String, Object&gt; map;
+	 * </pre>
+	 *
+	 * The type argument 0 is <code>String</code>, and type argument 1 is
+	 * <code>Object</code>.
+	 *
+	 * @param i
+	 *            The index of the type argument
+	 * @return <code>ReifiedType(Object.class)<code>, subclasses must override this and return the generic argument at index <code>i</code>
+	 */
+	public ReifiedType getActualTypeArgument(int i) {
+		return ALL;
+	}
+
+	/**
+	 * Return the number of type arguments.
+	 *
+	 * This method should be overridden by a subclass to support Java 5 types.
+	 *
+	 * @return 0, subclasses must override this and return the number of generic
+	 *         arguments
+	 */
+	public int size() {
+		return 0;
+	}
+}

http://git-wip-us.apache.org/repos/asf/karaf/blob/1ee78df9/shell/command-api/src/main/java/org/apache/karaf/shell/commands/meta/ActionMetaData.java
----------------------------------------------------------------------
diff --git a/shell/command-api/src/main/java/org/apache/karaf/shell/commands/meta/ActionMetaData.java b/shell/command-api/src/main/java/org/apache/karaf/shell/commands/meta/ActionMetaData.java
new file mode 100644
index 0000000..e0bd11a
--- /dev/null
+++ b/shell/command-api/src/main/java/org/apache/karaf/shell/commands/meta/ActionMetaData.java
@@ -0,0 +1,296 @@
+/*
+ * 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.karaf.shell.commands.meta;
+
+import static org.apache.karaf.shell.commands.ansi.SimpleAnsi.INTENSITY_BOLD;
+import static org.apache.karaf.shell.commands.ansi.SimpleAnsi.INTENSITY_NORMAL;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.PrintStream;
+import java.io.Reader;
+import java.io.StringWriter;
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.felix.gogo.commands.Action;
+import org.apache.karaf.shell.commands.Argument;
+import org.apache.karaf.shell.commands.Command;
+import org.apache.karaf.shell.commands.HelpOption;
+import org.apache.karaf.shell.commands.Option;
+import org.apache.karaf.shell.commands.ansi.SimpleAnsi;
+import org.apache.karaf.shell.console.Completer;
+
+public class ActionMetaData {
+
+    private final Class<? extends Action> actionClass;
+    private final Command command;
+    private final Map<Option, Field> options;
+    private final Map<Argument, Field> arguments;
+    List<Argument> orderedArguments;
+    private final Completer[] completers;
+
+    public ActionMetaData(Class<? extends Action> actionClass, Command command, Map<Option, Field> options, Map<Argument, Field> args,
+            List<Argument> orderedArguments, Completer[] completers) {
+        super();
+        this.actionClass = actionClass;
+        this.command = command;
+        this.options = options;
+        this.arguments = args;
+        this.orderedArguments = orderedArguments;
+        this.completers = completers;
+    }
+
+    public Class<? extends Action> getActionClass() {
+        return actionClass;
+    }
+    
+    public Command getCommand() {
+        return command;
+    }
+
+    public Map<Option, Field> getOptions() {
+        return options;
+    }
+
+    public Map<Argument, Field> getArguments() {
+        return arguments;
+    }
+
+    public Completer[] getCompleters() {
+        return completers;
+    }
+
+    public List<Argument> getOrderedArguments() {
+        return orderedArguments;
+    }
+
+    public void printUsage(Action action, PrintStream out, boolean globalScope, int termWidth) {
+        if (command != null) {
+            List<Argument> argumentsSet = new ArrayList<Argument>(arguments.keySet());
+            Collections.sort(argumentsSet, new Comparator<Argument>() {
+                public int compare(Argument o1, Argument o2) {
+                    return Integer.valueOf(o1.index()).compareTo(Integer.valueOf(o2.index()));
+                }
+            });
+            Set<Option> optionsSet = new HashSet<Option>(options.keySet());
+            optionsSet.add(HelpOption.HELP);
+            if (command != null && (command.description() != null || command.name() != null)) {
+                out.println(INTENSITY_BOLD + "DESCRIPTION" + INTENSITY_NORMAL);
+                out.print("        ");
+                if (command.name() != null) {
+                    if (globalScope) {
+                        out.println(INTENSITY_BOLD + command.name() + INTENSITY_NORMAL);
+                    } else {
+                        out.println(command.scope() + ":" + INTENSITY_BOLD + command.name() + INTENSITY_NORMAL);
+                    }
+                    out.println();
+                }
+                out.print("\t");
+                out.println(command.description());
+                out.println();
+            }
+            StringBuffer syntax = new StringBuffer();
+            if (command != null) {
+                if (globalScope) {
+                    syntax.append(command.name());
+                } else {
+                    syntax.append(String.format("%s:%s", command.scope(), command.name()));
+                }
+            }
+            if (options.size() > 0) {
+                syntax.append(" [options]");
+            }
+            if (arguments.size() > 0) {
+                syntax.append(' ');
+                for (Argument argument : argumentsSet) {
+                    if (!argument.required()) {
+                        syntax.append(String.format("[%s] ", argument.name()));
+                    } else {
+                        syntax.append(String.format("%s ", argument.name()));
+                    }
+                }
+            }
+
+            out.println(INTENSITY_BOLD + "SYNTAX" + INTENSITY_NORMAL);
+            out.print("        ");
+            out.println(syntax.toString());
+            out.println();
+            if (arguments.size() > 0) {
+                out.println(INTENSITY_BOLD + "ARGUMENTS" + INTENSITY_NORMAL);
+                for (Argument argument : argumentsSet) {
+                    out.print("        ");
+                    out.println(INTENSITY_BOLD + argument.name() + INTENSITY_NORMAL);
+                    ActionMetaData.printFormatted("                ", argument.description(), termWidth, out, true);
+                    if (!argument.required()) {
+                        if (argument.valueToShowInHelp() != null && argument.valueToShowInHelp().length() != 0) {
+                            if (Argument.DEFAULT_STRING.equals(argument.valueToShowInHelp())) {
+                                Object o = getDefaultValue(action, argument);
+                                String defaultValue = getDefaultValueString(o);
+                                if (defaultValue != null) {
+                                    printDefaultsTo(out, defaultValue);
+                                }
+                            } else {
+                                printDefaultsTo(out, argument.valueToShowInHelp());
+                            }
+                        }
+                    }
+                }
+                out.println();
+            }
+            if (options.size() > 0) {
+                out.println(INTENSITY_BOLD + "OPTIONS" + INTENSITY_NORMAL);
+                for (Option option : optionsSet) {
+                    String opt = option.name();
+                    for (String alias : option.aliases()) {
+                        opt += ", " + alias;
+                    }
+                    out.print("        ");
+                    out.println(INTENSITY_BOLD + opt + INTENSITY_NORMAL);
+                    ActionMetaData.printFormatted("                ", option.description(), termWidth, out, true);
+                    if (option.valueToShowInHelp() != null && option.valueToShowInHelp().length() != 0) {
+                        if (Option.DEFAULT_STRING.equals(option.valueToShowInHelp())) {
+                            Object o = getDefaultValue(action, option);
+                            String defaultValue = getDefaultValueString(o);
+                            if (defaultValue != null) {
+                                printDefaultsTo(out, defaultValue);
+                            }
+                        } else {
+                            printDefaultsTo(out, option.valueToShowInHelp());
+                        }
+                    }
+                }
+                out.println();
+            }
+            if (command.detailedDescription().length() > 0) {
+                out.println(INTENSITY_BOLD + "DETAILS" + INTENSITY_NORMAL);
+                String desc = getDetailedDescription();
+                ActionMetaData.printFormatted("        ", desc, termWidth, out, true);
+            }
+        }
+    }
+    
+    public Object getDefaultValue(Action action, Argument argument) {
+        try {
+            arguments.get(argument).setAccessible(true);
+            return arguments.get(argument).get(action);
+        } catch (Exception e) {
+            return null;
+        }
+    }
+    
+    public Object getDefaultValue(Action action, Option option) {
+        try {
+            options.get(option).setAccessible(true);
+            return options.get(option).get(action);
+        } catch (Exception e) {
+            return null;
+        }
+    }
+    
+    public String getDetailedDescription() {
+        String desc = command.detailedDescription();
+        return loadDescription(actionClass, desc);
+    }
+    
+    private String loadDescription(Class<?> clazz, String desc) {
+        if (desc != null && desc.startsWith("classpath:")) {
+            desc = loadClassPathResource(clazz, desc.substring("classpath:".length()));
+        }
+        return desc;
+    }
+    
+    public String getDefaultValueString(Object o) {
+        if (o != null && (!(o instanceof Boolean) || ((Boolean)o))
+            && (!(o instanceof Number) || ((Number)o).doubleValue() != 0.0)) {
+            return o.toString();
+        } else {
+            return null;
+        }
+    }
+
+    private void printDefaultsTo(PrintStream out, String value) {
+        out.println("                (defaults to " + value + ")");
+    }
+
+    static void printFormatted(String prefix, String str, int termWidth, PrintStream out, boolean prefixFirstLine) {
+        int pfxLen = prefix.length();
+        int maxwidth = termWidth - pfxLen;
+        Pattern wrap = Pattern.compile("(\\S\\S{" + maxwidth + ",}|.{1," + maxwidth + "})(\\s+|$)");
+        int cur = 0;
+        while (cur >= 0) {
+            int lst = str.indexOf('\n', cur);
+            String s = (lst >= 0) ? str.substring(cur, lst) : str.substring(cur);
+            if (s.length() == 0) {
+                out.println();
+            } else {
+                Matcher m = wrap.matcher(s);
+                while (m.find()) {
+                    if (cur > 0 || prefixFirstLine) {
+                        out.print(prefix);
+                    }
+                    out.println(m.group());
+                }
+            }
+            if (lst >= 0) {
+                cur = lst + 1;
+            } else {
+                break;
+            }
+        }
+    }
+
+    private String loadClassPathResource(Class<?> clazz, String path) {
+        InputStream is = clazz.getResourceAsStream(path);
+        if (is == null) {
+            is = clazz.getClassLoader().getResourceAsStream(path);
+        }
+        if (is == null) {
+            return "Unable to load description from " + path;
+        }
+    
+        try {
+            Reader r = new InputStreamReader(is);
+            StringWriter sw = new StringWriter();
+            int c;
+            while ((c = r.read()) != -1) {
+                sw.append((char) c);
+            }
+            return sw.toString();
+        } catch (IOException e) {
+            return "Unable to load description from " + path;
+        } finally {
+            try {
+                is.close();
+            } catch (IOException e) {
+                // Ignore
+            }
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/karaf/blob/1ee78df9/shell/command-api/src/main/java/org/apache/karaf/shell/commands/meta/ActionMetaDataFactory.java
----------------------------------------------------------------------
diff --git a/shell/command-api/src/main/java/org/apache/karaf/shell/commands/meta/ActionMetaDataFactory.java b/shell/command-api/src/main/java/org/apache/karaf/shell/commands/meta/ActionMetaDataFactory.java
new file mode 100644
index 0000000..91bc48f
--- /dev/null
+++ b/shell/command-api/src/main/java/org/apache/karaf/shell/commands/meta/ActionMetaDataFactory.java
@@ -0,0 +1,251 @@
+/*
+ * 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.karaf.shell.commands.meta;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.felix.gogo.commands.Action;
+import org.apache.karaf.shell.commands.Argument;
+import org.apache.karaf.shell.commands.Command;
+import org.apache.karaf.shell.commands.Option;
+
+public class ActionMetaDataFactory {
+
+    public ActionMetaData create(Class<? extends Action> actionClass) {
+        Command command = getCommand(actionClass);
+        Map<Option, Field> options = new HashMap<Option, Field>();
+        Map<Argument, Field> arguments = new HashMap<Argument, Field>();
+        List<Argument> orderedArguments = new ArrayList<Argument>();
+
+        for (Class<?> type = actionClass; type != null; type = type.getSuperclass()) {
+            for (Field field : type.getDeclaredFields()) {
+                Option option = field.getAnnotation(Option.class);
+                if (option == null) {
+                    option = getAndConvertDeprecatedOption(field);
+                }
+                if (option != null) {
+                    options.put(option, field);
+                }
+
+                Argument argument = field.getAnnotation(Argument.class);
+                if (argument == null) {
+                    argument = getAndConvertDeprecatedArgument(field);
+                }
+                if (argument != null) {
+                    argument = replaceDefaultArgument(field, argument);
+                    arguments.put(argument, field);
+                    int index = argument.index();
+                    while (orderedArguments.size() <= index) {
+                        orderedArguments.add(null);
+                    }
+                    if (orderedArguments.get(index) != null) {
+                        throw new IllegalArgumentException("Duplicate argument index: " + index + " on Action " + actionClass.getName());
+                    }
+                    orderedArguments.set(index, argument);
+                }
+            }
+        }
+        assertIndexesAreCorrect(actionClass, orderedArguments);
+
+        return new ActionMetaData(actionClass, command, options, arguments, orderedArguments, null);
+    }
+
+    public Command getCommand(Class<? extends Action> actionClass) {
+        Command command = actionClass.getAnnotation(Command.class);
+        if (command == null) {
+            command = getAndConvertDeprecatedCommand(actionClass);
+        }
+        return command;
+    }
+
+    @SuppressWarnings("deprecation")
+    public Command getAndConvertDeprecatedCommand(Class<? extends Action> actionClass) {
+        final org.apache.felix.gogo.commands.Command oldCommand = actionClass.getAnnotation(org.apache.felix.gogo.commands.Command.class);
+        if (oldCommand == null) {
+            return null;
+        }
+        return new Command() {
+            
+            @Override
+            public Class<? extends Annotation> annotationType() {
+                return Command.class;
+            }
+            
+            @Override
+            public String scope() {
+                return oldCommand.scope();
+            }
+            
+            @Override
+            public String name() {
+                return oldCommand.name();
+            }
+            
+            @Override
+            public String detailedDescription() {
+                return oldCommand.detailedDescription();
+            }
+
+            @Override
+            public String description() {
+                return oldCommand.description();
+            }
+        };
+    }
+
+    @SuppressWarnings("deprecation")
+    private Option getAndConvertDeprecatedOption(Field field) {
+        final org.apache.felix.gogo.commands.Option oldOption = field.getAnnotation(org.apache.felix.gogo.commands.Option.class);
+        if (oldOption == null) {
+            return null;
+        }
+        return new Option() {
+            
+            @Override
+            public Class<? extends Annotation> annotationType() {
+                return Option.class;
+            }
+            
+            @Override
+            public String valueToShowInHelp() {
+                return oldOption.valueToShowInHelp();
+            }
+            
+            @Override
+            public boolean required() {
+                return oldOption.required();
+            }
+            
+            @Override
+            public String name() {
+                return oldOption.name();
+            }
+            
+            @Override
+            public boolean multiValued() {
+                return oldOption.multiValued();
+            }
+            
+            @Override
+            public String description() {
+                return oldOption.description();
+            }
+            
+            @Override
+            public String[] aliases() {
+                return oldOption.aliases();
+            }
+        };
+    }
+    
+    @SuppressWarnings("deprecation")
+    private Argument getAndConvertDeprecatedArgument(Field field) {
+        final org.apache.felix.gogo.commands.Argument oldArgument = field.getAnnotation(org.apache.felix.gogo.commands.Argument.class);
+        if (oldArgument == null) {
+            return null;
+        }
+        return new Argument() {
+            
+            @Override
+            public Class<? extends Annotation> annotationType() {
+                return Argument.class;
+            }
+            
+            @Override
+            public String valueToShowInHelp() {
+                return oldArgument.valueToShowInHelp();
+            }
+            
+            @Override
+            public boolean required() {
+                return oldArgument.required();
+            }
+            
+            @Override
+            public String name() {
+                return oldArgument.name();
+            }
+            
+            @Override
+            public boolean multiValued() {
+                return oldArgument.multiValued();
+            }
+            
+            @Override
+            public int index() {
+                return oldArgument.index();
+            }
+            
+            @Override
+            public String description() {
+                return oldArgument.description();
+            }
+        };
+    }
+
+    private Argument replaceDefaultArgument(Field field, Argument argument) {
+        if (Argument.DEFAULT.equals(argument.name())) {
+            final Argument delegate = argument;
+            final String name = field.getName();
+            argument = new Argument() {
+                public String name() {
+                    return name;
+                }
+
+                public String description() {
+                    return delegate.description();
+                }
+
+                public boolean required() {
+                    return delegate.required();
+                }
+
+                public int index() {
+                    return delegate.index();
+                }
+
+                public boolean multiValued() {
+                    return delegate.multiValued();
+                }
+
+                public String valueToShowInHelp() {
+                    return delegate.valueToShowInHelp();
+                }
+
+                public Class<? extends Annotation> annotationType() {
+                    return delegate.annotationType();
+                }
+            };
+        }
+        return argument;
+    }
+    
+    private void assertIndexesAreCorrect(Class<? extends Action> actionClass, List<Argument> orderedArguments) {
+        for (int i = 0; i < orderedArguments.size(); i++) {
+            if (orderedArguments.get(i) == null) {
+                throw new IllegalArgumentException("Missing argument for index: " + i + " on Action " + actionClass.getName());
+            }
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/karaf/blob/1ee78df9/shell/command-api/src/main/java/org/apache/karaf/shell/console/AbstractAction.java
----------------------------------------------------------------------
diff --git a/shell/command-api/src/main/java/org/apache/karaf/shell/console/AbstractAction.java b/shell/command-api/src/main/java/org/apache/karaf/shell/console/AbstractAction.java
new file mode 100644
index 0000000..f9990c5
--- /dev/null
+++ b/shell/command-api/src/main/java/org/apache/karaf/shell/console/AbstractAction.java
@@ -0,0 +1,50 @@
+/*
+ * 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.karaf.shell.console;
+
+import org.apache.karaf.shell.commands.Action;
+import org.apache.felix.service.command.CommandSession;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public abstract class AbstractAction implements Action {
+
+    protected final Logger log = LoggerFactory.getLogger(getClass());
+    protected CommandSession session;
+
+    public Object execute(CommandSession session) throws Exception {
+        this.session = session;
+        return doExecute();
+    }
+
+    protected abstract Object doExecute() throws Exception;
+    
+    /**
+     * This is for long running commands to be interrupted by ctrl-c
+     * 
+     * @throws InterruptedException
+     */
+    public static void checkInterrupted() throws InterruptedException {
+        Thread.yield(); 
+        if (Thread.currentThread().isInterrupted()) {
+            throw new InterruptedException();
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/karaf/blob/1ee78df9/shell/command-api/src/main/java/org/apache/karaf/shell/console/BlueprintContainerAware.java
----------------------------------------------------------------------
diff --git a/shell/command-api/src/main/java/org/apache/karaf/shell/console/BlueprintContainerAware.java b/shell/command-api/src/main/java/org/apache/karaf/shell/console/BlueprintContainerAware.java
new file mode 100644
index 0000000..d566f48
--- /dev/null
+++ b/shell/command-api/src/main/java/org/apache/karaf/shell/console/BlueprintContainerAware.java
@@ -0,0 +1,27 @@
+/*
+ * 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.karaf.shell.console;
+
+import org.osgi.service.blueprint.container.BlueprintContainer;
+
+public interface BlueprintContainerAware {
+
+    void setBlueprintContainer(BlueprintContainer blueprintContainer);
+
+}

http://git-wip-us.apache.org/repos/asf/karaf/blob/1ee78df9/shell/command-api/src/main/java/org/apache/karaf/shell/console/BundleContextAware.java
----------------------------------------------------------------------
diff --git a/shell/command-api/src/main/java/org/apache/karaf/shell/console/BundleContextAware.java b/shell/command-api/src/main/java/org/apache/karaf/shell/console/BundleContextAware.java
new file mode 100644
index 0000000..bbd03c5
--- /dev/null
+++ b/shell/command-api/src/main/java/org/apache/karaf/shell/console/BundleContextAware.java
@@ -0,0 +1,27 @@
+/*
+ * 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.karaf.shell.console;
+
+import org.osgi.framework.BundleContext;
+
+public interface BundleContextAware {
+
+    void setBundleContext(BundleContext bundleContext);
+
+}

http://git-wip-us.apache.org/repos/asf/karaf/blob/1ee78df9/shell/command-api/src/main/java/org/apache/karaf/shell/console/CloseShellException.java
----------------------------------------------------------------------
diff --git a/shell/command-api/src/main/java/org/apache/karaf/shell/console/CloseShellException.java b/shell/command-api/src/main/java/org/apache/karaf/shell/console/CloseShellException.java
new file mode 100644
index 0000000..81cee88
--- /dev/null
+++ b/shell/command-api/src/main/java/org/apache/karaf/shell/console/CloseShellException.java
@@ -0,0 +1,27 @@
+/*
+ * 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.karaf.shell.console;
+
+/**
+ * Exception thrown to indicate the console to close.
+ */
+@SuppressWarnings("serial")
+public class CloseShellException extends Exception {
+
+}

http://git-wip-us.apache.org/repos/asf/karaf/blob/1ee78df9/shell/command-api/src/main/java/org/apache/karaf/shell/console/CommandSessionHolder.java
----------------------------------------------------------------------
diff --git a/shell/command-api/src/main/java/org/apache/karaf/shell/console/CommandSessionHolder.java b/shell/command-api/src/main/java/org/apache/karaf/shell/console/CommandSessionHolder.java
new file mode 100644
index 0000000..f07554f
--- /dev/null
+++ b/shell/command-api/src/main/java/org/apache/karaf/shell/console/CommandSessionHolder.java
@@ -0,0 +1,38 @@
+/*
+ * 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.karaf.shell.console;
+
+import org.apache.felix.service.command.CommandSession;
+
+public class CommandSessionHolder {
+
+    private static final ThreadLocal<CommandSession> session = new ThreadLocal<CommandSession>();
+
+    public static CommandSession getSession() {
+        return session.get();
+    }
+
+    public static void setSession(CommandSession commandSession) {
+        session.set(commandSession);
+    }
+
+    public static void unset() {
+        session.remove();
+    }
+}

http://git-wip-us.apache.org/repos/asf/karaf/blob/1ee78df9/shell/command-api/src/main/java/org/apache/karaf/shell/console/CompletableFunction.java
----------------------------------------------------------------------
diff --git a/shell/command-api/src/main/java/org/apache/karaf/shell/console/CompletableFunction.java b/shell/command-api/src/main/java/org/apache/karaf/shell/console/CompletableFunction.java
new file mode 100644
index 0000000..fcb96da
--- /dev/null
+++ b/shell/command-api/src/main/java/org/apache/karaf/shell/console/CompletableFunction.java
@@ -0,0 +1,31 @@
+/*
+ * 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.karaf.shell.console;
+
+import java.util.List;
+import java.util.Map;
+
+import org.apache.felix.service.command.Function;
+
+public interface CompletableFunction extends Function {
+
+    List<Completer> getCompleters();
+    Map<String, Completer> getOptionalCompleters();
+
+}

http://git-wip-us.apache.org/repos/asf/karaf/blob/1ee78df9/shell/command-api/src/main/java/org/apache/karaf/shell/console/Completer.java
----------------------------------------------------------------------
diff --git a/shell/command-api/src/main/java/org/apache/karaf/shell/console/Completer.java b/shell/command-api/src/main/java/org/apache/karaf/shell/console/Completer.java
new file mode 100644
index 0000000..59f7897
--- /dev/null
+++ b/shell/command-api/src/main/java/org/apache/karaf/shell/console/Completer.java
@@ -0,0 +1,27 @@
+/*
+ * 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.karaf.shell.console;
+
+import java.util.List;
+
+public interface Completer {
+
+    int complete(String buffer, int cursor, List<String> candidates);
+
+}

http://git-wip-us.apache.org/repos/asf/karaf/blob/1ee78df9/shell/command-api/src/main/java/org/apache/karaf/shell/console/Console.java
----------------------------------------------------------------------
diff --git a/shell/command-api/src/main/java/org/apache/karaf/shell/console/Console.java b/shell/command-api/src/main/java/org/apache/karaf/shell/console/Console.java
new file mode 100644
index 0000000..fcca7ad
--- /dev/null
+++ b/shell/command-api/src/main/java/org/apache/karaf/shell/console/Console.java
@@ -0,0 +1,29 @@
+/*
+ * 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.karaf.shell.console;
+
+import org.apache.felix.service.command.CommandSession;
+
+public interface Console extends Runnable {
+
+    CommandSession getSession();
+
+    void close(boolean closedByUser);
+
+}

http://git-wip-us.apache.org/repos/asf/karaf/blob/1ee78df9/shell/command-api/src/main/java/org/apache/karaf/shell/console/ExitAction.java
----------------------------------------------------------------------
diff --git a/shell/command-api/src/main/java/org/apache/karaf/shell/console/ExitAction.java b/shell/command-api/src/main/java/org/apache/karaf/shell/console/ExitAction.java
new file mode 100644
index 0000000..1449315
--- /dev/null
+++ b/shell/command-api/src/main/java/org/apache/karaf/shell/console/ExitAction.java
@@ -0,0 +1,46 @@
+/*
+ * 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.karaf.shell.console;
+
+import org.apache.karaf.shell.commands.Command;
+
+/**
+ * Exit from the current sub-shell and get back to the previous one.
+ */
+@Command(scope = "*", name = "exit", description = "Exit from the current shell")
+public class ExitAction extends AbstractAction {
+    
+    public Object doExecute() throws Exception {
+        // get the current sub-shell
+        String currentSubShell = (String) session.get("SUBSHELL");
+        if (!currentSubShell.isEmpty()) {
+            if (currentSubShell.contains(":")) {
+                int index = currentSubShell.lastIndexOf(":");
+                session.put("SUBSHELL", currentSubShell.substring(0, index));
+            } else {
+                session.put("SUBSHELL", "");
+            }
+            String currentScope = (String) session.get("SCOPE");
+            int index = currentScope.indexOf(":");
+            session.put("SCOPE", currentScope.substring(index + 1));
+        }
+        return null;
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/karaf/blob/1ee78df9/shell/command-api/src/main/java/org/apache/karaf/shell/console/HelpProvider.java
----------------------------------------------------------------------
diff --git a/shell/command-api/src/main/java/org/apache/karaf/shell/console/HelpProvider.java b/shell/command-api/src/main/java/org/apache/karaf/shell/console/HelpProvider.java
new file mode 100644
index 0000000..7e3bca7
--- /dev/null
+++ b/shell/command-api/src/main/java/org/apache/karaf/shell/console/HelpProvider.java
@@ -0,0 +1,26 @@
+/**
+ *
+ * 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.karaf.shell.console;
+
+import org.apache.felix.service.command.CommandSession;
+
+public interface HelpProvider {
+    
+    String getHelp(CommandSession session, String path);
+    
+}

http://git-wip-us.apache.org/repos/asf/karaf/blob/1ee78df9/shell/command-api/src/main/java/org/apache/karaf/shell/console/MultiException.java
----------------------------------------------------------------------
diff --git a/shell/command-api/src/main/java/org/apache/karaf/shell/console/MultiException.java b/shell/command-api/src/main/java/org/apache/karaf/shell/console/MultiException.java
new file mode 100644
index 0000000..6e6185c
--- /dev/null
+++ b/shell/command-api/src/main/java/org/apache/karaf/shell/console/MultiException.java
@@ -0,0 +1,95 @@
+/*
+ * 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.karaf.shell.console;
+
+import java.io.PrintStream;
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.List;
+
+@SuppressWarnings("serial")
+public class MultiException extends Exception {
+
+    private List<Exception> exceptions = new ArrayList<Exception>();
+
+    public MultiException(String message) {
+        super(message);
+    }
+
+    public MultiException(String message, List<Exception> exceptions) {
+        super(message);
+        this.exceptions = exceptions;
+    }
+
+    public void addException(Exception e) {
+        exceptions.add(e);
+    }
+
+    public void throwIfExceptions() throws MultiException {
+        if (!exceptions.isEmpty()) {
+            throw this;
+        }
+    }
+    
+    public Throwable[] getCauses() {
+        return exceptions.toArray(new Throwable[exceptions.size()]);
+    }
+
+    @Override
+    public void printStackTrace()
+    {
+        super.printStackTrace();
+        for (Exception e : exceptions) {
+            e.printStackTrace();
+        }
+    }
+
+
+    /* ------------------------------------------------------------------------------- */
+    /**
+     * @see java.lang.Throwable#printStackTrace(java.io.PrintStream)
+     */
+    @Override
+    public void printStackTrace(PrintStream out)
+    {
+        super.printStackTrace(out);
+        for (Exception e : exceptions) {
+            e.printStackTrace(out);
+        }
+    }
+
+    @Override
+    public void printStackTrace(PrintWriter out)
+    {
+        super.printStackTrace(out);
+        for (Exception e : exceptions) {
+            e.printStackTrace(out);
+        }
+    }
+
+    public static void throwIf(String message, List<Exception> exceptions) throws MultiException {
+        if (exceptions != null && !exceptions.isEmpty()) {
+            StringBuilder sb = new StringBuilder(message);
+            sb.append(":");
+            for (Exception e : exceptions) {
+                sb.append("\n\t");
+                sb.append(e.getMessage());
+            }
+            throw new MultiException(sb.toString(), exceptions);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/karaf/blob/1ee78df9/shell/command-api/src/main/java/org/apache/karaf/shell/console/NameScoping.java
----------------------------------------------------------------------
diff --git a/shell/command-api/src/main/java/org/apache/karaf/shell/console/NameScoping.java b/shell/command-api/src/main/java/org/apache/karaf/shell/console/NameScoping.java
new file mode 100644
index 0000000..355464d
--- /dev/null
+++ b/shell/command-api/src/main/java/org/apache/karaf/shell/console/NameScoping.java
@@ -0,0 +1,79 @@
+/**
+ *
+ * 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.karaf.shell.console;
+
+import org.apache.felix.service.command.CommandSession;
+
+
+/**
+ * A helper class for name scoping
+ */
+public class NameScoping {
+
+    public static final String MULTI_SCOPE_MODE_KEY = "MULTI_SCOPE_MODE";
+
+    /**
+     * Returns the name of the command which can omit the global scope prefix if the command starts with the
+     * same prefix as the current application
+     */
+    public static String getCommandNameWithoutGlobalPrefix(CommandSession session, String key) {
+        if (!isMultiScopeMode(session)) {
+            String globalScope = (String) (session != null ? session.get("APPLICATION") : null);
+            if (globalScope != null) {
+                String prefix = globalScope + ":";
+                if (key.startsWith(prefix)) {
+                    // TODO we may only want to do this for single-scope mode when outside of OSGi?
+                    // so we may want to also check for a isMultiScope mode == false
+                    return key.substring(prefix.length());
+                }
+            }
+        }
+        return key;
+    }
+
+    /**
+     * Returns true if the given scope is the global scope so that it can be hidden from help messages
+     */
+    public static boolean isGlobalScope(CommandSession session, String scope) {
+        if (session == null)
+            return false;
+
+        if (!isMultiScopeMode(session)) {
+            String globalScope = (String) session.get("APPLICATION");
+            if (globalScope != null) {
+                return scope.equals(globalScope);
+            }
+        }
+        return false;
+    }
+
+    /**
+     * Returns true if we are in multi-scope mode (the default) or if we are in single scope mode which means we
+     * avoid prefixing commands with their scope
+     */
+    public static boolean isMultiScopeMode(CommandSession session) {
+        if (session == null)
+            return false;
+
+        Object value = session.get(MULTI_SCOPE_MODE_KEY);
+        if (value != null && value.equals("false")) {
+            return false;
+        }
+        return true;
+    }
+}

http://git-wip-us.apache.org/repos/asf/karaf/blob/1ee78df9/shell/command-api/src/main/java/org/apache/karaf/shell/console/OsgiCommandSupport.java
----------------------------------------------------------------------
diff --git a/shell/command-api/src/main/java/org/apache/karaf/shell/console/OsgiCommandSupport.java b/shell/command-api/src/main/java/org/apache/karaf/shell/console/OsgiCommandSupport.java
new file mode 100644
index 0000000..d737865
--- /dev/null
+++ b/shell/command-api/src/main/java/org/apache/karaf/shell/console/OsgiCommandSupport.java
@@ -0,0 +1,103 @@
+/*
+ * 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.karaf.shell.console;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+import org.apache.felix.service.command.CommandSession;
+import org.apache.karaf.shell.commands.Action;
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.InvalidSyntaxException;
+import org.osgi.framework.ServiceReference;
+
+public abstract class OsgiCommandSupport extends AbstractAction implements Action, BundleContextAware {
+
+    protected BundleContext bundleContext;
+    protected List<ServiceReference<?>> usedReferences;
+
+    @Override
+    public Object execute(CommandSession session) throws Exception {
+        try {
+            return super.execute(session);
+        } finally {
+            ungetServices();
+        }
+    }
+
+    public BundleContext getBundleContext() {
+        Bundle framework = bundleContext.getBundle(0);
+        return framework == null? bundleContext: framework.getBundleContext();
+    }
+
+    public void setBundleContext(BundleContext bundleContext) {
+        this.bundleContext = bundleContext;
+    }
+
+    protected <T> List<T> getAllServices(Class<T> clazz) {
+        try {
+            return getAllServices(clazz, null);
+        } catch (InvalidSyntaxException e) {
+            throw new IllegalStateException(e);
+        }
+    }
+
+    protected <T> List<T> getAllServices(Class<T> clazz, String filter) throws InvalidSyntaxException {
+        Collection<ServiceReference<T>> references = getBundleContext().getServiceReferences(clazz, filter);
+        List<T> services = new ArrayList<T>();
+        if (references != null) {
+            for (ServiceReference<T> ref : references) {
+                T t = getService(clazz, ref);
+                services.add(t);
+            }
+        }
+        return services;
+    }
+
+    protected <T> T getService(Class<T> clazz) {
+        ServiceReference<T> sr = getBundleContext().getServiceReference(clazz);
+        if (sr != null) {
+            return getService(clazz, sr);
+        } else {
+            return null;
+        }
+    }
+
+    protected <T> T getService(Class<T> clazz, ServiceReference<T> reference) {
+        T t = getBundleContext().getService(reference);
+        if (t != null) {
+            if (usedReferences == null) {
+                usedReferences = new ArrayList<ServiceReference<?>>();
+            }
+            usedReferences.add(reference);
+        }
+        return t;
+    }
+
+    protected void ungetServices() {
+        if (usedReferences != null) {
+            for (ServiceReference<?> ref : usedReferences) {
+                getBundleContext().ungetService(ref);
+            }
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/karaf/blob/1ee78df9/shell/command-api/src/main/java/org/apache/karaf/shell/console/SessionProperties.java
----------------------------------------------------------------------
diff --git a/shell/command-api/src/main/java/org/apache/karaf/shell/console/SessionProperties.java b/shell/command-api/src/main/java/org/apache/karaf/shell/console/SessionProperties.java
new file mode 100644
index 0000000..30f3433
--- /dev/null
+++ b/shell/command-api/src/main/java/org/apache/karaf/shell/console/SessionProperties.java
@@ -0,0 +1,28 @@
+/*
+ * 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.karaf.shell.console;
+
+public class SessionProperties {
+
+    public static final String PRINT_STACK_TRACES = "karaf.printStackTraces";
+    public static final String LAST_EXCEPTION = "karaf.lastException";
+    public static final String IGNORE_INTERRUPTS = "karaf.ignoreInterrupts";
+    public static final String COMPLETION_MODE = "karaf.completionMode";
+
+}

http://git-wip-us.apache.org/repos/asf/karaf/blob/1ee78df9/shell/command-api/src/main/java/org/apache/karaf/shell/console/SubShell.java
----------------------------------------------------------------------
diff --git a/shell/command-api/src/main/java/org/apache/karaf/shell/console/SubShell.java b/shell/command-api/src/main/java/org/apache/karaf/shell/console/SubShell.java
new file mode 100644
index 0000000..2de0d20
--- /dev/null
+++ b/shell/command-api/src/main/java/org/apache/karaf/shell/console/SubShell.java
@@ -0,0 +1,38 @@
+/*
+ * 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.karaf.shell.console;
+
+public interface SubShell {
+
+    /**
+     * Returns the name of the command if used inside a shell
+     */
+    String getName();
+
+    /**
+     * Returns the description of the command which is used to generate command line help
+     */
+    String getDescription();
+
+    /**
+     * Returns a detailed description of the command
+     */
+    String getDetailedDescription();
+
+}

http://git-wip-us.apache.org/repos/asf/karaf/blob/1ee78df9/shell/command-api/src/main/java/org/apache/karaf/shell/console/SubShellAction.java
----------------------------------------------------------------------
diff --git a/shell/command-api/src/main/java/org/apache/karaf/shell/console/SubShellAction.java b/shell/command-api/src/main/java/org/apache/karaf/shell/console/SubShellAction.java
new file mode 100644
index 0000000..8774927
--- /dev/null
+++ b/shell/command-api/src/main/java/org/apache/karaf/shell/console/SubShellAction.java
@@ -0,0 +1,39 @@
+/**
+ *
+ * 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.karaf.shell.console;
+
+
+
+/**
+ * Switch to a sub-shell.
+ */
+public class SubShellAction extends AbstractAction {
+    
+    private String subShell;
+    
+    public Object doExecute() throws Exception {
+        session.put("SUBSHELL", subShell);
+        session.put("SCOPE", subShell + ":" + session.get("SCOPE"));
+        return null;
+    }
+    
+    public void setSubShell(String subShell) {
+        this.subShell = subShell;
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/karaf/blob/1ee78df9/shell/command-api/src/main/java/org/apache/karaf/shell/console/commands/AnnotatedSubShell.java
----------------------------------------------------------------------
diff --git a/shell/command-api/src/main/java/org/apache/karaf/shell/console/commands/AnnotatedSubShell.java b/shell/command-api/src/main/java/org/apache/karaf/shell/console/commands/AnnotatedSubShell.java
new file mode 100644
index 0000000..9cd3dda
--- /dev/null
+++ b/shell/command-api/src/main/java/org/apache/karaf/shell/console/commands/AnnotatedSubShell.java
@@ -0,0 +1,43 @@
+/**
+ *
+ * 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.karaf.shell.console.commands;
+
+import org.apache.karaf.shell.console.SubShell;
+
+public class AnnotatedSubShell implements SubShell {
+
+    public String getName() {
+        return getAnnotation().name();
+    }
+
+    public String getDescription() {
+        return getAnnotation().description();
+    }
+
+    public String getDetailedDescription() {
+        return getAnnotation().detailedDescription();
+    }
+    
+    org.apache.felix.gogo.commands.SubShell getAnnotation() {
+        org.apache.felix.gogo.commands.SubShell ann = getClass().getAnnotation(org.apache.felix.gogo.commands.SubShell.class);
+        if (ann == null) {
+            throw new IllegalStateException("The class should be annotated with the org.apache.felix.gogo.commands.SubShell annotation");
+        }
+        return ann;
+    }
+}