org.apache.felix.gogo.command_0.8.0.v201108120515

16:41:04.161 INFO  jd.cli.Main - Decompiling org.apache.felix.gogo.command_0.8.0.v201108120515.jar
package org.apache.felix.gogo.command;

import java.util.Hashtable;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.util.tracker.ServiceTracker;

public class Activator
  implements BundleActivator
{
  private volatile ServiceTracker m_tracker = null;
  
  public void start(BundleContext bc)
    throws Exception
  {
    Hashtable props = new Hashtable();
    props.put("osgi.command.scope", "felix");
    props.put("osgi.command.function", new String[] { "bundlelevel", "frameworklevel", "headers", "help", "install", "inspect", "lb", "log", "refresh", "resolve", "start", "stop", "uninstall", "update", "which" });
    
    bc.registerService(Basic.class.getName(), new Basic(bc), props);
    
    props.put("osgi.command.scope", "felix");
    props.put("osgi.command.function", new String[] { "cd", "ls" });
    
    bc.registerService(Files.class.getName(), new Files(bc), props);
    
    m_tracker = new ServiceTracker(bc, "org.apache.felix.bundlerepository.RepositoryAdmin", null);
    
    m_tracker.open();
    props.put("osgi.command.scope", "obr");
    props.put("osgi.command.function", new String[] { "deploy", "info", "javadoc", "list", "repos", "source" });
    
    bc.registerService(OBR.class.getName(), new OBR(bc, m_tracker), props);
  }
  
  public void stop(BundleContext bc)
    throws Exception
  {
    m_tracker.close();
  }
}

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

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Base64Encoder
{
  private static final byte[] encTab = { 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47 };
  
  public static String base64Encode(String s)
    throws IOException
  {
    return encode(s.getBytes(), 0);
  }
  
  public static String encode(byte[] in, int len)
    throws IOException
  {
    ByteArrayOutputStream baos = null;
    ByteArrayInputStream bais = null;
    try
    {
      baos = new ByteArrayOutputStream();
      bais = new ByteArrayInputStream(in);
      encode(bais, baos, len);
      
      return new String(baos.toByteArray());
    }
    finally
    {
      if (baos != null) {
        baos.close();
      }
      if (bais != null) {
        bais.close();
      }
    }
  }
  
  public static void encode(InputStream in, OutputStream out, int len)
    throws IOException
  {
    if (len % 4 != 0) {
      throw new IllegalArgumentException("Length must be a multiple of 4");
    }
    int bits = 0;
    int nbits = 0;
    int nbytes = 0;
    int b;
    while ((b = in.read()) != -1)
    {
      bits = bits << 8 | b;
      nbits += 8;
      while (nbits >= 6)
      {
        nbits -= 6;
        out.write(encTab[(0x3F & bits >> nbits)]);
        nbytes++;
        if ((len != 0) && (nbytes >= len))
        {
          out.write(13);
          out.write(10);
          nbytes -= len;
        }
      }
    }
    switch (nbits)
    {
    case 2: 
      out.write(encTab[(0x3F & bits << 4)]);
      out.write(61);
      out.write(61);
      break;
    case 4: 
      out.write(encTab[(0x3F & bits << 2)]);
      out.write(61);
    }
    if (len != 0)
    {
      if (nbytes != 0)
      {
        out.write(13);
        out.write(10);
      }
      out.write(13);
      out.write(10);
    }
  }
}

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

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import org.apache.felix.service.command.Descriptor;
import org.apache.felix.service.command.Parameter;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.BundleReference;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.service.log.LogEntry;
import org.osgi.service.log.LogReaderService;
import org.osgi.service.packageadmin.PackageAdmin;
import org.osgi.service.startlevel.StartLevel;

public class Basic
{
  private final BundleContext m_bc;
  
  public Basic(BundleContext bc)
  {
    m_bc = bc;
  }
  
  @Descriptor("query bundle start level")
  public void bundlelevel(@Descriptor("bundle to query") Bundle bundle)
  {
    List<ServiceReference> refs = new ArrayList();
    
    StartLevel sl = (StartLevel)Util.getService(m_bc, StartLevel.class, refs);
    if (sl == null) {
      System.out.println("Start Level service is unavailable.");
    } else if (bundle != null) {
      System.out.println(bundle + " is level " + sl.getBundleStartLevel(bundle));
    }
    Util.ungetServices(m_bc, refs);
  }
  
