org.apache.felix.gogo.shell_0.8.0.v201110170705

16:41:05.326 INFO  jd.cli.Main - Decompiling org.apache.felix.gogo.shell_0.8.0.v201110170705.jar
package org.apache.felix.gogo.options;

import java.util.List;

public abstract interface Option
{
  public abstract Option setStopOnBadOption(boolean paramBoolean);
  
  public abstract Option setOptionsFirst(boolean paramBoolean);
  
  public abstract Option parse(List<? extends Object> paramList, boolean paramBoolean);
  
  public abstract Option parse(List<? extends Object> paramList);
  
  public abstract Option parse(Object[] paramArrayOfObject, boolean paramBoolean);
  
  public abstract Option parse(Object[] paramArrayOfObject);
  
  public abstract boolean isSet(String paramString);
  
  public abstract String get(String paramString);
  
  public abstract List<String> getList(String paramString);
  
  public abstract Object getObject(String paramString);
  
  public abstract List<Object> getObjectList(String paramString);
  
  public abstract int getNumber(String paramString);
  
  public abstract List<String> args();
  
  public abstract List<Object> argObjects();
  
  public abstract void usage();
  
  public abstract IllegalArgumentException usageError(String paramString);
}

/* Location:
 * Qualified Name:     org.apache.felix.gogo.options.Option
 * Java Class Version: 5 (49.0)
 * JD-Core Version:    0.7.1
 */
package org.apache.felix.gogo.options;

