felix-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From rickh...@apache.org
Subject svn commit: r783826 [1/2] - in /felix/trunk/gogo: ./ src/ src/aQute/ src/aQute/cpeg/ src/aQute/osgi/ src/aQute/osgi/launcher/ src/aQute/shell/ src/aQute/shell/console/ src/aQute/shell/equinox/ src/aQute/shell/lang/ src/aQute/shell/osgi/ src/aQute/shell...
Date Thu, 11 Jun 2009 16:07:22 GMT
Author: rickhall
Date: Thu Jun 11 16:07:20 2009
New Revision: 783826

URL: http://svn.apache.org/viewvc?rev=783826&view=rev
Log:
Initial commit of OSGi Shell contribution. (FELIX-946)

Added:
    felix/trunk/gogo/
    felix/trunk/gogo/aQute.osgi.launcher.bnd
    felix/trunk/gogo/aQute.shell.equinox.bnd
    felix/trunk/gogo/aQute.shell.runtime.bnd
    felix/trunk/gogo/aQute.shell.stdio.bnd
    felix/trunk/gogo/aQute.shell.support.bnd
    felix/trunk/gogo/aQute.shell.telnet.bnd
    felix/trunk/gogo/aQute.threadio.bnd
    felix/trunk/gogo/default.bnd
    felix/trunk/gogo/proc.bnd
    felix/trunk/gogo/src/
    felix/trunk/gogo/src/aQute/
    felix/trunk/gogo/src/aQute/cpeg/
    felix/trunk/gogo/src/aQute/cpeg/Procedural.java
    felix/trunk/gogo/src/aQute/osgi/
    felix/trunk/gogo/src/aQute/osgi/launcher/
    felix/trunk/gogo/src/aQute/osgi/launcher/Launcher.java
    felix/trunk/gogo/src/aQute/shell/
    felix/trunk/gogo/src/aQute/shell/console/
    felix/trunk/gogo/src/aQute/shell/console/Console.java
    felix/trunk/gogo/src/aQute/shell/equinox/
    felix/trunk/gogo/src/aQute/shell/equinox/Equinox.java
    felix/trunk/gogo/src/aQute/shell/lang/
    felix/trunk/gogo/src/aQute/shell/lang/Support.java
    felix/trunk/gogo/src/aQute/shell/osgi/
    felix/trunk/gogo/src/aQute/shell/osgi/OSGiCommands.java
    felix/trunk/gogo/src/aQute/shell/osgi/OSGiShell.java
    felix/trunk/gogo/src/aQute/shell/osgi/ServiceCommand.java
    felix/trunk/gogo/src/aQute/shell/runtime/
    felix/trunk/gogo/src/aQute/shell/runtime/Closure.java
    felix/trunk/gogo/src/aQute/shell/runtime/Command.java
    felix/trunk/gogo/src/aQute/shell/runtime/CommandSessionImpl.java
    felix/trunk/gogo/src/aQute/shell/runtime/CommandShellImpl.java
    felix/trunk/gogo/src/aQute/shell/runtime/Parser.java
    felix/trunk/gogo/src/aQute/shell/runtime/Pipe.java
    felix/trunk/gogo/src/aQute/shell/runtime/Reflective.java
    felix/trunk/gogo/src/aQute/shell/stdio/
    felix/trunk/gogo/src/aQute/shell/stdio/StdioConsole.java
    felix/trunk/gogo/src/aQute/shell/telnet/
    felix/trunk/gogo/src/aQute/shell/telnet/Handler.java
    felix/trunk/gogo/src/aQute/shell/telnet/TelnetShell.java
    felix/trunk/gogo/src/aQute/threadio/
    felix/trunk/gogo/src/aQute/threadio/Marker.java
    felix/trunk/gogo/src/aQute/threadio/ThreadIOImpl.java
    felix/trunk/gogo/src/aQute/threadio/ThreadInputStream.java
    felix/trunk/gogo/src/aQute/threadio/ThreadPrintStream.java
    felix/trunk/gogo/src/org/
    felix/trunk/gogo/src/org/osgi/
    felix/trunk/gogo/src/org/osgi/framework/
    felix/trunk/gogo/src/org/osgi/framework/boot/
    felix/trunk/gogo/src/org/osgi/framework/boot/SystemBundle.java
    felix/trunk/gogo/src/org/osgi/service/
    felix/trunk/gogo/src/org/osgi/service/command/
    felix/trunk/gogo/src/org/osgi/service/command/CommandProcessor.java
    felix/trunk/gogo/src/org/osgi/service/command/CommandSession.java
    felix/trunk/gogo/src/org/osgi/service/command/Converter.java
    felix/trunk/gogo/src/org/osgi/service/command/Function.java
    felix/trunk/gogo/src/org/osgi/service/threadio/
    felix/trunk/gogo/src/org/osgi/service/threadio/ThreadIO.java
    felix/trunk/gogo/test/
    felix/trunk/gogo/test/test/
    felix/trunk/gogo/test/test/aQute/
    felix/trunk/gogo/test/test/aQute/shell/
    felix/trunk/gogo/test/test/aQute/shell/runtime/
    felix/trunk/gogo/test/test/aQute/shell/runtime/Context.java
    felix/trunk/gogo/test/test/aQute/shell/runtime/TestParser.java
    felix/trunk/gogo/test/test/aQute/threadio/
    felix/trunk/gogo/test/test/aQute/threadio/TestThreadIO.java

Added: felix/trunk/gogo/aQute.osgi.launcher.bnd
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/aQute.osgi.launcher.bnd?rev=783826&view=auto
==============================================================================
--- felix/trunk/gogo/aQute.osgi.launcher.bnd (added)
+++ felix/trunk/gogo/aQute.osgi.launcher.bnd Thu Jun 11 16:07:20 2009
@@ -0,0 +1,4 @@
+Private-Package: aQute.osgi.launcher, aQute.shell.runtime, aQute.shell.osgi, aQute.threadio, \
+ org.osgi.service.shell, org.osgi.service.threadio, aQute.shell.console, org.osgi.framework 
+Main-Class: aQute.osgi.launcher.Launcher
+

Added: felix/trunk/gogo/aQute.shell.equinox.bnd
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/aQute.shell.equinox.bnd?rev=783826&view=auto
==============================================================================
--- felix/trunk/gogo/aQute.shell.equinox.bnd (added)
+++ felix/trunk/gogo/aQute.shell.equinox.bnd Thu Jun 11 16:07:20 2009
@@ -0,0 +1,6 @@
+-include: ~default.bnd
+Service-Component: aQute.shell.equinox.Equinox; \
+   pka=org.osgi.service.packageadmin.PackageAdmin?; \
+   lrs=org.osgi.service.log.LogReaderService?; \
+   sls=org.osgi.service.startlevel.StartLevel?
+Private-Package: aQute.shell.equinox

Added: felix/trunk/gogo/aQute.shell.runtime.bnd
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/aQute.shell.runtime.bnd?rev=783826&view=auto
==============================================================================
--- felix/trunk/gogo/aQute.shell.runtime.bnd (added)
+++ felix/trunk/gogo/aQute.shell.runtime.bnd Thu Jun 11 16:07:20 2009
@@ -0,0 +1,9 @@
+-include: ~default.bnd
+Bundle-Name: Command Shell Service
+Bundle-Description: Provides a shell service
+Private-Package: aQute.shell.osgi, aQute.shell.runtime
+Export-Package: org.osgi.service.command
+Service-Component: aQute.shell.osgi.OSGiShell; \
+  provide:=org.osgi.service.command.CommandProcessor; \
+  threadio=org.osgi.service.threadio.ThreadIO; \
+  converter=org.osgi.service.command.Converter*

Added: felix/trunk/gogo/aQute.shell.stdio.bnd
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/aQute.shell.stdio.bnd?rev=783826&view=auto
==============================================================================
--- felix/trunk/gogo/aQute.shell.stdio.bnd (added)
+++ felix/trunk/gogo/aQute.shell.stdio.bnd Thu Jun 11 16:07:20 2009
@@ -0,0 +1,4 @@
+-include: ~default.bnd
+Service-Component: aQute.shell.stdio.StdioConsole; \
+   processor=org.osgi.service.command.CommandProcessor
+Private-Package: aQute.shell.stdio,aQute.shell.console

Added: felix/trunk/gogo/aQute.shell.support.bnd
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/aQute.shell.support.bnd?rev=783826&view=auto
==============================================================================
--- felix/trunk/gogo/aQute.shell.support.bnd (added)
+++ felix/trunk/gogo/aQute.shell.support.bnd Thu Jun 11 16:07:20 2009
@@ -0,0 +1,6 @@
+-include: ~default.bnd
+Bundle-Name: aQute Shell Support
+Bundle-Description: Commands for the shell that turn it into a programming language
+Private-Package: aQute.shell.lang
+Service-Component: aQute.shell.lang.Support; \
+  provide:=org.osgi.service.command.Converter
\ No newline at end of file

Added: felix/trunk/gogo/aQute.shell.telnet.bnd
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/aQute.shell.telnet.bnd?rev=783826&view=auto
==============================================================================
--- felix/trunk/gogo/aQute.shell.telnet.bnd (added)
+++ felix/trunk/gogo/aQute.shell.telnet.bnd Thu Jun 11 16:07:20 2009
@@ -0,0 +1,7 @@
+-include: ~default.bnd
+
+Bundle-Name: Telnet Shell Service
+Bundle-Description: Listens to port 2019 (unless overridden with configuration "port" for pid=aQute.shell.telnet.TelnetShell)
+Private-Package: aQute.shell.telnet, aQute.shell.console
+Service-Component: aQute.shell.telnet.TelnetShell; \
+  processor=org.osgi.service.command.CommandProcessor