  @Descriptor("set bundle start level or initial bundle start level")
  public void bundlelevel(@Descriptor("set the bundle's start level") @Parameter(names={"-s", "--setlevel"}, presentValue="true", absentValue="false") boolean set, @Descriptor("set the initial bundle start level") @Parameter(names={"-i", "--setinitial"}, presentValue="true", absentValue="false") boolean initial, @Descriptor("target level") int level, @Descriptor("target identifiers") Bundle[] bundles)
  {
    List<ServiceReference> refs = new ArrayList();
    
    StartLevel sl = (StartLevel)Util.getService(m_bc, StartLevel.class, refs);
    if (sl == null) {
      System.out.println("Start Level service is unavailable.");
    } else if ((set) && (initial)) {
      System.out.println("Cannot specify '-s' and '-i' at the same time.");
    } else if ((!set) && (!initial)) {
      System.out.println("Must specify either '-s' or '-i'.");
    } else if (level <= 0) {
      System.out.println("Specified start level must be greater than zero.");
    } else if (initial)
    {
      if ((bundles != null) && (bundles.length == 0)) {
        sl.setInitialBundleStartLevel(level);
      } else {
        System.out.println("Cannot specify bundles when setting initial start level.");
      }
    }
    else if (set) {
      if ((bundles != null) && (bundles.length != 0)) {
        for (Bundle bundle : bundles) {
          sl.setBundleStartLevel(bundle, level);
        }
      } else {
        System.out.println("Must specify target bundles.");
      }
    }
    Util.ungetServices(m_bc, refs);
  }
  
  @Descriptor("query framework active start level")
  public void frameworklevel()
  {
    List<ServiceReference> refs = new ArrayList();
    
    StartLevel sl = (StartLevel)Util.getService(m_bc, StartLevel.class, refs);
    if (sl == null) {
      System.out.println("Start Level service is unavailable.");
    }
    System.out.println("Level is " + sl.getStartLevel());
    Util.ungetServices(m_bc, refs);
  }
  
  @Descriptor("set framework active start level")
  public void frameworklevel(@Descriptor("target start level") int level)
  {
    List<ServiceReference> refs = new ArrayList();
    
    StartLevel sl = (StartLevel)Util.getService(m_bc, StartLevel.class, refs);
    if (sl == null) {
      System.out.println("Start Level service is unavailable.");
    }
    sl.setStartLevel(level);
    Util.ungetServices(m_bc, refs);
  }
  
  @Descriptor("display bundle headers")
  public void headers(@Descriptor("target bundles") Bundle[] bundles)
  {
    bundles = (bundles == null) || (bundles.length == 0) ? m_bc.getBundles() : bundles;
    for (Bundle bundle : bundles)
    {
      String title = Util.getBundleName(bundle);
      System.out.println("\n" + title);
      System.out.println(Util.getUnderlineString(title.length()));
      Dictionary dict = bundle.getHeaders();
      Enumeration keys = dict.keys();
      while (keys.hasMoreElements())
      {
        Object k = (String)keys.nextElement();
        Object v = dict.get(k);
        System.out.println(k + " = " + Util.getValueString(v));
      }
    }
  }
  
  @Descriptor("displays available commands")
  public void help()
  {
    Map<String, List<Method>> commands = getCommands();
    for (String name : commands.keySet()) {
      System.out.println(name);
    }
  }
  