import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Options
  implements Option
{
  public static void main(String[] args)
  {
    String[] usage = { "test - test Options usage", "  text before Usage: is displayed when usage() is called and no error has occurred.", "  so can be used as a simple help message.", "", "Usage: testOptions [OPTION]... PATTERN [FILES]...", "  Output control: arbitary non-option text can be included.", "  -? --help                show help", "  -c --count=COUNT           show COUNT lines", "  -h --no-filename         suppress the prefixing filename on output", "  -q --quiet, --silent     suppress all normal output", "     --binary-files=TYPE   assume that binary files are TYPE", "                           TYPE is 'binary', 'text', or 'without-match'", "  -I                       equivalent to --binary-files=without-match", "  -d --directories=ACTION  how to handle directories (default=skip)", "                           ACTION is 'read', 'recurse', or 'skip'", "  -D --devices=ACTION      how to handle devices, FIFOs and sockets", "                           ACTION is 'read' or 'skip'", "  -R, -r --recursive       equivalent to --directories=recurse" };
    
    Option opt = compile(usage).parse(args);
    if (opt.isSet("help"))
    {
      opt.usage();
      return;
    }
    if (opt.args().size() == 0) {
      throw opt.usageError("PATTERN not specified");
    }
    System.out.println(opt);
    if (opt.isSet("count")) {
      System.out.println("count = " + opt.getNumber("count"));
    }
    System.out.println("--directories specified: " + opt.isSet("directories"));
    System.out.println("directories=" + opt.get("directories"));
  }
  
  public static final String NL = System.getProperty("line.separator", "\n");
  private static final String regex = "(?x)\\s*(?:-([^-]))?(?:,?\\s*-(\\w))?(?:,?\\s*--(\\w[\\w-]*)(=\\w+)?)?(?:,?\\s*--(\\w[\\w-]*))?.*?(?:\\(default=(.*)\\))?\\s*";
  private static final int GROUP_SHORT_OPT_1 = 1;
  private static final int GROUP_SHORT_OPT_2 = 2;
  private static final int GROUP_LONG_OPT_1 = 3;
  private static final int GROUP_ARG_1 = 4;
  private static final int GROUP_LONG_OPT_2 = 5;
  private static final int GROUP_DEFAULT = 6;
  private final Pattern parser = Pattern.compile("(?x)\\s*(?:-([^-]))?(?:,?\\s*-(\\w))?(?:,?\\s*--(\\w[\\w-]*)(=\\w+)?)?(?:,?\\s*--(\\w[\\w-]*))?.*?(?:\\(default=(.*)\\))?\\s*");
  private final Pattern uname = Pattern.compile("^Usage:\\s+(\\w+)");
  private final Map<String, Boolean> unmodifiableOptSet;
  private final Map<String, Object> unmodifiableOptArg;
  private final Map<String, Boolean> optSet = new HashMap();
  private final Map<String, Object> optArg = new HashMap();
  private final Map<String, String> optName = new HashMap();
  private final Map<String, String> optAlias = new HashMap();
  private final List<Object> xargs = new ArrayList();
  private List<String> args = null;
  private static final String UNKNOWN = "unknown";
  private String usageName = "unknown";
  private int usageIndex = 0;
  private final String[] spec;
  private final String[] gspec;
  private final String defOpts;
  private final String[] defArgs;
  private PrintStream errStream = System.err;
  private String error = null;
  private boolean optionsFirst = false;
  private boolean stopOnBadOption = false;
  
  public static Option compile(String[] optSpec)
  {
    return new Options(optSpec, null, null);
  }
  
  public static Option compile(String optSpec)
  {
    return compile(optSpec.split("\\n"));
  }
  
  public static Option compile(String[] optSpec, Option gopt)
  {
    return new Options(optSpec, null, gopt);
  }
  
  public static Option compile(String[] optSpec, String[] gspec)
  {
    return new Options(optSpec, gspec, null);
  }
  
  public Option setStopOnBadOption(boolean stopOnBadOption)
  {
    this.stopOnBadOption = stopOnBadOption;
    return this;
  }
  
  public Option setOptionsFirst(boolean optionsFirst)
  {
    this.optionsFirst = optionsFirst;
    return this;
  }
  
  public boolean isSet(String name)
  {
    if (!optSet.containsKey(name)) {
      throw new IllegalArgumentException("option not defined in spec: " + name);
    }
    return ((Boolean)optSet.get(name)).booleanValue();
  }
  
  public Object getObject(String name)
  {
    if (!optArg.containsKey(name)) {
      throw new IllegalArgumentException("option not defined with argument: " + name);
    }
    List<Object> list = getObjectList(name);
    
    return list.isEmpty() ? "" : list.get(list.size() - 1);
  }
  
  public List<Object> getObjectList(String name)
  {
    Object arg = optArg.get(name);
    if (arg == null) {
      throw new IllegalArgumentException("option not defined with argument: " + name);
    }
    List<Object> list;
    if ((arg instanceof String))
    {
      List<Object> list = new ArrayList();
      if (!"".equals(arg)) {
        list.add(arg);
      }
    }
    else
    {
      list = (List)arg;
    }
    return list;
  }
  
  public List<String> getList(String name)
  {
    ArrayList<String> list = new ArrayList();
    for (Object o : getObjectList(name)) {
      try
      {
        list.add((String)o);
      }
      catch (ClassCastException e)
      {
        throw new IllegalArgumentException("option not String: " + name);
      }
    }
    return list;
  }
  
  private void addArg(String name, Object value)
  {
    Object arg = optArg.get(name);
    List<Object> list;
    if ((arg instanceof String))
    {
      List<Object> list = new ArrayList();
      optArg.put(name, list);
    }
    else
    {
      list = (List)arg;
    }
    list.add(value);
  }
  
  public String get(String name)
  {
    try
    {
      return (String)getObject(name);
    }
    catch (ClassCastException e)
    {
      throw new IllegalArgumentException("option not String: " + name);
    }
  }
  
  public int getNumber(String name)
  {
    String number = get(name);
    try
    {
      if (number != null) {
        return Integer.parseInt(number);
      }
      return 0;
    }
    catch (NumberFormatException e)
    {
      throw new IllegalArgumentException("option '" + name + "' not Number: " + number);
    }
  }
  
  public List<Object> argObjects()
  {
    return xargs;
  }
  
  public List<String> args()
  {
    if (args == null)
    {
      args = new ArrayList();
      for (Object arg : xargs) {
        args.add(arg == null ? "null" : arg.toString());
      }
    }
    return args;
  }
  
  public void usage()
  {
    StringBuilder buf = new StringBuilder();
    int index = 0;
    if (error != null)
    {
      buf.append(error);
      buf.append(NL);
      index = usageIndex;
    }
    for (int i = index; i < spec.length; i++)
    {
      buf.append(spec[i]);
      buf.append(NL);
    }
    String msg = buf.toString();
    if (errStream != null) {
      errStream.print(msg);
    }
  }
  
  public IllegalArgumentException usageError(String s)
  {
    error = (usageName + ": " + s);
    usage();
    return new IllegalArgumentException(error);
  }
  
  private Options(String[] spec, String[] gspec, Option opt)
  {
    this.gspec = gspec;
    Options gopt = (Options)opt;
    if ((gspec == null) && (gopt == null))
    {
      this.spec = spec;
    }
    else
    {
      ArrayList<String> list = new ArrayList();
      list.addAll(Arrays.asList(spec));
      list.addAll(Arrays.asList(gspec != null ? gspec : gspec));
      this.spec = ((String[])list.toArray(new String[0]));
    }
    Map<String, Boolean> myOptSet = new HashMap();
    Map<String, Object> myOptArg = new HashMap();
    
    parseSpec(myOptSet, myOptArg);
    if (gopt != null)
    {
      for (Map.Entry<String, Boolean> e : optSet.entrySet()) {
        if (((Boolean)e.getValue()).booleanValue()) {
          myOptSet.put(e.getKey(), Boolean.valueOf(true));
        }
      }
      for (Map.Entry<String, Object> e : optArg.entrySet()) {
        if (!e.getValue().equals("")) {
          myOptArg.put(e.getKey(), e.getValue());
        }
      }
      gopt.reset();
    }
    unmodifiableOptSet = Collections.unmodifiableMap(myOptSet);
    unmodifiableOptArg = Collections.unmodifiableMap(myOptArg);
    
    defOpts = System.getenv(usageName.toUpperCase() + "_OPTS");
    defArgs = (defOpts != null ? defOpts.split("\\s+") : new String[0]);
  }
  
  private void parseSpec(Map<String, Boolean> myOptSet, Map<String, Object> myOptArg)
  {
    int index = 0;
    for (String line : spec)
    {
      Matcher m = parser.matcher(line);
      if (m.matches())
      {
        String opt = m.group(3);
        String name = opt != null ? opt : m.group(1);
        if (name != null)
        {
          if (myOptSet.containsKey(name)) {
            throw new IllegalArgumentException("duplicate option in spec: --" + name);
          }
          myOptSet.put(name, Boolean.valueOf(false));
        }
        String dflt = m.group(6) != null ? m.group(6) : "";
        if (m.group(4) != null) {
          myOptArg.put(opt, dflt);
        }
        String opt2 = m.group(5);
        if (opt2 != null)
        {
          optAlias.put(opt2, opt);
          myOptSet.put(opt2, Boolean.valueOf(false));
          if (m.group(4) != null) {
            myOptArg.put(opt2, "");
          }
        }
        for (int i = 0; i < 2; i++)
        {
          String sopt = m.group(i == 0 ? 1 : 2);
          if (sopt != null)
          {
            if (optName.containsKey(sopt)) {
              throw new IllegalArgumentException("duplicate option in spec: -" + sopt);
            }
            optName.put(sopt, name);
          }
        }
      }
      if (usageName == "unknown")
      {
        Matcher u = uname.matcher(line);
        if (u.find())
        {
          usageName = u.group(1);
          usageIndex = index;
        }
      }
      index++;
    }
  }
  
  private void reset()
  {
    optSet.clear();
    optSet.putAll(unmodifiableOptSet);
    optArg.clear();
    optArg.putAll(unmodifiableOptArg);
    xargs.clear();
    args = null;
    error = null;
  }
  
  public Option parse(Object[] argv)
  {
    return parse(argv, false);
  }
  
  public Option parse(List<? extends Object> argv)
  {
    return parse(argv, false);
  }
  
  public Option parse(Object[] argv, boolean skipArg0)
  {
    if (null == argv) {
      throw new IllegalArgumentException("argv is null");
    }
    return parse(Arrays.asList(argv), skipArg0);
  }
  
  public Option parse(List<? extends Object> argv, boolean skipArg0)
  {
    reset();
    List<Object> args = new ArrayList();
    args.addAll(Arrays.asList(defArgs));
    for (Object arg : argv) {
      if (skipArg0)
      {
        skipArg0 = false;
        usageName = arg.toString();
      }
      else
      {
        args.add(arg);
      }
    }
    String needArg = null;
    String needOpt = null;
    boolean endOpt = false;
    for (Object oarg : args)
    {
      String arg = oarg == null ? "null" : oarg.toString();
      if (endOpt)
      {
        xargs.add(oarg);
      }
      else if (needArg != null)
      {
        addArg(needArg, oarg);
        needArg = null;
        needOpt = null;
      }
      else if ((!arg.startsWith("-")) || ("-".equals(oarg)))
      {
        if (optionsFirst) {
          endOpt = true;
        }
        xargs.add(oarg);
      }
      else if (arg.equals("--"))
      {
        endOpt = true;
      }
      else if (arg.startsWith("--"))
      {
        int eq = arg.indexOf("=");
        String value = eq == -1 ? null : arg.substring(eq + 1);
        String name = arg.substring(2, eq == -1 ? arg.length() : eq);
        List<String> names = new ArrayList();
        if (optSet.containsKey(name)) {
          names.add(name);
        } else {
          for (String k : optSet.keySet()) {
            if (k.startsWith(name)) {
              names.add(k);
            }
          }
        }
        switch (names.size())
        {
        case 1: 
          name = (String)names.get(0);
          optSet.put(name, Boolean.valueOf(true));
          if (optArg.containsKey(name))
          {
            if (value != null) {
              addArg(name, value);
            } else {
              needArg = name;
            }
          }
          else if (value != null) {
            throw usageError("option '--" + name + "' doesn't allow an argument");
          }
          break;
        case 0: 
          if (stopOnBadOption)
          {
            endOpt = true;
            xargs.add(oarg);
          }
          else
          {
            throw usageError("invalid option '--" + name + "'");
          }
          break;
        default: 
          throw usageError("option '--" + name + "' is ambiguous: " + names);
        }
      }
      else
      {
        int i = 0;
        for (String c : arg.substring(1).split("")) {
          if (i++ != 0) {
            if (optName.containsKey(c))
            {
              String name = (String)optName.get(c);
              optSet.put(name, Boolean.valueOf(true));
              if (optArg.containsKey(name))
              {
                if (i < arg.length())
                {
                  addArg(name, arg.substring(i)); break;
                }
                needOpt = c;
                needArg = name;
                
                break;
              }
            }
            else if (stopOnBadOption)
            {
              xargs.add("-" + c);
              endOpt = true;
            }
            else
            {
              throw usageError("invalid option '" + c + "'");
            }
          }
        }
      }
    }
    if (needArg != null)
    {
      String name = "--" + needArg;
      throw usageError("option '" + name + "' requires an argument");
    }
    for (Map.Entry<String, String> alias : optAlias.entrySet())
    {
      if (((Boolean)optSet.get(alias.getKey())).booleanValue())
      {
        optSet.put(alias.getValue(), Boolean.valueOf(true));
        if (optArg.containsKey(alias.getKey())) {
          optArg.put(alias.getValue(), optArg.get(alias.getKey()));
        }
      }
      optSet.remove(alias.getKey());
      optArg.remove(alias.getKey());
    }
    return this;
  }
  
  public String toString()
  {
    return "isSet" + optSet + "\nArg" + optArg + "\nargs" + xargs;
  }
}