Added: felix/trunk/gogo/aQute.threadio.bnd
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/aQute.threadio.bnd?rev=783826&view=auto
==============================================================================
--- felix/trunk/gogo/aQute.threadio.bnd (added)
+++ felix/trunk/gogo/aQute.threadio.bnd Thu Jun 11 16:07:20 2009
@@ -0,0 +1,8 @@
+-include: ~default.bnd
+
+Bundle-Name: Thread IO
+Bundle-Description: Multiplexes input/output/error streams based on the thread.
+Private-Package: aQute.threadio 
+Export-Package: org.osgi.service.threadio
+Service-Component: aQute.threadio.ThreadIOImpl;\
+  provide:=org.osgi.service.threadio.ThreadIO

Added: felix/trunk/gogo/default.bnd
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/default.bnd?rev=783826&view=auto
==============================================================================
--- felix/trunk/gogo/default.bnd (added)
+++ felix/trunk/gogo/default.bnd Thu Jun 11 16:07:20 2009
@@ -0,0 +1,3 @@
+-output: work
+-sources: true
+Bundle-Version: 0.0.12
\ No newline at end of file

Added: felix/trunk/gogo/proc.bnd
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/proc.bnd?rev=783826&view=auto
==============================================================================
--- felix/trunk/gogo/proc.bnd (added)
+++ felix/trunk/gogo/proc.bnd Thu Jun 11 16:07:20 2009
@@ -0,0 +1,5 @@
+-output: work
+Private-Package: aQute.cpeg
+Service-Component: aQute.cpeg.Procedural; \
+  provide:=aQute.cpeg.Procedural; \
+  properties:="osgi.command.scope=proc,osgi.command.function=new"

