KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > cjdbc > console > text > module > AbstractConsoleModule


1 /**
2  * C-JDBC: Clustered JDBC.
3  * Copyright (C) 2002-2004 French National Institute For Research In Computer
4  * Science And Control (INRIA).
5  * Contact: c-jdbc@objectweb.org
6  *
7  * This library is free software; you can redistribute it and/or modify it
8  * under the terms of the GNU Lesser General Public License as published by the
9  * Free Software Foundation; either version 2.1 of the License, or any later
10  * version.
11  *
12  * This library is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
15  * for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public License
18  * along with this library; if not, write to the Free Software Foundation,
19  * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
20  *
21  * Initial developer(s): Nicolas Modrzyk.
22  * Contributor(s): Mathieu Peltier.
23  */

24
25 package org.objectweb.cjdbc.console.text.module;
26
27 import java.util.Arrays JavaDoc;
28 import java.util.Hashtable JavaDoc;
29 import java.util.Iterator JavaDoc;
30 import java.util.LinkedList JavaDoc;
31 import java.util.List JavaDoc;
32 import java.util.Map JavaDoc;
33 import java.util.StringTokenizer JavaDoc;
34 import java.util.TreeSet JavaDoc;
35 import java.util.prefs.Preferences JavaDoc;
36
37 import jline.ArgumentCompletor;
38 import jline.Completor;
39 import jline.FileNameCompletor;
40 import jline.SimpleCompletor;
41
42 import org.objectweb.cjdbc.common.i18n.ConsoleTranslate;
43 import org.objectweb.cjdbc.console.text.Console;
44 import org.objectweb.cjdbc.console.text.commands.ConsoleCommand;
45 import org.objectweb.cjdbc.console.text.commands.Help;
46 import org.objectweb.cjdbc.console.text.commands.History;
47 import org.objectweb.cjdbc.console.text.commands.Quit;
48
49 /**
50  * This class defines a AbstractConsoleModule
51  *
52  * @author <a HREF="mailto:Nicolas.Modrzyk@inria.fr">Nicolas Modrzyk </a>
53  * @author <a HREF="mailto:Mathieu.Peltier@inrialpes.fr">Mathieu Peltier </a>
54  * @version 1.0
55  */