/* Location:
 * Qualified Name:     org.apache.felix.gogo.options.Options
 * Java Class Version: 5 (49.0)
 * JD-Core Version:    0.7.1
 */
package org.apache.felix.gogo.shell;

import org.apache.felix.service.command.CommandProcessor;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;

class Activator$1
  extends ServiceTracker
{
  Activator$1(Activator paramActivator, BundleContext x0, String x1, ServiceTrackerCustomizer x2)
  {
    super(x0, x1, x2);
  }
  
  public Object addingService(ServiceReference reference)
  {
    CommandProcessor processor = (CommandProcessor)super.addingService(reference);
    Activator.access$000(this$0, context, processor);
    return processor;
  }
  
  public void removedService(ServiceReference reference, Object service)
  {
    if (Activator.access$100(this$0) != null) {
      Activator.access$100(this$0).interrupt();
    }
    super.removedService(reference, service);
  }
}

/* Location:
 * Qualified Name:     org.apache.felix.gogo.shell.Activator.1
 * Java Class Version: 5 (49.0)
 * JD-Core Version:    0.7.1
 */
package org.apache.felix.gogo.shell;

import java.io.PrintStream;
import java.util.Dictionary;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
import org.apache.felix.service.command.CommandProcessor;
import org.apache.felix.service.command.CommandSession;
import org.apache.felix.service.command.Converter;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;