Added: felix/trunk/gogo/src/aQute/cpeg/Procedural.java
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/src/aQute/cpeg/Procedural.java?rev=783826&view=auto
==============================================================================
--- felix/trunk/gogo/src/aQute/cpeg/Procedural.java (added)
+++ felix/trunk/gogo/src/aQute/cpeg/Procedural.java Thu Jun 11 16:07:20 2009
@@ -0,0 +1,59 @@
+/*
+ * 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 aQute.cpeg;
+
+
+import org.osgi.framework.*;
+import org.osgi.service.command.*;
+
+
+public class Procedural {
+    
+    public Object _if( CommandSession session, Function condition, Function ifTrue, Function ifFalse ) throws Exception {
+        Object result = condition.execute(session, null);
+        if ( isTrue(result)) {
+            return ifTrue.execute(session, null);
+        } else {
+            if ( ifFalse != null )
+                return ifFalse.execute(session,null);
+        }
+        return null;
+    }
+    
+    public Object _new(String name, Bundle bundle) throws Exception {
+        if ( bundle == null)
+            return Class.forName(name).newInstance();
+        else {
+            return bundle.loadClass(name).newInstance();
+        }
+    }
+
+    private boolean isTrue(Object result) {
+        if ( result == null)
+            return false;
+        
+        if ( result instanceof String && ((String)result).equals(""))
+            return false;
+        
+        if ( result instanceof Boolean )
+            return ((Boolean)result).booleanValue();
+        
+        return true;
+    }
+}

Added: felix/trunk/gogo/src/aQute/osgi/launcher/Launcher.java
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/src/aQute/osgi/launcher/Launcher.java?rev=783826&view=auto
==============================================================================
--- felix/trunk/gogo/src/aQute/osgi/launcher/Launcher.java (added)
+++ felix/trunk/gogo/src/aQute/osgi/launcher/Launcher.java Thu Jun 11 16:07:20 2009
@@ -0,0 +1,121 @@
+/*
+ * 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 aQute.osgi.launcher;
+
+import java.io.*;
+import java.lang.reflect.*;
+import java.net.*;
+import java.util.*;
+
+import org.osgi.framework.*;
+import org.osgi.service.command.*;
+
+import aQute.shell.console.*;
+import aQute.shell.osgi.*;
+import aQute.threadio.*;
+
+public class Launcher {
+	static List<URL> classpath = new ArrayList<URL>();
+	static File cwd = new File("").getAbsoluteFile();
+	
+	public static void main(String args[]) throws Exception {
+		StringBuffer sb = new StringBuffer();
+		String framework = null;
+		PrintStream		out = System.out;
+		InputStream		in = System.in;
+		boolean console = false;
+		
+		for (int i = 0; i < args.length; i++) {
+			String arg = args[i];
+			if (arg.equals("-f")) {
+				framework = args[++i];
+			} else if (arg.equals("-cp") || arg.equals("-classpath")) {
+				classpath(args[++i]);
+			} else if (arg.equals("-console")) {
+				console = true;
+			} else if (arg.equals("-i")) {
+				in = new FileInputStream(args[++i]);
+			} else if (arg.equals("-o")) {
+				out = new PrintStream(new FileOutputStream(args[++i]));
+			} else {
+				sb.append(' ');
+				sb.append(arg);
+			}
+		}
+
+		if (framework == null) {
+			System.err.println("No framework set");
+			System.exit(1);
+		}
+
+		ThreadIOImpl threadio = new ThreadIOImpl();
+		threadio.start();
+		URL[] urls = classpath.toArray(new URL[classpath.size()]);
+		URLClassLoader urlcl = new URLClassLoader(urls, Launcher.class.getClassLoader());
+		Class<?> fw = urlcl.loadClass(framework);
+		
+		Constructor<?> c = fw.getConstructor(Map.class, List.class );
+		Properties p = new Properties( System.getProperties());
+		p.setProperty("felix.cache.profile", "default");
+		p.setProperty("felix.embedded.execution", "true");
+		Bundle bundle = (Bundle) c.newInstance(p,null);
+		
+		OSGiShell shell = new OSGiShell();
+		shell.setThreadio(threadio);
+		shell.setBundle(bundle);
+		shell.start();
+		
+		
+		CommandSession session = shell.createSession(in, out,
+				System.err);
+		session.put("shell", shell);
+		session.put("threadio", threadio);
+		
+		session.execute(sb);
+		out.flush();
+		
+		if ( bundle.getState() == Bundle.ACTIVE ) {
+			bundle.getBundleContext().registerService(CommandProcessor.class.getName(), shell, null );
+		}
+		if ( console ) {
+			Console cons = new Console();
+			cons.setSession(session);
+			cons.run();
+		}
+	}
+
+
+	private static void classpath(String string) throws MalformedURLException {
+		StringTokenizer st = new StringTokenizer(string, File.pathSeparator);
+		while (st.hasMoreTokens()) {
+			String part = st.nextToken();
+			if ( part.equals("."))
+				classpath.add( cwd.toURL() );
+			
+			File f = new File(part);
+			if ( ! f.isAbsolute() ) {
+				f = new File( cwd, part );
+			}
+			if ( f.exists() )
+				classpath.add( f.toURL());
+			else
+				System.err.println("Can not find " + part );
+		}
+	}	
+}

Added: felix/trunk/gogo/src/aQute/shell/console/Console.java
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/src/aQute/shell/console/Console.java?rev=783826&view=auto
==============================================================================
--- felix/trunk/gogo/src/aQute/shell/console/Console.java (added)
+++ felix/trunk/gogo/src/aQute/shell/console/Console.java Thu Jun 11 16:07:20 2009
@@ -0,0 +1,143 @@
+/*
+ * 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 aQute.shell.console;
+
+import java.io.*;
+import java.lang.reflect.*;
+import java.util.*;
+
+import org.osgi.service.command.*;
+
+public class Console implements Runnable {
+	StringBuilder		sb;
+	CommandSession		session;
+	List<CharSequence>	history	= new ArrayList<CharSequence>();
+	int					current	= 0;
+	boolean				quit;
+
+	public void setSession(CommandSession session) {
+	    this.session= session;
+	}
+	
+	public void run() {
+		try {
+			while (!quit) {
+				try {
+					CharSequence line = getLine(session.getKeybord());
+					if (line != null) {
+						history.add(line);
+						if (history.size() > 40)
+							history.remove(0);
+						Object result = session.execute(line);
+						if (result != null)
+							session.getConsole().println(
+									session.format(result, Converter.INSPECT));
+					} else
+						quit = true;
+
+				} catch (InvocationTargetException ite) {
+					session.getConsole().println(
+							"E: " + ite.getTargetException());
+					session.put("exception", ite.getTargetException());
+				} catch (Throwable e) {
+					if (!quit) {
+						session.getConsole().println("E: " + e.getMessage());
+						session.put("exception", e);
+					}
+				}
+			}
+		} catch (Exception e) {
+			if (!quit)
+				e.printStackTrace();
+		}
+	}
+
+	CharSequence getLine(InputStream in) throws IOException {
+		sb = new StringBuilder();
+		session.getConsole().print("$ ");
+		int outer = 0;
+		while (!quit) {
+			session.getConsole().flush();
+			int c = in.read();
+			if (c < 0)
+				quit = true;
+			else {
+				switch (c) {
+				case '\r':
+				    break;
+				case '\n':
+					if (outer == 0 && sb.length() > 0) {
+						return sb;
+					} else {
+					        session.getConsole().print("$ ");
+					}
+					break;
+
+				case '\u001b':
+					c = in.read();
+					if (c == '[') {
+						c = in.read();
+						session.getConsole().print("\b\b\b");
+						switch (c) {
+						case 'A':
+							history(current - 1);
+							break;
+						case 'B':
+							history(current + 1);
+							break;
+						case 'C': // right(); break;
+						case 'D': // left(); break;
+						}
+					}
+					break;
+
+				case '\b':
+					if (sb.length() > 0) {
+						session.getConsole().print("\b \b");
+						sb.deleteCharAt(sb.length() - 1);
+					}
+					break;
+
+				default:
+					sb.append((char) c);
+					break;
+				}
+			}
+		}
+		return null;
+	}
+
+	void history(int n) {
+		if (n < 0 || n > history.size())
+			return;
+		current = n;
+		for (int i = 0; i < sb.length(); i++)
+			session.getConsole().print("\b \b");
+
+		sb = new StringBuilder(history.get(current));
+		session.getConsole().print(sb);
+	}
+
+    public void close() {
+        quit = true;
+    }
+    
+    public void open() {}
+}

Added: felix/trunk/gogo/src/aQute/shell/equinox/Equinox.java
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/src/aQute/shell/equinox/Equinox.java?rev=783826&view=auto
==============================================================================
--- felix/trunk/gogo/src/aQute/shell/equinox/Equinox.java (added)
+++ felix/trunk/gogo/src/aQute/shell/equinox/Equinox.java Thu Jun 11 16:07:20 2009
@@ -0,0 +1,389 @@
+package aQute.shell.equinox;
+
+import java.io.*;
+import java.net.*;
+import java.util.*;
+
+import org.osgi.framework.*;
+import org.osgi.service.command.*;
+import org.osgi.service.component.*;
+import org.osgi.service.log.*;
+import org.osgi.service.packageadmin.*;
+import org.osgi.service.startlevel.*;
+
+public class Equinox implements Converter {
+    BundleContext         context;
+    PackageAdmin          pka;
+    LogReaderService      lrs;
+    StartLevel            sls;
+    final static String[] functions = { "active", "bundles", "close", "diag",
+            "exec", "exit", "fork", "gc", "getprop", "headers", "init",
+            "install", "launch", "log", "packages", "packages", "refresh",
+            "services", "setbsl", "setfwsl", "setibsl", "setprop", "shutdown",
+            "sl", "ss", "start", "status", "stop", "uninstall", "update" };
+
+    protected void activate(ComponentContext context) {
+        this.context = context.getBundleContext();
+        Dictionary<String, Object> dict = new Hashtable<String, Object>();
+        dict.put(CommandProcessor.COMMAND_SCOPE, "eqx");
+        dict.put(CommandProcessor.COMMAND_FUNCTION, functions);
+        this.context.registerService( Converter.class.getName(), this, dict);
+    }
+
+    BundleContext getContext() {
+        return context;
+    }
+
+    public void setPka(PackageAdmin pka) {
+        this.pka = pka;
+    }
+
+    public void setLrs(LogReaderService lrs) {
+        this.lrs = lrs;
+    }
+
+    public void setSls(StartLevel sls) {
+        this.sls = sls;
+    }
+
+    /**
+     * - Displays unsatisfied constraints for the specified bundle(s).
+     */
+    public void diag() {
+    }
+
+    /*
+     * active - Displays a list of all bundles currently in the ACTIVE state.
+     */
+    public List<Bundle> active() {
+        List<Bundle> result = new ArrayList<Bundle>();
+        Bundle[] bundles = getContext().getBundles();
+        for (Bundle b : bundles) {
+            if (b.getState() == Bundle.ACTIVE)
+                result.add(b);
+        }
+        return result;
+    }
+
+    /*
+     * getprop { name } - Displays the system properties with the given name, or
+     * all of them.
+     */
+
+    public Object getprop(CharSequence name) {
+        if (name == null)
+            return System.getProperties();
+        else
+            return System.getProperty(name.toString());
+    }
+
+    /**
+     * launch - start the OSGi Framework
+     */
+
+    public void launch() {
+        throw new IllegalStateException("Already running");
+    }
+
+    /**
+     * shutdown - shutdown the OSGi Framework
+     */
+    public void shutdown() throws BundleException {
+        getContext().getBundle().stop();
+    }
+
+    /**
+     * close - shutdown and exit
+     */
+    public void close(CommandSession session) {
+        session.close();
+    }
+
+    /**
+     * exit - exit immediately (System.exit)
+     */
+
+    public void exit(int exitValue) {
+        exit(exitValue);
+    }
+
+    /**
+     * gc - perform a garbage collection
+     */
+    public long gc() {
+        Runtime.getRuntime().gc();
+        return Runtime.getRuntime().freeMemory();
+    }
+
+    /**
+     * init - uninstall all bundles
+     */
+
+    public void init() throws Exception {
+        Bundle bundles[] = getContext().getBundles();
+        for (Bundle b : bundles)
+            if (b.getBundleId() != 0)
+                b.uninstall();
+    }
+
+    /**
+     * setprop <key>=<value> - set the OSGi property
+     */
+    public void setprop(CommandSession session, String key, String value) {
+        session.put(key, value);
+    }
+
+    /**
+     * install - install and optionally start bundle from the given URL
+     * 
+     * @throws BundleException
+     */
+
+    public Bundle install(URL url) throws BundleException {
+        return getContext().installBundle(url.toExternalForm());
+    }
+
+    /**
+     * uninstall - uninstall the specified bundle(s)
+     * 
+     * @throws BundleException
+     */
+    public void uninstall(Bundle[] bundles) throws BundleException {
+        for (Bundle b : bundles) {
+            b.uninstall();
+        }
+    }
+
+    /**
+     * start - start the specified bundle(s)
+     */
+    public void start(Bundle[] bundles) throws BundleException {
+        for (Bundle b : bundles) {
+            b.start();
+        }
+    }
+
+    /**
+     * stop - stop the specified bundle(s)
+     */
+    public void stop(Bundle[] bundles) throws BundleException {
+        for (Bundle b : bundles) {
+            b.stop();
+        }
+    }
+
+    /**
+     * refresh - refresh the packages of the specified bundles
+     */
+    public void refresh(Bundle[] bundles) throws Exception {
+        if (pka != null)
+            pka.refreshPackages(bundles);
+        else
+            throw new RuntimeException("No PackageAdmin service registered");
+    }
+
+    /**
+     * update - update the specified bundle(s)
+     */
+    public void update(Bundle[] bundles) throws BundleException {
+        for (Bundle b : bundles) {
+            b.update();
+        }
+    }
+
+    /**
+     * status - display installed bundles and registered services
+     */
+    public List<Object> status() throws Exception {
+        List<Object> status = new ArrayList<Object>();
+        status.addAll(Arrays.asList(getContext().getBundles()));
+        status.addAll(Arrays.asList(getContext().getServiceReferences(null,
+                null)));
+        return status;
+    }
+
+    /**
+     * ss - display installed bundles (short status)
+     */
+    public Bundle[] ss() {
+        return getContext().getBundles();
+    }
+
+    /**
+     * services {filter} - display registered service details
+     */
+    public ServiceReference[] services(String filter) throws Exception {
+        return getContext().getServiceReferences(null, filter);
+    }
+
+    /**
+     * packages {<pkgname>|<id>|<location>} - display imported/exported
+     * package details
+     */
+    public ExportedPackage[] packages(Bundle bundle) throws Exception {
+        if (pka != null)
+            return pka.getExportedPackages(bundle);
+        else
+            throw new RuntimeException("No PackageAdmin service registered");
+    }
+
+    public ExportedPackage[] packages(String packageName) throws Exception {
+        if (pka != null)
+            return pka.getExportedPackages(packageName);
+        return null;
+    }
+
+    /**
+     * bundles - display details for all installed bundles
+     */
+    public Bundle[] bundles() {
+        return ss();
+    }
+
+    /**
+     * bundle (<id>|<location>) - display details for the specified bundle(s)
+     */
+
+    /**
+     * headers (<id>|<location>) - print bundle headers
+     */
+
+    @SuppressWarnings("unchecked")
+    public Dictionary headers(Bundle b, String locale) {
+        return b.getHeaders(locale);
+    }
+
+    /**
+     * log (<id>|<location>) - display log entries
+     */
+
+    @SuppressWarnings("unchecked")
+    public Collection<LogEntry> log(Bundle bundle) throws Exception {
+        if (lrs != null)
+            return Collections.list((Enumeration<LogEntry>) lrs.getLog());
+        else
+            throw new RuntimeException("LogReader not available");
+    }
+
+    /**
+     * exec <command> - execute a command in a separate process and wait
+     * 
+     * @throws IOException
+     */
+
+    public int exec(Object[] args, boolean fork) throws IOException {
+        StringBuffer sb = new StringBuffer();
+        String del = "";
+        for (Object arg : args) {
+            sb.append(del);
+            sb.append(arg);
+            del = " ";
+        }
+        Process p = Runtime.getRuntime().exec(sb.toString());
+        if (fork) {
+            int c;
+            while ((c = p.getInputStream().read()) > 0)
+                System.out.print(c);
+        }
+        return p.exitValue();
+    }
+
+    /**
+     * fork <command> - execute a command in a separate process
+     */
+
+    public void fork(Object args[]) throws Exception {
+        exec(args, true);
+    }
+
+    /**
+     * sl {(<id>|<location>)} - display the start level for the specified
+     * bundle, or for the framework if no bundle specified
+     */
+    public int sl(Bundle b) throws Exception {
+        if (sls == null)
+            throw new RuntimeException("No StartLevel service registered");
+        if (b == null)
+            return sls.getStartLevel();
+        else
+            return sls.getBundleStartLevel(b);
+    }
+
+    /**
+     * setfwsl <start level> - set the framework start level
+     */
+    public int setfwsl(int n) throws Exception {
+        if (sls == null)
+            throw new RuntimeException("No StartLevel service registered");
+        int old = sls.getStartLevel();
+        sls.setStartLevel(n);
+        return old;
+    }
+
+    /**
+     * setbsl <start level> (<id>|<location>) - set the start level for the
+     * bundle(s)
+     */
+    public int setbsl(Bundle b, int n) throws Exception {
+        if (sls == null)
+            throw new RuntimeException("No StartLevel service registered");
+        int old = sls.getBundleStartLevel(b);
+        sls.setBundleStartLevel(b, n);
+        return old;
+    }
+
+    /**
+     * setibsl <start level> - set the initial bundle start level
+     */
+    public int setibsl(int n) throws Exception {
+        if (sls == null)
+            throw new RuntimeException("No StartLevel service registered");
+        int old = sls.getInitialBundleStartLevel();
+        sls.setInitialBundleStartLevel(n);
+        return old;
+    }
+
+    public Object convert(Class<?> desiredType, Object in) throws Exception {
+        return null;
+    }
+
+    String getLevel(int index) {
+        switch (index) {
+        case LogService.LOG_DEBUG:
+            return "DEBUG";
+        case LogService.LOG_INFO:
+            return "INFO ";
+        case LogService.LOG_WARNING:
+            return "WARNI";
+        case LogService.LOG_ERROR:
+            return "ERROR";
+        default:
+            return "<" + index + ">";
+        }
+    }
+
+    public CharSequence format(Object target, int level, Converter escape) {
+        if (target instanceof LogEntry) {
+            LogEntry entry = (LogEntry) target;
+            switch (level) {
+            case LINE:
+                Formatter f = new Formatter();
+                f.format("%tT %04d %s %s", entry.getTime(), entry.getBundle()
+                        .getBundleId(), getLevel(entry.getLevel())+"", entry
+                        .getMessage()+"");
+                return f.toString();
+                
+            case PART:
+                Formatter f2 = new Formatter();
+                f2.format("%tT %s", entry.getTime(), entry
+                        .getMessage());
+                return f2.toString();
+            }
+        }
+        return null;
+    }
+    /**
+     * profilelog - Display & flush the profile log messages
+     */
+
+}