  @Descriptor("displays information about a specific command")
  public void help(@Descriptor("target command") String name)
  {
    Map<String, List<Method>> commands = getCommands();
    
    List<Method> methods = null;
    
    int scopeIdx = name.indexOf(':');
    if (scopeIdx < 0) {
      for (Map.Entry<String, List<Method>> entry : commands.entrySet())
      {
        String k = ((String)entry.getKey()).substring(((String)entry.getKey()).indexOf(':') + 1);
        if (name.equals(k))
        {
          name = (String)entry.getKey();
          methods = (List)entry.getValue();
          break;
        }
      }
    } else {
      methods = (List)commands.get(name);
    }
    if ((methods != null) && (methods.size() > 0)) {
      for (Method m : methods)
      {
        Descriptor d = (Descriptor)m.getAnnotation(Descriptor.class);
        if (d == null) {
          System.out.println("\n" + m.getName());
        } else {
          System.out.println("\n" + m.getName() + " - " + d.value());
        }
        System.out.println("   scope: " + name.substring(0, name.indexOf(':')));
        
        Class[] paramTypes = m.getParameterTypes();
        Map<String, Parameter> flags = new TreeMap();
        Map<String, String> flagDescs = new TreeMap();
        Map<String, Parameter> options = new TreeMap();
        Map<String, String> optionDescs = new TreeMap();
        List<String> params = new ArrayList();
        Annotation[][] anns = m.getParameterAnnotations();
        for (int paramIdx = 0; paramIdx < anns.length; paramIdx++)
        {
          Parameter p = (Parameter)findAnnotation(anns[paramIdx], Parameter.class);
          d = (Descriptor)findAnnotation(anns[paramIdx], Descriptor.class);
          if (p != null)
          {
            if (p.presentValue().equals("org.apache.felix.service.command.unspecified.parameter"))
            {
              options.put(p.names()[0], p);
              if (d != null) {
                optionDescs.put(p.names()[0], d.value());
              }
            }
            else
            {
              flags.put(p.names()[0], p);
              if (d != null) {
                flagDescs.put(p.names()[0], d.value());
              }
            }
          }
          else if (d != null)
          {
            params.add(paramTypes[paramIdx].getSimpleName());
            params.add(d.value());
          }
          else
          {
            params.add(paramTypes[paramIdx].getSimpleName());
            params.add("");
          }
        }
        if (flags.size() > 0)
        {
          System.out.println("   flags:");
          for (Map.Entry<String, Parameter> entry : flags.entrySet())
          {
            String[] names = ((Parameter)entry.getValue()).names();
            System.out.print("      " + names[0]);
            for (int aliasIdx = 1; aliasIdx < names.length; aliasIdx++) {
              System.out.print(", " + names[aliasIdx]);
            }
            System.out.println("   " + (String)flagDescs.get(entry.getKey()));
          }
        }
        if (options.size() > 0)
        {
          System.out.println("   options:");
          for (Map.Entry<String, Parameter> entry : options.entrySet())
          {
            String[] names = ((Parameter)entry.getValue()).names();
            System.out.print("      " + names[0]);
            for (int aliasIdx = 1; aliasIdx < names.length; aliasIdx++) {
              System.out.print(", " + names[aliasIdx]);
            }
            System.out.println("   " + (String)optionDescs.get(entry.getKey()) + (((Parameter)entry.getValue()).absentValue() == null ? "" : " [optional]"));
          }
        }
        if (params.size() > 0)
        {
          System.out.println("   parameters:");
          for (it = params.iterator(); it.hasNext();) {
            System.out.println("      " + (String)it.next() + "   " + (String)it.next());
          }
        }
      }
    }
    Iterator<String> it;
  }
  
  private static <T extends Annotation> T findAnnotation(Annotation[] anns, Class<T> clazz)
  {
    for (int i = 0; (anns != null) && (i < anns.length); i++) {
      if (clazz.isInstance(anns[i])) {
        return (Annotation)clazz.cast(anns[i]);
      }
    }
    return null;
  }
  
  private Map<String, List<Method>> getCommands()
  {
    ServiceReference[] refs = null;
    try
    {
      refs = m_bc.getAllServiceReferences(null, "(osgi.command.scope=*)");
    }
    catch (InvalidSyntaxException ex) {}
    Map<String, List<Method>> commands = new TreeMap();
    for (ServiceReference ref : refs)
    {
      Object svc = m_bc.getService(ref);
      if (svc != null)
      {
        String scope = (String)ref.getProperty("osgi.command.scope");
        String[] funcs = (String[])ref.getProperty("osgi.command.function");
        for (String func : funcs) {
          commands.put(scope + ":" + func, new ArrayList());
        }
        if (!commands.isEmpty())
        {
          Method[] methods = svc.getClass().getMethods();
          for (Method method : methods)
          {
            List<Method> commandMethods = (List)commands.get(scope + ":" + method.getName());
            if (commandMethods != null) {
              commandMethods.add(method);
            }
          }
        }
        Iterator<Map.Entry<String, List<Method>>> it = commands.entrySet().iterator();
        while (it.hasNext()) {
          if (((List)((Map.Entry)it.next()).getValue()).size() == 0) {
            it.remove();
          }
        }
      }
    }
    return commands;
  }
  
  @Descriptor("inspects bundle dependency information")
  public void inspect(@Descriptor("(package | bundle | fragment | service)") String type, @Descriptor("(capability | requirement)") String direction, @Descriptor("target bundles") Bundle[] bundles)
  {
    Inspect.inspect(m_bc, type, direction, bundles);
  }
  
  @Descriptor("install bundle using URLs")
  public void install(@Descriptor("target URLs") String[] urls)
  {
    StringBuffer sb = new StringBuffer();
    for (String url : urls)
    {
      String location = url.trim();
      Bundle bundle = null;
      try
      {
        bundle = m_bc.installBundle(location, null);
      }
      catch (IllegalStateException ex)
      {
        System.err.println(ex.toString());
      }
      catch (BundleException ex)
      {
        if (ex.getNestedException() != null) {
          System.err.println(ex.getNestedException().toString());
        } else {
          System.err.println(ex.toString());
        }
      }
      catch (Exception ex)
      {
        System.err.println(ex.toString());
      }
      if (bundle != null)
      {
        if (sb.length() > 0) {
          sb.append(", ");
        }
        sb.append(bundle.getBundleId());
      }
    }
    if (sb.toString().indexOf(',') > 0) {
      System.out.println("Bundle IDs: " + sb.toString());
    } else if (sb.length() > 0) {
      System.out.println("Bundle ID: " + sb.toString());
    }
  }
  