public class Activator
  implements BundleActivator, Runnable
{
  private BundleContext context;
  private ServiceTracker commandProcessorTracker;
  private Set<ServiceRegistration> regs = new HashSet();
  private CommandSession session;
  private Shell shell;
  private Thread thread;
  
  public void start(BundleContext ctxt)
    throws Exception
  {
    context = ctxt;
    commandProcessorTracker = processorTracker();
  }
  
  public void stop(BundleContext context)
    throws Exception
  {
    if (thread != null) {
      thread.interrupt();
    }
    commandProcessorTracker.close();
    
    Iterator<ServiceRegistration> iterator = regs.iterator();
    while (iterator.hasNext())
    {
      ServiceRegistration reg = (ServiceRegistration)iterator.next();
      reg.unregister();
      iterator.remove();
    }
  }
  
  public void run()
  {
    try
    {
      Thread.sleep(100L);
      String args = context.getProperty("gosh.args");
      args = args == null ? "" : args;
      session.execute("gosh --login " + args);
    }
    catch (Exception e)
    {
      Object loc = session.get(".location");
      if ((null == loc) || (!loc.toString().contains(":"))) {
        loc = "gogo";
      }
      System.err.println(loc + ": " + e.getClass().getSimpleName() + ": " + e.getMessage());
      e.printStackTrace();
    }
    finally
    {
      session.close();
    }
  }
  
  private void startShell(BundleContext context, CommandProcessor processor)
  {
    Dictionary<String, Object> dict = new Hashtable();
    dict.put("osgi.command.scope", "gogo");
    
    regs.add(context.registerService(Converter.class.getName(), new Converters(context), null));
    
    dict.put("osgi.command.function", Builtin.functions);
    regs.add(context.registerService(Builtin.class.getName(), new Builtin(), dict));
    
    dict.put("osgi.command.function", Procedural.functions);
    regs.add(context.registerService(Procedural.class.getName(), new Procedural(), dict));
    
    dict.put("osgi.command.function", Posix.functions);
    regs.add(context.registerService(Posix.class.getName(), new Posix(), dict));
    
    dict.put("osgi.command.function", Telnet.functions);
    regs.add(context.registerService(Telnet.class.getName(), new Telnet(processor), dict));
    
    shell = new Shell(context, processor);
    dict.put("osgi.command.function", Shell.functions);
    regs.add(context.registerService(Shell.class.getName(), shell, dict));
    
    session = processor.createSession(System.in, System.out, System.err);
    thread = new Thread(this, "Gogo shell");
    thread.start();
  }
  
  private ServiceTracker processorTracker()
  {
    ServiceTracker t = new ServiceTracker(context, CommandProcessor.class.getName(), null)
    {
      public Object addingService(ServiceReference reference)
      {
        CommandProcessor processor = (CommandProcessor)super.addingService(reference);
        Activator.this.startShell(context, processor);
        return processor;
      }
      
      public void removedService(ServiceReference reference, Object service)
      {
        if (thread != null) {
          thread.interrupt();
        }
        super.removedService(reference, service);
      }
    };
    t.open();
    return t;
  }
}