Added: felix/trunk/gogo/src/aQute/shell/lang/Support.java
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/src/aQute/shell/lang/Support.java?rev=783826&view=auto
==============================================================================
--- felix/trunk/gogo/src/aQute/shell/lang/Support.java (added)
+++ felix/trunk/gogo/src/aQute/shell/lang/Support.java Thu Jun 11 16:07:20 2009
@@ -0,0 +1,49 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package aQute.shell.lang;
+
+import java.lang.reflect.*;
+import java.util.*;
+
+import org.osgi.service.command.*;
+
+
+
+public class Support implements Converter {
+
+    public Object convert(Class<?> desiredType, final Object in) throws Exception {
+        if ( in instanceof Function  && desiredType.isInterface() && desiredType.getDeclaredMethods().length == 1) {
+            return Proxy.newProxyInstance(desiredType.getClassLoader(), new Class[] {desiredType}, new InvocationHandler() {
+                Function command = ((Function) in);
+
+                public Object invoke(Object proxy, Method method, Object[] args)
+                        throws Throwable {
+                    return command.execute(null,Arrays.asList(args));
+                }
+                
+            });
+        }
+        return null;
+    }
+
+    public CharSequence format(Object target, int level, Converter escape)
+            throws Exception {
+        return null;
+    }
+}