  @Descriptor("list all installed bundles")
  public void lb(@Descriptor("show location") @Parameter(names={"-l", "--location"}, presentValue="true", absentValue="false") boolean showLoc, @Descriptor("show symbolic name") @Parameter(names={"-s", "--symbolicname"}, presentValue="true", absentValue="false") boolean showSymbolic, @Descriptor("show update location") @Parameter(names={"-u", "--updatelocation"}, presentValue="true", absentValue="false") boolean showUpdate)
  {
    lb(showLoc, showSymbolic, showUpdate, null);
  }
  
  @Descriptor("list installed bundles matching a substring")
  public void lb(@Descriptor("show location") @Parameter(names={"-l", "--location"}, presentValue="true", absentValue="false") boolean showLoc, @Descriptor("show symbolic name") @Parameter(names={"-s", "--symbolicname"}, presentValue="true", absentValue="false") boolean showSymbolic, @Descriptor("show update location") @Parameter(names={"-u", "--updatelocation"}, presentValue="true", absentValue="false") boolean showUpdate, @Descriptor("subtring matched against name or symbolic name") String pattern)
  {
    List<ServiceReference> refs = new ArrayList();
    
    StartLevel sl = (StartLevel)Util.getService(m_bc, StartLevel.class, refs);
    if (sl == null) {
      System.out.println("Start Level service is unavailable.");
    }
    List<Bundle> found = new ArrayList();
    if (pattern == null)
    {
      found.addAll(Arrays.asList(m_bc.getBundles()));
    }
    else
    {
      Bundle[] bundles = m_bc.getBundles();
      for (int i = 0; i < bundles.length; i++)
      {
        Bundle bundle = bundles[i];
        String name = (String)bundle.getHeaders().get("Bundle-Name");
        if ((matchBundleName(bundle.getSymbolicName(), pattern)) || (matchBundleName(name, pattern))) {
          found.add(bundle);
        }
      }
    }
    if (found.size() > 0) {
      printBundleList((Bundle[])found.toArray(new Bundle[found.size()]), sl, showLoc, showSymbolic, showUpdate);
    } else {
      System.out.println("No matching bundles found");
    }
    Util.ungetServices(m_bc, refs);
  }
  
  private boolean matchBundleName(String name, String pattern)
  {
    return (name != null) && (name.toLowerCase().contains(pattern.toLowerCase()));
  }
  
  @Descriptor("display all matching log entries")
  public void log(@Descriptor("minimum log level [ debug | info | warn | error ]") String logLevel)
  {
    log(-1, logLevel);
  }
  
  @Descriptor("display some matching log entries")
  public void log(@Descriptor("maximum number of entries") int maxEntries, @Descriptor("minimum log level [ debug | info | warn | error ]") String logLevel)
  {
    List<ServiceReference> refs = new ArrayList();
    
    LogReaderService lrs = (LogReaderService)Util.getService(m_bc, LogReaderService.class, refs);
    if (lrs == null)
    {
      System.out.println("Log reader service is unavailable.");
    }
    else
    {
      Enumeration entries = lrs.getLog();
      
      int minLevel = logLevelAsInt(logLevel);
      
      int index = 0;
      while ((entries.hasMoreElements()) && ((maxEntries < 0) || (index < maxEntries)))
      {
        LogEntry entry = (LogEntry)entries.nextElement();
        if (entry.getLevel() <= minLevel)
        {
          display(entry);
          index++;
        }
      }
      Util.ungetServices(m_bc, refs);
    }
  }
  
  private void display(LogEntry entry)
  {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
    
    StringBuffer buffer = new StringBuffer();
    buffer.append(sdf.format(new Date(entry.getTime()))).append(" ");
    buffer.append(logLevelAsString(entry.getLevel())).append(" - ");
    buffer.append("Bundle: ").append(entry.getBundle().getSymbolicName());
    if (entry.getServiceReference() != null)
    {
      buffer.append(" - ");
      buffer.append(entry.getServiceReference().toString());
    }
    buffer.append(" - ").append(entry.getMessage());
    if (entry.getException() != null)
    {
      buffer.append(" - ");
      StringWriter writer = new StringWriter();
      PrintWriter pw = new PrintWriter(writer);
      entry.getException().printStackTrace(pw);
      buffer.append(writer.toString());
    }
    System.out.println(buffer.toString());
  }
  