/* Location:
 * Qualified Name:     org.apache.felix.gogo.shell.Activator
 * Java Class Version: 5 (49.0)
 * JD-Core Version:    0.7.1
 */
package org.apache.felix.gogo.shell;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.StringWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.apache.felix.gogo.options.Option;
import org.apache.felix.gogo.options.Options;
import org.apache.felix.service.command.CommandSession;

public class Builtin
{
  static final String[] functions = { "format", "getopt", "new", "set", "tac", "type" };
  private static final String[] packages = { "java.lang", "java.io", "java.net", "java.util" };
  
  public CharSequence format(CommandSession session)
  {
    return format(session, session.get("_"));
  }
  
  public CharSequence format(CommandSession session, Object arg)
  {
    CharSequence result = session.format(arg, 0);
    System.out.println(result);
    return result;
  }
  
  public Option getopt(List<Object> spec, Object[] args)
  {
    String[] optSpec = new String[spec.size()];
    for (int i = 0; i < optSpec.length; i++) {
      optSpec[i] = spec.get(i).toString();
    }
    return Options.compile(optSpec).parse(args);
  }
  
  public Object _new(Object name, Object[] argv)
    throws Exception
  {
    Class<?> clazz = null;
    if ((name instanceof Class)) {
      clazz = (Class)name;
    } else {
      clazz = loadClass(name.toString());
    }
    for (Constructor<?> c : clazz.getConstructors())
    {
      Class<?>[] types = c.getParameterTypes();
      if (types.length == argv.length)
      {
        boolean match = true;
        for (int i = 0; i < argv.length; i++) {
          if (!types[i].isAssignableFrom(argv[i].getClass()))
          {
            if (!types[i].isAssignableFrom(String.class))
            {
              match = false;
              break;
            }
            argv[i] = argv[i].toString();
          }
        }
        if (match) {
          try
          {
            return c.newInstance(argv);
          }
          catch (InvocationTargetException ite)
          {
            Throwable cause = ite.getCause();
            if ((cause instanceof Exception)) {
              throw ((Exception)cause);
            }
            throw ite;
          }
        }
      }
    }
    throw new IllegalArgumentException("can't coerce " + Arrays.asList(argv) + " to any of " + Arrays.asList(clazz.getConstructors()));
  }
  
  private Class<?> loadClass(String name)
    throws ClassNotFoundException
  {
    if (!name.contains(".")) {
      for (String p : packages)
      {
        String pkg = p + "." + name;
        try
        {
          return Class.forName(pkg);
        }
        catch (ClassNotFoundException e) {}
      }
    }
    return Class.forName(name);
  }
  
