kward       2002/11/08 17:13:48

  Added:       java/scratchpad/admin/src/org/apache/xindice/admin
                        XindiceAdmin.java
               java/scratchpad/admin/src/org/apache/xindice/admin/commandline
                        BaseCommand.java BasePrompt.java Command.java
                        CommandException.java CommandRegister.java
                        Prompt.java ShellPrompt.java
                        XindiceToolBuilder.java XindiceTools.java
               java/scratchpad/admin/src/org/apache/xindice/admin/commands
                        AddDocumentCommand.java CreateCommand.java
                        DirCommand.java ExitCommand.java
                        GetConfigCommand.java HelpCommand.java
                        ListCommand.java QueryCommand.java
                        RunScriptCommand.java TimeCommand.java
                        URLCommand.java UseCommand.java
               java/scratchpad/admin/src/org/apache/xindice/admin/utility
                        URLUtils.java
  Log:
  Adding scratchpad command line tools
  
  Revision  Changes    Path
  1.1                  
xml-xindice/java/scratchpad/admin/src/org/apache/xindice/admin/XindiceAdmin.java
  
  Index: XindiceAdmin.java
  ===================================================================
  /*
   * Created by IntelliJ IDEA.
   * User: kward
   * Date: Oct 30, 2002
   * Time: 9:57:34 PM
   * To change template for new class use
   * Code Style | Class Templates options (Tools | IDE Options).
   */
  
  import org.apache.xindice.admin.commandline.ShellPrompt;
  
  import java.util.Iterator;
  
  /**
   * Example program that creates a ShellPrompt and then starts it. Type
   * exit to exit.
   */
  public class XindiceAdmin {
  
        public static void main(String args[]) {
                ShellPrompt prompt = new ShellPrompt("Xindice ");
                prompt.start();
        }
  }
  
  
  
  1.1                  
