KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > continuent > sequoia > console > text > Console


1 /**
2  * Sequoia: Database clustering technology.
3  * Copyright (C) 2002-2004 French National Institute For Research In Computer
4  * Science And Control (INRIA).
5  * Contact: sequoia@continuent.org
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  * Initial developer(s): Emmanuel Cecchet.
20  * Contributor(s): Mathieu Peltier,Nicolas Modrzyk
21  */

22
23 package org.continuent.sequoia.console.text;
24
25 import java.io.IOException JavaDoc;
26 import java.io.InputStream JavaDoc;
27 import java.io.PrintWriter JavaDoc;
28 import java.util.Arrays JavaDoc;
29 import java.util.List JavaDoc;
30 import java.util.prefs.Preferences JavaDoc;
31
32 import jline.ConsoleReader;
33 import jline.History;
34
35 import org.continuent.sequoia.common.i18n.ConsoleTranslate;
36 import org.continuent.sequoia.console.jmx.RmiJmxClient;
37 import org.continuent.sequoia.console.text.module.ControllerConsole;
38 import org.continuent.sequoia.console.text.module.VirtualDatabaseAdmin;
39 import org.continuent.sequoia.console.text.module.VirtualDatabaseConsole;
40
41 /**
42  * This is the Sequoia controller console that allows remote administration and
43  * monitoring of any Sequoia controller.
44  *
45  * @author <a HREF="mailto:Emmanuel.Cecchet@inria.fr">Emmanuel Cecchet </a>
46  * @author <a HREF="mailto:Mathieu.Peltier@inrialpes.fr">Mathieu Peltier </a>
47  * @author <a HREF="mailto:Nicolas.Modrzyk@inrialpes.fr">Nicolas Modrzyk </a>
48  * @version 1.0
49  */