  public void set(CommandSession session, String[] argv)
    throws Exception
  {
    String[] usage = { "set - show session variables", "Usage: set [OPTIONS] [PREFIX]", "  -? --help                show help", "  -a --all                 show all variables, including those starting with .", "  -x                       set xtrace option", "  +x                       unset xtrace option", "If PREFIX given, then only show variable(s) starting with PREFIX" };
    
    Option opt = Options.compile(usage).parse(argv);
    if (opt.isSet("help"))
    {
      opt.usage();
      return;
    }
    List<String> args = opt.args();
    String prefix = args.isEmpty() ? "" : (String)args.get(0);
    boolean all;
    if (opt.isSet("x"))
    {
      session.put("echo", Boolean.valueOf(true));
    }
    else if ("+x".equals(prefix))
    {
      session.put("echo", null);
    }
    else
    {
      all = opt.isSet("all");
      for (String key : new TreeSet(Shell.getVariables(session))) {
        if ((key.startsWith(prefix)) && (
        
          (!key.startsWith(".")) || (all) || (prefix.length() > 0)))
        {
          Object target = session.get(key);
          String type = null;
          String value = null;
          if (target != null)
          {
            Class<? extends Object> clazz = target.getClass();
            type = clazz.getSimpleName();
            value = target.toString();
          }
          String trunc = (value == null) || (value.length() < 55) ? "" : "...";
          System.out.println(String.format("%-15.15s %-15s %.45s%s", new Object[] { type, key, value, trunc }));
        }
      }
    }
  }
  
  public Object tac(CommandSession session, String[] argv)
    throws IOException
  {
    String[] usage = { "tac - capture stdin as String or List and optionally write to file.", "Usage: tac [-al] [FILE]", "  -a --append              append to FILE", "  -l --list                return List<String>", "  -? --help                show help" };
    
    Option opt = Options.compile(usage).parse(argv);
    if (opt.isSet("help"))
    {
      opt.usage();
      return null;
    }
    List<String> args = opt.args();
    BufferedWriter fw = null;
    if (args.size() == 1)
    {
      String path = (String)args.get(0);
      File file = new File(Shell.cwd(session).resolve(path));
      fw = new BufferedWriter(new FileWriter(file, opt.isSet("append")));
    }
    StringWriter sw = new StringWriter();
    BufferedReader rdr = new BufferedReader(new InputStreamReader(System.in));
    
    ArrayList<String> list = null;
    if (opt.isSet("list")) {
      list = new ArrayList();
    }
    boolean first = true;
    String s;
    while ((s = rdr.readLine()) != null)
    {
      if (list != null)
      {
        list.add(s);
      }
      else
      {
        if (!first) {
          sw.write(32);
        }
        first = false;
        sw.write(s);
      }
      if (fw != null)
      {
        fw.write(s);
        fw.newLine();
      }
    }
    if (fw != null) {
      fw.close();
    }
    return list != null ? list : sw.toString();
  }
  
  public boolean type(CommandSession session, String[] argv)
    throws Exception
  {
    String[] usage = { "type - show command type", "Usage: type [OPTIONS] [name[:]]", "  -a --all                 show all matches", "  -? --help                show help", "  -q --quiet               don't print anything, just return status", "  -s --scope=NAME          list all commands in named scope", "  -t --types               show full java type names" };
    
    Option opt = Options.compile(usage).parse(argv);
    List<String> args = opt.args();
    if (opt.isSet("help"))
    {
      opt.usage();
      return true;
    }
    boolean all = opt.isSet("all");
    
    String optScope = null;
    if (opt.isSet("scope")) {
      optScope = opt.get("scope");
    }
    if (args.size() == 1)
    {
      String arg = (String)args.get(0);
      if (arg.endsWith(":")) {
        optScope = (String)args.remove(0);
      }
    }
    if ((optScope != null) || ((args.isEmpty()) && (all)))
    {
      Set<String> snames = new TreeSet();
      for (String sname : getCommands(session)) {
        if ((optScope == null) || (sname.startsWith(optScope))) {
          snames.add(sname);
        }
      }
      for (String sname : snames) {
        System.out.println(sname);
      }
      return true;
    }
    if (args.size() == 0)
    {
      Map<String, Integer> scopes = new TreeMap();
      for (String sname : getCommands(session))
      {
        int colon = sname.indexOf(':');
        String scope = sname.substring(0, colon);
        Integer count = (Integer)scopes.get(scope);
        if (count == null) {
          count = Integer.valueOf(0);
        }
        scopes.put(scope, count = Integer.valueOf(count.intValue() + 1));
      }
      for (Map.Entry<String, Integer> entry : scopes.entrySet()) {
        System.out.println((String)entry.getKey() + ":" + entry.getValue());
      }
      return true;
    }
    String name = ((String)args.get(0)).toLowerCase();
    
    int colon = name.indexOf(':');
    String MAIN = "_main";
    
    StringBuilder buf = new StringBuilder();
    Set<String> cmds = new LinkedHashSet();
    if ((colon != -1) || (session.get(name) != null))
    {
      cmds.add(name);
    }
    else if (session.get("_main") != null)
    {
      cmds.add("_main");
    }
    else
    {
      String path = session.get("SCOPE") != null ? session.get("SCOPE").toString() : "*";
      for (String s : path.split(":")) {
        if (s.equals("*"))
        {
          for (String sname : getCommands(session)) {
            if (sname.endsWith(":" + name))
            {
              cmds.add(sname);
              if (!all) {
                break;
              }
            }
          }
        }
        else
        {
          String sname = s + ":" + name;
          if (session.get(sname) != null)
          {
            cmds.add(sname);
            if (!all) {
              break;
            }
          }
        }
      }
    }
    for (Iterator i$ = cmds.iterator(); i$.hasNext();)
    {
      key = (String)i$.next();
      
      Object target = session.get(key);
      if (target != null)
      {
        CharSequence source = getClosureSource(session, key);
        if (source != null)
        {
          buf.append(name);
          buf.append(" is function {");
          buf.append(source);
          buf.append("}");
        }
        else
        {
          for (Method m : getMethods(session, key))
          {
            StringBuilder params = new StringBuilder();
            for (Class<?> type : m.getParameterTypes())
            {
              if (params.length() > 0) {
                params.append(", ");
              }
              params.append(type.getSimpleName());
            }
            String rtype = m.getReturnType().getSimpleName();
            if (buf.length() > 0) {
              buf.append("\n");
            }
            if (opt.isSet("types"))
            {
              String cname = m.getDeclaringClass().getName();
              buf.append(String.format("%s %s.%s(%s)", new Object[] { rtype, cname, m.getName(), params }));
            }
            else
            {
              buf.append(String.format("%s is %s %s(%s)", new Object[] { name, rtype, key, params }));
            }
          }
        }
      }
    }
    String key;
    if (buf.length() > 0)
    {
      if (!opt.isSet("quiet")) {
        System.out.println(buf);
      }
      return true;
    }
    if (!opt.isSet("quiet")) {
      System.err.println("type: " + name + " not found.");
    }
    return false;
  }
  