xml-xindice/java/scratchpad/admin/src/org/apache/xindice/admin/commandline/BaseCommand.java
  
  Index: BaseCommand.java
  ===================================================================
  package org.apache.xindice.admin.commandline;
  
  import java.util.Iterator;
  import java.util.Vector;
  import java.util.Hashtable;
  
  
  /**
   * Base class for creating named commands. The BaseCommand constructor should
   * be called from the constructor of a derived class that is the actual 
   * command. For example:
   * <p><pre>
   * class ExitCommand extends BaseCommand { 
   *  ExitCommand() { 
   *    super("exit", 0, "calls the System to exit");
   *  }
   * }
   * </pre>
   * <p>
   * For a complete example of creating a command, see the RunScriptCommand.
   * @see RunScriptCommand
   */
  public abstract class BaseCommand implements Command {
  
        protected String name_;
        protected int numArgs_;
        protected CommandRegister register_;
        protected String help_;
  
        protected static BasePrompt prompt = null;
        
        /**
         * All inheriting classes are required to call this constructor using 
         * <pre>super(name, numArgs, help)</pre>.
         *
         * @param name the name of the command - an exception will be thrown if 
         *  a command already exists with this name
         * @param numArgs the number of arguments this command takes.
         * -1 can be specified if the command takes a variable number of 
         * arguments, in which case it is up to the derived command to carefully
         * check the arguments.
         * @param help this string is returned to the user when they request 
         * help about a command. It should include a brief description of what
         * the command accomplishes and what each of the required arguments is.
         */
        public BaseCommand(String name, int numArgs, String help) {
                name_ = name;
                numArgs_ = numArgs;
                help_ = help;
        }
        
        /**
         * This method is called by the CommandRegister whenever a new command
         * is registered - this gives commands access to help information for 
         * other commands - eg. see the HelpCommand.
         */
        public void set(CommandRegister cregister) {
                register_ = cregister;
        }
  
        public CommandRegister getRegister() {
                return register_;
        }
        
  
        static void setPrompt(BasePrompt prompt) {
                BaseCommand.prompt = prompt;
        }
  
        protected BasePrompt getPrompt() {
                if (prompt == null) {
                        System.err.println("cannot access prompt as it has not 
been set");
                }
                return prompt;
        }
  
        public String getName() { return name_; }
        
        /**
         * This method enables a command to be used independently of the 
         * command prompt. You instantiate a command, and then execute it 
         * by passing a string containing the arguments. If the arguments are
         * not properly formatted, an error will be printed.
         */
        public void execute(String args)
        {
                if (register_ == null) {
                        prompt.err.println("Warning: command '" +
                                getName() + "' not registered: can't execute");
                        return;
                }
                execute(register_.parseCommand(args));
        }
        
        /**
         * This method should be overloaded by each command that is defined -
         * it will be called by the CommandRegister after the number of
         * arguments have been checked.
         */
        public abstract void execute(String args[]);
        
        /**
         * This method is called internally whenever a command is executed to 
         * check the arguments. After checking arguments, it will call the 
         * execute(String[]) method for the specific command.
         */
        public void execute(Iterator iter) {
  
          String args[] = null;
                if (numArgs_ != -1) {
                        args = new String[numArgs_];
                        for (int i=0; i<numArgs_; i++) {
                                if (!iter.hasNext()) {
                                        prompt.out.println(getHelp());
                                        return;
                                }
                                args[i] = (String)iter.next();
                        }
                        // check that there are not extra arguments
                        if (iter.hasNext()) {
                                prompt.err.println("Too many arguments in 
command");
                                prompt.out.println(getHelp());
                                return;
                        }
                // unknown number of arguments indicated by -1
                } else {        
                        Vector vector = new Vector(10);
                        while(iter.hasNext()) {
                                vector.add(iter.next());
                        }
                        args = new String[vector.size()];
                        vector.toArray(args);
                }
                execute(args);
        }
        
        /**
         * Return a the help string for this command. This is basically the help
         * string required in the constructor for all BaseCommands.
         */
        public String getHelp() { 
                return "usage:\n" + name_ + " " + help_;
        }
  }
  
  
  
  1.1                  
xml-xindice/java/scratchpad/admin/src/org/apache/xindice/admin/commandline/BasePrompt.java
  
  Index: BasePrompt.java
  ===================================================================
  package org.apache.xindice.admin.commandline;
  
  import java.util.StringTokenizer;
  import java.util.Hashtable;
  import java.util.Vector;
  import java.util.Iterator;
  import java.io.*;
  
  /**
   * Base class for all command prompts. This class handles the
   * prompt-independent processing, such as the basic user-interaction loop and
   * command execution. 
   *
   * Optionally, System.in, System.err, System.out can be redirected to the
   * prompt's streams.
   *
   * @see ShellPrompt
   * @see TextAreaPrompt
   */
  public class BasePrompt extends Thread implements Prompt {
        
        private String name_;
        private BufferedReader reader_;
        private CommandRegister register_;
  
        public PrintStream out;
        public PrintStream err;
        public InputStream in;
        
        // If System streams are redirected, a handle to the originals must 
        // be kept so that we can reset them if asked to exit
        //
        private PrintStream defaultOut_;
        private PrintStream defaultErr_;
        private InputStream defaultIn_;
  
        protected BasePrompt(   String name,
                                                        CommandRegister 
register,
                                                        PrintStream out,
                                                        PrintStream err,
                                                        InputStream in) {
                name_ = name;
  
                this.out = out;
                this.err = err;
                this.in = in;
  
                reader_ = new BufferedReader(new InputStreamReader(in));
  
                if (register == null) {
                        register_ = new CommandRegister();
                } else {
                        register_ = register;
                }
  
                BaseCommand.setPrompt(this);
        }
  
        public void redirectSystemIOToPrompt() {
  
                // maintain a handle to the default System.out and System.err
                // streams so that we can reset these when we exit
                //
                defaultOut_ = System.out;
                defaultErr_ = System.err;
                defaultIn_ = System.in;
                
                // reassign standard output, error and input to the same as 
that 
                // being used by the prompt. The whole idea here is to still be 
                // able to write "System.out.println()" in your code and have 
this
                // automatically redirected to the command prompt.
                //
                System.setOut(out);
  
                // At one time, I was prefixing all error messages with "Error: 
".
                // However, this acts somewhat funny for multi-line error 
messages.
                // System.setErr(new PrefixPrintStream(error, "Error: "));
                //
                System.setErr(err);
  
                System.setIn(in);
        }               
        
        /**
         * This method is called to register a new command to be used with this
         * prompt. Note, every prompt contains a reference to a CommandRegister 
         * that keeps track of available commands.
         */
        public void registerCommand(Command command) {
                register_.add(command);
        }
        
        public void registerPackage(XindiceToolBuilder ci) {
                register_.add(ci);
        }
        
        /**
         * Iterates through all the registered packages and tells them we are 
         * exiting - just in case they have resources to free.
         */
        public void exit() {
  
                register_.exit();
  
                // reset the output Streams to the defaults
                // (some messages might be displayed on exit, however these will
                // not be visible if the out and err streams are directed to a
                // TextArea and this is no longer visible)
                //
                System.setOut(defaultOut_);
                System.setErr(defaultErr_);
                System.setIn(defaultIn_);
  
                System.exit(0);
        }
        
        protected void printPrompt() {
                out.print(name_ + "> "); 
                out.flush();
        }
        
        /**
         * This method starts the prompt in interactive mode. Note that this is
         * the starting point for a new thread of execution whcih blocks until
         * the user enters input into the input stream.
         */
        public void run() {
                for(;;) {
                        printPrompt();
                        String command = null;
                        try {
                                command = reader_.readLine();
                                if (command != null && command.length() != 0) {
                                        register_.execute(command);
                                }
                        } catch (CommandException e) {
                                err.println("Error: " + e);
                        } catch (IOException e) {
                                err.println("could not read line");
                        }
                }
        }
        
        /**
         * Ask the user a boolean question. Eg. "How are you today?"
         * @return true if the user responds "yes" or "y", false if they respond
         *  "no" or "n" - all case insensitive.
         */
        public boolean askBooleanQuestion(String question) {
                String response = askQuestion(question, "n");
                if (response.equalsIgnoreCase("yes") || 
                        response.equalsIgnoreCase("y")) {
                        return true;
                } 
                return false;
        }
        
        /**
         * Ask the user a question.
         * @return a string containing the typed response.
         */
        public String askQuestion(String question) {
                return askQuestion(question, null);
        }
        
        /**
         * Ask the user a question and provide a default answer (to save the 
         * user typing if it is a likely default).
         * @return a string containing the typed response, or the default answer
         *  if the user just hits enter.
         */
        public String askQuestion(String question, String defaultAns) {
                out.print(question);
                if (defaultAns != null) {
                        out.print(" (" + defaultAns + ")"); 
                }
                out.print(": ");
                out.flush();
                String response = "";
  
                try {
                        response = reader_.readLine();
                        if (defaultAns != null &&
                                (response.equalsIgnoreCase("") ||
                                response.equalsIgnoreCase("\n"))) {
                                return defaultAns;
                        }
                } catch (IOException e) {
                        err.println("could not read response");
                }
                return response;
        }
  }
  
  
  
  1.1                  
xml-xindice/java/scratchpad/admin/src/org/apache/xindice/admin/commandline/Command.java
  
  Index: Command.java
  ===================================================================
  package org.apache.xindice.admin.commandline;
  
  import java.util.Iterator;
  
  /**
   * Interface implemented by all commands. Note that this interface is
   * implemented by BaseCommand.
   *
   * @see BaseCommand
   */
  public interface Command {
        String getName();
        String getHelp();
        void execute(String args[]);
        void execute(Iterator iterator);
        void set(CommandRegister cregister);
  }
  
  
  
  1.1                  
xml-xindice/java/scratchpad/admin/src/org/apache/xindice/admin/commandline/CommandException.java
  
  Index: CommandException.java
  ===================================================================
  package org.apache.xindice.admin.commandline;
  
  /**
   * If an unrecoverable error occurs when executing a command (eg. invalid 
   * parameters etc.), a CommandException should be thrown that will 
   * cleanly be handled by the prompt. The user can then retry the command
   * with the correct parameters, or atleast they will have an idea why the 
   * command is failing.
   */
  public class CommandException extends RuntimeException {
  
        String error_;
  
        public CommandException(String error) {
                error_ = error;
        }
  
        public String toString() {
                return error_;
        }
  }
  
  
  
  1.1                  
xml-xindice/java/scratchpad/admin/src/org/apache/xindice/admin/commandline/CommandRegister.java
  
  Index: CommandRegister.java
  ===================================================================
  package org.apache.xindice.admin.commandline;
  
  import java.util.StringTokenizer;
  import java.util.Iterator;
  import java.util.Hashtable;
  import java.util.Vector;
  
  /**
   * This class is used internally by the BasePrompt to maintain a table
   * of registered commands. You should never be required to interact with it
   * using the cline package.
   */
  public class CommandRegister extends Hashtable {
  
        private Hashtable packages_ = new Hashtable(20);
  
        public CommandRegister() {
                super(100);
  
          // always register the basic XindiceTools
                add(new XindiceTools());
        }
  
        public final void add(Command command) {
                command.set(this);
                put(command.getName(), command);
        }
  
        /**
         * Registers an entire Java package for use with the command line. All
         * commands returned by this packages getCommands() method will be 
         * registerred when this method is called.
         */
        public void add(XindiceToolBuilder ci) {
                String key = ci.getClass().getName();
                if (packages_.contains(key)) {
                        System.err.println("attempt to register duplicate 
package");
                        return;
                }
                packages_.put(key, ci);
  
                // now register all the commands from this package
                Command[] commands = ci.getCommands();
                for (int i=0; i<commands.length; i++) {
                        add(commands[i]);
                }
        }
  
        public void exit() {
                Iterator iter = packages_.values().iterator();
                while (iter.hasNext()) {
                        XindiceToolBuilder ci = (XindiceToolBuilder)iter.next();
                        ci.exit();
                }
        }
        
        /**
         * This method returns the tokens from a String that does not contain
         * any quotations.
         */
        private final Iterator parseCommandNoQuotes(String input) {
                StringTokenizer tokenizer = new StringTokenizer(input, " \t");
  
                // convert from an Enumeration to an Iterator to try and be
                // consistent with our use of Collections
                // 
                Vector tokens = new Vector();
                while (tokenizer.hasMoreElements()) {
                        tokens.add(tokenizer.nextElement());
                }
                return tokens.iterator();
        }
        
        /**
         * This command returns the tokens from a string. If the string contains
         * a quote, the words between the quotes are returned as a single token.
         */
        final Iterator parseCommand(String input) {
                if (input.indexOf('"') == -1) {
                        return parseCommandNoQuotes(input);
                }
  
                // else we might have to parse between quotations
                // For example, the string below: 
                // question "how are you" 2
                // contains three tokens (question, how are you, 2)
  
                int curIndex = 0;
                int endIndex = input.length();
  
                // used to hold the arguments of the command
                Vector vector = new Vector(4);  // 4 args is a large command
  
                while (curIndex < endIndex) {
                        int spaceIndex = input.indexOf(' ', curIndex);
                        int quotationIndex = input.indexOf('"', curIndex);
  
                        //System.out.println("spaceIndex: [" + spaceIndex +
                        //      "] quotationIndex: [" + quotationIndex +
                        //      "] curIndex: [" + curIndex + "]");
  
                        String next = null;
                        if (quotationIndex == -1) {
                                Iterator iter = parseCommandNoQuotes(
                                        input.substring(curIndex, endIndex));
                                while (iter.hasNext()) {
                                        vector.add(iter.next());
                                }
                                break;
                        } else if (spaceIndex != -1 && spaceIndex < 
quotationIndex) {
                                next = input.substring(curIndex, spaceIndex);
                                curIndex = spaceIndex+1;
                        } else {        // quotationIndex != -1
                                // we have to extract a string between 
quotations
                                int matchingQuote =     input.indexOf('"', 
quotationIndex+1);
                                if (matchingQuote == -1) {
                                        throw new CommandException("quotations 
do not match");
                                }
                                next = input.substring(quotationIndex+1, 
matchingQuote);
  
                                // this assumes that an end quote will always 
be followed
                                // by a space
                                curIndex = matchingQuote+2;
                        }
                        vector.add(next);
                }
                return vector.iterator();
        }
  
        public final Command getCommand(String name) {
                if (containsKey(name)) {
                        return (Command)get(name);
                } 
                return null;
        }
        
        /**
         * Parses a string containing a command name and arguments and then
         * executes the command if it was well structured (the string 'command'
         * will be parsed - looking for the name of the command and any 
         * arguments required for that command).
         */
        public void execute(String command) {
                executeCommand(parseCommand(command));
        }
        
        /**
         * Execute a command - the first String in the iterator should be the 
         * name of the command, the following strings are the parameters that 
         * will be passed to the command.
         */
        private final void executeCommand(Iterator iter) {
                if (!iter.hasNext()) {
                        throw new CommandException("no command specified");
                }
                String name = (String)iter.next();
                Command command = getCommand(name);
                if (command != null) {
                        command.execute(iter);
                } else {
                        throw new CommandException("invalid syntax near \"" + 
name + "\"");
                }
        }
  }
  
  
  
  1.1                  
xml-xindice/java/scratchpad/admin/src/org/apache/xindice/admin/commandline/Prompt.java
  
  Index: Prompt.java
  ===================================================================
  package org.apache.xindice.admin.commandline;
  
  /**
   * Command prompt interface.
   *
   * @see ShellPrompt
   */
  public interface Prompt {
  
        public void registerCommand(Command command);
        public void registerPackage(XindiceToolBuilder ci);
        public void start();
        public void exit();
        public boolean askBooleanQuestion(String question);
        public String askQuestion(String question);
  
  }
  
  
  
  1.1                  
xml-xindice/java/scratchpad/admin/src/org/apache/xindice/admin/commandline/ShellPrompt.java
  
  Index: ShellPrompt.java
  ===================================================================
  package org.apache.xindice.admin.commandline;
  
  import java.util.StringTokenizer;
  import java.util.Enumeration;
  import java.util.Hashtable;
  import java.io.*;
  
  /**
   * Command prompt to be used within a xterm or DOS-shell. 
   *
   * @see BasePrompt
   * @see TextAreaPrompt
   */
  public class ShellPrompt extends BasePrompt {
        
        /**
         * The shell prompt is an easy one - it just makes use of System.out,
         * System.err and System.in. The second parameter is a register of 
         * commands - which might have been created before we needed to allocate
         * a ShellPrompt.
         */
        public ShellPrompt(String name, CommandRegister register) {
                super(name, register, System.out, System.err, System.in);
        }
  
        /**
         * Same idea as the other constructor, however will construct a new
         * CommandRegister for use with the prompt.
         */
        public ShellPrompt(String name) {
                super(name, null, System.out, System.err, System.in);
        }
  }
  
  
  
  1.1                  
xml-xindice/java/scratchpad/admin/src/org/apache/xindice/admin/commandline/XindiceToolBuilder.java
  
  Index: XindiceToolBuilder.java
  ===================================================================
  package org.apache.xindice.admin.commandline;
  
  /**
   * Any Java package that is intended to be used with the cline package needs
   * to implement this interface and return an array of Commands that it would
   * like to use with the command prompt.
   *
   * @see BasePrompt#registerPackage(XindiceToolBuilder)
   */
  public interface XindiceToolBuilder {
        public Command[] getCommands();
        public void exit();
  }
  
  
  
  1.1                  
xml-xindice/java/scratchpad/admin/src/org/apache/xindice/admin/commandline/XindiceTools.java
  
  Index: XindiceTools.java
  ===================================================================
  package org.apache.xindice.admin.commandline;
  
  import org.apache.xindice.admin.commands.*;
  
  /**
   * Package containing all commands that will be automatically registered for
   * use with the command prompt. These include basic commands such as the 
   * HelpCommand, RunScriptCommand etc.
   */
  
  class XindiceTools implements XindiceToolBuilder {
  
        public Command[] getCommands() {
                Command[] commands = {
                        // Help,Dir and Time are util commands
              new HelpCommand(),
              new DirCommand(),
              new TimeCommand(),
              new GetConfigCommand(),
              new ListCommand(),
              new UseCommand(),
              new AddDocumentCommand(),
              new CreateCommand(),
              new QueryCommand(),
              new RunScriptCommand(),
              new ExitCommand()
                };
                return commands;
        }
  
        public void exit() {
        }
  }
  
  
  
  1.1                  
xml-xindice/java/scratchpad/admin/src/org/apache/xindice/admin/commands/AddDocumentCommand.java
  
  Index: AddDocumentCommand.java
  ===================================================================
  package org.apache.xindice.admin.commands;
  
  import java.util.Iterator;
  import java.util.Set;
  
  import org.apache.xindice.admin.commandline.BaseCommand;
  import org.apache.xindice.admin.commandline.Command;
  
  /**
   * This command is used to query information about any command that has
   * been registered with the prompt.
   */
  public class AddDocumentCommand extends BaseCommand {
  
        public AddDocumentCommand() {
                super("add", 1, "adds an XML document to the current 
collection");
        }
  
        public void execute(String args[]) {
                String document = args[0];
                prompt.out.println("Added document " + document);
  
        }
  
  }
  
  
  
  1.1                  
xml-xindice/java/scratchpad/admin/src/org/apache/xindice/admin/commands/CreateCommand.java
  
  Index: CreateCommand.java
  ===================================================================
  package org.apache.xindice.admin.commands;
  
  import java.util.Iterator;
  import java.util.Set;
  
  import org.apache.xindice.admin.commandline.BaseCommand;
  import org.apache.xindice.admin.commandline.Command;
  
  /**
   * This command is used to query information about any command that has
   * been registered with the prompt.
   */
  public class CreateCommand extends BaseCommand {
  
        public CreateCommand() {
                super("create", 1, "creates a new collection in the current 
collection");
        }
  
        public void execute(String args[]) {
                String collection = args[0];
                prompt.out.println("Created collection " + collection);
  
        }
  
  }
  
  
  
  1.1                  
xml-xindice/java/scratchpad/admin/src/org/apache/xindice/admin/commands/DirCommand.java
  
  Index: DirCommand.java
  ===================================================================
  package org.apache.xindice.admin.commands;
  
  import org.apache.xindice.admin.commandline.BaseCommand;
  
  import java.io.File;
  
  /**
   * Command to display the contents of the current working directory. 
   * Probably not available when running in an Applet.
   */
  public class DirCommand extends BaseCommand {
        
        public DirCommand() {
                super("ls", 0, 
                        "\n- lists the contents of the current working 
directory");
        }
  
        public void execute(String args[]) {
                try {
                        String dir = System.getProperty("user.dir");
                        File file = new File(dir);
                        String[] files = file.list();
                        for (int i=0; i<files.length; i++) {
                                prompt.out.println("\t"+files[i]);
                        }
                } catch (SecurityException e) {
                        prompt.err.println("System security exception: " + e);
                } catch (NullPointerException e) {
                        prompt.err.println("Null system property key: " + e);
                } catch (IllegalArgumentException e) {
                        prompt.err.println("Bad system property key: " + e);
                }
        }
  }
  
  
  
  1.1                  
xml-xindice/java/scratchpad/admin/src/org/apache/xindice/admin/commands/ExitCommand.java
  
  Index: ExitCommand.java
  ===================================================================
  package org.apache.xindice.admin.commands;
  
  import org.apache.xindice.admin.commandline.BaseCommand;
  
  /**
   * Command to exit the program. This command calls the prompt to exit the 
   * System and therefore requires special permissions - usually not available
   * when running in an Applet.
   */
  public class ExitCommand extends BaseCommand {
  
        public ExitCommand() {
                super("exit", 0,"\n- closes the prompt and any registered 
command packages");
        }
  
        public void execute(String args[]) {
          prompt.out.println("Goodbye");
                prompt.exit();
        }
  }
  
  
  
  1.1                  
xml-xindice/java/scratchpad/admin/src/org/apache/xindice/admin/commands/GetConfigCommand.java
  
  Index: GetConfigCommand.java
  ===================================================================
  package org.apache.xindice.admin.commands;
  
  import org.apache.xindice.admin.commandline.BaseCommand;
  import org.apache.xmlrpc.XmlRpc;
  import org.apache.xmlrpc.XmlRpcClient;
  import java.util.Hashtable;
  import java.util.Vector;
  import java.util.Date;
  
  /**
   * Simple command to prints out the current date/time.
   */
  public class GetConfigCommand extends BaseCommand {
  
        public GetConfigCommand() {
                super("info", 0,
                        "\n- prints out server version and server API version");
        }
  
      public static Hashtable run(Hashtable message) throws Exception {
          XmlRpc.setEncoding("UTF8");
          XmlRpc.setDriver("xerces");
          XmlRpcClient client = new 
XmlRpcClient("http://localhost:8080/Xindice";);
          Vector params = new Vector();
          params.addElement(message);
  
          return (Hashtable) client.execute("run", params);
     }
  
        public void execute(String args[]) {
  
                try {
                        String dir = System.getProperty("user.dir");
                        prompt.out.println("\n\tWorking directory: "+dir);
                } catch (SecurityException e) {
                        prompt.err.println("System security exception: " + e);
                } catch (NullPointerException e) {
                        prompt.err.println("Null system property key: " + e);
                } catch (IllegalArgumentException e) {
                        prompt.err.println("Bad system property key: " + e);
                }
  
          Hashtable message = new Hashtable();
          message.put("message", "GetServerVersion");
          Hashtable result = null;
          try {
              result = run(message);
          } catch(Exception e) {
  
          }
          prompt.out.println("\tServer Version: " + result.get("result"));
  
          message.clear();
          message.put("message", "GetApiVersion");
  
          try {
              result = run(message);
          } catch(Exception e) {
  
          }
          prompt.out.println("\tAPI Version: " + result.get("result"));
          prompt.out.println("\tCopyright 2002, Apache Software Foundation\n");
        }
  }
  
  
  
  1.1                  
xml-xindice/java/scratchpad/admin/src/org/apache/xindice/admin/commands/HelpCommand.java
  
  Index: HelpCommand.java
  ===================================================================
  package org.apache.xindice.admin.commands;
  
  import java.util.Iterator;
  import java.util.Set;
  
  import org.apache.xindice.admin.commandline.BaseCommand;
  import org.apache.xindice.admin.commandline.Command;
  
  /**
   * This command is used to query information about any command that has
   * been registered with the prompt.
   */
  public class HelpCommand extends BaseCommand {
  
        public HelpCommand() {
                super("help", 1, "command" +
                        "\n- prints out help information for a command");
        }
  
        public void execute(String args[]) {
                String topic = args[0];
                Command command = getRegister().getCommand(topic);
                if (command == null) {
                        prompt.out.println("No help available for " + topic);
                } else {
                        prompt.out.println(command.getHelp());
                }
        }
        
        /**
         * This method overloads the BaseCommand help function - the HelpCommand
         * is the only class where this makes sense.
         */
        public String getHelp() {
  
                String help = super.getHelp();
  
                // create a list of the command topics available
                help += "\n  Commands available are: ";
                
                Set keySet = getRegister().keySet();
                Iterator iterator = keySet.iterator();
                while (iterator.hasNext()) {
                        String commandName = (String)iterator.next();
                        help += "\n    " + commandName;
                }
                return help;
        }
  }
  
  
  
  1.1                  
xml-xindice/java/scratchpad/admin/src/org/apache/xindice/admin/commands/ListCommand.java
  
  Index: ListCommand.java
  ===================================================================
  package org.apache.xindice.admin.commands;
  
  import org.apache.xindice.admin.commandline.BaseCommand;
  import org.apache.xmlrpc.XmlRpc;
  import org.apache.xmlrpc.XmlRpcClient;
  import java.util.Hashtable;
  import java.util.Vector;
  import java.util.Date;
  
  /**
   * Simple command to prints out the current date/time.
   */
  public class ListCommand extends BaseCommand {
  
        public ListCommand() {
                super("list", 0, "\n- prints the current collection's 
structure.");
        }
  
        public void execute(String args[]) {
  
          XmlRpcClient client = null;
  
          try {
          XmlRpc.setEncoding("UTF8");
          XmlRpc.setDriver("xerces");
          } catch(Exception e) {
  
          }
  
          try {
          client = new XmlRpcClient("http://localhost:8080/Xindice";);
          } catch(Exception e) {
  
          }
  
          Hashtable message = new Hashtable();
          message.put("message", "ListCollections");
          message.put("collection", "/db");
          Hashtable result = null;
          Vector params = new Vector();
          params.addElement( message );
          try {
              result = (Hashtable) client.execute("run", params);
          } catch(Exception e) {
  
          }
          prompt.out.println("\t"+result.get("result"));
        }
  }
  
  
  
  1.1                  
xml-xindice/java/scratchpad/admin/src/org/apache/xindice/admin/commands/QueryCommand.java
  
  Index: QueryCommand.java
  ===================================================================
  package org.apache.xindice.admin.commands;
  
  import java.util.Iterator;
  import java.util.Set;
  
  import org.apache.xindice.admin.commandline.BaseCommand;
  import org.apache.xindice.admin.commandline.Command;
  
  /**
   * This command is used to query information about any command that has
   * been registered with the prompt.
   */
  public class QueryCommand extends BaseCommand {
  
        public QueryCommand() {
                super("query", 0, "executes an XPath or XUpdate query against a 
document or collection");
        }
  
        public void execute(String args[]) {
                //String collection = args[0];
                prompt.out.println("Query results...");
  
        }
  
  }
  
  
  
  1.1                  
xml-xindice/java/scratchpad/admin/src/org/apache/xindice/admin/commands/RunScriptCommand.java
  
  Index: RunScriptCommand.java
  ===================================================================
  package org.apache.xindice.admin.commands;
  
  import org.apache.xindice.admin.commandline.CommandException;
  
  import java.util.Iterator;
  import java.net.URL;
  import java.io.*;
  
  /**
   * This command reads in a text file (or URL) containing a list of commands.
   * It is basically a utility for batch executions. Each line of the file 
   * should contain a command to be executed. Comment lines can be inserted
   * by placing a '#' at the start of the line. By convention, I name all my 
   * scripts with a .scr ending (good old ms-dos syntax).
   */
  public class RunScriptCommand extends URLCommand {
  
        public RunScriptCommand() {
                super("exec", 1, "url" +
                        "\n- reads the specified url containing a list of 
commands");
        }
  
        public void execute(String args[]) {
                Iterator urls = getURLs(args);
                if (urls == null || ( ! urls.hasNext()) ) {
                        prompt.err.println("must specify valid script URL");
                        return;
                }
  
                URL url = (URL)urls.next();
                BufferedReader in = getBufferedReader(url);
                if (in == null) {
                        return;
                }
  
                String nextCommand = null;
                int lineNumber=0;
                try {
                        while ((nextCommand=in.readLine()) != null) {
                                lineNumber++;
                                if (nextCommand.equals("") || 
nextCommand.startsWith("#")) {
                                        continue;
                                }
                                try {
                                        register_.execute(nextCommand);
                                } catch (CommandException e) {
                                        prompt.err.println("while reading 
script file '" +
                                                url + "' on line " + 
lineNumber);
                                        prompt.err.println(e);
                                        return;
                                }
                        }
                        in.close();
                } catch (IOException e) {
                        prompt.err.println("IOException reading script from: " 
+ 
                                url);
                }
        }
  }
  
  
  
  1.1                  
xml-xindice/java/scratchpad/admin/src/org/apache/xindice/admin/commands/TimeCommand.java
  
  Index: TimeCommand.java
  ===================================================================
  package org.apache.xindice.admin.commands;
  
  import org.apache.xindice.admin.commandline.BaseCommand;
  
  import java.util.Date;
  
  /**
   * Simple command to prints out the current date/time.
   */
  public class TimeCommand extends BaseCommand {
  
        public TimeCommand() {
                super("time", 0,
                        "\n- prints out the current date and time");
        }
  
        public void execute(String args[]) {
                prompt.out.println("Current time is: " + (new 
Date()).toString());
        }
  }
  
  
  
  1.1                  
xml-xindice/java/scratchpad/admin/src/org/apache/xindice/admin/commands/URLCommand.java
  
  Index: URLCommand.java
  ===================================================================
  package org.apache.xindice.admin.commands;
  
  import org.apache.xindice.admin.utility.URLUtils;
  import org.apache.xindice.admin.commandline.BaseCommand;
  
  import java.util.Iterator;
  import java.util.Vector;
  import java.net.URL;
  import java.io.*;
  
  /**
   * Any command that loads a URL (eg. file) for input should extend this 
   * command. It basically checks that the Strings representing the URLs
   * are valid and returns URL instances as an enumeration (takes some of
   * the pain out of creating URLs). It is used by the RunScriptCommand.
   *
   * @see RunScriptCommand
   */
  public abstract class URLCommand extends BaseCommand {
  
        protected URLCommand(String name, int numArgs, String help) {
                super(name, numArgs, help);
        }
        
        public Iterator getURLs(String args[]) {
                Vector urls = new Vector(args.length);
  
                // build the URL
                for (int i=0; i<args.length; i++) {
                        URL url = URLUtils.createURL(args[i]);
                        if (url != null) {
                                urls.add(url);
                        }
                }
                return urls.iterator();
        }
        
        /**
         * Utility method
         */
        public BufferedReader getBufferedReader(URL url) {
                BufferedReader reader = null;
                try {
                        reader = new BufferedReader(
                                new InputStreamReader(url.openStream()));
                } catch (IOException e) {
                        prompt.err.println("error opening url: " + url);
                }
                return reader;
        }
  }
  
  
  
  1.1                  
xml-xindice/java/scratchpad/admin/src/org/apache/xindice/admin/commands/UseCommand.java
  
  Index: UseCommand.java
  ===================================================================
  package org.apache.xindice.admin.commands;
  
  import java.util.Iterator;
  import java.util.Set;
  
  import org.apache.xindice.admin.commandline.BaseCommand;
  import org.apache.xindice.admin.commandline.Command;
  
  /**
   * This command is used to query information about any command that has
   * been registered with the prompt.
   */
  public class UseCommand extends BaseCommand {
  
        public UseCommand() {
                super("use", 1, "command sets the current database collection");
        }
  
        public void execute(String args[]) {
                String collection = args[0];
                prompt.out.println("Collection changed to "+ collection);
  
        }
  
  }
  
  
  
  1.1                  
xml-xindice/java/scratchpad/admin/src/org/apache/xindice/admin/utility/URLUtils.java
  
  Index: URLUtils.java
  ===================================================================
  package org.apache.xindice.admin.utility;
  
  import java.io.File;
  import java.net.URL;
  import java.net.MalformedURLException;
  
  public class URLUtils {
  
        public static final boolean isURLString(String string) {
                if (string.indexOf("://") != -1) {
                        return true;
                } else if (     string.indexOf("/") != -1 ||
                                        string.indexOf("\\") != -1 ) {
  
                        // this might be a file, this is expensive but we need 
to try
                        URL test = createURL(string);
                        if (test != null) {
                                return true;
                        }
                }
                return false;
        }
  
        public static final URL createURL(String name) {
                // try and determine if this string is a full URL or just a 
                // partial file name (default protocol if "protocol://" is not 
                // prepended to the string)
                URL url = null;
                if (name.indexOf("://") != -1) {
                        try {
                                url = new URL(name);
                        } catch (MalformedURLException e) {
                                System.err.println("Could not create URL from 
'" +
                                        name + "'");
                                return null;
                        }
                } else {
                        // else we default to the file protocol
                        File file = new File(name);
                        try {
                                url = file.toURL();
                        } catch (MalformedURLException e) {
                                // if the command has mixed fileName and 
integer (or non-file
                                // name) arguments, we might be trying to 
create a URL for
                                // an integer argument - just skip this name 
and return null
                                // System.err.println(
                                //      "URL path '" + name + "' is not valid: 
" + e);
                                return null;
                        }
                }
                return url;
        }
  }
  
  
  

Reply via email to