  private static int logLevelAsInt(String logLevel)
  {
    if ("error".equalsIgnoreCase(logLevel)) {
      return 1;
    }
    if ("warn".equalsIgnoreCase(logLevel)) {
      return 2;
    }
    if ("info".equalsIgnoreCase(logLevel)) {
      return 3;
    }
    return 4;
  }
  
  private static String logLevelAsString(int level)
  {
    switch (level)
    {
    case 1: 
      return "ERROR";
    case 2: 
      return "WARNING";
    case 3: 
      return "INFO";
    }
    return "DEBUG";
  }
  
  @Descriptor("refresh bundles")
  public void refresh(@Descriptor("target bundles (can be null or empty)") Bundle[] bundles)
  {
    if ((bundles != null) && (bundles.length == 0)) {
      bundles = null;
    }
    List<ServiceReference> refs = new ArrayList();
    
    PackageAdmin pa = (PackageAdmin)Util.getService(m_bc, PackageAdmin.class, refs);
    if (pa == null) {
      System.out.println("Package Admin service is unavailable.");
    }
    pa.refreshPackages(bundles == null ? null : bundles);
    
    Util.ungetServices(m_bc, refs);
  }
  
  @Descriptor("resolve bundles")
  public void resolve(@Descriptor("target bundles (can be null or empty)") Bundle[] bundles)
  {
    if ((bundles != null) && (bundles.length == 0)) {
      bundles = null;
    }
    List<ServiceReference> refs = new ArrayList();
    
    PackageAdmin pa = (PackageAdmin)Util.getService(m_bc, PackageAdmin.class, refs);
    if (pa == null) {
      System.out.println("Package Admin service is unavailable.");
    }
    pa.resolveBundles(bundles == null ? null : bundles);
    
    Util.ungetServices(m_bc, refs);
  }
  
  @Descriptor("start bundles")
  public void start(@Descriptor("start bundle transiently") @Parameter(names={"-t", "--transient"}, presentValue="true", absentValue="false") boolean trans, @Descriptor("use declared activation policy") @Parameter(names={"-p", "--policy"}, presentValue="true", absentValue="false") boolean policy, @Descriptor("target bundle identifiers or URLs") String[] ss)
  {
    int options = 0;
    if (trans) {
      options |= 0x1;
    }
    if (policy) {
      options |= 0x2;
    }
    if ((ss != null) && (ss.length >= 1)) {
      for (String s : ss)
      {
        String id = s.trim();
        try
        {
          Bundle bundle = null;
          if (Character.isDigit(id.charAt(0)))
          {
            long l = Long.parseLong(id);
            bundle = m_bc.getBundle(l);
          }
          else
          {
            bundle = m_bc.installBundle(id);
          }
          if (bundle != null) {
            bundle.start(options);
          } else {
            System.err.println("Bundle ID " + id + " is invalid.");
          }
        }
        catch (NumberFormatException ex)
        {
          System.err.println("Unable to parse id '" + id + "'.");
        }
        catch (BundleException ex)
        {
          if (ex.getNestedException() != null)
          {
            ex.printStackTrace();
            System.err.println(ex.getNestedException().toString());
          }
          else
          {
            System.err.println(ex.toString());
          }
        }
        catch (Exception ex)
        {
          System.err.println(ex.toString());
        }
      }
    } else {
      System.err.println("Incorrect number of arguments");
    }
  }
  
  @Descriptor("stop bundles")
  public void stop(@Descriptor("stop bundle transiently") @Parameter(names={"-t", "--transient"}, presentValue="true", absentValue="false") boolean trans, @Descriptor("target bundles") Bundle[] bundles)
  {
    if ((bundles == null) || (bundles.length == 0)) {
      System.out.println("Please specify the bundles to stop.");
    }
    int options = 0;
    if (trans) {
      options |= 0x1;
    }
    for (Bundle bundle : bundles) {
      try
      {
        bundle.stop(options);
      }
      catch (BundleException ex)
      {
        if (ex.getNestedException() != null) {
          System.err.println(ex.getNestedException().toString());
        } else {
          System.err.println(ex.toString());
        }
      }
      catch (Exception ex)
      {
        System.err.println(ex.toString());
      }
    }
  }
  