  static Set<String> getCommands(CommandSession session)
  {
    return (Set)session.get(".commands");
  }
  
  private boolean isClosure(Object target)
  {
    return target.getClass().getSimpleName().equals("Closure");
  }
  
  private boolean isCommand(Object target)
  {
    return target.getClass().getSimpleName().equals("CommandProxy");
  }
  
  private CharSequence getClosureSource(CommandSession session, String name)
    throws Exception
  {
    Object target = session.get(name);
    if (target == null) {
      return null;
    }
    if (!isClosure(target)) {
      return null;
    }
    Field sourceField = target.getClass().getDeclaredField("source");
    sourceField.setAccessible(true);
    return (CharSequence)sourceField.get(target);
  }
  
  private List<Method> getMethods(CommandSession session, String scmd)
    throws Exception
  {
    int colon = scmd.indexOf(':');
    String function = colon == -1 ? scmd : scmd.substring(colon + 1);
    String name = KEYWORDS.contains(function) ? "_" + function : function;
    String get = "get" + function;
    String is = "is" + function;
    String set = "set" + function;
    String MAIN = "_main";
    
    Object target = session.get(scmd);
    if (target == null) {
      return null;
    }
    if (isClosure(target)) {
      return null;
    }
    if (isCommand(target))
    {
      Method method = target.getClass().getMethod("getTarget", (Class[])null);
      method.setAccessible(true);
      target = method.invoke(target, (Object[])null);
    }
    ArrayList<Method> list = new ArrayList();
    Class<?> tc = (target instanceof Class) ? (Class)target : target.getClass();
    
    Method[] methods = tc.getMethods();
    for (Method m : methods)
    {
      String mname = m.getName().toLowerCase();
      if ((mname.equals(name)) || (mname.equals(get)) || (mname.equals(set)) || (mname.equals(is)) || (mname.equals("_main"))) {
        list.add(m);
      }
    }
    return list;
  }
  
  private static final Set<String> KEYWORDS = new HashSet(Arrays.asList(new String[] { "abstract", "continue", "for", "new", "switch", "assert", "default", "goto", "package", "synchronized", "boolean", "do", "if", "private", "this", "break", "double", "implements", "protected", "throw", "byte", "else", "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", "void", "class", "finally", "long", "strictfp", "volatile", "const", "float", "native", "super", "while" }));
}

/* Location:
 * Qualified Name:     org.apache.felix.gogo.shell.Builtin
 * Java Class Version: 5 (49.0)
 * JD-Core Version:    0.7.1
 */
package org.apache.felix.gogo.shell;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import org.apache.felix.service.command.CommandSession;

