You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@karaf.apache.org by gn...@apache.org on 2016/10/19 09:28:18 UTC
[2/3] karaf git commit: [KARAF-397] Allow completion of non Karaf
based osgi commands [KARAF-2454] Portable way to make custom shell commands
http://git-wip-us.apache.org/repos/asf/karaf/blob/f1dd4a94/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/NewAction.java
----------------------------------------------------------------------
diff --git a/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/NewAction.java b/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/NewAction.java
deleted file mode 100644
index 6173ca2..0000000
--- a/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/NewAction.java
+++ /dev/null
@@ -1,379 +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.karaf.shell.commands.impl;
-
-import java.lang.reflect.Array;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Type;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.karaf.shell.api.action.Action;
-import org.apache.karaf.shell.api.action.Argument;
-import org.apache.karaf.shell.api.action.Command;
-import org.apache.karaf.shell.api.action.lifecycle.Reference;
-import org.apache.karaf.shell.api.action.lifecycle.Service;
-import org.apache.karaf.shell.support.converter.DefaultConverter;
-import org.apache.karaf.shell.support.converter.GenericType;
-import org.apache.karaf.shell.support.converter.ReifiedType;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.wiring.BundleCapability;
-import org.osgi.framework.wiring.BundleRevision;
-import org.osgi.framework.wiring.BundleWiring;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Instantiate a new object
- */
-@Command(scope = "shell", name = "new", description = "Creates a new java object.")
-@Service
-@SuppressWarnings("rawtypes")
-public class NewAction implements Action {
- private static final Logger LOG = LoggerFactory.getLogger(NewAction.class);
- @Argument(name = "class", index = 0, multiValued = false, required = true, description = "FQN of the class to load")
- String clazzName;
-
- @Argument(name = "args", index = 1, multiValued = true, required = false, description = "Constructor arguments")
- List<Object> args;
-
- boolean reorderArguments;
-
- protected DefaultConverter converter;
-
- @Reference
- BundleContext context;
-
- @Override
- public Object execute() throws Exception {
- if (args == null) {
- args = Collections.emptyList();
- }
- String packageName = getPackageName(clazzName);
- Bundle bundle = getBundleOfferingPackage(packageName);
- LOG.info("Using bundle {} classloader to load {}.", bundle.getSymbolicName(), clazzName);
- ClassLoader classLoader = getClassLoader(bundle);
- converter = new DefaultConverter(classLoader);
- Class<?> clazz = (Class<?>)converter.convert(clazzName, Class.class);
- // Handle arrays
- if (clazz.isArray()) {
- Object obj = Array.newInstance(clazz.getComponentType(), args.size());
- for (int i = 0; i < args.size(); i++) {
- Array.set(obj, i, convert(args.get(i), clazz.getComponentType()));
- }
- return obj;
- }
-
- // Map of matching constructors
- Map<Constructor, List<Object>> matches = findMatchingConstructors(clazz, args, Arrays.asList(new ReifiedType[args.size()]));
- if (matches.size() == 1) {
- try {
- Map.Entry<Constructor, List<Object>> match = matches.entrySet().iterator().next();
- return newInstance(match.getKey(), match.getValue().toArray());
- } catch (Throwable e) {
- throw new Exception("Error when instantiating object of class " + clazz.getName(), getRealCause(e));
- }
- } else if (matches.size() == 0) {
- throw new Exception("Unable to find a matching constructor on class " + clazz.getName() + " for arguments " + args + " when instantiating object.");
- } else {
- throw new Exception("Multiple matching constructors found on class " + clazz.getName() + " for arguments " + args + " when instantiating object: " + matches.keySet());
- }
- }
-
- private String getPackageName(String name) {
- int nameSeperator = name.lastIndexOf(".");
- if (nameSeperator <= 0) {
- return null;
- }
- return name.substring(0, nameSeperator);
- }
-
- /**
- * Get class loader offering a named package. This only works if we do not care
- * which package we get in case of several package versions
- *
- * @param reqPackageName
- * @return
- */
- private Bundle getBundleOfferingPackage(String reqPackageName) {
- Bundle[] bundles = context.getBundles();
- for (Bundle bundle : bundles) {
- BundleRevision rev = bundle.adapt(BundleRevision.class);
- if (rev != null) {
- List<BundleCapability> caps = rev.getDeclaredCapabilities(BundleRevision.PACKAGE_NAMESPACE);
- for (BundleCapability cap : caps) {
- Map<String, Object> attr = cap.getAttributes();
- String packageName = (String)attr.get(BundleRevision.PACKAGE_NAMESPACE);
- if (packageName.equals(reqPackageName)) {
- return bundle;
- }
- }
- }
- }
- return context.getBundle(0);
- }
-
- private ClassLoader getClassLoader(Bundle bundle) {
- BundleWiring wiring = bundle.adapt(BundleWiring.class);
- return wiring.getClassLoader();
- }
-
- //
- // Code below comes from Aries blueprint implementation. Given this code is not available
- // from a public API it has been copied here.
- //
- private Object newInstance(Constructor constructor, Object... args) throws Exception {
- return constructor.newInstance(args);
- }
-
- private Map<Constructor, List<Object>> findMatchingConstructors(Class type, List<Object> args, List<ReifiedType> types) {
- Map<Constructor, List<Object>> matches = new HashMap<Constructor, List<Object>>();
- // Get constructors
- List<Constructor> constructors = new ArrayList<Constructor>(Arrays.asList(type.getConstructors()));
- // Discard any signature with wrong cardinality
- for (Iterator<Constructor> it = constructors.iterator(); it.hasNext();) {
- if (it.next().getParameterTypes().length != args.size()) {
- it.remove();
- }
- }
- // Find a direct match with assignment
- if (matches.size() != 1) {
- Map<Constructor, List<Object>> nmatches = new HashMap<Constructor, List<Object>>();
- for (Constructor cns : constructors) {
- boolean found = true;
- List<Object> match = new ArrayList<Object>();
- for (int i = 0; i < args.size(); i++) {
- ReifiedType argType = new GenericType(cns.getGenericParameterTypes()[i]);
- if (types.get(i) != null && !argType.getRawClass().equals(types.get(i).getRawClass())) {
- found = false;
- break;
- }
- if (!isAssignable(args.get(i), argType)) {
- found = false;
- break;
- }
- try {
- match.add(convert(args.get(i), cns.getGenericParameterTypes()[i]));
- } catch (Throwable t) {
- found = false;
- break;
- }
- }
- if (found) {
- nmatches.put(cns, match);
- }
- }
- if (nmatches.size() > 0) {
- matches = nmatches;
- }
- }
- // Find a direct match with conversion
- if (matches.size() != 1) {
- Map<Constructor, List<Object>> nmatches = new HashMap<Constructor, List<Object>>();
- for (Constructor cns : constructors) {
- boolean found = true;
- List<Object> match = new ArrayList<Object>();
- for (int i = 0; i < args.size(); i++) {
- ReifiedType argType = new GenericType(cns.getGenericParameterTypes()[i]);
- if (types.get(i) != null && !argType.getRawClass().equals(types.get(i).getRawClass())) {
- found = false;
- break;
- }
- try {
- Object val = convert(args.get(i), argType);
- match.add(val);
- } catch (Throwable t) {
- found = false;
- break;
- }
- }
- if (found) {
- nmatches.put(cns, match);
- }
- }
- if (nmatches.size() > 0) {
- matches = nmatches;
- }
- }
- // Start reordering with assignment
- if (matches.size() != 1 && reorderArguments && args.size() > 1) {
- Map<Constructor, List<Object>> nmatches = new HashMap<Constructor, List<Object>>();
- for (Constructor cns : constructors) {
- ArgumentMatcher matcher = new ArgumentMatcher(cns.getGenericParameterTypes(), false);
- List<Object> match = matcher.match(args, types);
- if (match != null) {
- nmatches.put(cns, match);
- }
- }
- if (nmatches.size() > 0) {
- matches = nmatches;
- }
- }
- // Start reordering with conversion
- if (matches.size() != 1 && reorderArguments && args.size() > 1) {
- Map<Constructor, List<Object>> nmatches = new HashMap<Constructor, List<Object>>();
- for (Constructor cns : constructors) {
- ArgumentMatcher matcher = new ArgumentMatcher(cns.getGenericParameterTypes(), true);
- List<Object> match = matcher.match(args, types);
- if (match != null) {
- nmatches.put(cns, match);
- }
- }
- if (nmatches.size() > 0) {
- matches = nmatches;
- }
- }
- return matches;
- }
-
- protected Object convert(Object obj, Type type) throws Exception {
- return converter.convert(obj, new GenericType(type));
- }
-
- protected Object convert(Object obj, ReifiedType type) throws Exception {
- return converter.convert(obj, type);
- }
-
- @SuppressWarnings("unchecked")
- 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 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 static Object UNMATCHED = new Object();
-
- private class ArgumentMatcher {
-
- private List<TypeEntry> entries;
- private boolean convert;
-
- public ArgumentMatcher(Type[] types, boolean convert) {
- entries = new ArrayList<TypeEntry>();
- for (Type type : types) {
- entries.add(new TypeEntry(new GenericType(type)));
- }
- this.convert = convert;
- }
-
- public List<Object> match(List<Object> arguments, List<ReifiedType> forcedTypes) {
- if (find(arguments, forcedTypes)) {
- return getArguments();
- }
- return null;
- }
-
- private List<Object> getArguments() {
- List<Object> list = new ArrayList<Object>();
- for (TypeEntry entry : entries) {
- if (entry.argument == UNMATCHED) {
- throw new RuntimeException("There are unmatched types");
- } else {
- list.add(entry.argument);
- }
- }
- return list;
- }
-
- private boolean find(List<Object> arguments, List<ReifiedType> forcedTypes) {
- if (entries.size() == arguments.size()) {
- boolean matched = true;
- for (int i = 0; i < arguments.size() && matched; i++) {
- matched = find(arguments.get(i), forcedTypes.get(i));
- }
- return matched;
- }
- return false;
- }
-
- private boolean find(Object arg, ReifiedType forcedType) {
- for (TypeEntry entry : entries) {
- Object val = arg;
- if (entry.argument != UNMATCHED) {
- continue;
- }
- if (forcedType != null) {
- if (!forcedType.equals(entry.type)) {
- continue;
- }
- } else if (arg != null) {
- if (convert) {
- try {
- // TODO: call canConvert instead of convert()
- val = convert(arg, entry.type);
- } catch (Throwable t) {
- continue;
- }
- } else {
- if (!isAssignable(arg, entry.type)) {
- continue;
- }
- }
- }
- entry.argument = val;
- return true;
- }
- return false;
- }
-
- }
-
- private static class TypeEntry {
-
- private final ReifiedType type;
- private Object argument;
-
- public TypeEntry(ReifiedType type) {
- this.type = type;
- this.argument = UNMATCHED;
- }
-
- }
-
- public static Throwable getRealCause(Throwable t) {
- if (t instanceof InvocationTargetException && t.getCause() != null) {
- return t.getCause();
- }
- return t;
- }
-}
http://git-wip-us.apache.org/repos/asf/karaf/blob/f1dd4a94/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/SleepAction.java
----------------------------------------------------------------------
diff --git a/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/SleepAction.java b/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/SleepAction.java
deleted file mode 100644
index e8b1103..0000000
--- a/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/SleepAction.java
+++ /dev/null
@@ -1,58 +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.karaf.shell.commands.impl;
-
-import org.apache.karaf.shell.api.action.Action;
-import org.apache.karaf.shell.api.action.Argument;
-import org.apache.karaf.shell.api.action.Command;
-import org.apache.karaf.shell.api.action.Option;
-import org.apache.karaf.shell.api.action.lifecycle.Service;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-@Command(scope = "shell", name = "sleep", description = "Sleeps for a bit then wakes up.")
-@Service
-public class SleepAction implements Action {
-
- private final Logger log = LoggerFactory.getLogger(getClass());
-
- @Argument(index = 0, name = "duration", description = "The amount of time to sleep. The default time unit is millisecond, use -s option to use second instead.", required = true, multiValued = false)
- private long time = -1;
-
- @Option(name = "-s", aliases = { "--second" }, description = "Use a duration time in seconds instead of milliseconds.", required = false, multiValued = false)
- private boolean second = false;
-
- @Override
- public Object execute() throws Exception {
- if (second) {
- log.info("Sleeping for {} second(s)", time);
- time = time * 1000;
- } else {
- log.info("Sleeping for {} millisecond(s)", time);
- }
-
- try {
- Thread.sleep(time);
- }
- catch (InterruptedException ignore) {
- log.debug("Sleep was interrupted... :-(");
- }
-
- log.info("Awake now");
- return null;
- }
-}
http://git-wip-us.apache.org/repos/asf/karaf/blob/f1dd4a94/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/SortAction.java
----------------------------------------------------------------------
diff --git a/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/SortAction.java b/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/SortAction.java
deleted file mode 100644
index 4b9d165..0000000
--- a/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/SortAction.java
+++ /dev/null
@@ -1,404 +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.karaf.shell.commands.impl;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.PrintStream;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.List;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.apache.karaf.shell.api.action.Action;
-import org.apache.karaf.shell.api.action.Argument;
-import org.apache.karaf.shell.api.action.Command;
-import org.apache.karaf.shell.api.action.Option;
-import org.apache.karaf.shell.api.action.lifecycle.Service;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Sort lines of text
- */
-@Command(scope = "shell", name = "sort", description = "Writes sorted concatenation of all files to standard output.")
-@Service
-public class SortAction implements Action {
-
- private final Logger log = LoggerFactory.getLogger(getClass());
-
- @Option(name = "-f", aliases = { "-ignore-case" }, description = "fold lower case to upper case characters", required = false, multiValued = false)
- private boolean caseInsensitive;
-
- @Option(name = "-r", aliases = { "--reverse" }, description = "reverse the result of comparisons", required = false, multiValued = false)
- private boolean reverse;
-
- @Option(name = "-u", aliases = { "--unique" }, description = "output only the first of an equal run", required = false, multiValued = false)
- private boolean unique;
-
- @Option(name = "-t", aliases = { "--field-separator" }, description = "use SEP instead of non-blank to blank transition", required = false, multiValued = false)
- private String separator;
-
- @Option(name = "-b", aliases = { "--ignore-leading-blanks" }, description = "ignore leading blanks", required = false, multiValued = false)
- private boolean ignoreBlanks;
-
- @Option(name = "-k", aliases = { "--key" }, description = "Fields to use for sorting separated by whitespaces", required = false, multiValued = true)
- private List<String> sortFields;
-
- @Option(name = "-n", aliases = { "--numeric-sort" }, description = "compare according to string numerical value", required = false, multiValued = false)
- private boolean numeric;
-
- @Argument(index = 0, name = "files", description = "A list of files separated by whitespaces", required = false, multiValued = true)
- private List<String> paths;
-
- @Override
- public Object execute() throws Exception {
- if (paths != null && paths.size() > 0) {
- List<String> lines = new ArrayList<String>();
- for (String filename : paths) {
- BufferedReader reader;
-
- // First try a URL
- try {
- URL url = new URL(filename);
- log.info("Printing URL: " + url);
- reader = new BufferedReader(new InputStreamReader(url.openStream()));
- }
- catch (MalformedURLException ignore) {
- // They try a file
- File file = new File(filename);
- log.info("Printing file: " + file);
- reader = new BufferedReader(new FileReader(file));
- }
-
- try {
- read(reader, lines);
- }
- finally {
- try {
- reader.close();
- } catch (IOException e) {
- // Ignore
- }
- }
- }
- sort(lines, System.out);
- }
- else {
- sort(System.in, System.out);
- }
- return null;
- }
-
- protected void read(BufferedReader r, List<String> lines) throws Exception {
- for (String s = r.readLine(); s != null; s = r.readLine()) {
- lines.add(s);
- }
- }
-
- protected void sort(InputStream input, PrintStream out) throws Exception {
- List<String> strings = new ArrayList<String>();
- BufferedReader r = new BufferedReader(new InputStreamReader(input));
- read(r, strings);
- sort(strings, out);
- }
-
- protected void sort(List<String> strings, PrintStream out) throws Exception {
- char sep = (separator == null || separator.length() == 0) ? '\0' : separator.charAt(0);
- Collections.sort(strings, new SortComparator(caseInsensitive, reverse, ignoreBlanks, numeric, sep, sortFields));
- String last = null;
- for (String s : strings) {
- if (!unique || last == null || !s.equals(last)) {
- out.println(s);
- }
- last = s;
- }
- }
-
- public static class SortComparator implements Comparator<String> {
-
- private boolean caseInsensitive;
- private boolean reverse;
- private boolean ignoreBlanks;
- private boolean numeric;
- private char separator;
- private List<Key> sortKeys;
-
- private static Pattern fpPattern;
- static {
- final String Digits = "(\\p{Digit}+)";
- final String HexDigits = "(\\p{XDigit}+)";
- final String Exp = "[eE][+-]?" + Digits;
- final String fpRegex = "([\\x00-\\x20]*[+-]?(NaN|Infinity|(((" + Digits + "(\\.)?(" + Digits + "?)(" + Exp + ")?)|(\\.(" + Digits + ")(" + Exp + ")?)|(((0[xX]" + HexDigits + "(\\.)?)|(0[xX]" + HexDigits + "?(\\.)" + HexDigits + "))[pP][+-]?" + Digits + "))" + "[fFdD]?))[\\x00-\\x20]*)(.*)";
- fpPattern = Pattern.compile(fpRegex);
- }
-
- public SortComparator(boolean caseInsensitive,
- boolean reverse,
- boolean ignoreBlanks,
- boolean numeric,
- char separator,
- List<String> sortFields) {
- this.caseInsensitive = caseInsensitive;
- this.reverse = reverse;
- this.separator = separator;
- this.ignoreBlanks = ignoreBlanks;
- this.numeric = numeric;
- if (sortFields == null || sortFields.size() == 0) {
- sortFields = new ArrayList<String>();
- sortFields.add("1");
- }
- sortKeys = new ArrayList<Key>();
- for (String f : sortFields) {
- sortKeys.add(new Key(f));
- }
- }
-
- public int compare(String o1, String o2) {
- int res = 0;
-
- List<Integer> fi1 = getFieldIndexes(o1);
- List<Integer> fi2 = getFieldIndexes(o2);
- for (Key key : sortKeys) {
- int[] k1 = getSortKey(o1, fi1, key);
- int[] k2 = getSortKey(o2, fi2, key);
- if (key.numeric) {
- Double d1 = getDouble(o1, k1[0], k1[1]);
- Double d2 = getDouble(o2, k2[0], k2[1]);
- res = d1.compareTo(d2);
- } else {
- res = compareRegion(o1, k1[0], k1[1], o2, k2[0], k2[1], key.caseInsensitive);
- }
- if (res != 0) {
- if (key.reverse) {
- res = - res;
- }
- break;
- }
- }
- return res;
- }
-
- protected Double getDouble(String s, int start, int end) {
- Matcher m = fpPattern.matcher(s.substring(start, end));
- m.find();
- return new Double(s.substring(0, m.end(1)));
- }
-
- protected int compareRegion(String s1, int start1, int end1, String s2, int start2, int end2, boolean caseInsensitive) {
- int n1 = end1, n2 = end2;
- for (int i1 = start1, i2 = start2; i1 < end1 && i2 < n2; i1++, i2++) {
- char c1 = s1.charAt(i1);
- char c2 = s2.charAt(i2);
- if (c1 != c2) {
- if (caseInsensitive) {
- c1 = Character.toUpperCase(c1);
- c2 = Character.toUpperCase(c2);
- if (c1 != c2) {
- c1 = Character.toLowerCase(c1);
- c2 = Character.toLowerCase(c2);
- if (c1 != c2) {
- return c1 - c2;
- }
- }
- } else {
- return c1 - c2;
- }
- }
- }
- return n1 - n2;
- }
-
- protected int[] getSortKey(String str, List<Integer> fields, Key key) {
- int start;
- int end;
- if (key.startField * 2 <= fields.size()) {
- start = fields.get((key.startField - 1) * 2);
- if (key.ignoreBlanksStart) {
- while (start < fields.get((key.startField - 1) * 2 + 1) && Character.isWhitespace(str.charAt(start))) {
- start++;
- }
- }
- if (key.startChar > 0) {
- start = Math.min(start + key.startChar - 1, fields.get((key.startField - 1) * 2 + 1));
- }
- } else {
- start = 0;
- }
- if (key.endField > 0 && key.endField * 2 <= fields.size()) {
- end = fields.get((key.endField - 1) * 2);
- if (key.ignoreBlanksEnd) {
- while (end < fields.get((key.endField - 1) * 2 + 1) && Character.isWhitespace(str.charAt(end))) {
- end++;
- }
- }
- if (key.endChar > 0) {
- end = Math.min(end + key.endChar - 1, fields.get((key.endField - 1) * 2 + 1));
- }
- } else {
- end = str.length();
- }
- return new int[] { start, end };
- }
-
- protected List<Integer> getFieldIndexes(String o) {
- List<Integer> fields = new ArrayList<Integer>();
- if (o.length() > 0) {
- if (separator == '\0') {
- int i = 0;
- fields.add(0);
- for (int idx = 1; idx < o.length(); idx++) {
- if (Character.isWhitespace(o.charAt(idx)) && !Character.isWhitespace(o.charAt(idx - 1))) {
- fields.add(idx - 1);
- fields.add(idx);
- }
- }
- fields.add(o.length() - 1);
- } else {
- int last = -1;
- for (int idx = o.indexOf(separator); idx >= 0; idx = o.indexOf(separator, idx + 1)) {
- if (last >= 0) {
- fields.add(last);
- fields.add(idx - 1);
- } else if (idx > 0) {
- fields.add(0);
- fields.add(idx - 1);
- }
- last = idx + 1;
- }
- if (last < o.length()) {
- fields.add(last < 0 ? 0 : last);
- fields.add(o.length() - 1);
- }
- }
- }
- return fields;
- }
-
- public class Key {
- int startField;
- int startChar;
- int endField;
- int endChar;
- boolean ignoreBlanksStart;
- boolean ignoreBlanksEnd;
- boolean caseInsensitive;
- boolean reverse;
- boolean numeric;
-
- public Key(String str) {
- boolean modifiers = false;
- boolean startPart = true;
- boolean inField = true;
- boolean inChar = false;
- for (char c : str.toCharArray()) {
- switch (c) {
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- if (!inField && !inChar) {
- throw new IllegalArgumentException("Bad field syntax: " + str);
- }
- if (startPart) {
- if (inChar) {
- startChar = startChar * 10 + (c - '0');
- } else {
- startField = startField * 10 + (c - '0');
- }
- } else {
- if (inChar) {
- endChar = endChar * 10 + (c - '0');
- } else {
- endField = endField * 10 + (c - '0');
- }
- }
- break;
- case '.':
- if (!inField) {
- throw new IllegalArgumentException("Bad field syntax: " + str);
- }
- inField = false;
- inChar = true;
- break;
- case 'n':
- inField = false;
- inChar = false;
- modifiers = true;
- numeric = true;
- break;
- case 'f':
- inField = false;
- inChar = false;
- modifiers = true;
- caseInsensitive = true;
- break;
- case 'r':
- inField = false;
- inChar = false;
- modifiers = true;
- reverse = true;
- break;
- case 'b':
- inField = false;
- inChar = false;
- modifiers = true;
- if (startPart) {
- ignoreBlanksStart = true;
- } else {
- ignoreBlanksEnd = true;
- }
- break;
- case ',':
- inField = true;
- inChar = false;
- startPart = false;
- break;
- default:
- throw new IllegalArgumentException("Bad field syntax: " + str);
- }
- }
- if (!modifiers) {
- ignoreBlanksStart = ignoreBlanksEnd = SortComparator.this.ignoreBlanks;
- reverse = SortComparator.this.reverse;
- caseInsensitive = SortComparator.this.caseInsensitive;
- numeric = SortComparator.this.numeric;
- }
- if (startField < 1) {
- throw new IllegalArgumentException("Bad field syntax: " + str);
- }
- }
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/karaf/blob/f1dd4a94/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/TacAction.java
----------------------------------------------------------------------
diff --git a/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/TacAction.java b/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/TacAction.java
deleted file mode 100644
index 5cf1b20..0000000
--- a/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/TacAction.java
+++ /dev/null
@@ -1,77 +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.karaf.shell.commands.impl;
-
-import java.io.StringWriter;
-import java.io.BufferedReader;
-import java.io.InputStreamReader;
-import java.io.File;
-import java.io.BufferedWriter;
-import java.io.FileOutputStream;
-import java.io.OutputStreamWriter;
-import java.io.Writer;
-
-import org.apache.karaf.shell.api.action.Action;
-import org.apache.karaf.shell.api.action.Command;
-import org.apache.karaf.shell.api.action.Option;
-import org.apache.karaf.shell.api.console.Session;
-import org.apache.karaf.shell.api.action.lifecycle.Reference;
-import org.apache.karaf.shell.api.action.lifecycle.Service;
-
-/**
- * Grab the text from the standard input and return it as a string.
- * Also write this text to a file if specified
- */
-@Command(scope = "shell", name = "tac", description = "Captures the STDIN and returns it as a string. Optionally writes the content to a file.")
-@Service
-public class TacAction implements Action {
-
- @Option(name = "-f", aliases = {}, description = "Outputs the content to the given file", required = false, multiValued = false)
- private File file;
-
- @Reference
- Session session;
-
- @Override
- public Object execute() throws Exception {
- StringWriter sw = new StringWriter();
- Writer[] writers;
- if (file != null) {
- writers = new Writer[] { sw, new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))) };
- } else {
- writers = new Writer[] { sw };
- }
- BufferedReader rdr = new BufferedReader(new InputStreamReader(System.in));
- String s = rdr.readLine();
- boolean first = true;
- while (s != null)
- {
- for (Writer w : writers) {
- if (!first) {
- w.write("\n");
- }
- w.write(s);
- }
- first = false;
- s = rdr.readLine();
- }
- for (Writer w : writers) {
- w.close();
- }
- return sw.toString();
- }
-}
http://git-wip-us.apache.org/repos/asf/karaf/blob/f1dd4a94/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/TailAction.java
----------------------------------------------------------------------
diff --git a/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/TailAction.java b/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/TailAction.java
deleted file mode 100644
index 435816c..0000000
--- a/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/TailAction.java
+++ /dev/null
@@ -1,136 +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.karaf.shell.commands.impl;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.LinkedList;
-
-import org.apache.karaf.shell.api.action.Action;
-import org.apache.karaf.shell.api.action.Argument;
-import org.apache.karaf.shell.api.action.Command;
-import org.apache.karaf.shell.api.action.Option;
-import org.apache.karaf.shell.api.action.lifecycle.Service;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-@Command(scope = "shell", name = "tail", description = "Displays the last lines of a file.")
-@Service
-public class TailAction implements Action {
-
- private final Logger log = LoggerFactory.getLogger(getClass());
-
- private static final int DEFAULT_NUMBER_OF_LINES = 10;
-
- private static final int DEFAULT_SLEEP_INTERVAL = 200;
-
- @Option(name = "-n", aliases = {}, description = "The number of lines to display, starting at 1.", required = false, multiValued = false)
- private int numberOfLines;
-
- @Option(name = "-f", aliases = {}, description = "Follow file changes", required = false, multiValued = false)
- private boolean continuous;
-
- @Option(name = "-s", aliases = {}, description = "Sleep interval (used for follow)", required = false, multiValued = false)
- private long sleepInterval;
-
- @Argument(index = 0, name = "path or url", description = "A file path or url to display.", required = false, multiValued = false)
- private String path;
-
- @Override
- public Object execute() throws Exception {
- //If no paths provided assume standar input
- if (path == null || path.trim().length() == 0) {
- if (log.isDebugEnabled()) {
- log.debug("Tailing STDIN");
- }
- tail(new BufferedReader(new InputStreamReader(System.in)));
- } else {
- BufferedReader reader;
-
- // First try a URL
- try {
- URL url = new URL(path);
- if (log.isDebugEnabled()) {
- log.debug("Tailing URL: " + url);
- }
- reader = new BufferedReader(new InputStreamReader(url.openStream()));
- }
- catch (MalformedURLException ignore) {
- // They try a file
- File file = new File(path);
- if (log.isDebugEnabled()) {
- log.debug("Tailing file: " + file);
- }
- reader = new BufferedReader(new FileReader(file));
- }
-
- try {
- tail(reader);
- }
- finally {
- try {
- reader.close();
- } catch (IOException e) {
- // Ignore
- }
- }
- }
- return null;
- }
-
- /**
- * prints the tail of the file / url
- *
- * @param reader
- * @throws IOException
- */
- private void tail(final BufferedReader reader) throws InterruptedException, IOException {
-
- if (numberOfLines < 1) {
- numberOfLines = DEFAULT_NUMBER_OF_LINES;
- }
- if (sleepInterval < 1) {
- sleepInterval = DEFAULT_SLEEP_INTERVAL;
- }
-
- LinkedList<String> lines = new LinkedList<String>();
- String line;
- while ((line = reader.readLine()) != null) {
- lines.add(line);
- if (lines.size() > numberOfLines) {
- lines.removeFirst();
- }
- }
-
- for (String l : lines) {
- System.out.println(l);
- }
-
- //If command is running as continuous
- while (continuous) {
- Thread.sleep(sleepInterval);
- while ((line = reader.readLine()) != null) {
- System.out.println(line);
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/karaf/blob/f1dd4a94/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/WcAction.java
----------------------------------------------------------------------
diff --git a/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/WcAction.java b/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/WcAction.java
deleted file mode 100644
index 4a063f8..0000000
--- a/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/WcAction.java
+++ /dev/null
@@ -1,218 +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.karaf.shell.commands.impl;
-
-import org.apache.karaf.shell.api.action.Action;
-import org.apache.karaf.shell.api.action.Argument;
-import org.apache.karaf.shell.api.action.Command;
-import org.apache.karaf.shell.api.action.Option;
-import org.apache.karaf.shell.api.action.lifecycle.Service;
-
-import java.io.*;
-import java.util.List;
-
-@Command(scope = "shell", name = "wc", description = "Print newline, word, and byte counts for each file.")
-@Service
-public class WcAction implements Action {
-
- @Option(name = "-l", aliases = { "--lines" }, description = "Print the newline counts.", required = false, multiValued = false)
- private boolean lines;
-
- @Option(name = "-w", aliases = { "--words" }, description = "Print the word counts.", required = false, multiValued = false)
- private boolean words;
-
- @Option(name = "-m", aliases = { "--chars" }, description = "Print the character counts.", required = false, multiValued = false)
- private boolean chars;
-
- @Option(name = "-c", aliases = { "--bytes" }, description = "Print the byte counts.", required = false, multiValued = false)
- private boolean bytes;
-
- @Argument(index = 0, name = "files", description = "The list of files where to perform the count", required = false, multiValued = true)
- private List<File> files;
-
- @Override
- public Object execute() throws Exception {
- this.setDefaultOptions();
-
- String outputString;
-
- if (files == null) {
- WordCounts wordCounts = getWordCounts(System.in);
- outputString = formatWordCounts(wordCounts, null);
- } else {
- outputString = getFilesWordCountReport(files);
- }
-
- System.out.println(outputString);
- return null;
- }
-
- /**
- * Create a combined word count report of the required files.
- * If there are more than one file supplied, a total row will be added.
- *
- * @param files the list of files.
- * @return the word count report String.
- * @throws IOException in case of a count failure.
- */
- protected String getFilesWordCountReport(List<File> files) throws IOException {
- StringBuilder stringBuilder = new StringBuilder();
- WordCounts totalWordCounts = new WordCounts();
- for (File file : files) {
- WordCounts fileWordCount = getWordCounts(new FileInputStream(file));
- String fileFormattedString = formatWordCounts(fileWordCount, file.getName());
- // add it to the running total which will be outputted at the end
- totalWordCounts = totalWordCounts.add(fileWordCount);
- stringBuilder.append(fileFormattedString).append('\n');
- }
- // add additional total row
- if (files.size() > 1) {
- stringBuilder.append(formatWordCounts(totalWordCounts, "total"));
- }
-
- String report = stringBuilder.toString();
- return report;
- }
-
- /**
- * Set the default options for this action if none have been supplied.
- */
- protected void setDefaultOptions() {
- boolean noOptionsSupplied = !(bytes || chars || lines || words);
-
- if (noOptionsSupplied) {
- lines = true;
- words = true;
- bytes = true;
- }
- }
-
- /**
- * <p>Perform the main logic of counting the relevant data within a given input stream.</p>
- * <p>Note, a line is considered to be terminated by linefeed '\n' or carriage return '\r'.</p>
- * <p>A previous linefeed will be consumed.</p>
- * <p>This method assumes UTF-8.</p>
- *
- * @param inputStream the input stream.
- * @return the word count result.
- * @throws IOException in case of word count failure.
- */
- protected WordCounts getWordCounts(InputStream inputStream) throws IOException {
- WordCounts wordCounts = new WordCounts();
-
- BufferedReader bufferedReader = null;
- try {
- bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
-
- int current;
- boolean skipNextLineFeed = false;
- boolean previouslyWhitespace = true;
- while ((current = bufferedReader.read()) != -1) {
- wordCounts.byteCount++;
- wordCounts.charCount++;
-
- // line handling
- // if the previous read was a new line, skip the next newline feed
- boolean isSkipNewlineFeed = skipNextLineFeed && current == '\n';
- skipNextLineFeed = false;
- if (isSkipNewlineFeed) {
- continue;
- }
-
- boolean eol = (current == '\n' || current == '\r');
- if (eol) {
- wordCounts.lineCount++;
- // store the state to skip the next newline feed if required
- if (current == '\r') {
- skipNextLineFeed = true;
- }
- }
-
- // word handling
- boolean isCurrentWhitespace = Character.isWhitespace(current);
- if (!isCurrentWhitespace && previouslyWhitespace) {
- wordCounts.wordCount++;
- }
- previouslyWhitespace = isCurrentWhitespace;
- }
- } finally {
- if (bufferedReader != null) {
- bufferedReader.close();
- }
- }
-
- return wordCounts;
- }
-
- /**
- * Create a human readable format of the given count information.
- *
- * @param wordCounts the word count object containing the information.
- * @param reportName the name associated with the word counts, ie a file name.
- * @return a human readable String representing the word count information.
- */
- protected String formatWordCounts(WordCounts wordCounts, String reportName) {
- // line word chars
- StringBuilder stringBuilder = new StringBuilder();
-
- if (lines) {
- stringBuilder.append('\t').append(wordCounts.lineCount);
- }
-
- if (words) {
- stringBuilder.append('\t').append(wordCounts.wordCount);
- }
-
- if (chars) {
- stringBuilder.append('\t').append(wordCounts.charCount);
- }
-
- if (bytes) {
- stringBuilder.append('\t').append(wordCounts.byteCount);
- }
-
- if (reportName != null) {
- stringBuilder.append('\t').append(reportName);
- }
-
- String formattedString = stringBuilder.toString();
-
- return formattedString;
- }
-
- /**
- * Represent a basic object to store the word count data.
- */
- protected static class WordCounts {
-
- protected int lineCount;
- protected int wordCount;
- protected int byteCount;
- protected int charCount;
-
- public WordCounts add(WordCounts append) {
- WordCounts wordCounts = new WordCounts();
- wordCounts.charCount = charCount + append.charCount;
- wordCounts.byteCount = byteCount + append.byteCount;
- wordCounts.lineCount = lineCount + append.lineCount;
- wordCounts.wordCount = wordCount + append.wordCount;
- return wordCounts;
- }
-
- }
-
-}
http://git-wip-us.apache.org/repos/asf/karaf/blob/f1dd4a94/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/WhileAction.java
----------------------------------------------------------------------
diff --git a/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/WhileAction.java b/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/WhileAction.java
deleted file mode 100644
index 90b17a6..0000000
--- a/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/WhileAction.java
+++ /dev/null
@@ -1,73 +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.karaf.shell.commands.impl;
-
-import java.util.Collection;
-import java.util.Collections;
-
-import org.apache.karaf.shell.api.action.Action;
-import org.apache.karaf.shell.api.action.Argument;
-import org.apache.karaf.shell.api.action.Command;
-import org.apache.karaf.shell.api.action.lifecycle.Reference;
-import org.apache.karaf.shell.api.action.lifecycle.Service;
-import org.apache.karaf.shell.api.console.Function;
-import org.apache.karaf.shell.api.console.Session;
-
-/**
- * Execute a closure on a list of arguments.
- */
-@Command(scope = "shell", name = "while", description = "Loop while the condition is true.")
-@Service
-public class WhileAction implements Action {
-
- @Argument(name = "condition", index = 0, multiValued = false, required = true, description = "The condition of the loop")
- Function condition;
-
- @Argument(name = "function", index = 1, multiValued = false, required = true, description = "The function to execute")
- Function function;
-
- @Reference
- Session session;
-
- @Override
- public Object execute() throws Exception {
- while (isTrue(condition.execute(session, null))) {
- function.execute(session, null);
- if (Thread.currentThread().isInterrupted()) {
- throw new InterruptedException();
- }
- }
- return null;
- }
-
- private boolean isTrue(Object result) {
- if (result == null) {
- return false;
- }
- if (result instanceof String && ((String) result).equals("")) {
- return false;
- }
- if (result instanceof Number) {
- return ((Number) result).doubleValue() != 0.0d;
- }
- if (result instanceof Boolean) {
- return (Boolean) result;
- }
- return true;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/karaf/blob/f1dd4a94/shell/commands/src/main/resources/META-INF/services/org/apache/karaf/shell/commands
----------------------------------------------------------------------
diff --git a/shell/commands/src/main/resources/META-INF/services/org/apache/karaf/shell/commands b/shell/commands/src/main/resources/META-INF/services/org/apache/karaf/shell/commands
index 686ce64..483823b 100644
--- a/shell/commands/src/main/resources/META-INF/services/org/apache/karaf/shell/commands
+++ b/shell/commands/src/main/resources/META-INF/services/org/apache/karaf/shell/commands
@@ -14,33 +14,14 @@
## See the License for the specific language governing permissions and
## limitations under the License.
##---------------------------------------------------------------------------
-org.apache.karaf.shell.commands.impl.AliasAction
-org.apache.karaf.shell.commands.impl.CatAction
-org.apache.karaf.shell.commands.impl.ClearAction
org.apache.karaf.shell.commands.impl.CompletionAction
-org.apache.karaf.shell.commands.impl.DateAction
-org.apache.karaf.shell.commands.impl.EachAction
-org.apache.karaf.shell.commands.impl.EchoAction
-org.apache.karaf.shell.commands.impl.EditAction
-org.apache.karaf.shell.commands.impl.EnvAction
org.apache.karaf.shell.commands.impl.ExecuteAction
-org.apache.karaf.shell.commands.impl.GrepAction
-org.apache.karaf.shell.commands.impl.HeadAction
-org.apache.karaf.shell.commands.impl.HistoryAction
-org.apache.karaf.shell.commands.impl.IfAction
org.apache.karaf.shell.commands.impl.InfoAction
org.apache.karaf.shell.commands.impl.JavaAction
org.apache.karaf.shell.commands.impl.LogoutAction
-org.apache.karaf.shell.commands.impl.MoreAction
-org.apache.karaf.shell.commands.impl.NewAction
org.apache.karaf.shell.commands.impl.PrintfAction
org.apache.karaf.shell.commands.impl.PrintStackTracesAction
-org.apache.karaf.shell.commands.impl.SleepAction
-org.apache.karaf.shell.commands.impl.SortAction
org.apache.karaf.shell.commands.impl.SourceAction
-org.apache.karaf.shell.commands.impl.TacAction
-org.apache.karaf.shell.commands.impl.TailAction
org.apache.karaf.shell.commands.impl.ThreadsAction
org.apache.karaf.shell.commands.impl.TTopAction
org.apache.karaf.shell.commands.impl.WatchAction
-org.apache.karaf.shell.commands.impl.WcAction
http://git-wip-us.apache.org/repos/asf/karaf/blob/f1dd4a94/shell/commands/src/main/resources/org/apache/karaf/shell/commands/impl/grep.txt
----------------------------------------------------------------------
diff --git a/shell/commands/src/main/resources/org/apache/karaf/shell/commands/impl/grep.txt b/shell/commands/src/main/resources/org/apache/karaf/shell/commands/impl/grep.txt
deleted file mode 100644
index 1ada069..0000000
--- a/shell/commands/src/main/resources/org/apache/karaf/shell/commands/impl/grep.txt
+++ /dev/null
@@ -1 +0,0 @@
-Grep uses Java regular expressions for pattern matching. For more informations, see http://download.oracle.com/javase/1.5.0/docs/api/java/util/regex/Pattern.html
http://git-wip-us.apache.org/repos/asf/karaf/blob/f1dd4a94/shell/commands/src/main/resources/org/apache/karaf/shell/commands/impl/wc.txt
----------------------------------------------------------------------
diff --git a/shell/commands/src/main/resources/org/apache/karaf/shell/commands/impl/wc.txt b/shell/commands/src/main/resources/org/apache/karaf/shell/commands/impl/wc.txt
deleted file mode 100644
index 0923c71..0000000
--- a/shell/commands/src/main/resources/org/apache/karaf/shell/commands/impl/wc.txt
+++ /dev/null
@@ -1,35 +0,0 @@
-This command will output the information in the following format
-
- Lines Words Characters Bytes Name
-
-Note, the name field will not always be present. For example, in the case of a piped
-application of wc.
-
-Example usage :
-
- Display information about a single file
-
- wc LICENSE
-
- Which outputs
-
- 475 4053 28230 LICENSE
-
- Display information about multiple files
-
- wc LICENSE README RELEASE-NOTES
-
- Which outputs
-
- 475 4053 28230 LICENSE
- 77 562 3933 README
- 1831 16765 118449 RELEASE-NOTES
- 2383 21380 150612 total
-
- Piped example
-
- echo "Hello World" | wc -w -l
-
- Which outputs
-
- 1 2
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/karaf/blob/f1dd4a94/shell/commands/src/test/java/org/apache/karaf/shell/commands/impl/GrepTest.java
----------------------------------------------------------------------
diff --git a/shell/commands/src/test/java/org/apache/karaf/shell/commands/impl/GrepTest.java b/shell/commands/src/test/java/org/apache/karaf/shell/commands/impl/GrepTest.java
deleted file mode 100644
index c2bea94..0000000
--- a/shell/commands/src/test/java/org/apache/karaf/shell/commands/impl/GrepTest.java
+++ /dev/null
@@ -1,312 +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.karaf.shell.commands.impl;
-
-import org.apache.karaf.shell.impl.action.command.DefaultActionPreparator;
-import org.junit.Test;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.io.PrintStream;
-import java.util.Arrays;
-import java.util.List;
-import java.util.stream.Collectors;
-
-import static org.junit.Assert.*;
-
-public class GrepTest {
-
- private static final String ANSI_COLOR = "\u001b[1;31m";
- private static final String ANSI_RESET = "\u001b[0m";
-
- @Test
- public void testGrep() throws Exception {
- final String expectedColoredString = "1\n" + ANSI_COLOR + "2"
- + ANSI_RESET + "\n"
- + "3\n4\n5\n6\n7\n8\n9";
-
- GrepAction grep = new GrepAction();
- DefaultActionPreparator preparator = new DefaultActionPreparator();
- preparator.prepare(grep, null, Arrays.asList("--color", "always", "-C", "100", "2"));
- final String returnedString = systemInOutDecorator("1\n2\n3\n4\n5\n6\n7\n8\n9\n", grep);
- assertEquals(expectedColoredString, returnedString);
- }
-
- @Test
- public void testGrepInverted() throws Exception {
- GrepAction grep = new GrepAction();
- DefaultActionPreparator preparator = new DefaultActionPreparator();
- preparator.prepare(grep, null, Arrays.asList("-v", "--color", "never", "mine"));
- final String returnedString = systemInOutDecorator("This is Hello World\nWorld is mine\nHello World!\n",
- grep);
- assertEquals("This is Hello World\nHello World!", returnedString);
- }
-
- @Test
- public void testGrepMatching() throws Exception {
- GrepAction grep = new GrepAction();
- DefaultActionPreparator preparator = new DefaultActionPreparator();
- preparator.prepare(grep, null, Arrays.asList("--color", "never", "mine"));
- final String returnedString = systemInOutDecorator("This is Hello World\nWorld is mine\nHello World!\n",
- grep);
- assertEquals("World is mine", returnedString);
- }
-
- @Test
- public void testGrepMatchingWithColours() throws Exception {
- GrepAction grep = new GrepAction();
- DefaultActionPreparator preparator = new DefaultActionPreparator();
- preparator.prepare(grep, null, Arrays.asList("--color", "always", "mine"));
- final String returnedString = systemInOutDecorator("This is Hello World\nWorld is mine\nHello World!\n",
- grep);
- assertEquals("World is " + ANSI_COLOR + "mine" + ANSI_RESET, returnedString);
- }
-
- @Test
- public void testGrepCount() throws Exception {
- GrepAction grep = new GrepAction();
- DefaultActionPreparator preparator = new DefaultActionPreparator();
- preparator.prepare(grep, null, Arrays.asList("-c", "Hello World"));
- final String returnedString = systemInOutDecorator("This is Hello World\nWorld is mine\nHello World!\n",
- grep);
- assertEquals("2", returnedString);
- }
-
- @Test
- public void testGrepCountInvert() throws Exception {
- GrepAction grep = new GrepAction();
- DefaultActionPreparator preparator = new DefaultActionPreparator();
- preparator.prepare(grep, null, Arrays.asList("-c", "-v", "Hello World"));
- final String returnedString = systemInOutDecorator("This is Hello World\nWorld is mine\nHello World!\n",
- grep);
- assertEquals("1", returnedString);
- }
-
- @Test
- public void testGrepInvertedWithLineNumbers() throws Exception {
- GrepAction grep = new GrepAction();
- DefaultActionPreparator preparator = new DefaultActionPreparator();
- preparator.prepare(grep, null, Arrays.asList("-n", "-v", "--color", "never", "mine"));
- final String returnedString = systemInOutDecorator("This is Hello World\nWorld is mine\nHello World!\n",
- grep);
- assertEquals(" 1 This is Hello World\n 3 Hello World!", returnedString);
- }
-
- @Test
- public void testGrepMatchingWithLineNumbers() throws Exception {
- GrepAction grep = new GrepAction();
- DefaultActionPreparator preparator = new DefaultActionPreparator();
- preparator.prepare(grep, null, Arrays.asList("-n", "--color", "never", "Hello"));
- final String returnedString = systemInOutDecorator("This is Hello World\nWorld is mine\nHello World!\n",
- grep);
- assertEquals(" 1 This is Hello World\n 3 Hello World!", returnedString);
- }
-
- @Test
- public void testGrepWordRegExp() throws Exception {
- GrepAction grep = new GrepAction();
- DefaultActionPreparator preparator = new DefaultActionPreparator();
- preparator.prepare(grep, null, Arrays.asList("-w", "--color", "never", "is"));
- final String returnedString = systemInOutDecorator("This is Hello World\nWorld is mine\nHello World!\n",
- grep);
- assertEquals("This is Hello World\nWorld is mine", returnedString);
- }
-
- @Test
- public void testGrepIs() throws Exception {
- GrepAction grep = new GrepAction();
- DefaultActionPreparator preparator = new DefaultActionPreparator();
- preparator.prepare(grep, null, Arrays.asList("--color", "never", "is"));
- final String returnedString = systemInOutDecorator("This is Hello World\nWorld is mine\nHello World!\n",
- grep);
- assertEquals("This is Hello World\nWorld is mine", returnedString);
- }
-
- @Test
- public void testGrepRegExpWithColour() throws Exception {
- GrepAction grep = new GrepAction();
- final String expected = "Th"
- + ANSI_COLOR
- + "is" + ANSI_RESET
- + " "
- + ANSI_COLOR
- + "is" + ANSI_RESET
- + " Hello World\nWorld "
- + ANSI_COLOR
- + "is" + ANSI_RESET
- + " mine";
- DefaultActionPreparator preparator = new DefaultActionPreparator();
- preparator.prepare(grep, null, Arrays.asList("--color", "always", "is"));
- final String returnedString = systemInOutDecorator("This is Hello World\nWorld is mine\nHello World!\n",
- grep);
- assertEquals(expected, returnedString);
- }
-
- @Test
- public void testGrepWordRegExpWithColour() throws Exception {
- GrepAction grep = new GrepAction();
- final String expected = "This "
- + ANSI_COLOR
- + "is" + ANSI_RESET
- + " Hello World\nWorld "
- + ANSI_COLOR
- + "is" + ANSI_RESET
- + " mine";
- DefaultActionPreparator preparator = new DefaultActionPreparator();
- preparator.prepare(grep, null, Arrays.asList("-w", "--color", "always", "is"));
- final String returnedString = systemInOutDecorator("This is Hello World\nWorld is mine\nHello World!\n",
- grep);
- assertEquals(expected, returnedString);
- }
-
- @Test
- public void testGrepLineRegExpWithColour() throws Exception {
- GrepAction grep = new GrepAction();
- final String expected = ANSI_COLOR
- + "This is Hello World" + ANSI_RESET;
- DefaultActionPreparator preparator = new DefaultActionPreparator();
- preparator.prepare(grep, null, Arrays.asList("-x", "--color", "always", ".*Hello World"));
- final String returnedString = systemInOutDecorator("This is Hello World\nWorld is mine\nHello World!\n",
- grep);
- assertEquals(expected, returnedString);
- }
-
- @Test
- public void testGrepTwoLinesRegExpWithColour() throws Exception {
- GrepAction grep = new GrepAction();
- final String expected = ANSI_COLOR
- + "This is Hello World" + ANSI_RESET + "\n"
- + ANSI_COLOR
- + "Hello World!" + ANSI_RESET;
- DefaultActionPreparator preparator = new DefaultActionPreparator();
- preparator.prepare(grep, null, Arrays.asList("-x", "--color", "always", ".*Hello World.*"));
- final String returnedString = systemInOutDecorator("This is Hello World\nWorld is mine\nHello World!\n",
- grep);
- assertEquals(expected, returnedString);
- }
-
- @Test
- public void testGrepIgnoreCaseWithColour() throws Exception {
- GrepAction grep = new GrepAction();
- final String expected = "This is "
- + ANSI_COLOR
- + "hello" + ANSI_RESET + " World\n"
- + ANSI_COLOR
- + "Hello" + ANSI_RESET + " World!";
- DefaultActionPreparator preparator = new DefaultActionPreparator();
- preparator.prepare(grep, null, Arrays.asList("-i", "--color", "always", "HELLO"));
- final String returnedString = systemInOutDecorator("This is hello World\nWorld is mine\nHello World!\n",
- grep);
- assertEquals(expected, returnedString);
- }
-
- @Test
- public void testGrepContextOneWithColour() throws Exception {
- GrepAction grep = new GrepAction();
- final String expected = "This is "
- + ANSI_COLOR
- + "Hello" + ANSI_RESET + " World\n"
- + "World is mine\n"
- + ANSI_COLOR
- + "Hello" + ANSI_RESET + " World!";
- DefaultActionPreparator preparator = new DefaultActionPreparator();
- preparator.prepare(grep, null, Arrays.asList("-C", "1", "--color", "always", "Hello"));
- final String returnedString = systemInOutDecorator("This is Hello World\nWorld is mine\nHello World!\n",
- grep);
- assertEquals(expected, returnedString);
- }
-
- @Test
- public void testGrepBeforeContextOneWithColour() throws Exception {
- GrepAction grep = new GrepAction();
- final String expected = "World is mine\n"
- + ANSI_COLOR
- + "Hello World!" + ANSI_RESET;
- DefaultActionPreparator preparator = new DefaultActionPreparator();
- preparator.prepare(grep, null, Arrays.asList("-B", "1", "--color", "always", "Hello World!"));
- final String returnedString = systemInOutDecorator("This is Hello World\nWorld is mine\nHello World!\n",
- grep);
- assertEquals(expected, returnedString);
- }
-
- @Test
- public void testGrepAfterContextOneWithColour() throws Exception {
- GrepAction grep = new GrepAction();
- final String expected = "World is "
- + ANSI_COLOR
- + "mine" + ANSI_RESET
- + "\nHello World!";
- DefaultActionPreparator preparator = new DefaultActionPreparator();
- preparator.prepare(grep, null, Arrays.asList("-A", "1", "--color", "always", "mine"));
- final String returnedString = systemInOutDecorator("This is Hello World\nWorld is mine\nHello World!\n",
- grep);
- assertEquals(expected, returnedString);
- }
-
- @Test
- public void testGrepOnlyMatching() throws Exception {
- GrepAction grep = new GrepAction();
- DefaultActionPreparator preparator = new DefaultActionPreparator();
- preparator.prepare(grep, null, Arrays.asList("-o", "--color", "never", "He.*rld"));
- final String expectedString = systemInOutDecorator("This is Hello World\nWorld is mine\nHello World!\n",
- grep);
- assertEquals("Hello World\nHello World", expectedString);
- }
-
- @Test
- public void testGrepOnlyMatchingGroup() throws Exception {
- GrepAction grep = new GrepAction();
- DefaultActionPreparator preparator = new DefaultActionPreparator();
- preparator.prepare(grep, null, Arrays.asList("-o", "--color", "never", "(This).*(Hello)"));
- final String expectedString = systemInOutDecorator("This is Hello World\nWorld is mine\nHello World!\n",
- grep);
- assertEquals("This is Hello", expectedString);
- }
-
- @Test
- public void testHonorColorNever() throws Exception {
- GrepAction grep = new GrepAction();
- DefaultActionPreparator preparator = new DefaultActionPreparator();
- preparator.prepare(grep, null, Arrays.asList("--color", "never", "b"));
- final String expectedString = systemInOutDecorator("abc\n",
- grep);
- assertEquals("abc", expectedString);
-
- }
-
- private String systemInOutDecorator(String inputString, GrepAction grepExecute) throws Exception {
- InputStream input = System.in;
- PrintStream output = System.out;
- try {
- ByteArrayInputStream bais = new ByteArrayInputStream(inputString.getBytes());
- System.setIn(bais);
-
- String result = ((List<Object>) grepExecute.execute()).stream()
- .map(Object::toString).collect(Collectors.joining("\n"));
- if (result.length() > 1 && result.charAt(result.length() - 1) == '\n') {
- result = result.substring(0, result.length() - 1);
- }
- return result;
- } finally {
- System.setIn(input);
- System.setOut(output);
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/karaf/blob/f1dd4a94/shell/commands/src/test/java/org/apache/karaf/shell/commands/impl/SortTest.java
----------------------------------------------------------------------
diff --git a/shell/commands/src/test/java/org/apache/karaf/shell/commands/impl/SortTest.java b/shell/commands/src/test/java/org/apache/karaf/shell/commands/impl/SortTest.java
deleted file mode 100644
index f2b2f1b..0000000
--- a/shell/commands/src/test/java/org/apache/karaf/shell/commands/impl/SortTest.java
+++ /dev/null
@@ -1,91 +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.karaf.shell.commands.impl;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.PrintStream;
-import java.lang.reflect.Field;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Collections;
-
-import org.apache.karaf.shell.commands.impl.SortAction;
-
-import junit.framework.TestCase;
-
-public class SortTest extends TestCase {
-
- public void testFieldIndexesDefaultSep() {
- SortAction.SortComparator comparator = new SortAction.SortComparator(false, false, false, false, '\0', null);
- List<Integer> indexes = comparator.getFieldIndexes(" ad re t ");
- assertTrue(Arrays.asList(0, 2, 3, 6, 7, 9, 10, 10).equals(indexes));
- }
-
- public void testFieldIndexesWithSep() {
- SortAction.SortComparator comparator = new SortAction.SortComparator(false, false, false, false, '[', null);
- List<Integer> indexes = comparator.getFieldIndexes("[ 10] [Active ] [ ] [ 8] OPS4J Pax Logging - Service (1.3.0)");
- assertTrue(Arrays.asList(1, 6, 8, 20, 22, 30, 32, 73 ).equals(indexes));
-
- indexes = comparator.getFieldIndexes(" ad re t ");
- assertTrue(Arrays.asList(0, 10).equals(indexes));
- }
-
- public void testSort() {
- String s0 = "0321 abcd ddcba a";
- String s1 = " 57t bcad ddacb b";
- String s2 = " 128 cab ddbac c";
- List<String> strings = Arrays.asList(s0, s1, s2);
-
- Collections.sort(strings, new SortAction.SortComparator(false, false, false, false, '\0', Arrays.asList("2")));
- assertTrue(Arrays.asList(s0, s1, s2).equals(strings));
-
- Collections.sort(strings, new SortAction.SortComparator(false, false, false, false, '\0', Arrays.asList("2.2b")));
- assertTrue(Arrays.asList(s2, s0, s1).equals(strings));
-
- Collections.sort(strings, new SortAction.SortComparator(false, false, false, true, '\0', null));
- assertTrue(Arrays.asList(s1, s2, s0).equals(strings));
-
- Collections.sort(strings, new SortAction.SortComparator(false, true, false, false, '\0', Arrays.asList("4")));
- assertTrue(Arrays.asList(s2, s1, s0).equals(strings));
- }
-
- public void testSortToStdout() throws Exception {
- String newLine = System.getProperty("line.separator");
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- byte[] input = ("abc" + newLine + "def" + newLine).getBytes();
- new SortAction().sort(new ByteArrayInputStream(input), new PrintStream(baos));
- assertEquals(new String(input), new String(baos.toByteArray()));
- }
-
- public void testUniqSortToStdout() throws Exception {
- String newLine = System.getProperty("line.separator");
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- String inputString = "def" + newLine + "def" + newLine + "abc" + newLine + "abc" + newLine + "def" + newLine;
- byte[] input = inputString.getBytes();
- String outputString = ("abc" + newLine + "def" + newLine);
- SortAction sort = new SortAction();
- Field unique = SortAction.class.getDeclaredField("unique");
- unique.setAccessible(true);
- unique.set(sort, true);
- sort.sort(new ByteArrayInputStream(input), new PrintStream(baos));
- assertEquals(outputString, new String(baos.toByteArray()));
- }
-
-}
http://git-wip-us.apache.org/repos/asf/karaf/blob/f1dd4a94/shell/console/pom.xml
----------------------------------------------------------------------
diff --git a/shell/console/pom.xml b/shell/console/pom.xml
index 45804c4..0fc579b 100644
--- a/shell/console/pom.xml
+++ b/shell/console/pom.xml
@@ -175,9 +175,10 @@
org.apache.karaf.shell.inject;version=${project.version};-noimport:=true,
org.apache.karaf.shell.util;version=${project.version};-noimport:=true,
org.apache.karaf.shell.util;version=2.3.0;-noimport:=true,
- org.apache.felix.gogo*;version=${felix.gogo.runtime.version};-noimport:=true,
- org.apache.felix.service.command;version=${felix.gogo.runtime.version};-noimport:=true,
- org.apache.felix.service.threadio;version=${felix.gogo.runtime.version};status=provisional;mandatory:=status;-noimport:=true
+ org.apache.felix.gogo.api;version=0.17.0;status=provisional;-noimport:=true,
+ org.apache.felix.gogo.commands.*;version=0.17.0;-noimport:=true,
+ org.apache.felix.service.command;version=0.17.0;status=provisional;-noimport:=true,
+ org.apache.felix.service.threadio;version=0.17.0;status=provisional;-noimport:=true
</Export-Package>
<Private-Package>
org.apache.karaf.shell.commands.ansi,
http://git-wip-us.apache.org/repos/asf/karaf/blob/f1dd4a94/shell/console/src/main/java/org/apache/karaf/shell/compat/CommandTracker.java
----------------------------------------------------------------------
diff --git a/shell/console/src/main/java/org/apache/karaf/shell/compat/CommandTracker.java b/shell/console/src/main/java/org/apache/karaf/shell/compat/CommandTracker.java
index 8891135..e079ab9 100644
--- a/shell/console/src/main/java/org/apache/karaf/shell/compat/CommandTracker.java
+++ b/shell/console/src/main/java/org/apache/karaf/shell/compat/CommandTracker.java
@@ -19,13 +19,10 @@
package org.apache.karaf.shell.compat;
import java.lang.reflect.Method;
-import java.util.ArrayList;
import java.util.List;
-import org.apache.felix.gogo.runtime.CommandProxy;
import org.apache.felix.service.command.CommandProcessor;
import org.apache.felix.service.command.CommandSession;
-import org.apache.felix.service.command.Function;
import org.apache.karaf.shell.api.console.CommandLine;
import org.apache.karaf.shell.api.console.Completer;
import org.apache.karaf.shell.api.console.Parser;
@@ -34,6 +31,7 @@ import org.apache.karaf.shell.api.console.SessionFactory;
import org.apache.karaf.shell.commands.Command;
import org.apache.karaf.shell.commands.CommandWithAction;
import org.osgi.framework.BundleContext;
+import org.osgi.framework.Constants;
import org.osgi.framework.Filter;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTracker;
@@ -53,8 +51,10 @@ public class CommandTracker implements ServiceTrackerCustomizer<Object, Object>
}
public void init() throws Exception {
- Filter filter = context.createFilter(String.format("(&(%s=*)(%s=*))",
- CommandProcessor.COMMAND_SCOPE, CommandProcessor.COMMAND_FUNCTION));
+ Filter filter = context.createFilter(String.format("(&(%s=*)(%s=*)(|(%s=%s)(%s=%s)))",
+ CommandProcessor.COMMAND_SCOPE, CommandProcessor.COMMAND_FUNCTION,
+ Constants.OBJECTCLASS, CommandWithAction.class.getName(),
+ Constants.OBJECTCLASS, org.apache.felix.gogo.commands.CommandWithAction.class.getName()));
this.tracker = new ServiceTracker<Object, Object>(context, filter, this);
this.tracker.open();
}
@@ -178,96 +178,7 @@ public class CommandTracker implements ServiceTrackerCustomizer<Object, Object>
sessionFactory.getRegistry().register(command);
return command;
} else {
- final String scope = reference.getProperty(CommandProcessor.COMMAND_SCOPE).toString();
- final Object function = reference.getProperty(CommandProcessor.COMMAND_FUNCTION);
-
- List<org.apache.karaf.shell.api.console.Command> commands = new ArrayList<>();
-
- if (function.getClass().isArray()) {
- for (final Object f : ((Object[]) function)) {
- final Function target;
-
- target = new CommandProxy(context, reference, f.toString());
- org.apache.karaf.shell.api.console.Command command = new org.apache.karaf.shell.api.console.Command() {
- @Override
- public String getScope() {
- return scope;
- }
-
- @Override
- public String getName() {
- return f.toString();
- }
-
- @Override
- public String getDescription() {
- Object property = reference.getProperty("osgi.command.description");
- if (property != null) {
- return property.toString();
- } else {
- return getName();
- }
- }
-
- @Override
- public Completer getCompleter(final boolean scoped) {
- return null;
- }
-
- @Override
- public Parser getParser() {
- return null;
- }
-
- @Override
- public Object execute(Session session, List<Object> arguments) throws Exception {
- // TODO: remove not really nice cast
- CommandSession commandSession = (CommandSession) session.get(".commandSession");
- return target.execute(commandSession, arguments);
- }
- };
- sessionFactory.getRegistry().register(command);
- commands.add(command);
- }
- } else {
- final Function target = new CommandProxy(context, reference, function.toString());
- org.apache.karaf.shell.api.console.Command command = new org.apache.karaf.shell.api.console.Command() {
- @Override
- public String getScope() {
- return scope;
- }
-
- @Override
- public String getName() {
- return function.toString();
- }
-
- @Override
- public String getDescription() {
- return reference.getProperty("osgi.command.description").toString();
- }
-
- @Override
- public Completer getCompleter(final boolean scoped) {
- return null;
- }
-
- @Override
- public Parser getParser() {
- return null;
- }
-
- @Override
- public Object execute(Session session, List<Object> arguments) throws Exception {
- // TODO: remove not really nice cast
- CommandSession commandSession = (CommandSession) session.get(".commandSession");
- return target.execute(commandSession, arguments);
- }
- };
- sessionFactory.getRegistry().register(command);
- commands.add(command);
- }
- return commands;
+ return null;
}
}