Added: felix/trunk/gogo/src/aQute/shell/osgi/OSGiCommands.java
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/src/aQute/shell/osgi/OSGiCommands.java?rev=783826&view=auto
==============================================================================
--- felix/trunk/gogo/src/aQute/shell/osgi/OSGiCommands.java (added)
+++ felix/trunk/gogo/src/aQute/shell/osgi/OSGiCommands.java Thu Jun 11 16:07:20 2009
@@ -0,0 +1,302 @@
+/*
+ * 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 aQute.shell.osgi;
+
+import java.io.*;
+import java.util.*;
+import java.util.regex.*;
+
+import org.osgi.framework.*;
+import org.osgi.service.command.*;
+
+public class OSGiCommands implements Converter {
+	Bundle	bundle;
+	String	COLUMN	= "%40s %s\n";
+
+	protected OSGiCommands(Bundle bundle) {
+		this.bundle = bundle;
+	}
+
+//	Bundle[] getBundles() {
+//		return getContext().getBundles();
+//	}
+
+	public BundleContext getContext() {
+		if ( bundle.getState() != Bundle.ACTIVE )
+			throw new IllegalStateException("Framework is not started yet");
+		return bundle.getBundleContext();
+	}
+	
+	CharSequence print(Bundle bundle) {
+	    String version = (String) bundle.getHeaders().get("Bundle-Version");
+	    if ( version == null )
+	        version = "0.0.0";
+		return String.format("%06d %s %s-%s", bundle.getBundleId(),
+				getState(bundle), bundle.getSymbolicName(), version);
+	}
+
+	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", ref.getProperty("service.id"), ref
+				.getBundle().getBundleId(), getShortNames((String[]) ref
+				.getProperty("objectclass")), spid);
+		return sb;
+	}
+
+	CharSequence getShortNames(String[] list) {
+		StringBuilder sb = new StringBuilder();
+		String del = "";
+		for (String s : list) {
+			sb.append(del + getShortName(s));
+			del = " | ";
+		}
+		return sb;
+	}
+
+	CharSequence getShortName(String name) {
+		int n = name.lastIndexOf('.');
+		if (n < 0)
+			n = 0;
+		else
+			n++;
+		return name.subSequence(n, name.length());
+	}
+
+	private String getState(Bundle bundle) {
+		switch (bundle.getState()) {
+		case Bundle.ACTIVE:
+			return "ACT";
+
+		case Bundle.INSTALLED:
+			return "INS";
+
+		case Bundle.RESOLVED:
+			return "RES";
+
+		case Bundle.STARTING:
+			return "STA";
+
+		case Bundle.STOPPING:
+			return "STO";
+
+		case Bundle.UNINSTALLED:
+			return "UNI ";
+		}
+		return null;
+	}
+
+	public void grep(String match) throws IOException {
+		Pattern p = Pattern.compile(match);
+		BufferedReader rdr = new BufferedReader(
+				new InputStreamReader(System.in));
+		String s = rdr.readLine();
+		while (s != null) {
+			if (p.matcher(s).find()) {
+				System.out.println(s);
+			}
+			s = rdr.readLine();
+		}
+	}
+
+	public String tac() throws IOException {
+		StringWriter sw = new StringWriter();
+		BufferedReader rdr = new BufferedReader(
+				new InputStreamReader(System.in));
+		String s = rdr.readLine();
+		while (s != null) {
+			sw.write(s);
+			s = rdr.readLine();
+		}
+		return sw.toString();
+	}
+
+	public CharSequence echo(CommandSession session, Object args[]) {
+		StringBuilder sb = new StringBuilder();
+		String del = "";
+		for (Object arg : args) {
+			sb.append(del);
+			if (arg != null) {
+				sb.append(arg);
+				del = " ";
+			}
+		}
+		return sb;
+	}
+
+	public void each(CommandSession session, Collection<Object> list, Function closure) throws Exception {
+		List<Object> args = new ArrayList<Object>();
+		args.add(null);
+		for (Object x : list) {
+			args.set(0, x);
+			Object result = closure.execute(session, args);
+			System.out.println(session.format(result,Converter.INSPECT));
+		}
+	}
+
+	public Bundle bundle(Bundle i) {
+		return i;
+	}
+
+	public String[] ls(CommandSession session, File f) throws Exception{
+		File cwd = (File) session.get("_cwd");
+		if (cwd == null)
+			cwd = new File("").getAbsoluteFile();
+		
+		if (  f == null )
+			f = cwd;
+		else if (!f.isAbsolute())
+			f = new File(cwd, f.getPath());
+
+		if ( f.isDirectory() )
+			return f.list();
+
+		if ( f.isFile() ) {
+			cat(session,f);
+		}
+		
+		return null;
+	}
+
+	public Object cat(CommandSession session, File f ) throws Exception {
+		File cwd = (File) session.get("_cwd");
+		if (cwd == null)
+			cwd = new File("").getAbsoluteFile();
+		
+		if ( !f.isAbsolute() )
+			f = new File(cwd,f.getPath());
+		
+		ByteArrayOutputStream bout = new ByteArrayOutputStream();
+		FileInputStream in = new FileInputStream(f);
+		byte [] buffer = new byte[ (int) (f.length() % 100000) ];
+		int size = in.read(buffer);
+		while ( size > 0 ) {
+			bout.write(buffer,0,size);
+			size = in.read(buffer);
+		}
+		return new String(bout.toByteArray());
+	}
+	public Object convert(Class<?> desiredType, Object in) throws Exception {
+		if (desiredType == Bundle.class)
+			return convertBundle(in);
+        else if (desiredType == ServiceReference.class)
+            return convertServiceReference(in);
+        else if (desiredType == Class.class)
+            return Class.forName(in.toString());
+        else if (desiredType.isAssignableFrom(String.class) && in instanceof InputStream)
+            return read(((InputStream) in));
+
+		return null;
+	}
+
+	private Object convertServiceReference(Object in)
+			throws InvalidSyntaxException {
+		String s = in.toString();
+		if (s.startsWith("(") && s.endsWith(")")) {
+			ServiceReference refs[] = getContext().getServiceReferences(null, String
+					.format("(|(service.id=%s)(service.pid=%s))", in, in));
+			if (refs != null && refs.length > 0)
+				return refs[0];
+		}
+
+		ServiceReference refs[] = getContext().getServiceReferences(null, String
+				.format("(|(service.id=%s)(service.pid=%s))", in, in));
+		if (refs != null && refs.length > 0)
+			return refs[0];
+		return null;
+	}
+
+	private Object convertBundle(Object in) {
+		String s = in.toString();
+		try {
+			long id = Long.parseLong(s);
+			return getContext().getBundle(id);
+		} catch (NumberFormatException nfe) {
+			// Ignore
+		}
+
+		Bundle bundles[] = getContext().getBundles();
+		for (Bundle b : bundles) {
+			if (b.getLocation().equals(s))
+				return b;
+
+			if (b.getSymbolicName().equals(s))
+				return b;
+		}
+
+		return null;
+	}
+
+	public CharSequence format(Object target, int level, Converter converter ) throws IOException {
+	    if ( level == INSPECT && target instanceof InputStream ) {
+	        return read(((InputStream)target));   
+	    }
+		if (level == LINE && target instanceof Bundle)
+			return print((Bundle) target);
+		if (level == LINE && target instanceof ServiceReference)
+			return print((ServiceReference) target);
+		if (level == PART && target instanceof Bundle)
+			return ((Bundle) target).getSymbolicName();
+		if (level == PART && target instanceof ServiceReference)
+			return getShortNames((String[]) ((ServiceReference) target)
+					.getProperty("objectclass"));
+		return null;
+	}	
+
+	public CharSequence read(InputStream in) throws IOException {
+	    int c;
+	    StringBuffer sb = new StringBuffer();
+	    while ( (c=in.read())> 0 ) {
+	        if ( c >=32 && c <= 0x7F || c=='\n' || c=='\r') {
+	            sb.append( (char) c);
+	        } else {
+	            String s = Integer.toHexString(c).toUpperCase();
+	            sb.append("\\");
+	            if ( s.length() < 1)
+	                sb.append(0);
+	            sb.append(s);
+	        }
+	    }
+	    return sb;
+    }
+
+    public void start(Bundle b) throws BundleException {
+		b.start();
+	}
+	
+	public void stop(Bundle b) throws BundleException {
+		b.stop();
+	}
+	
+	public Object service(String clazz, String filter) throws InvalidSyntaxException {
+		ServiceReference ref[] = getContext().getServiceReferences(clazz,filter);
+		if (ref == null )
+			return null;
+		
+		return getContext().getService(ref[0]);
+	}
+	
+}

Added: felix/trunk/gogo/src/aQute/shell/osgi/OSGiShell.java
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/src/aQute/shell/osgi/OSGiShell.java?rev=783826&view=auto
==============================================================================
--- felix/trunk/gogo/src/aQute/shell/osgi/OSGiShell.java (added)
+++ felix/trunk/gogo/src/aQute/shell/osgi/OSGiShell.java Thu Jun 11 16:07:20 2009
@@ -0,0 +1,111 @@
+/*
+ * 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 aQute.shell.osgi;
+
+import org.osgi.framework.*;
+import org.osgi.service.command.*;
+import org.osgi.service.component.*;
+import org.osgi.service.packageadmin.*;
+import org.osgi.service.permissionadmin.*;
+import org.osgi.service.startlevel.*;
+import org.osgi.service.threadio.*;
+
+import aQute.shell.runtime.*;
+
+public class OSGiShell extends CommandShellImpl {
+    Bundle       bundle;
+    OSGiCommands commands;
+
+    protected void activate(ComponentContext context) throws Exception {
+        this.bundle = context.getBundleContext().getBundle();
+        if (threadIO == null)
+            threadIO = (ThreadIO) context.locateService("x");
+        start();
+    }
+
+    public void start() throws Exception {
+        commands = new OSGiCommands(bundle);
+        addCommand("osgi", this.bundle);
+        addCommand("osgi", commands);
+        setConverter(commands);
+        if (bundle.getState() == Bundle.ACTIVE) {
+            addCommand("osgi", commands.service(StartLevel.class.getName(),
+                    null), StartLevel.class);
+            addCommand("osgi", commands.service(PackageAdmin.class.getName(),
+                    null), PackageAdmin.class);
+            addCommand("osgi", commands.service(
+                    PermissionAdmin.class.getName(), null),
+                    PermissionAdmin.class);
+            addCommand("osgi", commands.getContext(), BundleContext.class);
+        }
+    }
+
+    protected void deactivate(ComponentContext context) {
+        System.out.println("Deactivating");
+    }
+
+    public Object get(String name) {
+        if (bundle.getBundleContext() != null) {
+            BundleContext context = bundle.getBundleContext();
+            try {
+                Object cmd = super.get(name);
+                if (cmd != null)
+                    return cmd;
+
+                int n = name.indexOf(':');
+                if (n < 0)
+                    return null;
+
+                String service = name.substring(0, n);
+                String function = name.substring(n + 1);
+
+                String filter = String.format(
+                        "(&(osgi.command.scope=%s)(osgi.command.function=%s))",
+                        service, function);
+                ServiceReference refs[] = context.getServiceReferences(null,
+                        filter);
+                if (refs == null || refs.length == 0)
+                    return null;
+
+                if (refs.length > 1)
+                    throw new IllegalArgumentException(
+                            "Command name is not unambiguous: " + name
+                                    + ", found multiple impls");
+
+                return new ServiceCommand(this, refs[0], function);
+            } catch (InvalidSyntaxException ise) {
+                ise.printStackTrace();
+            }
+        }
+        return super.get(name);
+    }
+
+    public void setThreadio(Object t) {
+        super.setThreadio((ThreadIO) t);
+    }
+
+    public void setBundle(Bundle bundle) {
+        this.bundle = bundle;
+    }
+
+    public void setConverter(Converter c) {
+        super.setConverter(c);
+    }
+
+}

Added: felix/trunk/gogo/src/aQute/shell/osgi/ServiceCommand.java
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/src/aQute/shell/osgi/ServiceCommand.java?rev=783826&view=auto
==============================================================================
--- felix/trunk/gogo/src/aQute/shell/osgi/ServiceCommand.java (added)
+++ felix/trunk/gogo/src/aQute/shell/osgi/ServiceCommand.java Thu Jun 11 16:07:20 2009
@@ -0,0 +1,51 @@
+/*
+ * 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 aQute.shell.osgi;
+
+import java.util.*;
+
+import org.osgi.framework.*;
+import org.osgi.service.command.*;
+
+import aQute.shell.runtime.*;
+
+public class ServiceCommand extends Reflective implements Function {
+	ServiceReference	ref;
+	OSGiShell			shell;
+	String				name;
+	
+	public ServiceCommand(OSGiShell shell, ServiceReference ref, String name) {
+		this.shell =shell;
+		this.ref = ref;
+		this.name = name;
+	}
+
+	public Object execute(CommandSession session, List<Object> arguments) throws Exception {
+		try {
+			Object target = shell.bundle.getBundleContext().getService(ref);
+			Object result = method(session,target, name, arguments);
+			if ( result != CommandShellImpl.NO_SUCH_COMMAND )
+				return result;
+			
+			throw new IllegalArgumentException("Service does not implement promised command " + ref + " " + name );
+		} finally {
+			shell.bundle.getBundleContext().ungetService(ref);
+		}
+	}
+}

Added: felix/trunk/gogo/src/aQute/shell/runtime/Closure.java
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/src/aQute/shell/runtime/Closure.java?rev=783826&view=auto
==============================================================================
--- felix/trunk/gogo/src/aQute/shell/runtime/Closure.java (added)
+++ felix/trunk/gogo/src/aQute/shell/runtime/Closure.java Thu Jun 11 16:07:20 2009
@@ -0,0 +1,233 @@
+/*
+ * 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 aQute.shell.runtime;
+
+import java.util.*;
+
+import org.osgi.service.command.*;
+
+public class Closure extends Reflective implements Function {
+    private static final long serialVersionUID = 1L;
+    final CharSequence        source;
+    final Closure             parent;
+    CommandSessionImpl        session;
+    List<Object>              parms;
+
+    Closure(CommandSessionImpl session, Closure parent, CharSequence source) {
+        this.session = session;
+        this.parent = parent;
+        this.source = source;
+    }
+
+    public Object execute(CommandSession x, List<Object> values)
+            throws Exception {
+        parms = values;
+        Parser parser = new Parser(source);
+        ArrayList<Pipe> pipes = new ArrayList<Pipe>();
+        List<List<List<CharSequence>>> program = parser.program();
+
+        for (List<List<CharSequence>> statements : program) {
+            Pipe current = new Pipe(this, statements);
+
+            if (pipes.isEmpty()) {
+                current.setIn(session.in);
+                current.setOut(session.out);
+            } else {
+                Pipe previous = pipes.get(pipes.size() - 1);
+                previous.connect(current);
+            }
+            pipes.add(current);
+        }
+        if (pipes.size() == 0)
+            return null;
+
+        if (pipes.size() == 1) {
+            pipes.get(0).run();
+        } else {
+            for (Pipe pipe : pipes) {
+                pipe.start();
+            }
+            for (Pipe pipe : pipes) {
+                pipe.join();
+            }
+        }
+
+        Pipe last = pipes.get(pipes.size() - 1);
+        if (last.exception != null)
+            throw last.exception;
+
+        if (last.result instanceof Object[]) {
+            return Arrays.asList((Object[]) last.result);
+        }
+        return last.result;
+    }
+
+    Object executeStatement(List<CharSequence> statement) throws Exception {
+        Object result;
+        List<Object> values = new ArrayList<Object>();
+        Object cmd = eval(statement.remove(0));
+        for (CharSequence token : statement)
+            values.add(eval(token));
+
+        result = execute(cmd, values);
+        return result;
+    }
+
+    private Object execute(Object cmd, List<Object> values) throws Exception {
+        if (cmd == null) {
+            if (values.isEmpty())
+                return null;
+            else
+                throw new IllegalArgumentException(
+                        "Command name evaluates to null");
+        }
+
+        // Now there are the following cases
+        // <string> '=' statement // complex assignment
+        // <string> statement // cmd call
+        // <object> // value of <object>
+        // <object> statement // method call
+
+        if (cmd instanceof CharSequence) {
+            String scmd = cmd.toString();
+
+            if (values.size() > 0 && "=".equals(values.get(0))) {
+                if (values.size() == 0)
+                    return session.variables.remove(scmd);
+                else {
+                    Object value = execute(values.get(1), values.subList(2,
+                            values.size()));
+                    return assignment(scmd, value);
+                }
+            } else {
+                String scopedFunction = scmd;
+                Object x = get(scmd);
+                if ( !(x instanceof Function) ) {
+                    if (scmd.indexOf(':') < 0) {
+                        scopedFunction = "*:" + scmd;
+                    }
+                    x = get(scopedFunction);
+                    if (x == null || !(x instanceof Function)) {
+                        if (values.isEmpty())
+                            return scmd;
+                        throw new IllegalArgumentException("Command not found:  "
+                                + scopedFunction);
+                    } 
+                 }
+                return ((Function) x).execute(session, values);
+            }
+        } else {
+            if (values.isEmpty())
+                return cmd;
+            else
+                return method(session, cmd, values.remove(0).toString(), values);
+        }
+    }
+
+    private Object assignment(Object name, Object value) {
+        session.variables.put(name, value);
+        return value;
+    }
+
+    private Object eval(CharSequence seq) throws Exception {
+        int end = seq.length();
+        switch (seq.charAt(0)) {
+        case '$':
+            return var(seq);
+        case '<':
+            Closure c = new Closure(session, this, seq.subSequence(1, end - 1));
+            return c.execute(session, parms);
+        case '[':
+            return array(seq.subSequence(1, end - 1));
+
+        case '{':
+            return new Closure(session, this, seq.subSequence(1, end - 1));
+
+        default:
+            String result = new Parser(seq).unescape();
+            if ("null".equals(result))
+                return null;
+            if ("true".equalsIgnoreCase(result))
+                return true;
+            if ("false".equalsIgnoreCase(result))
+                return false;
+            return seq;
+        }
+    }
+
+    private Object array(CharSequence array) throws Exception {
+        List<Object> list = new ArrayList<Object>();
+        Map<Object, Object> map = new LinkedHashMap<Object, Object>();
+        Parser p = new Parser(array);
+
+        while (!p.eof()) {
+            CharSequence token = p.value();
+
+            p.ws();
+            if (p.peek() == '=') {
+                p.next();
+                p.ws();
+                if (!p.eof()) {
+                    CharSequence value = p.messy();
+                    map.put(eval(token), eval(value));
+                }
+            } else
+                list.add(eval(token));
+
+            if (p.peek() == ',')
+                p.next();
+            p.ws();
+        }
+        p.ws();
+        if (!p.eof())
+            throw new IllegalArgumentException("Invalid array syntax: " + array);
+
+        if (map.size() != 0 && list.size() != 0)
+            throw new IllegalArgumentException(
+                    "You can not mix maps and arrays: " + array);
+
+        if (map.size() > 0)
+            return map;
+        else
+            return list;
+    }
+
+    private Object var(CharSequence var) throws Exception {
+        String name = eval(var.subSequence(1, var.length())).toString();
+        return get(name);
+    }
+
+    /**
+     * 
+     * @param name
+     * @return
+     */
+    private Object get(String name) {
+        if (parms != null) {
+            if ("it".equals(name))
+                return parms.get(0);
+            if ("args".equals(name))
+                return parms;
+
+            if (name.length() == 1 && Character.isDigit(name.charAt(0)))
+                return parms.get(name.charAt(0) - '0');
+        }
+        return session.get(name);
+    }
+}