public class Console
  implements Runnable
{
  private final CommandSession session;
  private final InputStream in;
  private final PrintStream out;
  private boolean quit;
  
  public Console(CommandSession session)
  {
    this.session = session;
    in = session.getKeyboard();
    out = session.getConsole();
  }
  
  public void run()
  {
    try
    {
      while (!quit)
      {
        Object prompt = session.get("prompt");
        if (prompt == null) {
          prompt = "g! ";
        }
        CharSequence line = getLine(prompt.toString());
        if (line == null) {
          break;
        }
        try
        {
          Object result = session.execute(line);
          session.put("_", result);
          if ((result != null) && (!Boolean.FALSE.equals(session.get(".Gogo.format")))) {
            out.println(session.format(result, 0));
          }
        }
        catch (Throwable e)
        {
          String SESSION_CLOSED = "session is closed";
          if (((e instanceof IllegalStateException)) && ("session is closed".equals(e.getMessage())))
          {
            out.println("gosh: " + e);
            quit = true;
          }
          if (!quit)
          {
            session.put("exception", e);
            Object loc = session.get(".location");
            if ((null == loc) || (!loc.toString().contains(":"))) {
              loc = "gogo";
            }
            out.println(loc + ": " + e.getClass().getSimpleName() + ": " + e.getMessage());
          }
        }
      }
    }
    catch (Exception e)
    {
      if (!quit) {
        e.printStackTrace();
      }
    }
  }
  
  private CharSequence getLine(String prompt)
    throws IOException
  {
    StringBuilder sb = new StringBuilder();
    out.print(prompt);
    while (!quit)
    {
      out.flush();
      int c = in.read();
      switch (c)
      {
      case -1: 
      case 4: 
        quit = true;
        break;
      case 13: 
        break;
      case 10: 
        if (sb.length() > 0) {
          return sb;
        }
        out.print(prompt);
        break;
      case 8: 
        if (sb.length() > 0)
        {
          out.print("\b \b");
          sb.deleteCharAt(sb.length() - 1);
        }
        break;
      case 0: 
      case 1: 
      case 2: 
      case 3: 
      case 5: 
      case 6: 
      case 7: 
      case 9: 
      case 11: 
      case 12: 
      default: 
        sb.append((char)c);
      }
    }
    return null;
  }
}

/* Location:
 * Qualified Name:     org.apache.felix.gogo.shell.Console
 * Java Class Version: 5 (49.0)
 * JD-Core Version:    0.7.1
 */
package org.apache.felix.gogo.shell;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.apache.felix.service.command.Function;

class Converters$1
  implements InvocationHandler
{
  Function command = (Function)val$in;
  
  Converters$1(Converters paramConverters, Object paramObject) {}
  
  public Object invoke(Object proxy, Method method, Object[] args)
    throws Throwable
  {
    return command.execute(null, Arrays.asList(args));
  }
}

/* Location:
 * Qualified Name:     org.apache.felix.gogo.shell.Converters.1
 * Java Class Version: 5 (49.0)
 * JD-Core Version:    0.7.1
 */
package org.apache.felix.gogo.shell;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.Formatter;
import org.apache.felix.service.command.Converter;
import org.apache.felix.service.command.Function;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.service.startlevel.StartLevel;

public class Converters
  implements Converter
{
  private final BundleContext context;
  
  public Converters(BundleContext context)
  {
    this.context = context;
  }
  
  private CharSequence print(Bundle bundle)
  {
    StartLevel sl = null;
    ServiceReference ref = context.getServiceReference(StartLevel.class.getName());
    if (ref != null) {
      sl = (StartLevel)context.getService(ref);
    }
    if (sl == null) {
      return String.format("%5d|%-11s|%s (%s)", new Object[] { Long.valueOf(bundle.getBundleId()), getState(bundle), bundle.getSymbolicName(), bundle.getVersion() });
    }
    int level = sl.getBundleStartLevel(bundle);
    context.ungetService(ref);
    
    return String.format("%5d|%-11s|%5d|%s (%s)", new Object[] { Long.valueOf(bundle.getBundleId()), getState(bundle), Integer.valueOf(level), bundle.getSymbolicName(), bundle.getVersion() });
  }
  
  private CharSequence print(ServiceReference ref)
  {
    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);
    
    String spid = "";
    Object pid = ref.getProperty("service.pid");
    if (pid != null) {
      spid = pid.toString();
    }
    f.format("%06d %3s %-40s %s", new Object[] { ref.getProperty("service.id"), Long.valueOf(ref.getBundle().getBundleId()), getShortNames(
1 2

Further reading...

For more information on Java 1.5 Tiger, you may find Java 1.5 Tiger, A developer's Notebook by D. Flanagan and B. McLaughlin from O'Reilly of interest.

New!JAR listings


Copyright 2006-2017. Infinite Loop Ltd