+ private String cookie = null;
+ public Object send(Request request) throws IOException {
+ URLConnection c = server.openConnection();
+ ((HttpURLConnection)c).setRequestMethod("POST");
+ c.setDoOutput(true);
+ if (cookie != null) c.setRequestProperty("Cookie", cookie);
+
+ c.connect();
+
+ ObjectOutputStream out = new ObjectOutputStream(c.getOutputStream());
+ out.writeObject(request);
+ out.close();
+
+ String cook = c.getHeaderField("Set-Cookie");
+ if (cook != null && !cook.equals("")) cookie = cook.substring(0, cook.indexOf(';'));
+
+ try {
+ return new ObjectInputStream(c.getInputStream()).readObject();
+ } catch (ClassNotFoundException e) {
+ e.printStackTrace();
+ throw new IOException("unexpected ClassNotFoundException");
+ }
+ }
+
+ public abstract class Command {
+ /** Returns the command name. */
+ public abstract String name();
+
+ /** Returns single-line of usage information, eg. <tt>pattern]</tt> */
+ public abstract String usage();
+
+ /** Returns single-line description of command. */
+ public abstract String summary();
+
+ /** Returns multi-line description. */
+ public abstract String help();
+
+ /** Writes result of execution, even if result is an error. */
+ public abstract void execute(Writer w, String[] args) throws IOException;
+ }
+
+ /** Returns the command matching the given name. */
+ protected Command command(String name) {
+ for (int i=0; i < commands.length; i++)
+ if (commands[i].name().equals(name)) return commands[i];
+ return null;
+ }
+
+ public class HelpCommand extends Command {
+ public String name() { return "help"; }
+ public String usage() { return "[command name]"; }
+ public String summary() { return "Lists available commands."; }
+ public String help() { return ""; }
+
+ public void execute(Writer w, String[] c) throws IOException {
+ if (c.length > 1) {
+ Command cmd = command(c[1]);
+ if (c == null) {
+ w.write("help: ");
+ w.write(c[1]);
+ w.write(": command not found");
+ } else {
+ w.write("usage: ");
+ w.write(cmd.name());
+ w.write(" ");
+ w.write(cmd.usage());
+ w.write("\n\n");
+ w.write(cmd.help());
+ w.write("\n");
+ }
+ } else {
+ int len = 3;
+ for (int i=0; i < commands.length; i++)
+ len = Math.max(commands[i].name().length(), len);
+
+ w.write("Available commands:\n");
+ for (int i=0; i < commands.length; i++) {
+ Command cmd = commands[i];
+ w.write(" ");
+ w.write(cmd.name());
+ for (int j=len - cmd.name().length(); j >= 0; j--) w.write(" ");
+ w.write(" - ");
+ w.write(cmd.summary());
+ w.write("\n");
+ }
+ w.write("\nFor usage details, type help [command name].");
+ }
+ }