You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@felix.apache.org by gn...@apache.org on 2009/06/23 00:27:14 UTC
svn commit: r787428 [2/3] - in /felix/trunk/gogo: ./
src/main/java/org/apache/felix/gogo/cpeg/
src/main/java/org/apache/felix/gogo/launcher/
src/main/java/org/apache/felix/gogo/shell/console/
src/main/java/org/apache/felix/gogo/shell/equinox/ src/main/...
Modified: felix/trunk/gogo/src/main/java/org/apache/felix/gogo/shell/runtime/CommandSessionImpl.java
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/src/main/java/org/apache/felix/gogo/shell/runtime/CommandSessionImpl.java?rev=787428&r1=787427&r2=787428&view=diff
==============================================================================
--- felix/trunk/gogo/src/main/java/org/apache/felix/gogo/shell/runtime/CommandSessionImpl.java (original)
+++ felix/trunk/gogo/src/main/java/org/apache/felix/gogo/shell/runtime/CommandSessionImpl.java Mon Jun 22 22:27:13 2009
@@ -21,13 +21,17 @@
// DWB10: add SCOPE support: https://www.osgi.org/bugzilla/show_bug.cgi?id=51
package org.apache.felix.gogo.shell.runtime;
-import java.io.*;
-import java.lang.reflect.*;
-import java.util.*;
+import org.osgi.service.command.CommandSession;
+import org.osgi.service.command.Converter;
-import org.osgi.service.command.*;
+import java.io.InputStream;
+import java.io.PrintStream;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.*;
-public class CommandSessionImpl implements CommandSession, Converter {
+public class CommandSessionImpl implements CommandSession, Converter
+{
String COLUMN = "%-20s %s\n";
InputStream in;
PrintStream out;
@@ -36,199 +40,302 @@
Map<Object, Object> variables = new HashMap<Object, Object>();
private boolean closed; // derek
- CommandSessionImpl(CommandShellImpl service, InputStream in, PrintStream out, PrintStream err) {
+ 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 void close()
+ {
this.closed = true; // derek
}
- public Object execute(CharSequence commandline) throws Exception {
+ public Object execute(CharSequence commandline) throws Exception
+ {
assert service != null;
assert service.threadIO != null;
-
+
if (closed)
+ {
throw new IllegalStateException("session is closed"); // derek
+ }
Closure impl = new Closure(this, null, commandline);
Object result = impl.execute(this, null);
return result;
}
- public InputStream getKeyboard() {
+ public InputStream getKeyboard()
+ {
return in;
}
- public Object get(String name) {
+ public Object get(String name)
+ {
// XXX: derek.baum@paremus.com
// there is no API to list all variables, so overload name == null
if (name == null)
+ {
return variables.keySet();
+ }
if (variables != null && variables.containsKey(name))
+ {
return variables.get(name);
+ }
// XXX: derek: add SCOPE support
- if (name.startsWith("*:")) {
- String path = variables.containsKey("SCOPE") ? variables.get("SCOPE").toString()
- : "osgi:*";
+ if (name.startsWith("*:"))
+ {
+ String path = variables.containsKey("SCOPE") ? variables.get("SCOPE").toString() : "osgi:*";
String func = name.substring(2);
- for (String scope : path.split(":")) {
+ for (String scope : path.split(":"))
+ {
Object result = service.get(scope + ":" + func);
if (result != null)
+ {
return result;
+ }
}
return null;
}
return service.get(name);
}
- public void put(String name, Object value) {
+ public void put(String name, Object value)
+ {
variables.put(name, value);
}
- public PrintStream getConsole() {
+ public PrintStream getConsole()
+ {
return out;
}
@SuppressWarnings("unchecked")
- public CharSequence format(Object target, int level, Converter escape) throws Exception {
+ 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) {
+ 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().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);
+ }
+ 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) {
+ if (target instanceof Collection)
+ {
+ if (level == Converter.INSPECT)
+ {
StringBuilder sb = new StringBuilder();
Collection<?> c = (Collection<?>) target;
- for (Object o : c) {
+ 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 = ", ";
+ 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;
}
- sb.append("]");
- return sb;
}
}
- if (target instanceof Dictionary) {
+ if (target instanceof Dictionary)
+ {
Map<Object, Object> result = new HashMap<Object, Object>();
- for (Enumeration e = ((Dictionary) target).keys(); e.hasMoreElements();) {
+ 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) {
+ if (target instanceof Map)
+ {
+ if (level == Converter.INSPECT)
+ {
StringBuilder sb = new StringBuilder();
Map<?, ?> c = (Map<?, ?>) target;
- for (Map.Entry<?, ?> entry : c.entrySet()) {
+ 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 = ", ";
+ 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;
}
- sb.append("]");
- return sb;
}
}
if (level == Converter.INSPECT)
+ {
return inspect(target);
+ }
else
+ {
return target.toString();
+ }
}
- CharSequence inspect(Object b) {
+ CharSequence inspect(Object b)
+ {
boolean found = false;
Formatter f = new Formatter();
Method methods[] = b.getClass().getMethods();
- for (Method m : methods) {
- try {
+ 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())) {
+ 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) {
+ }
+ catch (IllegalAccessException e)
+ {
// Ignore
- } catch (Exception e) {
+ }
+ catch (Exception e)
+ {
e.printStackTrace();
}
}
if (found)
+ {
return (StringBuilder) f.out();
+ }
else
+ {
return b.toString();
+ }
}
- public Object convert(Class<?> desiredType, Object in) {
+ public Object convert(Class<?> desiredType, Object in)
+ {
return service.convert(desiredType, in);
}
- public CharSequence format(Object result, int inspect) {
- try {
+ public CharSequence format(Object result, int inspect)
+ {
+ try
+ {
return format(result, inspect, this);
- } catch (Exception e) {
+ }
+ catch (Exception e)
+ {
return "<can not format " + result + ":" + e;
}
}
Modified: felix/trunk/gogo/src/main/java/org/apache/felix/gogo/shell/runtime/CommandShellImpl.java
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/src/main/java/org/apache/felix/gogo/shell/runtime/CommandShellImpl.java?rev=787428&r1=787427&r2=787428&view=diff
==============================================================================
--- felix/trunk/gogo/src/main/java/org/apache/felix/gogo/shell/runtime/CommandShellImpl.java (original)
+++ felix/trunk/gogo/src/main/java/org/apache/felix/gogo/shell/runtime/CommandShellImpl.java Mon Jun 22 22:27:13 2009
@@ -21,145 +21,196 @@
// DWB13: addCommand() fails to add static methods (if target is Class)
package org.apache.felix.gogo.shell.runtime;
-import java.io.*;
-import java.lang.reflect.*;
+import org.osgi.service.command.CommandProcessor;
+import org.osgi.service.command.CommandSession;
+import org.osgi.service.command.Converter;
+import org.osgi.service.command.Function;
+import org.osgi.service.threadio.ThreadIO;
+
+import java.io.InputStream;
+import java.io.PrintStream;
+import java.lang.reflect.Method;
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 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>();
+ Map<String, Object> commands = new LinkedHashMap<String, Object>();
+
+ public CommandShellImpl()
+ {
+ addCommand("shell", this, "addCommand");
+ addCommand("shell", this, "removeCommand"); // derek
+ }
- public CommandShellImpl() {
- addCommand("shell", this, "addCommand" );
- addCommand("shell", this, "removeCommand" ); // derek
- }
-
- public CommandSession createSession(InputStream in, PrintStream out,
- PrintStream err) {
+ public CommandSession createSession(InputStream in, PrintStream out, PrintStream err)
+ {
return new CommandSessionImpl(this, in, out, err);
}
- public void setThreadio(ThreadIO threadIO) {
+ public void setThreadio(ThreadIO threadIO)
+ {
this.threadIO = threadIO;
}
- public void setConverter(Converter c) {
+ public void setConverter(Converter c)
+ {
converters.add(c);
}
- public void unsetConverter(Converter c) {
+ public void unsetConverter(Converter c)
+ {
converters.remove(c);
}
- public Object get(String name) {
+ 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)) {
+ if (commands.containsKey(name))
+ {
cmd = commands.get(name);
- } else {
+ }
+ else
+ {
String scope = name.substring(0, n);
- if (scope.equals("*")) {
- for (Map.Entry<String, Object> entry : commands.entrySet()) {
- if (entry.getKey().endsWith(function)) {
+ if (scope.equals("*"))
+ {
+ for (Map.Entry<String, Object> entry : commands.entrySet())
+ {
+ if (entry.getKey().endsWith(function))
+ {
cmd = entry.getValue();
break;
}
}
}
-
+
// XXX: derek.baum@paremus.com
// there is no API to list commands
// so override otherwise illegal name ":"
- if (cmd == null && name.equals(":")) {
+ if (cmd == null && name.equals(":"))
+ {
return Collections.unmodifiableSet(commands.keySet());
}
}
-
+
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) {
+ public void addCommand(String scope, Object target)
+ {
// derek - fix target class
Class<?> tc = (target instanceof Class) ? (Class<?>) target : target.getClass();
addCommand(scope, target, tc);
}
- public void addCommand(String scope, Object target, Class<?> functions) {
+ public void addCommand(String scope, Object target, Class<?> functions)
+ {
if (target == null)
+ {
return;
+ }
String[] names = getFunctions(functions);
- for (String function : names) {
+ for (String function : names)
+ {
addCommand(scope, target, function);
}
}
- public void addCommand(String scope, Object target, String function) {
+ public void addCommand(String scope, Object target, String function)
+ {
commands.put((scope + ":" + function).toLowerCase(), target);
}
-
+
// derek.baum@paremus.com: need removeCommand, so stopped bundles can clean up.
- public void removeCommand(String scope, String function) {
+ public void removeCommand(String scope, String function)
+ {
String func = (scope + ":" + function).toLowerCase();
commands.remove(func);
}
-
- public void removeCommand(Object target) {
- for (Iterator<Object> i = commands.values().iterator(); i.hasNext();) {
+
+ public void removeCommand(Object target)
+ {
+ for (Iterator<Object> i = commands.values().iterator(); i.hasNext();)
+ {
if (i.next() == target)
+ {
i.remove();
+ }
}
}
- private String[] getFunctions(Class<?> target) {
+ private String[] getFunctions(Class<?> target)
+ {
String[] functions;
Set<String> list = new TreeSet<String>();
Method methods[] = target.getMethods();
- for (Method m : methods) {
+ for (Method m : methods)
+ {
if (m.getDeclaringClass().equals(Object.class)) // derek
+ {
continue;
+ }
list.add(m.getName());
- if (m.getName().startsWith("get")) {
+ 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) {
+ 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 ) {
+ 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();
}
}
Modified: felix/trunk/gogo/src/main/java/org/apache/felix/gogo/shell/runtime/Parser.java
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/src/main/java/org/apache/felix/gogo/shell/runtime/Parser.java?rev=787428&r1=787427&r2=787428&view=diff
==============================================================================
--- felix/trunk/gogo/src/main/java/org/apache/felix/gogo/shell/runtime/Parser.java (original)
+++ felix/trunk/gogo/src/main/java/org/apache/felix/gogo/shell/runtime/Parser.java Mon Jun 22 22:27:13 2009
@@ -20,276 +20,365 @@
// DWB15: allow program to have trailing ';'
package org.apache.felix.gogo.shell.runtime;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.List;
-public class Parser {
- int current = 0;
- CharSequence text;
- boolean escaped;
- static final String SPECIAL = "<;|{[\"'$'`(=";
-
- public Parser(CharSequence program) {
- text = program;
- }
-
- void ws() {
- // derek: BUGFIX: loop if comment at beginning of input
- //while (!eof() && Character.isWhitespace(peek())) {
- while (!eof() && (Character.isWhitespace(peek()) || current == 0)) {
- if (current != 0 || Character.isWhitespace(peek()))
- current++;
- if (peek() == '/' && current < text.length()-2 && text.charAt(current + 1) == '/') {
- comment();
- }
- if (current == 0)
- break;
- }
- }
-
- 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;
- ++current;
- if (eof())
- throw new RuntimeException("Eof found after \\"); // derek
-
- 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++;
- // derek: BUGFIX: allow trailing ;
- ws();
- if (!eof())
- 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();
- }
+public class Parser
+{
+ int current = 0;
+ CharSequence text;
+ boolean escaped;
+ static final String SPECIAL = "<;|{[\"'$'`(=";
+
+ public Parser(CharSequence program)
+ {
+ text = program;
+ }
+
+ void ws()
+ {
+ // derek: BUGFIX: loop if comment at beginning of input
+ //while (!eof() && Character.isWhitespace(peek())) {
+ while (!eof() && (Character.isWhitespace(peek()) || current == 0))
+ {
+ if (current != 0 || Character.isWhitespace(peek()))
+ {
+ current++;
+ }
+ if (peek() == '/' && current < text.length() - 2 && text.charAt(current + 1) == '/')
+ {
+ comment();
+ }
+ if (current == 0)
+ {
+ break;
+ }
+ }
+ }
+
+ 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;
+ ++current;
+ if (eof())
+ {
+ throw new RuntimeException("Eof found after \\"); // derek
+ }
+
+ 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++;
+ // derek: BUGFIX: allow trailing ;
+ ws();
+ if (!eof())
+ {
+ 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();
+ }
}
Modified: felix/trunk/gogo/src/main/java/org/apache/felix/gogo/shell/runtime/Pipe.java
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/src/main/java/org/apache/felix/gogo/shell/runtime/Pipe.java?rev=787428&r1=787427&r2=787428&view=diff
==============================================================================
--- felix/trunk/gogo/src/main/java/org/apache/felix/gogo/shell/runtime/Pipe.java (original)
+++ felix/trunk/gogo/src/main/java/org/apache/felix/gogo/shell/runtime/Pipe.java Mon Jun 22 22:27:13 2009
@@ -19,70 +19,92 @@
// DWB16: redirect System.err when creating pipe
package org.apache.felix.gogo.shell.runtime;
-import java.io.*;
-import java.util.*;
+import org.osgi.service.command.Converter;
-import org.osgi.service.command.*;
+import java.io.*;
+import java.util.List;
-public class Pipe extends Thread {
- InputStream in;
- PrintStream out;
- PrintStream err; // derek
- 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 void setErr(PrintStream err) {
- this.err = err;
- }
-
- 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);
- closure.session.service.threadIO.setStreams(in, out, err); // derek
- 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();
- }
- }
- }
+public class Pipe extends Thread
+{
+ InputStream in;
+ PrintStream out;
+ PrintStream err; // derek
+ 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 void setErr(PrintStream err)
+ {
+ this.err = err;
+ }
+
+ 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);
+ closure.session.service.threadIO.setStreams(in, out, err); // derek
+ 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();
+ }
+ }
+ }
}
Modified: felix/trunk/gogo/src/main/java/org/apache/felix/gogo/shell/runtime/Reflective.java
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/src/main/java/org/apache/felix/gogo/shell/runtime/Reflective.java?rev=787428&r1=787427&r2=787428&view=diff
==============================================================================
--- felix/trunk/gogo/src/main/java/org/apache/felix/gogo/shell/runtime/Reflective.java (original)
+++ felix/trunk/gogo/src/main/java/org/apache/felix/gogo/shell/runtime/Reflective.java Mon Jun 22 22:27:13 2009
@@ -22,30 +22,23 @@
// DWB19: coerce() won't add empty array to satisfy Object[] argument
package org.apache.felix.gogo.shell.runtime;
-import java.lang.reflect.*;
+import org.osgi.service.command.CommandSession;
+
+import java.lang.reflect.Array;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
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 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 {
+ public Object method(CommandSession session, Object target, String name, List<Object> args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, Exception
+ {
// derek - support static methods
//Method[] methods = target.getClass().getMethods();
- Class<?> tc = (target instanceof Class) ? (Class<?>)target : target.getClass();
+ Class<?> tc = (target instanceof Class) ? (Class<?>) target : target.getClass();
Method[] methods = tc.getMethods();
name = name.toLowerCase();
@@ -54,41 +47,50 @@
String set = "set" + name;
if (KEYWORDS.contains(name))
+ {
name = "_" + name;
+ }
Method bestMethod = null;
Object[] bestArgs = null;
int match = -1;
ArrayList<Class<?>[]> possibleTypes = new ArrayList<Class<?>[]>(); // derek
- for (Method m : methods) {
+ for (Method m : methods)
+ {
String mname = m.getName().toLowerCase();
- if (mname.equals(name) || mname.equals(get) || mname.equals(set)
- || mname.equals(is) || mname.equals("_main")) { // derek - added _main
+ if (mname.equals(name) || mname.equals(get) || mname.equals(set) || mname.equals(is) || mname.equals("_main"))
+ { // derek - added _main
Class<?>[] types = m.getParameterTypes();
ArrayList<Object> xargs = new ArrayList<Object>(args); // derek - BUGFIX don't modify args
// Check if the command takes a session
- if (types.length > 0
- && CommandSession.class.isAssignableFrom(types[0])) {
+ if (types.length > 0 && CommandSession.class.isAssignableFrom(types[0]))
+ {
xargs.add(0, session);
}
Object[] parms = new Object[types.length];
// if (types.length >= args.size() ) {
int local = coerce(session, target, types, parms, xargs);
- if ((local >= xargs.size()) && (local >= types.length)) { // derek - stop no-args
+ if ((local >= xargs.size()) && (local >= types.length))
+ { // derek - stop no-args
boolean exact = (local == xargs.size() && local == types.length);
- if (exact || local > match) {
+ if (exact || local > match)
+ {
bestMethod = m;
bestArgs = parms;
match = local;
}
if (exact)
+ {
break;
+ }
}
else
+ {
possibleTypes.add(types); // derek
+ }
// }
// if (match == -1 && types.length == 1
// && types[0] == Object[].class) {
@@ -99,36 +101,47 @@
}
}
- if (bestMethod != null) {
+ if (bestMethod != null)
+ {
bestMethod.setAccessible(true);
// derek: BUGFIX catch InvocationTargetException
// return bestMethod.invoke(target, bestArgs);
- try {
+ try
+ {
return bestMethod.invoke(target, bestArgs);
- } catch (InvocationTargetException e) {
+ }
+ catch (InvocationTargetException e)
+ {
Throwable cause = e.getCause();
if (cause instanceof Exception)
- throw (Exception)cause;
+ {
+ throw (Exception) cause;
+ }
throw e;
}
- } else {
+ }
+ else
+ {
//throw new IllegalArgumentException("Cannot find command:" + name + " with args:" + args);
// { derek
ArrayList<String> list = new ArrayList<String>();
- for (Class<?>[] types : possibleTypes) {
+ for (Class<?>[] types : possibleTypes)
+ {
StringBuilder buf = new StringBuilder();
buf.append('(');
- for (Class<?> type : types) {
+ for (Class<?> type : types)
+ {
if (buf.length() > 1)
+ {
buf.append(", ");
+ }
buf.append(type.getSimpleName());
}
buf.append(')');
list.add(buf.toString());
}
- throw new IllegalArgumentException(
- String.format("Cannot coerce %s%s to any of %s", name, args, list));
+ throw new IllegalArgumentException(String.format("Cannot coerce %s%s to any of %s", name, args, list));
// } derek
}
}
@@ -138,7 +151,7 @@
* 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
@@ -148,47 +161,57 @@
* @throws Exception
*/
@SuppressWarnings("unchecked")
- private int coerce(CommandSession session, Object target, Class<?> types[],
- Object out[], List<Object> in) 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) {
+ while (i < out.length)
+ {
out[i] = null;
- try {
+ try
+ {
// Try to convert one argument
// derek: add empty array as extra argument
//out[i] = coerce(session, target, types[i], in.get(i));
if (i == in.size())
+ {
out[i] = NO_MATCH;
+ }
else
+ {
out[i] = coerce(session, target, types[i], in.get(i));
-
- if (out[i] == NO_MATCH) {
+ }
+
+ if (out[i] == NO_MATCH)
+ {
// Failed
// No match, check for varargs
- if (types[i].isArray() && i == types.length - 1) {
-
+ if (types[i].isArray() && i == types.length - 1)
+ {
+
// derek - expand final array arg
- if (i < in.size()) {
+ if (i < in.size())
+ {
Object arg = in.get(i);
- if (arg instanceof List) {
- List<Object> args = (List<Object>)arg;
+ if (arg instanceof List)
+ {
+ List<Object> args = (List<Object>) arg;
in = new ArrayList<Object>(in);
in.remove(i);
in.addAll(args);
}
}
-
+
// Try to parse the remaining arguments in an array
Class<?> component = types[i].getComponentType();
- Object components = Array.newInstance(component, in
- .size()
- - i);
+ Object components = Array.newInstance(component, in.size() - i);
int n = i;
- while (i < in.size()) {
- Object t = coerce(session, target, component, in
- .get(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++;
}
@@ -196,16 +219,20 @@
// Is last element, so we will quite hereafter
// return n;
if (i == in.size())
+ {
++i;
+ }
return i; // derek - return number of args converted
}
return -1;
}
i++;
- } catch (Exception e) {
+ }
+ catch (Exception e)
+ {
System.err.println("Reflective:" + e);
e.printStackTrace();
-
+
// should get rid of those exceptions, but requires
// reg ex matching to see if it throws an exception.
// dont know what is better
@@ -215,63 +242,125 @@
return i;
}
- Object coerce(CommandSession session, Object target, Class<?> type,
- Object arg) throws Exception {
+ 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()) {
+ 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;
+ }
+ else
+ {
+ if (!type.isPrimitive())
+ {
+ try
+ {
+ return type.getConstructor(String.class).newInstance(string);
+ }
+ catch (Exception e)
+ {
+ return NO_MATCH;
+ }
}
}
-
- try {
+
+ try
+ {
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);
+ }
+ 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);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
}
- catch (NumberFormatException e) {
+ catch (NumberFormatException e)
+ {
}
return NO_MATCH;
}
- public static boolean hasCommand(Object target, String function) {
+ public static boolean hasCommand(Object target, String function)
+ {
Method[] methods = target.getClass().getMethods();
- for (Method m : methods) {
+ for (Method m : methods)
+ {
if (m.getName().equals(function))
+ {
return true;
+ }
}
return false;
}
Modified: felix/trunk/gogo/src/main/java/org/apache/felix/gogo/shell/stdio/StdioConsole.java
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/src/main/java/org/apache/felix/gogo/shell/stdio/StdioConsole.java?rev=787428&r1=787427&r2=787428&view=diff
==============================================================================
--- felix/trunk/gogo/src/main/java/org/apache/felix/gogo/shell/stdio/StdioConsole.java (original)
+++ felix/trunk/gogo/src/main/java/org/apache/felix/gogo/shell/stdio/StdioConsole.java Mon Jun 22 22:27:13 2009
@@ -18,31 +18,37 @@
*/
package org.apache.felix.gogo.shell.stdio;
-import org.osgi.service.command.*;
-import org.osgi.service.component.*;
+import org.apache.felix.gogo.shell.console.Console;
+import org.osgi.service.command.CommandProcessor;
+import org.osgi.service.component.ComponentContext;
-import org.apache.felix.gogo.shell.console.*;
-
-public class StdioConsole extends Thread {
+public class StdioConsole extends Thread
+{
final Console console = new Console();
- public StdioConsole() {
+ public StdioConsole()
+ {
super("StdioConsole");
}
- protected void activate(ComponentContext context) {
+
+ protected void activate(ComponentContext context)
+ {
start();
}
- protected void deactivate(ComponentContext context) {
+ protected void deactivate(ComponentContext context)
+ {
console.close();
interrupt();
}
- public void setProcessor(CommandProcessor processor ) {
- console.setSession(processor.createSession(System.in,System.out,System.err));
+ public void setProcessor(CommandProcessor processor)
+ {
+ console.setSession(processor.createSession(System.in, System.out, System.err));
}
-
- public void run() {
+
+ public void run()
+ {
console.run();
}
}
Modified: felix/trunk/gogo/src/main/java/org/apache/felix/gogo/shell/telnet/Handler.java
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/src/main/java/org/apache/felix/gogo/shell/telnet/Handler.java?rev=787428&r1=787427&r2=787428&view=diff
==============================================================================
--- felix/trunk/gogo/src/main/java/org/apache/felix/gogo/shell/telnet/Handler.java (original)
+++ felix/trunk/gogo/src/main/java/org/apache/felix/gogo/shell/telnet/Handler.java Mon Jun 22 22:27:13 2009
@@ -18,44 +18,52 @@
*/
package org.apache.felix.gogo.shell.telnet;
-import java.io.*;
-import java.net.*;
+import org.apache.felix.gogo.shell.console.Console;
+import org.osgi.service.command.CommandSession;
-import org.osgi.service.command.*;
+import java.io.IOException;
+import java.net.Socket;
-import org.apache.felix.gogo.shell.console.*;
-
-public class Handler extends Thread {
- TelnetShell master;
- Socket socket;
- CommandSession session;
- Console console;
-
- public Handler(TelnetShell master, CommandSession session, Socket socket)
- throws IOException {
- this.master = master;
- this.socket = socket;
- this.session = session;
- }
-
- public void run() {
- try {
- console = new Console();
- console.setSession(session);
- console.run();
- } finally {
- close();
- master.handlers.remove(this);
- }
- }
-
- public void close() {
- session.close();
- try {
- socket.close();
- } catch (IOException e) {
- // Ignore, this is close
- }
- }
+public class Handler extends Thread
+{
+ TelnetShell master;
+ Socket socket;
+ CommandSession session;
+ Console console;
+
+ public Handler(TelnetShell master, CommandSession session, Socket socket) throws IOException
+ {
+ this.master = master;
+ this.socket = socket;
+ this.session = session;
+ }
+
+ public void run()
+ {
+ try
+ {
+ console = new Console();
+ console.setSession(session);
+ console.run();
+ }
+ finally
+ {
+ close();
+ master.handlers.remove(this);
+ }
+ }
+
+ public void close()
+ {
+ session.close();
+ try
+ {
+ socket.close();
+ }
+ catch (IOException e)
+ {
+ // Ignore, this is close
+ }
+ }
}
Modified: felix/trunk/gogo/src/main/java/org/apache/felix/gogo/shell/telnet/TelnetShell.java
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/src/main/java/org/apache/felix/gogo/shell/telnet/TelnetShell.java?rev=787428&r1=787427&r2=787428&view=diff
==============================================================================
--- felix/trunk/gogo/src/main/java/org/apache/felix/gogo/shell/telnet/TelnetShell.java (original)
+++ felix/trunk/gogo/src/main/java/org/apache/felix/gogo/shell/telnet/TelnetShell.java Mon Jun 22 22:27:13 2009
@@ -18,87 +18,128 @@
*/
package org.apache.felix.gogo.shell.telnet;
-import java.io.*;
-import java.net.*;
-import java.util.*;
-
-import org.osgi.service.command.*;
-import org.osgi.service.component.*;
-
-public class TelnetShell extends Thread {
- boolean quit;
+import org.osgi.service.command.CommandProcessor;
+import org.osgi.service.command.CommandSession;
+import org.osgi.service.component.ComponentContext;
+
+import java.io.IOException;
+import java.io.PrintStream;
+import java.net.BindException;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.util.ArrayList;
+import java.util.List;
+
+public class TelnetShell extends Thread
+{
+ boolean quit;
CommandProcessor processor;
- ServerSocket server;
- int port = 2019;
- List<Handler> handlers = new ArrayList<Handler>();
+ ServerSocket server;
+ int port = 2019;
+ List<Handler> handlers = new ArrayList<Handler>();
- protected void activate(ComponentContext context) {
+ protected void activate(ComponentContext context)
+ {
String s = (String) context.getProperties().get("port");
if (s != null)
+ {
port = Integer.parseInt(s);
+ }
System.out.println("Telnet Listener at port " + port);
start();
}
- protected void deactivate(ComponentContext ctx) throws Exception {
- try {
+ protected void deactivate(ComponentContext ctx) throws Exception
+ {
+ try
+ {
quit = true;
server.close();
interrupt();
- } catch (Exception e) {
+ }
+ catch (Exception e)
+ {
// Ignore
}
}
- public void run() {
+ public void run()
+ {
int delay = 0;
- try {
+ try
+ {
while (!quit)
- try {
+ {
+ try
+ {
server = new ServerSocket(port);
delay = 5;
- while (!quit) {
+ while (!quit)
+ {
Socket socket = server.accept();
- CommandSession session = processor.createSession(socket
- .getInputStream(), new PrintStream(socket
- .getOutputStream()), System.err);
+ CommandSession session = processor.createSession(socket.getInputStream(), new PrintStream(socket.getOutputStream()), System.err);
Handler handler = new Handler(this, session, socket);
handlers.add(handler);
handler.start();
}
- } catch (BindException be) {
+ }
+ catch (BindException be)
+ {
delay += 5;
System.err.println("Can not bind to port " + port);
- try {
+ try
+ {
Thread.sleep(delay * 1000);
- } catch (InterruptedException e) {
+ }
+ catch (InterruptedException e)
+ {
// who cares?
}
- } catch (Exception e) {
+ }
+ catch (Exception e)
+ {
if (!quit)
+ {
e.printStackTrace();
- } finally {
- try {
+ }
+ }
+ finally
+ {
+ try
+ {
server.close();
Thread.sleep(2000);
- } catch (Exception ie) {
+ }
+ catch (Exception ie)
+ {
//
}
}
+ }
- } finally {
- try {
+ }
+ finally
+ {
+ try
+ {
if (server != null)
+ {
server.close();
- } catch (IOException e) {
+ }
+ }
+ catch (IOException e)
+ {
//
}
for (Handler handler : handlers)
+ {
handler.close();
+ }
}
}
- public void setProcessor(CommandProcessor processor) {
+ public void setProcessor(CommandProcessor processor)
+ {
this.processor = processor;
}
}
Modified: felix/trunk/gogo/src/main/java/org/apache/felix/gogo/threadio/Marker.java
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/src/main/java/org/apache/felix/gogo/threadio/Marker.java?rev=787428&r1=787427&r2=787428&view=diff
==============================================================================
--- felix/trunk/gogo/src/main/java/org/apache/felix/gogo/threadio/Marker.java (original)
+++ felix/trunk/gogo/src/main/java/org/apache/felix/gogo/threadio/Marker.java Mon Jun 22 22:27:13 2009
@@ -18,25 +18,28 @@
*/
package org.apache.felix.gogo.threadio;
-import java.io.*;
+import java.io.InputStream;
+import java.io.PrintStream;
-public class Marker {
+public class Marker
+{
Marker previous;
InputStream in;
PrintStream out;
PrintStream err;
ThreadIOImpl parent;
-
- public Marker(ThreadIOImpl parent, InputStream in, PrintStream out,
- PrintStream err, Marker previous) {
+
+ public Marker(ThreadIOImpl parent, InputStream in, PrintStream out, PrintStream err, Marker previous)
+ {
this.previous = previous;
this.parent = parent;
this.in = in;
- this.out=out;
- this.err=err;
+ this.out = out;
+ this.err = err;
}
- Marker activate() {
+ Marker activate()
+ {
parent.in.setStream(in);
parent.out.setStream(out);
parent.err.setStream(err);
Modified: felix/trunk/gogo/src/main/java/org/apache/felix/gogo/threadio/ThreadIOImpl.java
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/src/main/java/org/apache/felix/gogo/threadio/ThreadIOImpl.java?rev=787428&r1=787427&r2=787428&view=diff
==============================================================================
--- felix/trunk/gogo/src/main/java/org/apache/felix/gogo/threadio/ThreadIOImpl.java (original)
+++ felix/trunk/gogo/src/main/java/org/apache/felix/gogo/threadio/ThreadIOImpl.java Mon Jun 22 22:27:13 2009
@@ -19,82 +19,101 @@
// DWB20: ThreadIO should check and reset IO if something (e.g. jetty) overrides
package org.apache.felix.gogo.threadio;
-import java.io.*;
-import java.util.logging.Logger;
+import org.osgi.service.component.ComponentContext;
+import org.osgi.service.threadio.ThreadIO;
-import org.osgi.service.component.*;
-import org.osgi.service.threadio.*;
+import java.io.InputStream;
+import java.io.PrintStream;
+import java.util.logging.Logger;
-public class ThreadIOImpl implements ThreadIO {
+public class ThreadIOImpl implements ThreadIO
+{
static private final Logger log = Logger.getLogger(ThreadIOImpl.class.getName());
- ThreadPrintStream err = new ThreadPrintStream(System.err);
- ThreadPrintStream out = new ThreadPrintStream(System.out);
- ThreadInputStream in = new ThreadInputStream(System.in);
+ ThreadPrintStream err = new ThreadPrintStream(System.err);
+ ThreadPrintStream out = new ThreadPrintStream(System.out);
+ ThreadInputStream in = new ThreadInputStream(System.in);
ThreadLocal<Marker> current = new ThreadLocal<Marker>();
-
- protected void activate(ComponentContext context) {
- start();
- }
-
- protected void deactivate() {
- stop();
- }
-
- public void stop() {
- System.setErr(err.dflt);
- System.setOut(out.dflt);
- System.setIn(in.dflt);
- }
-
- public void start() {
- if ( System.out instanceof ThreadPrintStream )
- throw new IllegalStateException("Thread Print Stream already set");
- System.setOut(out);
- System.setIn(in);
+
+ protected void activate(ComponentContext context)
+ {
+ start();
+ }
+
+ protected void deactivate()
+ {
+ stop();
+ }
+
+ public void stop()
+ {
+ System.setErr(err.dflt);
+ System.setOut(out.dflt);
+ System.setIn(in.dflt);
+ }
+
+ public void start()
+ {
+ if (System.out instanceof ThreadPrintStream)
+ {
+ throw new IllegalStateException("Thread Print Stream already set");
+ }
+ System.setOut(out);
+ System.setIn(in);
System.setErr(err);
- }
-
- private void checkIO() { // derek
- if (System.in != in) {
- log.fine("ThreadIO: eek! who's set System.in=" + System.in);
- System.setIn(in);
- }
-
- if (System.out != out) {
- log.fine("ThreadIO: eek! who's set System.out=" + System.out);
- System.setOut(out);
- }
-
- if (System.err != err) {
- log.fine("ThreadIO: eek! who's set System.err=" + System.err);
- System.setErr(err);
- }
- }
-
- public void close() {
- checkIO(); // derek
- Marker top = this.current.get();
- if ( top == null )
- throw new IllegalStateException("No thread io active");
-
- Marker previous = top.previous;
- if (previous==null) {
- in.end();
- out.end();
- err.end();
- } else {
+ }
+
+ private void checkIO()
+ { // derek
+ if (System.in != in)
+ {
+ log.fine("ThreadIO: eek! who's set System.in=" + System.in);
+ System.setIn(in);
+ }
+
+ if (System.out != out)
+ {
+ log.fine("ThreadIO: eek! who's set System.out=" + System.out);
+ System.setOut(out);
+ }
+
+ if (System.err != err)
+ {
+ log.fine("ThreadIO: eek! who's set System.err=" + System.err);
+ System.setErr(err);
+ }
+ }
+
+ public void close()
+ {
+ checkIO(); // derek
+ Marker top = this.current.get();
+ if (top == null)
+ {
+ throw new IllegalStateException("No thread io active");
+ }
+
+ Marker previous = top.previous;
+ if (previous == null)
+ {
+ in.end();
+ out.end();
+ err.end();
+ }
+ else
+ {
this.current.set(previous);
- previous.activate();
- }
- }
+ previous.activate();
+ }
+ }
- public void setStreams(InputStream in, PrintStream out, PrintStream err) {
+ public void setStreams(InputStream in, PrintStream out, PrintStream err)
+ {
assert in != null;
assert out != null;
assert err != null;
checkIO(); // derek
- Marker marker = new Marker(this,in,out,err, current.get());
- this.current.set(marker);
- marker.activate();
- }
+ Marker marker = new Marker(this, in, out, err, current.get());
+ this.current.set(marker);
+ marker.activate();
+ }
}
Modified: felix/trunk/gogo/src/main/java/org/apache/felix/gogo/threadio/ThreadInputStream.java
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/src/main/java/org/apache/felix/gogo/threadio/ThreadInputStream.java?rev=787428&r1=787427&r2=787428&view=diff
==============================================================================
--- felix/trunk/gogo/src/main/java/org/apache/felix/gogo/threadio/ThreadInputStream.java (original)
+++ felix/trunk/gogo/src/main/java/org/apache/felix/gogo/threadio/ThreadInputStream.java Mon Jun 22 22:27:13 2009
@@ -18,47 +18,63 @@
*/
package org.apache.felix.gogo.threadio;
-import java.io.*;
+import java.io.IOException;
+import java.io.InputStream;
-public class ThreadInputStream extends InputStream {
+public class ThreadInputStream extends InputStream
+{
ThreadLocal<InputStream> map = new ThreadLocal<InputStream>();
- InputStream dflt;
+ InputStream dflt;
- public ThreadInputStream(InputStream in) {
- dflt = in;
- }
-
- public int read(byte[] buffer, int offset, int length) throws IOException {
- return getCurrent().read(buffer, offset, length);
- }
-
- public int read(byte[] buffer) throws IOException {
- return getCurrent().read(buffer);
- }
-
- private InputStream getCurrent() {
- InputStream in = map.get();
- if (in != null)
- return in;
- return dflt;
- }
-
- public int read() throws IOException {
- return getCurrent().read();
- }
-
- public void setStream(InputStream in) {
- if ( in != dflt && in != this )
- map.set(in);
- else
- map.remove();
- }
-
- public void end() {
- map.remove();
- }
-
- InputStream getRoot() {
- return dflt;
- }
+ public ThreadInputStream(InputStream in)
+ {
+ dflt = in;
+ }
+
+ public int read(byte[] buffer, int offset, int length) throws IOException
+ {
+ return getCurrent().read(buffer, offset, length);
+ }
+
+ public int read(byte[] buffer) throws IOException
+ {
+ return getCurrent().read(buffer);
+ }
+
+ private InputStream getCurrent()
+ {
+ InputStream in = map.get();
+ if (in != null)
+ {
+ return in;
+ }
+ return dflt;
+ }
+
+ public int read() throws IOException
+ {
+ return getCurrent().read();
+ }
+
+ public void setStream(InputStream in)
+ {
+ if (in != dflt && in != this)
+ {
+ map.set(in);
+ }
+ else
+ {
+ map.remove();
+ }
+ }
+
+ public void end()
+ {
+ map.remove();
+ }
+
+ InputStream getRoot()
+ {
+ return dflt;
+ }
}
Modified: felix/trunk/gogo/src/main/java/org/apache/felix/gogo/threadio/ThreadPrintStream.java
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/src/main/java/org/apache/felix/gogo/threadio/ThreadPrintStream.java?rev=787428&r1=787427&r2=787428&view=diff
==============================================================================
--- felix/trunk/gogo/src/main/java/org/apache/felix/gogo/threadio/ThreadPrintStream.java (original)
+++ felix/trunk/gogo/src/main/java/org/apache/felix/gogo/threadio/ThreadPrintStream.java Mon Jun 22 22:27:13 2009
@@ -18,48 +18,61 @@
*/
package org.apache.felix.gogo.threadio;
-import java.io.*;
+import java.io.IOException;
+import java.io.PrintStream;
+
+public class ThreadPrintStream extends PrintStream
+{
+ PrintStream dflt;
+ ThreadLocal<PrintStream> map = new ThreadLocal<PrintStream>();
+
+ public ThreadPrintStream(PrintStream out)
+ {
+ super(out);
+ dflt = out;
+ }
+
+ public void write(byte[] buffer, int offset, int length)
+ {
+ getCurrent().write(buffer, offset, length);
+ }
+
+ public void write(byte[] buffer) throws IOException
+ {
+ getCurrent().write(buffer);
+ }
+
+ public PrintStream getCurrent()
+ {
+ PrintStream out = map.get();
+ if (out != null)
+ {
+ return out;
+ }
+ return dflt;
+ }
+
+ public void write(int b)
+ {
+ getCurrent().write(b);
+ }
+
+ public void setStream(PrintStream out)
+ {
+ if (out != dflt && out != this)
+ {
+ map.set(out);
+ }
+ else
+ {
+ map.remove();
+ }
+ }
+
+ public void end()
+ {
+ map.remove();
+ }
-public class ThreadPrintStream extends PrintStream {
- PrintStream dflt;
- ThreadLocal<PrintStream> map = new ThreadLocal<PrintStream>();
-
- public ThreadPrintStream(PrintStream out) {
- super(out);
- dflt = out;
- }
-
- public void write(byte[] buffer, int offset, int length) {
- getCurrent().write(buffer, offset, length);
- }
-
- public void write(byte[] buffer) throws IOException {
- getCurrent().write(buffer);
- }
-
- public PrintStream getCurrent() {
- PrintStream out = map.get();
- if (out != null)
- return out;
- return dflt;
- }
-
- public void write(int b) {
- getCurrent().write(b);
- }
-
- public void setStream(PrintStream out) {
- if (out != dflt && out != this) {
- map.set(out);
- }
- else {
- map.remove();
- }
- }
-
- public void end() {
- map.remove();
- }
-
}
Modified: felix/trunk/gogo/src/main/java/org/osgi/framework/boot/SystemBundle.java
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/src/main/java/org/osgi/framework/boot/SystemBundle.java?rev=787428&r1=787427&r2=787428&view=diff
==============================================================================
--- felix/trunk/gogo/src/main/java/org/osgi/framework/boot/SystemBundle.java (original)
+++ felix/trunk/gogo/src/main/java/org/osgi/framework/boot/SystemBundle.java Mon Jun 22 22:27:13 2009
@@ -18,17 +18,17 @@
*/
package org.osgi.framework.boot;
-import java.util.*;
+import java.util.Properties;
/**
* This interface should be implemented by framework implementations when their
* main object is created. It allows a configurator to set the properties and
* launch the framework.
- *
+ *
* @author aqute
- *
*/
-public interface SystemBundle {
+public interface SystemBundle
+{
/**
* The name of a Security Manager class with public empty constructor. A
* valid value is also true, this means that the framework should
@@ -36,7 +36,7 @@
* defined by a parent framework or there is no security. This can be
* detected by looking if there is a security manager set
*/
- String SECURITY = "org.osgi.framework.security";
+ String SECURITY = "org.osgi.framework.security";
/**
* A valid file path in the file system to a directory that exists. The
@@ -45,52 +45,46 @@
* should use a file area from the parent bundle. If it is not embedded, it
* must use a reasonable platform default.
*/
- String STORAGE = "org.osgi.framework.storage";
+ String STORAGE = "org.osgi.framework.storage";
/*
* A list of paths (separated by path separator) that point to additional
* directories to search for platform specific libraries
- */
- String LIBRARIES = "org.osgi.framework.libraries";
+ */ String LIBRARIES = "org.osgi.framework.libraries";
/*
* The command to give a file executable permission. This is necessary in
* some environments for running shared libraries.
- */
- String EXECPERMISSION = "org.osgi.framework.command.execpermission";
+ */ String EXECPERMISSION = "org.osgi.framework.command.execpermission";
/*
* Points to a directory with certificates. ###??? Keystore? Certificate
* format?
- */
- String ROOT_CERTIFICATES = "org.osgi.framework.root.certificates";
+ */ String ROOT_CERTIFICATES = "org.osgi.framework.root.certificates";
/*
* Set by the configurator but the framework should provide a reasonable
* default.
- */
- String WINDOWSYSTEM = "org.osgi.framework.windowsystem";
+ */ String WINDOWSYSTEM = "org.osgi.framework.windowsystem";
/**
* Configure this framework with the given properties. These properties can
* contain framework specific properties or of the general kind defined in
* the specification or in this interface.
- *
- * @param properties
- * The properties. This properties can be backed by another
- * properties, it can there not be assumed that it contains all
- * keys. Use it only through the getProperty methods. This parameter may be null.
- *
+ *
+ * @param properties The properties. This properties can be backed by another
+ * properties, it can there not be assumed that it contains all
+ * keys. Use it only through the getProperty methods. This parameter may be null.
*/
void init(Properties configuration);
/**
* Wait until the framework is completely finished.
- *
+ * <p/>
* This method will return if the framework is stopped and has cleaned up
- * all the framework resources.
- *
+ * all the framework resources.
+ *
* @param timeout Maximum number of milliseconds to wait until the framework is finished. Specifying a zero will wait indefinitely.
*/
-
+
void join(long timeout) throws InterruptedException;
}
Modified: felix/trunk/gogo/src/main/java/org/osgi/service/command/CommandProcessor.java
URL: http://svn.apache.org/viewvc/felix/trunk/gogo/src/main/java/org/osgi/service/command/CommandProcessor.java?rev=787428&r1=787427&r2=787428&view=diff
==============================================================================
--- felix/trunk/gogo/src/main/java/org/osgi/service/command/CommandProcessor.java (original)
+++ felix/trunk/gogo/src/main/java/org/osgi/service/command/CommandProcessor.java Mon Jun 22 22:27:13 2009
@@ -18,49 +18,47 @@
*/
package org.osgi.service.command;
-import java.io.*;
+import java.io.InputStream;
+import java.io.PrintStream;
/**
* A command shell can create and maintain a number of command sessions.
- *
+ *
* @author aqute
- *
*/
-public interface CommandProcessor {
- /**
- * The scope of commands provided by this service. This name can be used to distinguish
- * between different command providers with the same function names.
- */
- final static String COMMAND_SCOPE = "osgi.command.scope";
+public interface CommandProcessor
+{
+ /**
+ * The scope of commands provided by this service. This name can be used to distinguish
+ * between different command providers with the same function names.
+ */
+ final static String COMMAND_SCOPE = "osgi.command.scope";
- /**
- * A list of method names that may be called for this command provider. A
- * name may end with a *, this will then be calculated from all declared public
- * methods in this service.
- *
- * Help information for the command may be supplied with a space as
- * separation.
- */
- final static String COMMAND_FUNCTION = "osgi.command.function";
+ /**
+ * A list of method names that may be called for this command provider. A
+ * name may end with a *, this will then be calculated from all declared public
+ * methods in this service.
+ * <p/>
+ * Help information for the command may be supplied with a space as
+ * separation.
+ */
+ final static String COMMAND_FUNCTION = "osgi.command.function";
- /**
- * Create a new command session associated with IO streams.
- *
- * The session is bound to the life cycle of the bundle getting this
- * service. The session will be automatically closed when this bundle is
- * stopped or the service is returned.
- *
- * The shell will provide any available commands to this session and
- * can set additional variables.
- *
- * @param in
- * The value used for System.in
- * @param out
- * The stream used for System.out
- * @param err
- * The stream used for System.err
- * @return A new session.
- */
- CommandSession createSession(InputStream in, PrintStream out,
+ /**
+ * Create a new command session associated with IO streams.
+ * <p/>
+ * The session is bound to the life cycle of the bundle getting this
+ * service. The session will be automatically closed when this bundle is
+ * stopped or the service is returned.
+ * <p/>
+ * The shell will provide any available commands to this session and
+ * can set additional variables.
+ *
+ * @param in The value used for System.in
+ * @param out The stream used for System.out
+ * @param err The stream used for System.err
+ * @return A new session.
+ */
+ CommandSession createSession(InputStream in, PrintStream out,
PrintStream err);
}