Added: felix/trunk/gogo/src/aQute/shell/runtime/Command.java
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/src/aQute/shell/runtime/Command.java?rev=783826&view=auto
==============================================================================
--- felix/trunk/gogo/src/aQute/shell/runtime/Command.java (added)
+++ felix/trunk/gogo/src/aQute/shell/runtime/Command.java Thu Jun 11 16:07:20 2009
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package aQute.shell.runtime;
+
+import java.util.*;
+
+import org.osgi.service.command.*;
+
+public class Command extends Reflective implements Function {
+	Object target;
+	String function;
+
+	public Command(Object target, String function) {
+		this.function = function;
+		this.target = target;
+	}
+
+	public Object execute(CommandSession session, List<Object> arguments) throws Exception {
+		return method(session,target, function, arguments);
+	}
+
+}

Added: felix/trunk/gogo/src/aQute/shell/runtime/CommandSessionImpl.java
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/src/aQute/shell/runtime/CommandSessionImpl.java?rev=783826&view=auto
==============================================================================
--- felix/trunk/gogo/src/aQute/shell/runtime/CommandSessionImpl.java (added)
+++ felix/trunk/gogo/src/aQute/shell/runtime/CommandSessionImpl.java Thu Jun 11 16:07:20 2009
@@ -0,0 +1,215 @@
+/*
+ * 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 aQute.shell.runtime;
+
+import java.io.*;
+import java.lang.reflect.*;
+import java.util.*;
+
+import org.osgi.service.command.*;
+
+public class CommandSessionImpl implements CommandSession, Converter {
+	String						COLUMN			= "%-20s %s\n";
+	InputStream in;
+	PrintStream out;
+	PrintStream err;
+	CommandShellImpl service;
+	Map<Object, Object> variables = new HashMap<Object, Object>();
+
+	CommandSessionImpl(CommandShellImpl service, InputStream in,
+			PrintStream out, PrintStream err) {
+		this.service = service;
+		this.in = in;
+		this.out = out;
+		this.err = err;
+	}
+
+	public void close() {
+	}
+
+	public Object execute(CharSequence commandline) throws Exception {
+		assert service != null;
+		assert service.threadIO != null;
+		
+		Closure impl = new Closure(this, null, commandline);
+		Object result = impl.execute(this, null);
+		return result;
+	}
+
+	public InputStream getKeybord() {
+		return in;
+	}
+
+	public Object get(String name) {
+		if (variables != null && variables.containsKey(name))
+			return variables.get(name);
+
+		return service.get(name);
+	}
+
+	public void put(String name, Object value) {
+		variables.put(name, value);
+	}
+
+	public PrintStream getConsole() {
+		return out;
+	}
+	
+	
+	@SuppressWarnings("unchecked")
+	public
+	CharSequence format(Object target, int level, Converter escape ) throws Exception {
+		if (target == null)
+			return "null";
+
+		if (target instanceof CharSequence )
+			return (CharSequence) target;
+		
+		for (Converter c : service.converters) {
+			CharSequence s = c.format(target, level, this);
+			if (s != null)
+				return s;
+		}
+
+		if (target.getClass().isArray()) {
+			if ( target.getClass().getComponentType().isPrimitive()) {
+				if ( target.getClass().getComponentType() == boolean.class ) 
+					return Arrays.toString((boolean[]) target);
+				else if ( target.getClass().getComponentType() == byte.class ) 
+					return Arrays.toString((byte[]) target);
+				else if ( target.getClass().getComponentType() == short.class ) 
+					return Arrays.toString((short[]) target);
+				else if ( target.getClass().getComponentType() == int.class ) 
+					return Arrays.toString((int[]) target);
+				else if ( target.getClass().getComponentType() == long.class ) 
+					return Arrays.toString((long[]) target);
+				else if ( target.getClass().getComponentType() == float.class ) 
+					return Arrays.toString((float[]) target);
+				else if ( target.getClass().getComponentType() == double.class ) 
+					return Arrays.toString((double[]) target);
+				else if ( target.getClass().getComponentType() == char.class ) 
+					return Arrays.toString((char[]) target);
+			}
+			target = Arrays.asList((Object[]) target);
+		}
+		if (target instanceof Collection) {
+			if (level == Converter.INSPECT) {
+				StringBuilder sb = new StringBuilder();
+				Collection<?> c = (Collection<?>) target;
+				for (Object o : c) {
+					sb.append(format(o, level + 1, this));
+					sb.append("\n");
+				}
+				return sb;
+			} else if (level == Converter.LINE) {
+				StringBuilder sb = new StringBuilder();
+				String del = "[";
+				Collection<?> c = (Collection<?>) target;
+				for (Object o : c) {
+					sb.append(del);
+					sb.append(format(o, level + 1, this));
+					del = ", ";
+				}
+				sb.append("]");
+				return sb;
+			}
+		}
+		if ( target instanceof Dictionary ) {
+			Map<Object,Object> result = new HashMap<Object,Object>();
+			for ( Enumeration e = ((Dictionary)target).keys(); e.hasMoreElements(); ) {
+				Object key = e.nextElement();
+				result.put(key, ((Dictionary)target).get(key));
+			}
+			target = result;
+		}
+		if (target instanceof Map) {
+			if (level == Converter.INSPECT) {
+				StringBuilder sb = new StringBuilder();
+				Map<?,?> c = (Map<?,?>) target;
+				for (Map.Entry<?,?> entry : c.entrySet()) {
+					CharSequence key = format(entry.getKey(), level + 1, this);
+					sb.append(key);
+					for ( int i=key.length(); i<20; i++ )
+						sb.append(' ');
+					sb.append(format(entry.getValue(), level + 1, this));
+					sb.append("\n");
+				}
+				return sb;
+			} else if (level == Converter.LINE) {
+				StringBuilder sb = new StringBuilder();
+				String del = "[";
+				Map<?,?> c = (Map<?,?>) target;
+				for (Map.Entry<?,?> entry : c.entrySet()) {
+					sb.append(del);
+					sb.append(format(entry, level + 1,this));
+					del = ", ";
+				}
+				sb.append("]");
+				return sb;
+			}
+		}
+		if (level == Converter.INSPECT)
+			return inspect(target);
+		else
+			return target.toString();
+	}
+
+	CharSequence inspect(Object b) {
+		boolean found = false;
+		Formatter f = new Formatter();
+		Method methods[] = b.getClass().getMethods();
+		for (Method m : methods) {
+			try {
+				String name = m.getName();
+				if (m.getName().startsWith("get")
+						&& !m.getName().equals("getClass")
+						&& m.getParameterTypes().length == 0
+						&& Modifier.isPublic(m.getModifiers())) {
+					found = true;
+					name = name.substring(3);
+					m.setAccessible(true);
+					Object value = m.invoke(b, (Object[]) null);
+					f.format(COLUMN, name, format(value, Converter.LINE, this));
+				}
+			} catch (IllegalAccessException e) {
+				// Ignore
+			} catch (Exception e) {
+				e.printStackTrace();
+			}
+		}
+		if (found)
+			return (StringBuilder) f.out();
+		else
+			return b.toString();
+	}
+
+
+	public Object convert(Class<?> desiredType, Object in)  {
+		return service.convert(desiredType, in);
+	}
+
+	public CharSequence format(Object result, int inspect) {
+	    try {
+		return format(result,inspect,this);
+	    } catch(Exception e ) {
+	        return "<can not format " + result + ":" + e;
+	    }
+	}
+
+}

Added: felix/trunk/gogo/src/aQute/shell/runtime/CommandShellImpl.java
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/src/aQute/shell/runtime/CommandShellImpl.java?rev=783826&view=auto
==============================================================================
--- felix/trunk/gogo/src/aQute/shell/runtime/CommandShellImpl.java (added)
+++ felix/trunk/gogo/src/aQute/shell/runtime/CommandShellImpl.java Thu Jun 11 16:07:20 2009
@@ -0,0 +1,140 @@
+/*
+ * 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 aQute.shell.runtime;
+
+import java.io.*;
+import java.lang.reflect.*;
+import java.util.*;
+
+import org.osgi.service.command.*;
+import org.osgi.service.threadio.*;
+
+public class CommandShellImpl implements CommandProcessor {
+    Set<Converter>             converters      = new HashSet<Converter>();
+    protected ThreadIO         threadIO;
+    public final static Object NO_SUCH_COMMAND = new Object();
+    Map<String, Object>        commands        = new LinkedHashMap<String, Object>();
+
+    public CommandShellImpl() {
+        addCommand("shell", this, "addCommand" );
+    }
+
+    public CommandSession createSession(InputStream in, PrintStream out,
+            PrintStream err) {
+
+        return new CommandSessionImpl(this, in, out, err);
+    }
+
+    public void setThreadio(ThreadIO threadIO) {
+        this.threadIO = threadIO;
+    }
+
+    public void setConverter(Converter c) {
+        converters.add(c);
+    }
+
+    public void unsetConverter(Converter c) {
+        converters.remove(c);
+    }
+
+    public Object get(String name) {
+        name = name.toLowerCase();
+        int n = name.indexOf(':');
+        if (n < 0)
+            return null;
+
+        String function = name.substring(n);
+
+        Object cmd = null;
+
+        if (commands.containsKey(name)) {
+            cmd = commands.get(name);
+        } else {
+            String scope = name.substring(0, n);
+            if (scope.equals("*")) {
+                for (Map.Entry<String, Object> entry : commands.entrySet()) {
+                    if (entry.getKey().endsWith(function)) {
+                        cmd = entry.getValue();
+                        break;
+                    }
+                }
+            }
+        }
+        if (cmd == null)
+            return null;
+
+        if (cmd instanceof Function)
+            return cmd;
+        else
+            return new Command(cmd, function.substring(1));
+    }
+
+    public void addCommand(String scope, Object target) {
+        addCommand(scope,target,target.getClass());
+    }
+
+    public void addCommand(String scope, Object target, Class<?> functions) {
+        if (target == null)
+            return;
+
+        String[] names = getFunctions(functions);
+        for (String function : names) {
+            addCommand(scope, target, function);
+        }
+    }
+
+    public void addCommand(String scope, Object target, String function) {
+        commands.put((scope + ":" + function).toLowerCase(), target);
+    }
+
+    public String[] getFunctions(Class<?> target) {
+        String[] functions;
+        Set<String> list = new TreeSet<String>();
+        Method methods[] = target.getMethods();
+        for (Method m : methods) {
+            list.add(m.getName());
+            if (m.getName().startsWith("get")) {
+                String s = m.getName().substring(3);
+                if (s.length() > 0)
+                    list.add(s.substring(0, 1).toLowerCase() + s.substring(1));
+            }
+        }
+        functions = list.toArray(new String[list.size()]);
+        return functions;
+    }
+
+    protected void put(String name, Object target) {
+        commands.put(name, target);
+    }
+
+    public Object convert(Class<?> desiredType, Object in) {
+        for ( Converter c : converters ) {
+            try {
+            Object converted = c.convert(desiredType, in);
+            if ( converted != null)
+                return converted;
+            } catch( Exception e ) {
+                e.printStackTrace();
+            }
+        }
+        return null;
+    }
+
+}

Added: felix/trunk/gogo/src/aQute/shell/runtime/Parser.java
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/src/aQute/shell/runtime/Parser.java?rev=783826&view=auto
==============================================================================
--- felix/trunk/gogo/src/aQute/shell/runtime/Parser.java (added)
+++ felix/trunk/gogo/src/aQute/shell/runtime/Parser.java Thu Jun 11 16:07:20 2009
@@ -0,0 +1,280 @@
+/*
+ * 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 aQute.shell.runtime;
+
+import java.util.*;
+
+public class Parser {
+	int					current	= 0;
+	CharSequence		text;
+	boolean				escaped;
+	static final String	SPECIAL	= "<;|{[\"'$'`(=";
+
+	public Parser(CharSequence program) {
+		text = program;
+	}
+
+	void ws() {
+		while (!eof() && Character.isWhitespace(peek())) {
+			current++;
+			if (peek() == '/' && current < text.length()-2 && text.charAt(current + 1) == '/') {
+				comment();
+			}
+		}
+	}
+
+	private void comment() {
+		while (!eof() && peek() != '\n' && peek() != '\r')
+			next();
+	}
+
+	boolean eof() {
+		return current >= text.length();
+	}
+
+	char peek() {
+		escaped = false;
+		if (eof())
+			return 0;
+
+		char c = text.charAt(current);
+
+		if (c == '\\') {
+			escaped = true;
+			c = text.charAt(++current);
+
+			switch (c) {
+			case 't':
+				c = '\t';
+				break;
+			case '\r':
+			case '\n':
+				c = ' ';
+				break;
+			case 'b':
+				c = '\b';
+				break;
+			case 'f':
+				c = '\f';
+				break;
+			case 'n':
+				c = '\n';
+				break;
+			case 'r':
+				c = '\r';
+				break;
+			case 'u':
+				c = unicode();
+				break;
+			default:
+				// We just take the next character literally
+				// but have the escaped flag set, important for {},[] etc
+			}
+		}
+		return c;
+	}
+
+	public List<List<List<CharSequence>>> program() {
+		List<List<List<CharSequence>>> program = new ArrayList<List<List<CharSequence>>>();
+		ws();
+		if (!eof()) {
+			program.add(statements());
+			while (peek() == '|') {
+				current++;
+				program.add(statements());
+			}
+		}
+		if (!eof())
+			throw new RuntimeException("Program has trailing text: "
+					+ context(current));
+
+		return program;
+	}
+
+	CharSequence context(int around) {
+		return text.subSequence(Math.max(0, current - 20), Math.min(text
+				.length(), current + 4));
+	}
+
+	public List<List<CharSequence>> statements() {
+		List<List<CharSequence>> statements = new ArrayList<List<CharSequence>>();
+		statements.add(statement());
+		while (peek() == ';') {
+			current++;
+			statements.add(statement());
+		}
+		return statements;
+	}
+
+	public List<CharSequence> statement() {
+		List<CharSequence> statement = new ArrayList<CharSequence>();
+		statement.add(value());
+		while (!eof()) {
+			ws();
+			if (peek() == '|' || peek() == ';')
+				break;
+
+			if (!eof())
+				statement.add(messy());
+		}
+		return statement;
+	}
+
+	public CharSequence messy() {
+		char c = peek();
+		if (c > 0 && SPECIAL.indexOf(c)< 0) {
+			int start = current++;
+			while (!eof()) {
+				c = peek();
+				if (c == ';' || c == '|' || Character.isWhitespace(c))
+					break;
+				next();
+			}
+
+			return text.subSequence(start, current);
+		} else
+			return value();
+	}
+
+	CharSequence value() {
+		ws();
+
+		int start = current;
+		char c = next();
+		switch (c) {
+		case '{':
+			return text.subSequence(start, find('}', '{'));
+		case '(':
+			return text.subSequence(start, find(')', '('));
+		case '[':
+			return text.subSequence(start, find(']', '['));
+		case '"':
+			return text.subSequence(start + 1, quote('"'));
+		case '\'':
+			return text.subSequence(start + 1, quote('\''));
+		case '<':
+			return text.subSequence(start, find('>', '<'));
+		case '$':
+			value();
+			return text.subSequence(start, current);
+		}
+
+		if (Character.isJavaIdentifierPart(c)) {
+			// Some identifier or number
+			while (!eof()) {
+				c = peek();
+				if (c!=':' && !Character.isJavaIdentifierPart(c) && c != '.')
+					break;
+				next();
+			}
+		} else {
+			// Operator, repeat while in operator class
+			while (!eof()) {
+				c = peek();
+				if (Character.isWhitespace(c)
+						|| Character.isJavaIdentifierPart(c))
+					break;
+			}
+		}
+		return text.subSequence(start, current);
+	}
+
+	char next() {
+		char c = peek();
+		current++;
+		return c;
+	}
+
+	char unicode() {
+		if (current + 4 > text.length())
+			throw new IllegalArgumentException(
+					"Unicode \\u escape at eof at pos ..." + context(current)
+							+ "...");
+
+		String s = text.subSequence(current, current + 4).toString();
+		int n = Integer.parseInt(s, 16);
+		return (char) n;
+	}
+
+	private int find(char target, char deeper) {
+		int start = current;
+		int level = 1;
+
+		while (level != 0) {
+			if (eof())
+				throw new RuntimeException(
+						"Eof found in the middle of a compound for '" + target
+								+ deeper + "', begins at " + context(start));
+
+			char c = next();
+			if (!escaped) {
+				if (c == target)
+					level--;
+				else if (c == deeper)
+					level++;
+				else if (c == '"')
+					quote('"');
+				else if (c == '\'')
+					quote('\'');
+				else if (c == '`')
+					quote('`');
+			}
+		}
+		return current;
+	}
+
+	int quote(char which) {
+		while (!eof() && (peek() != which || escaped))
+			next();
+
+		return current++;
+	}
+
+	CharSequence findVar() {
+		int start = current - 1;
+		char c = peek();
+
+		if (c == '{') {
+			next();
+			int end = find('}', '{');
+			return text.subSequence(start, end);
+		}
+
+		if (Character.isJavaIdentifierStart(c)) {
+			while (!eof() && Character.isJavaIdentifierPart(c) || c == '.') {
+				next();
+			}
+			return text.subSequence(start, current);
+		}
+		throw new IllegalArgumentException(
+				"Reference to variable does not match syntax of a variable: "
+						+ context(start));
+	}
+
+	public String toString() {
+		return "..." + context(current) + "...";
+	}
+
+	public String unescape() {
+		StringBuilder sb = new StringBuilder();
+		while (!eof())
+			sb.append(next());
+		return sb.toString();
+	}
+}

Added: felix/trunk/gogo/src/aQute/shell/runtime/Pipe.java
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/src/aQute/shell/runtime/Pipe.java?rev=783826&view=auto
==============================================================================
--- felix/trunk/gogo/src/aQute/shell/runtime/Pipe.java (added)
+++ felix/trunk/gogo/src/aQute/shell/runtime/Pipe.java Thu Jun 11 16:07:20 2009
@@ -0,0 +1,82 @@
+/*
+ * 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 aQute.shell.runtime;
+
+import java.io.*;
+import java.util.*;
+
+import org.osgi.service.command.*;
+
+public class Pipe extends Thread {
+	InputStream in;
+	PrintStream out;
+	PipedOutputStream pout;
+	Closure closure;
+	Exception exception;
+	Object result;
+	List<List<CharSequence>> statements;
+
+	public Pipe(Closure closure, List<List<CharSequence>> statements) {
+		super("pipe-" + statements);
+		this.closure = closure;
+		this.statements = statements;
+	}
+
+	public void setIn(InputStream in) {
+		this.in = in;
+	}
+
+	public void setOut(PrintStream out) {
+		this.out = out;
+	}
+
+	public Pipe connect(Pipe next) throws IOException {
+		next.setOut(out);
+		pout = new PipedOutputStream();
+		next.setIn(new PipedInputStream(pout));
+		out = new PrintStream(pout);
+		return next;
+
+	}
+
+	public void run() {
+		closure.session.service.threadIO.setStreams(in, out, System.err);
+		try {
+			for (List<CharSequence> statement : statements) {
+				result = closure.executeStatement(statement);
+				if ( result != null && pout != null )
+					out.println(closure.session.format(result, Converter.INSPECT));
+			}
+		} catch (Exception e) {
+			exception = e;
+		} finally {
+			out.flush();
+			closure.session.service.threadIO.close();
+			try {
+				if ( in instanceof PipedInputStream )
+					in.close();
+				if (pout!=null)
+					pout.close();
+			} catch (IOException e) {
+				e.printStackTrace();
+			}
+		}
+	}
+}

Added: felix/trunk/gogo/src/aQute/shell/runtime/Reflective.java
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/src/aQute/shell/runtime/Reflective.java?rev=783826&view=auto
==============================================================================
--- felix/trunk/gogo/src/aQute/shell/runtime/Reflective.java (added)
+++ felix/trunk/gogo/src/aQute/shell/runtime/Reflective.java Thu Jun 11 16:07:20 2009
@@ -0,0 +1,207 @@
+/*
+ * 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 aQute.shell.runtime;
+
+import java.lang.reflect.*;
+import java.util.*;
+
+import org.osgi.service.command.*;
+
+public class Reflective {
+    public final static Object      NO_MATCH = new Object();
+    public final static Set<String> KEYWORDS = new HashSet<String>(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" }));
+
+    public Object method(CommandSession session, Object target, String name,
+            List<Object> args) throws IllegalArgumentException,
+            IllegalAccessException, InvocationTargetException, Exception {
+        Method[] methods = target.getClass().getMethods();
+        name = name.toLowerCase();
+
+        String get = "get" + name;
+        String is = "is" + name;
+        String set = "set" + name;
+
+        if (KEYWORDS.contains(name))
+            name = "_" + name;
+
+        Method bestMethod = null;
+        Object[] bestArgs = null;
+        int match = -1;
+        for (Method m : methods) {
+            String mname = m.getName().toLowerCase();
+            if (mname.equals(name) || mname.equals(get) || mname.equals(set)
+                    || mname.equals(is)) {
+                Class<?>[] types = m.getParameterTypes();
+
+                // Check if the command takes a session
+                if (types.length > 0
+                        && CommandSession.class.isAssignableFrom(types[0])) {
+                    args.add(0, session);
+                }
+
+                Object[] parms = new Object[types.length];
+                // if (types.length >= args.size() ) {
+                int local = coerce(session, target, types, parms, args);
+                if (local == types.length || local > match) {
+                    bestMethod = m;
+                    bestArgs = parms;
+                    match = local;
+                }
+                // }
+                // if (match == -1 && types.length == 1
+                // && types[0] == Object[].class) {
+                // bestMethod = m;
+                // Object value = args.toArray();
+                // bestArgs = new Object[] { value };
+                // }
+            }
+        }
+
+        if (bestMethod != null) {
+            bestMethod.setAccessible(true);
+            return bestMethod.invoke(target, bestArgs);
+        } else
+            throw new IllegalArgumentException("Cannot find command:" + name
+                    + " with args:" + args);
+    }
+
+    /**
+     * Complex routein to convert the arguments given from the command line to
+     * the arguments of the method call. First, an attempt is made to convert
+     * each argument. If this fails, a check is made to see if varargs can be
+     * applied. This happens when the last method argument is an array.
+     * 
+     * @param session
+     * @param target
+     * @param types
+     * @param out
+     * @param in
+     * @return
+     * @throws Exception
+     */
+    private int coerce(CommandSession session, Object target, Class<?> types[],
+            Object out[], List<Object> in) throws Exception {
+        int i = 0;
+        while (i < out.length) {
+            out[i] = null;
+            try {
+                // Try to convert one argument
+                out[i] = coerce(session, target, types[i], in.get(i));
+                if (out[i] == NO_MATCH) {
+                    // Failed
+                    // No match, check for varargs
+                    if (types[i].isArray() && i == types.length - 1) {
+                        // Try to parse the remaining arguments in an array
+                        Class<?> component = types[i].getComponentType();
+                        Object components = Array.newInstance(component, in
+                                .size()
+                                - i);
+                        int n = i;
+                        while (i < in.size()) {
+                            Object t = coerce(session, target, component, in
+                                    .get(i));
+                            if (t == NO_MATCH)
+                                return -1;
+                            Array.set(components, i - n, t);
+                            i++;
+                        }
+                        out[n] = components;
+                        // Is last element, so we will quite hereafter
+                        return n;
+                    }
+                    return -1;
+                }
+                i++;
+            } catch (Exception e) {
+                // e.printStackTrace();
+                System.err.println(e);
+                // should get rid of those exceptions, but requires
+                // reg ex matching to see if it throws an exception.
+                // dont know what is better
+                return -1;
+            }
+        }
+        return i;
+    }
+
+    Object coerce(CommandSession session, Object target, Class<?> type,
+            Object arg) throws Exception {
+        if (arg == null)
+            return null;
+
+        if (type.isAssignableFrom(arg.getClass()))
+            return arg;
+
+        Object converted = session.convert(type, arg);
+        if (converted != null)
+            return converted;
+
+        String string = arg.toString();
+        if (type.isAssignableFrom(String.class))
+            return string;
+
+        if (type.isArray()) {
+            // Must handle array types
+            return NO_MATCH;
+        } else if (!type.isPrimitive()) {
+            try {
+                return type.getConstructor(String.class).newInstance(string);
+            } catch (Exception e) {
+                return NO_MATCH;
+            }
+        }
+        if (type == boolean.class)
+            return new Boolean(string);
+        else if (type == byte.class)
+            return new Byte(string);
+        else if (type == char.class) {
+            if (string.length() == 1)
+                return string.charAt(0);
+        } else if (type == short.class)
+            return new Short(string);
+        else if (type == int.class)
+            return new Integer(string);
+        else if (type == float.class)
+            return new Float(string);
+        else if (type == double.class)
+            return new Double(string);
+        else if (type == long.class)
+            return new Long(string);
+
+        return NO_MATCH;
+    }
+
+    public static boolean hasCommand(Object target, String function) {
+        Method[] methods = target.getClass().getMethods();
+        for (Method m : methods) {
+            if (m.getName().equals(function))
+                return true;
+        }
+        return false;
+    }
+}



Mime
View raw message