  @Descriptor("uninstall bundles")
  public void uninstall(@Descriptor("target bundles") Bundle[] bundles)
  {
    if ((bundles == null) || (bundles.length == 0)) {
      System.out.println("Please specify the bundles to uninstall.");
    } else {
      try
      {
        for (Bundle bundle : bundles) {
          bundle.uninstall();
        }
      }
      catch (BundleException ex)
      {
        if (ex.getNestedException() != null)
        {
          ex.printStackTrace();
          System.err.println(ex.getNestedException().toString());
        }
        else
        {
          System.err.println(ex.toString());
        }
      }
      catch (Exception ex)
      {
        System.err.println(ex.toString());
      }
    }
  }
  
  @Descriptor("update bundle")
  public void update(@Descriptor("target bundle") Bundle bundle)
  {
    try
    {
      if (bundle != null) {
        bundle.update();
      }
    }
    catch (BundleException ex)
    {
      if (ex.getNestedException() != null) {
        System.err.println(ex.getNestedException().toString());
      } else {
        System.err.println(ex.toString());
      }
    }
    catch (Exception ex)
    {
      System.err.println(ex.toString());
    }
  }
  
  @Descriptor("update bundle from URL")
  public void update(@Descriptor("target bundle") Bundle bundle, @Descriptor("URL from where to retrieve bundle") String location)
  {
    if (location != null) {
      try
      {
        if (bundle != null)
        {
          InputStream is = new URL(location).openStream();
          bundle.update(is);
        }
        else
        {
          System.err.println("Please specify a bundle to update");
        }
      }
      catch (MalformedURLException ex)
      {
        System.err.println("Unable to parse URL");
      }
      catch (IOException ex)
      {
        System.err.println("Unable to open input stream: " + ex);
      }
      catch (BundleException ex)
      {
        if (ex.getNestedException() != null) {
          System.err.println(ex.getNestedException().toString());
        } else {
          System.err.println(ex.toString());
        }
      }
      catch (Exception ex)
      {
        System.err.println(ex.toString());
      }
    } else {
      System.err.println("Must specify a location.");
    }
  }
  
  @Descriptor("determines from where a bundle loads a class")
  public void which(@Descriptor("target bundle") Bundle bundle, @Descriptor("target class name") String className)
  {
    if (bundle == null)
    {
      System.err.println("Please specify a bundle");
    }
    else
    {
      Class clazz = null;
      try
      {
        clazz = bundle.loadClass(className);
        if (clazz.getClassLoader() == null)
        {
          System.out.println("Loaded from: boot class loader");
        }
        else if ((clazz.getClassLoader() instanceof BundleReference))
        {
          Bundle p = ((BundleReference)clazz.getClassLoader()).getBundle();
          System.out.println("Loaded from: " + p);
        }
        else
        {
          System.out.println("Loaded from: " + clazz.getClassLoader());
        }
      }
      catch (ClassNotFoundException ex)
      {
        System.out.println("Class not found");
      }
    }
  }
  
  private static void printBundleList(Bundle[] bundles, StartLevel startLevel, boolean showLoc, boolean showSymbolic, boolean showUpdate)
  {
    if (startLevel != null) {
      System.out.println("START LEVEL " + startLevel.getStartLevel());
    }
    String lastColumn = "Name";
    if (showLoc) {
      lastColumn = "Location";
    } else if (showSymbolic) {
      lastColumn = "Symbolic name";
    } else if (showUpdate) {
      lastColumn = "Update location";
    }
    if (startLevel != null) {
      System.out.println(String.format("%5s|%-11s|%5s|%s", new Object[] { "ID", "State", "Level", lastColumn }));
    } else {
      System.out.println(String.format("%5s|%-11s|%s", new Object[] { "ID", "State", lastColumn }));
    }
    for (Bundle bundle : bundles)
    {
      String name = (String)bundle.getHeaders().get("Bundle-Name");
      
      name = name == null ? bundle.getSymbolicName() : name;
      
      name = name == null ? bundle.getLocation() : name;
      if (showLoc)
      {
        name = bundle.getLocation();
      }
      else if (showSymbolic)
      {
        name = bundle.getSymbolicName();
        name = name == null ? "<no symbolic name>" : name;
      }
      else if (showUpdate)
      {
        name = (String)bundle.getHeaders().get("Bundle-UpdateLocation");
        
        name = name == null ? bundle.getLocation() : name;
      }
      name = (!showLoc) && (!showUpdate) ? name + " (" + bundle.getVersion() + ")" : name;
      
      int level = startLevel == null ? -1 : startLevel.getBundleStartLevel(bundle);
      if (level < 0) {
        System.out.println(String.format("%5d|%-11s|%s", new Object[] { Long.valueOf(bundle.getBundleId()), getStateString(bundle), name, bundle.getVersion() }));
      } else {
        System.out.println(String.format("%5d|%-11s|%5d|%s", new Object[] { Long.valueOf(bundle.getBundleId()), getStateString(bundle), Integer.valueOf(level), name, bundle.getVersion() }));
      }
    }
  }
  