56 public abstract class AbstractConsoleModule
57 {
58   private static final int HISTORY_MAX = 10;
59
60   Console console;
61
62   TreeSet JavaDoc commands;
63
64   boolean quit = false;
65
66   LinkedList JavaDoc history;
67
68   protected Completor consoleCompletor;
69
70   /**
71    * Creates a new <code>AbstractConsoleModule.java</code> object
72    *
73    * @param console to refer from
74    */

75   public AbstractConsoleModule(Console console)
76   {
77     this.console = console;
78     this.commands = new TreeSet JavaDoc();
79     this.history = new LinkedList JavaDoc();
80     commands.add(new Help(this));
81     commands.add(new History(this));
82     commands.add(new Quit(this));
83     if (console.isInteractive())
84       console.println(ConsoleTranslate.get("module.loading",
85           getDescriptionString()));
86     this.loadCommands();
87     this.loadCompletor();
88   }
89
90   /**
91    * Loads the commands for this module
92    */

93   protected abstract void loadCommands();
94
95   /**
96    * Loads the commands for this module
97    */

98   protected void loadCompletor()
99   {
100     List JavaDoc completors = new LinkedList JavaDoc();
101     int size = commands.size();
102     if (size > 0)
103     {
104       TreeSet JavaDoc set = new TreeSet JavaDoc();
105       Iterator JavaDoc it = commands.iterator();
106       while (it.hasNext())
107       {
108         set.add(((ConsoleCommand) it.next()).getCommandName());
109       }
110       completors.add(new SimpleCompletor((String JavaDoc[]) set
111           .toArray(new String JavaDoc[size])));
112     }
113     completors.add(new FileNameCompletor());
114
115     Completor[] completorsArray = (Completor[]) completors
116         .toArray(new Completor[completors.size()]);
117     consoleCompletor = new ArgumentCompletor(completorsArray,
118         new CommandDelimiter());
119   }
120
121   /**
122    * Reload the completor associated with this module. This method must be
123    * called if the list of commands has been dynamically modified.
124    */

125   protected synchronized void reloadCompletor()
126   {
127     console.getConsoleReader().removeCompletor(consoleCompletor);
128     loadCompletor();
129     console.getConsoleReader().addCompletor(consoleCompletor);
130   }
131
132   /**
133    * Text description of this module
134    *
135    * @return <code>String</code> description to display
136    */

137   public abstract String JavaDoc getDescriptionString();
138
139   /**
140    * Display help for this module
141    */

142   public void help()
143   {
144     console.println(ConsoleTranslate.get("module.commands.available",
145         getDescriptionString()));
146     ConsoleCommand command;
147     Iterator JavaDoc it = commands.iterator();
148     while (it.hasNext())
149     {
150       command = (ConsoleCommand) it.next();
151       console.printInfo(command.getCommandName() + " "
152           + command.getCommandParameters());
153       console.println(" " + command.getCommandDescription());
154     }
155   }
156
157   /**
158    * Quit this module
159    */

160   public void quit()
161   {
162     quit = true;
163     storeHistory();
164     console.getConsoleReader().removeCompletor(getCompletor());
165     console.getConsoleReader().addCompletor(
166         console.getControllerModule().getCompletor());
167   }
168
169   /**
170    * Load History from java Preferences
171    */

172   protected void loadHistory()
173   {
174     try
175     {
176       Preferences JavaDoc prefs = Preferences.userRoot()
177           .node(this.getClass().getName());
178       String JavaDoc[] historyKeys = prefs.keys();
179       Arrays.sort(historyKeys, 0, historyKeys.length);
180       for (int i = 0; i < historyKeys.length; i++)
181       {
182         String JavaDoc key = historyKeys[i];
183         String JavaDoc value = prefs.get(key, "");
184         manageHistory(value);
185       }
186     }
187     catch (Exception JavaDoc e)
188     {
189       // unable to load prefs: do nothing
190
}
191   }
192
193   /**
194    * Strore History to java Preferences
195    */

196   protected void storeHistory()
197   {
198     try
199     {
200       Preferences JavaDoc prefs = Preferences.userRoot()
201           .node(this.getClass().getName());
202       prefs.clear();
203       for (int i = 0; i < history.size(); i++)
204       {
205         prefs.put(String.valueOf(i), (String JavaDoc) history.get(i));
206       }
207       prefs.flush();
208     }
209     catch (Exception JavaDoc e)
210     {
211       // unable to store prefs: do nothing
212
}
213   }
214
215   /**
216    * Get all the commands for this module
217    *
218    * @return <code>TreeSet</code> of commands (commandName|commandObject)
219    */

220   public TreeSet JavaDoc getCommands()
221   {
222     return commands;
223   }
224
225   /**
226    * Get the prompt string for this module
227    *
228    * @return <code>String</code> to place before prompt
229    */

230   public abstract String JavaDoc getPromptString();
231
232   /**
233    * Handle a serie of commands
234    */

235   public void handlePrompt()
236   {
237
238     loadHistory();
239     
240     if (quit)
241     {
242       if (console.isInteractive())
243         console.printError(ConsoleTranslate.get("module.quitting",
244             getDescriptionString()));
245       return;
246     }
247
248     // login();
249
quit = false;
250     while (!quit)
251     {
252       
253       Hashtable JavaDoc hashCommands = getHashCommands();
254       try
255       {
256         String JavaDoc commandLine = console.readLine(getPromptString());
257         if (commandLine == null)
258         {
259           quit = true;
260           break;
261         }
262         if (commandLine.equals(""))
263           continue;
264         else
265           manageHistory(commandLine);
266
267         handleCommandLine(commandLine, hashCommands);
268
269       }
270       catch (Exception JavaDoc e)
271       {
272         console.printError(ConsoleTranslate.get("module.command.got.error",
273             new Object JavaDoc[]{e.getClass(), e.getMessage()}), e);
274       }
275     }
276   }
277
278   /**
279    * Get the list of commands as strings for this module
280    *
281    * @return <code>Hashtable</code> list of <code>String</code> objects
282    */

283   public final Hashtable JavaDoc getHashCommands()
284   {
285     Hashtable JavaDoc hashCommands = new Hashtable JavaDoc();
286     ConsoleCommand consoleCommand;
287     Iterator JavaDoc it = commands.iterator();
288     while (it.hasNext())
289     {
290       consoleCommand = (ConsoleCommand) it.next();
291       hashCommands.put(consoleCommand.getCommandName(), consoleCommand);
292     }
293     return hashCommands;
294   }
295
296   /**
297    * Handle module command
298    *
299    * @param commandLine the command line to handle
300    * @param hashCommands the list of commands available for this module
301    * @throws Exception if fails *
302    */

303   public final void handleCommandLine(String JavaDoc commandLine, Hashtable JavaDoc hashCommands)
304       throws Exception JavaDoc
305   {
306     StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(commandLine);
307     if (!st.hasMoreTokens())
308     {
309       console.printError(ConsoleTranslate.get("module.command.not.supported",
310           ""));
311       return;
312     }
313
314     ConsoleCommand consoleCommand = findConsoleCommand(commandLine,
315         hashCommands);
316     if (consoleCommand == null)
317     {
318       console.printError(ConsoleTranslate.get("module.command.not.supported",
319           commandLine));
320     }
321     else
322     {
323       consoleCommand.execute(commandLine.substring(consoleCommand
324           .getCommandName().length()));
325     }
326   }
327
328   /**
329    * Find the <code>ConsoleCommand</code> based on the name of the command
330    * from the <code>commandLine</code> in the <code>hashCommands</code>.
331    *
332    * If more than one <code>ConsoleCommand</code>'s command name start the
333    * same way, return the <code>ConsoleCommand</code> with the longest one.
334    *
335    * @param commandLine the command line to handle
336    * @param hashCommands the list of commands available for this module
337    * @return the <code>ConsoleCommand</code> corresponding to the name of the
338    * command from the <code>commandLine</code> or <code>null</code>
339    * if there is no matching
340    */

341   public ConsoleCommand findConsoleCommand(String JavaDoc commandLine,
342       Hashtable JavaDoc hashCommands)
343   {
344     ConsoleCommand foundCommand = null;
345     for (Iterator JavaDoc iter = hashCommands.entrySet().iterator(); iter.hasNext();)
346     {
347       Map.Entry JavaDoc commandEntry = (Map.Entry JavaDoc) iter.next();
348       String JavaDoc commandName = (String JavaDoc) commandEntry.getKey();
349       if (commandLine.startsWith(commandName))
350       {
351         ConsoleCommand command = (ConsoleCommand) commandEntry.getValue();
352         if (foundCommand == null)
353         {
354           foundCommand = command;
355         }
356         if (command.getCommandName().length() > foundCommand.getCommandName().length())
357         {
358           foundCommand = command;
359         }
360       }
361     }
362     return foundCommand;
363   }
364
365   /**
366    * Add the command to the history. Removes the first item in the list if the
367    * history is too large.
368    *
369    * @param command taken from the command line
370    */

371   public final void manageHistory(String JavaDoc command)
372   {
373     history.add(command);
374     if (history.size() > HISTORY_MAX)
375       history.removeFirst();
376   }
377
378   /**
379    * Handles login in this module
380    *
381    * @param params parameters to use to login in this module
382    * @throws Exception if fails
383    */

384   public abstract void login(String JavaDoc[] params) throws Exception JavaDoc;
385
386   /**
387    * Get access to the console
388    *
389    * @return <code>Console</code> instance
390    */

391   public Console getConsole()
392   {
393     return console;
394   }
395
396   /**
397    * Returns the history value.
398    *
399    * @return Returns the history.
400    */

401   public LinkedList JavaDoc getHistory()
402   {
403     return history;
404   }
405
406   /**
407    * Returns the console completor to use for this module.
408    *
409    * @return <code>Completor</code> object.
410    */

411   public Completor getCompletor()
412   {
413     return consoleCompletor;
414   }
415
416   /**
417    * This class defines a CommandDelimiter used to delimit a command from user
418    * input
419    */

420   class CommandDelimiter extends ArgumentCompletor.AbstractArgumentDelimiter
421   {
422     /**
423      * @see jline.ArgumentCompletor$AbstractArgumentDelimiter#isDelimiterChar(java.lang.String,
424      * int)
425      */

426     public boolean isDelimiterChar(String JavaDoc buffer, int pos)
427     {
428       String JavaDoc tentativeCmd = buffer.substring(0, pos);
429       return isACompleteCommand(tentativeCmd);
430     }
431
432     /**
433      * Test if the String input by the user insofar is a complete command or
434      * not.
435      *
436      * @param input Text input by the user
437      * @return <code>true</code> if the text input by the user is a complete
438      * command name, <code>false</code> else
439      */

440     private boolean isACompleteCommand(String JavaDoc input)
441     {
442       boolean foundCompleteCommand = false;
443       for (Iterator JavaDoc iter = commands.iterator(); iter.hasNext();)
444       {
445         ConsoleCommand command = (ConsoleCommand) iter.next();
446         if (input.equals(command.getCommandName()))
447         {
448           foundCompleteCommand = !otherCommandsStartWith(command
449               .getCommandName());
450         }
451       }
452       return foundCompleteCommand;
453     }
454
455     private boolean otherCommandsStartWith(String JavaDoc commandName)
456     {
457       for (Iterator JavaDoc iter = commands.iterator(); iter.hasNext();)
458       {
459         ConsoleCommand command = (ConsoleCommand) iter.next();
460         if (command.getCommandName().startsWith(commandName)
461             && !command.getCommandName().equals(commandName))
462         {
463           return true;
464         }
465       }
466       return false;
467     };
468   };
469 }
Popular Tags