50 public class Console
51 {
52   private static final Character JavaDoc PASSWORD_CHAR = new Character JavaDoc('\u0000');
53
54   /** <code>ConsoleReader</code> allowing to reading input. */
55   private ConsoleReader consoleReader;
56
57   /** <code>true</code> if the console is used in interactive mode. */
58   private boolean interactive;
59
60   private RmiJmxClient jmxClient;
61
62   /** Virtual database administration console. */
63   private VirtualDatabaseAdmin adminModule;
64
65   /** Virtual database console. */
66   private VirtualDatabaseConsole consoleModule;
67
68   /** Controller Console */
69   private ControllerConsole controllerModule;
70
71   /** Debug Mode */
72   private boolean debug;
73   private boolean silent = false;
74
75   private boolean exitOnError;
76
77   /**
78    * The number of history items to store in java Preferences file
79    */

80   private static final int STORED_HISTORY_SIZE = 100;
81
82   /**
83    * <code>true</code> if colors should be displayed in interactive mode (work
84    * only on non Windows system).
85    */

86   private boolean printColor;
87
88   private boolean sqlClientOnly;
89
90   /**
91    * Creates a new <code>Console</code> instance.
92    *
93    * @param jmxClient to connect to the jmxServer
94    * @param in the input stream to get the command from
95    * @param interactive if set to <code>true</code> will display prompt
96    * @param debug <code>true</code> if debug mode should be activated.
97    * @param silent <code>true</code> if silent mode is activated
98    * @param exitOnError <code>true</code> if the console should exit on error
99    * in non interactive mode.
100    * @param sqlClientOnly set to <code>true</code> if the console should
101    * behave as a sql client only
102    */

103   public Console(RmiJmxClient jmxClient, InputStream JavaDoc in, boolean interactive,
104       boolean debug, boolean silent, boolean exitOnError, boolean sqlClientOnly)
105   {
106     try
107     {
108       consoleReader = new ConsoleReader(in, new PrintWriter JavaDoc(System.out));
109     }
110     catch (IOException JavaDoc e)
111     {
112       System.err.println("Unable to create console: " + e.toString());
113     }
114     this.interactive = interactive;
115     this.jmxClient = jmxClient;
116     this.debug = debug;
117     this.silent = silent;
118     this.exitOnError = exitOnError;
119     this.sqlClientOnly = sqlClientOnly;
120
121     controllerModule = new ControllerConsole(this);
122     adminModule = new VirtualDatabaseAdmin(this);
123     consoleModule = new VirtualDatabaseConsole(this);
124     setPrintColor(true);
125     consoleReader.addCompletor(controllerModule.getCompletor());
126     consoleReader.setHistory(loadHistory());
127
128     Runtime.getRuntime().addShutdownHook(new Thread JavaDoc()
129     {
130       public void run()
131       {
132         storeHistory();
133       }
134     });
135   }
136
137   private History loadHistory()
138   {
139     jline.History jHistory = new jline.History();
140     try
141     {
142       Preferences JavaDoc prefs = Preferences.userRoot()
143           .node(this.getClass().getName());
144       String JavaDoc[] historyKeys = prefs.keys();
145       Arrays.sort(historyKeys, 0, historyKeys.length);
146       for (int i = 0; i < historyKeys.length; i++)
147       {
148         String JavaDoc key = historyKeys[i];
149         String JavaDoc value = prefs.get(key, ""); //$NON-NLS-1$
150
jHistory.addToHistory(value);
151       }
152     }
153     catch (Exception JavaDoc e)
154     {
155       // unable to load prefs: do nothing
156
}
157     return jHistory;
158   }
159
160   /**
161    * Retrieve the command history
162    *
163    * @return a List including the command history
164    */

165   public List JavaDoc getHistory()
166   {
167     return consoleReader.getHistory().getHistoryList();
168   }
169
170   /**
171    * Store the current command history
172    */

173   public void storeHistory()
174   {
175     List JavaDoc history = consoleReader.getHistory().getHistoryList();
176     try
177     {
178       Preferences JavaDoc prefs = Preferences.userRoot()
179           .node(this.getClass().getName());
180       prefs.clear();
181       int historySize = history.size();
182       int start = Math.max(0, historySize - STORED_HISTORY_SIZE);
183       // save up to the last 100th history items only
184
// witht the stored index starting at 0
185
for (int i = start; i < historySize; i++)
186       {
187         prefs.put(String.valueOf(i -start), (String JavaDoc) history.get(i + start));
188       }
189       prefs.flush();
190     }
191     catch (Exception JavaDoc e)
192     {
193       // unable to store prefs: do nothing
194
}
195   }
196
197   /**
198    * Should this console display color in interactive mode? Warning, colors only
199    * work on non Windows system.
200    *
201    * @param b <code>true</code> if the console should display color (ignored
202    * on Windows system).
203    */

204   public void setPrintColor(boolean b)
205   {
206     String JavaDoc os = System.getProperty("os.name").toLowerCase();
207     boolean windows = os.indexOf("nt") > -1 || os.indexOf("windows") > -1;
208     if (windows)
209       printColor = false;
210     else
211       printColor = b;
212
213     if (System.getProperty("sequoia.console.nocolor") != null)
214       printColor = false;
215   }
216
217   /**
218    * Returns the interactive value.
219    *
220    * @return Returns the interactive.
221    */

222   public boolean isInteractive()
223   {
224     return interactive;
225   }
226
227   /**
228    * Test if the console should exit on error in non interactive mode.
229    *
230    * @return <code>true</code> if the console should exit on error in non
231    * interactive mode.
232    */

233   public boolean isExitOnError()
234   {
235     return exitOnError;
236   }
237
238   /**
239    * Main menu prompt handling.
240    */

241   public void handlePrompt() throws Exception JavaDoc
242   {
243         if (sqlClientOnly)
244           sqlClientConsole();
245     else
246           controllerModule.handlePrompt();
247   }
248
249   private void sqlClientConsole()
250   {
251       try
252       {
253           consoleModule.login(new String JavaDoc[] { "" });
254       }
255       catch (Exception JavaDoc e)
256       {
257           printError(ConsoleTranslate.get("module.command.got.error", e
258                   .getMessage()), e);
259           System.exit(1);
260       }
261       consoleModule.handlePrompt();
262   }
263
264   /**
265    * Reads a line from the console.
266    *
267    * @param prompt the prompt to display
268    * @return the trimmed line read from the console
269    * @throws ConsoleException if an error occured
270    */

271   public String JavaDoc readLine(String JavaDoc prompt) throws ConsoleException
272   {
273     String JavaDoc line = "";
274     try
275     {
276       if (interactive)
277       {
278         prompt += " > ";
279         if (printColor)
280         {
281           prompt = ColorPrinter.getColoredMessage(prompt, ColorPrinter.PROMPT);
282         }
283         line = consoleReader.readLine(prompt);
284       }
285       else
286       {
287         line = consoleReader.readLine();
288       }
289     }
290     catch (IOException JavaDoc e)
291     {
292       throw new ConsoleException(ConsoleTranslate.get(
293           "console.read.command.failed", e));
294     }
295     if (line != null)
296       line = line.trim();
297     return line;
298   }
299
300   /**
301    * Read password from the console.
302    *
303    * @param prompt the promp to display
304    * @return the password read from the console
305    * @throws ConsoleException if an error occured
306    */

307   public String JavaDoc readPassword(String JavaDoc prompt) throws ConsoleException
308   {
309     String JavaDoc password;
310     try
311     {
312       if (interactive)
313       {
314         prompt += " > ";
315         if (printColor)
316         {
317           prompt = ColorPrinter.getColoredMessage(prompt, ColorPrinter.PROMPT);
318         }
319         password = consoleReader.readLine(prompt, PASSWORD_CHAR);
320       }
321       else
322       {
323         password = consoleReader.readLine(PASSWORD_CHAR);
324       }
325     }
326     catch (IOException JavaDoc e)
327     {
328       throw new ConsoleException(ConsoleTranslate.get(
329           "console.read.password.failed", e));
330     }
331     return password;
332   }
333
334   /**
335    * Prints a String on the console. Use this method to print <em>things</em>
336    * returned by Sequoia controller.
337    *
338    * @param s the String to print
339    */

340   public void print(String JavaDoc s)
341   {
342     System.out.print(s);
343   }
344
345   /**
346    * Prints a String on the console.<br />
347    * Use this method to print <em>things</em> returned by Sequoia controller.
348    *
349    * @param s the String to print
350    */

351   public void println(String JavaDoc s)
352   {
353     System.out.println(s);
354   }
355
356   /**
357    * Print in color
358    *
359    * @param s the message to display
360    * @param color the color to use
361    */

362   private void println(String JavaDoc s, int color)
363   {
364     if (printColor)
365       ColorPrinter.printMessage(s, System.out, color);
366     else
367       System.out.println(s);
368   }
369
370   /**
371    * Prints a new line.
372    */

373   public void println()
374   {
375     System.out.println();
376   }
377
378   /**
379    * Prints an error message.<br />
380    * Use this method to print <em>error</em> messages coming either from
381    * Sequoia controller or from the console.
382    *
383    * @param message error message to print
384    */

385   public void printError(String JavaDoc message)
386   {
387     if (printColor)
388       ColorPrinter.printMessage(message, System.err, ColorPrinter.ERROR);
389     else
390       System.err.println(message);
391   }
392
393   /**
394    * Prints an info message.<br />
395    * Use this method to print <em>info</em> messages coming from the console.
396    * An info message should not contain essential information that the user
397    * can't deduce from the commands he/she typed.
398    *
399    * @param message informational message to print
400    */

401   public void printInfo(String JavaDoc message)
402   {
403     if (!silent)
404     {
405       println(message, ColorPrinter.INFO);
406     }
407   }
408
409   /**
410    * Prints an error message (and displays the stack trace of an Exception if
411    * the debug option is active).<br />
412    * Use this method to print <em>error</em> messages coming either from
413    * Sequoia controller or from the console.
414    *
415    * @param message error message to print
416    * @param e an exception
417    */

418   public void printError(String JavaDoc message, Exception JavaDoc e)
419   {
420     if (debug)
421       e.printStackTrace();
422     printError(message);
423   }
424
425   /**
426    * Returns the jmxClient value.
427    *
428    * @return Returns the jmxClient.
429    */

430   public RmiJmxClient getJmxClient()
431   {
432     return jmxClient;
433   }
434
435   /**
436    * Sets a new JmxClient (used when console started without being connected).
437    *
438    * @param jmxClient the new JMX client to use
439    */

440   public void setJmxClient(RmiJmxClient jmxClient)
441   {
442     this.jmxClient = jmxClient;
443   }
444
445   /**
446    * Returns the adminModule value.
447    *
448    * @return Returns the adminModule.
449    */

450   public VirtualDatabaseAdmin getAdminModule()
451   {
452     return adminModule;
453   }
454
455   /**
456    * Returns the consoleModule value.
457    *
458    * @return Returns the consoleModule.
459    */

460   public VirtualDatabaseConsole getConsoleModule()
461   {
462     return consoleModule;
463   }
464
465   /**
466    * Returns the controllerModule value.
467    *
468    * @return Returns the controllerModule.
469    */

470   public ControllerConsole getControllerModule()
471   {
472     return controllerModule;
473   }
474
475   /**
476    * Returns the consoleReader value.
477    *
478    * @return Returns the consoleReader.
479    */

480   public final ConsoleReader getConsoleReader()
481   {
482     return consoleReader;
483   }
484
485   /**
486    * (ugly!) pass-through setter to set the request delimiter on the
487    * VirtualDatabaseConsole from the command line options of the console
488    *
489    * @param delimiter the String representing the request delimiter
490    * @see VirtualDatabaseConsole#setRequestDelimiter(String)
491    */

492   public void setRequestDelimiter(String JavaDoc delimiter)
493   {
494     consoleModule.setRequestDelimiter(delimiter);
495   }
496
497   /**
498    * (ugly!) pass-through setter to enable/disabled multiline statement on the
499    * VirtualDatabaseConsole from the command line options of the console
500    *
501    * @param multilineStatementEnabled <code>true</code> if multiline stamement
502    * is enabled, <code>false</code> else
503    * @see VirtualDatabaseConsole#setRequestDelimiter(String)
504    */

505   public void enableMultilineStatements(boolean multilineStatementEnabled)
506   {
507     consoleModule.enableMultilineStatement(multilineStatementEnabled);
508   }
509 }
510
Popular Tags