  private static String getStateString(Bundle bundle)
  {
    int state = bundle.getState();
    if (state == 32) {
      return "Active     ";
    }
    if (state == 2) {
      return "Installed  ";
    }
    if (state == 4) {
      return "Resolved   ";
    }
    if (state == 8) {
      return "Starting   ";
    }
    if (state == 16) {
      return "Stopping   ";
    }
    return "Unknown    ";
  }
}

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

import java.io.File;
import java.io.FileFilter;
import java.util.List;

class Files$1
  implements FileFilter
{
  Files$1(Files paramFiles, List paramList) {}
  
  public boolean accept(File pathname)
  {
    return Files.compareSubstring(val$pieces, pathname.getName());
  }
}

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

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.felix.service.command.CommandSession;
import org.apache.felix.service.command.Descriptor;
import org.osgi.framework.BundleContext;

public class Files
{
  private static final String CWD = "_cwd";
  private final BundleContext m_bc;
  
  public Files(BundleContext bc)
  {
    m_bc = bc;
  }
  
  @Descriptor("get current directory")
  public File cd(@Descriptor("automatically supplied shell session") CommandSession session)
  {
    try
    {
      return cd(session, null);
    }
    catch (IOException ex)
    {
      throw new RuntimeException("Unable to get current directory");
    }
  }
  
  @Descriptor("change current directory")
  public File cd(@Descriptor("automatically supplied shell session") CommandSession session, @Descriptor("target directory") String dir)
    throws IOException
  {
    File cwd = (File)session.get("_cwd");
    if (cwd == null)
    {
      cwd = new File(".").getCanonicalFile();
      session.put("_cwd", cwd);
    }
    if ((dir == null) || (dir.length() == 0)) {
      return cwd;
    }
    cwd = new File(cwd, dir);
    if (!cwd.exists()) {
      throw new IOException("Directory does not exist");
    }
    if (!cwd.isDirectory()) {
      throw new IOException("Target is not a directory");
    }
    session.put("_cwd", cwd.getCanonicalFile());
    return cwd;
  }
  
  @Descriptor("get current directory contents")
  public File[] ls(@Descriptor("automatically supplied shell session") CommandSession session)
    throws IOException
  {
    return ls(session, null);
  }
  
  @Descriptor("get specified path contents")
  public File[] ls(@Descriptor("automatically supplied shell session") CommandSession session, @Descriptor("path with optionally wildcarded file name") String pattern)
    throws IOException
  {
    pattern = (pattern == null) || (pattern.length() == 0) ? "." : pattern;
    pattern = (pattern.charAt(0) != File.separatorChar) && (pattern.charAt(0) != '.') ? "./" + pattern : pattern;
    
    int idx = pattern.lastIndexOf(File.separatorChar);
    String parent = idx < 0 ? "." : pattern.substring(0, idx + 1);
    String target = idx < 0 ? pattern : pattern.substring(idx + 1);
    
    File actualParent = (parent.charAt(0) == File.separatorChar ? new File(parent) : new File(cd(session), parent)).getCanonicalFile();
    
    idx = target.indexOf(File.separatorChar, idx);
    boolean isWildcarded = target.indexOf('*', idx) >= 0;
    File[] files;
    File[] files;
    if (isWildcarded)
    {
      if (!actualParent.exists()) {
        throw new IOException("File does not exist");
      }
      final List<String> pieces = parseSubstring(target);
      files = actualParent.listFiles(new FileFilter()
      {
        public boolean accept(File pathname)
        {
          return Files.compareSubstring(pieces, pathname.getName());
        }
      });
    }
    else
    {
      File actualTarget = new File(actualParent, target).getCanonicalFile();
      if (!actualTarget.exists()) {
        throw new IOException("File does not exist");
      }
      File[] files;
      if (actualTarget.isDirectory()) {
        files = actualTarget.listFiles();
      } else {
        files = new File[] { actualTarget };
      }
    }
    return files;
  }
  
  public static List<String> parseSubstring(String value)
  {
    List<String> pieces = new ArrayList();
    StringBuffer ss = new StringBuffer();
    
    boolean wasStar = false;
    boolean leftstar = false;
    boolean rightstar = false;
    
    int idx = 0;
    
    boolean escaped = false;
    for (;;)
    {
      if (idx >= value.length())
      {
        if (wasStar) {
          rightstar = true;
        } else {
          pieces.add(ss.toString());
        }
        ss.setLength(0);
        break;
      }
      char c = value.charAt(idx++);
      if ((!escaped) && ((c == '(') || (c == ')'))) {
        throw new IllegalArgumentException("Illegal value: " + value);
      }
      if ((!escaped) && (c == '*'))
      {
        if (wasStar) {
          throw new IllegalArgumentException("Invalid filter string: " + value);
        }
        if (ss.length() > 0) {
          pieces.add(ss.toString());
        }
        ss.setLength(0);
        if (pieces.size() == 0) {
          leftstar = true;
        }
        wasStar = true;
      }
      else if ((!escaped) && (c == '\\'))
      {
        escaped = true;
      }
      else
      {
        escaped = false;
        wasStar = false;
        ss.append(c);
      }
    }
    if ((leftstar) || (rightstar) || (pieces.size() > 1))
    {
      if (rightstar) {
        pieces.add("");
      }
      if (leftstar) {
        pieces.add(0, "");
      }
    }
    return pieces;
  }
  
  public static boolean compareSubstring(List<String> pieces, String s)
  {
    boolean result = true;
    int len = pieces.size();
    
    int index = 0;
    for (int i = 0; i < len; i++)
    {
      String piece = (String)pieces.get(i);
      if (i == 0) {
        if (!s.startsWith(piece))
        {
          result = false;
          break;
        }
      }
      if (i == len - 1)
      {
        if (s.endsWith(piece))
        {
          result = true; break;
        }
        result = false;
        
        break;
      }
      if ((i > 0) && (i < len - 1))
      {
        index = s.indexOf(piece, index);
        if (index < 0)
        {
          result = false;
          break;
        }
      }
      index += piece.length();
    }
    return result;
  }
}

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

import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.List;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.packageadmin.ExportedPackage;
import org.osgi.service.packageadmin.PackageAdmin;
import org.osgi.service.packageadmin.RequiredBundle;

public class Inspect
{
  public static final String PACKAGE_TYPE = "package";
  public static final String BUNDLE_TYPE = "bundle";
  public static final String FRAGMENT_TYPE = "fragment";
  public static final String SERVICE_TYPE = "service";
  public static final String CAPABILITY = "capability";
  public static final String REQUIREMENT = "requirement";
  
  public static void inspect(BundleContext bc, String type, String direction, Bundle[] bundles)
  {
    if ((isValidType(type)) && (isValidDirection(direction)))
    {
      if ("package".startsWith(type))
      {
        if ("capability".startsWith(direction)) {
          printExportedPackages(bc, bundles);
        } else {
          printImportedPackages(bc, bundles);
        }
      }
      else if ("bundle".startsWith(type))
      {
        if ("capability".startsWith(direction)) {
          printRequiringBundles(bc, bundles);
        } else {
          printRequiredBundles(bc, bundles);
        }
      }
      else if ("fragment".startsWith(type))
      {
        if ("capability".startsWith(direction)) {
          printFragmentHosts(bc, bundles);
        } else {
          printHostedFragments(bc, bundles);
        }
      }
      else if ("capability".startsWith(direction)) {
        printExportedServices(bc, bundles);
      } else {
        printImportedServices(bc, bundles);
      }
    }
    else
    {
      if (!isValidType(type)) {
        System.out.println("Invalid argument: " + type);
      }
      if (!isValidDirection(direction)) {
        System.out.println("Invalid argument: " + direction);
      }
    }
  }
  
  public static void printExportedPackages(BundleContext bc, Bundle[] bundles)
  {
    List<ServiceReference> refs = new ArrayList();
    
    PackageAdmin pa = (PackageAdmin)Util.getService(bc, PackageAdmin.class, refs);
    if (pa == null)
    {
      System.out.println("PackageAdmin service is unavailable.");
    }
    else
    {
      boolean separatorNeeded = false;
      if ((bundles == null) || (bundles.length == 0)) {
        bundles = bc.getBundles();
      }
      for (int bundleIdx = 0; bundleIdx < bundles.length; bundleIdx++) {
        try
        {
          if (bundles[bundleIdx] != null)
          {
            ExportedPackage[] exports = pa.getExportedPackages(bundles[bundleIdx]);
            if (separatorNeeded) {
              System.out.println("");
            }
            String title = bundles[bundleIdx] + " exports packages:";
            System.out.println(title);
            System.out.println(Util.getUnderlineString(title.length()));
            if ((exports != null) && (exports.length > 0)) {
              for (int expIdx = 0; expIdx < exports.length; expIdx++)
              {
                System.out.print(exports[expIdx]);
                Bundle[] importers = exports[expIdx].getImportingBundles();
                if ((importers == null) || (importers.length == 0))
                {
                  System.out.println(" UNUSED");
                }
                else
                {
                 
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