KickJava   Java API By Example, From Geeks To Geeks.

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


1 /**
2  * C-JDBC: Clustered JDBC.
3  * Copyright (C) 2002-2005 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): Emmanuel Cecchet.
22  * Contributor(s): Mathieu Peltier, Nicolas Modrzyk.
23  */

24
25 package org.objectweb.cjdbc.console.text.module;
26
27 import java.sql.Connection JavaDoc;
28 import java.sql.DriverManager JavaDoc;
29 import java.sql.PreparedStatement JavaDoc;
30 import java.sql.ResultSet JavaDoc;
31 import java.sql.SQLException JavaDoc;
32 import java.sql.Savepoint JavaDoc;
33 import java.util.Hashtable JavaDoc;
34
35 import org.objectweb.cjdbc.common.i18n.ConsoleTranslate;
36 import org.objectweb.cjdbc.common.util.Constants;
37 import org.objectweb.cjdbc.console.text.Console;
38 import org.objectweb.cjdbc.console.text.ConsoleException;
39 import org.objectweb.cjdbc.console.text.commands.ConsoleCommand;
40 import org.objectweb.cjdbc.console.text.commands.Help;
41 import org.objectweb.cjdbc.console.text.commands.History;
42 import org.objectweb.cjdbc.console.text.commands.Quit;
43 import org.objectweb.cjdbc.console.text.commands.sqlconsole.Begin;
44 import org.objectweb.cjdbc.console.text.commands.sqlconsole.CallStoredProcedure;
45 import org.objectweb.cjdbc.console.text.commands.sqlconsole.Commit;
46 import org.objectweb.cjdbc.console.text.commands.sqlconsole.Load;
47 import org.objectweb.cjdbc.console.text.commands.sqlconsole.Rollback;
48 import org.objectweb.cjdbc.console.text.commands.sqlconsole.SetFetchSize;
49 import org.objectweb.cjdbc.console.text.commands.sqlconsole.SetIsolation;
50 import org.objectweb.cjdbc.console.text.commands.sqlconsole.SetMaxRows;
51 import org.objectweb.cjdbc.console.text.commands.sqlconsole.SetSavePoint;
52 import org.objectweb.cjdbc.console.text.commands.sqlconsole.SetTimeout;
53 import org.objectweb.cjdbc.console.text.commands.sqlconsole.ShowTables;
54 import org.objectweb.cjdbc.console.text.formatter.ResultSetFormatter;
55
56 /**
57  * C-JDBC Controller Virtual Database Console module.
58  *
59  * @author <a HREF="mailto:Emmanuel.Cecchet@inria.fr">Emmanuel Cecchet </a>
60  * @author <a HREF="mailto:Mathieu.Peltier@inrialpes.fr">Mathieu Peltier </a>
61  * @author <a HREF="mailto:Nicolas.Modrzyk@inrialpes.fr">Nicolas Modrzyk </a>
62  * @version 1.0
63  */

64 public class VirtualDatabaseConsole extends AbstractConsoleModule
65 {
66   private Connection JavaDoc connection = null;
67   /** contains a hash of <String, SavePoint>
68    * to handle savepoints (used by SetSavePoint and Rollback
69    * commands)
70    */

71   private Hashtable JavaDoc savePoints = new Hashtable JavaDoc();
72
73   /** Default query timeout. */
74   private int timeout = 60;
75
76   private int fetchsize = 0;
77
78   private int maxrows = 0;
79
80   private String JavaDoc login;
81   private String JavaDoc url;
82
83   /**
84    * Creates a new <code>VirtualDatabaseAdmin</code> instance. Loads the
85    * driver
86    *
87    * @param console console console
88    */

89   public VirtualDatabaseConsole(Console console)
90   {
91     super(console);
92     try
93     {
94       Class.forName("org.objectweb.cjdbc.driver.Driver");
95     }
96     catch (Exception JavaDoc e)
97     {
98       console.printError(ConsoleTranslate
99           .get("sql.login.cannot.load.driver", e), e);
100       Runtime.getRuntime().exit(1);
101     }
102     if (console.isInteractive())
103       console.println(ConsoleTranslate.get("sql.login.loaded.driver",
104           Constants.VERSION));
105   }
106
107   /**
108    * Get the JDBC connection used by the sql console.
109    *
110    * @return a JDBC connection
111    */

112   public Connection JavaDoc getConnection()
113   {
114     return connection;
115   }
116
117   /**
118    * Create a new connection from the driver.
119    *
120    * @param url the C-JDBC url
121    * @param login the login to use to open the connection
122    * @param password the password to use to open the connection
123    * @return a new connection
124    * @throws ConsoleException if login failed
125    */

126   public Connection JavaDoc createConnection(String JavaDoc url, String JavaDoc login, String JavaDoc password)
127       throws ConsoleException
128   {
129     try
130     {
131       return DriverManager.getConnection(url, login, password);
132     }
133     catch (Exception JavaDoc e)
134     {
135       throw new ConsoleException(ConsoleTranslate.get(
136           "sql.login.connection.failed", new String JavaDoc[]{url, e.getMessage()}));
137     }
138   }
139
140   /**
141    * Executes a SQL statement.
142    *
143    * @param request the SQL request to execute
144    * @param displayResult <code>true</code> if the result must be printed on
145    * the standard output
146    */

147   public synchronized void execSQL(String JavaDoc request, boolean displayResult)
148   {
149     PreparedStatement JavaDoc stmt = null;
150     try
151     {
152       stmt = connection.prepareStatement(request);
153       stmt.setQueryTimeout(timeout);
154       if (fetchsize != 0)
155         stmt.setFetchSize(fetchsize);
156       if (maxrows != 0)
157         stmt.setMaxRows(maxrows);
158
159       long start = System.currentTimeMillis();
160       long end;
161       if (request.regionMatches(true, 0, "select ", 0, 7))
162       {
163         ResultSet JavaDoc rs = stmt.executeQuery();
164         end = System.currentTimeMillis();
165         if (displayResult)
166           ResultSetFormatter.formatAndDisplay(rs, fetchsize, console);
167       }
168       else
169       {
170         int result = stmt.executeUpdate();
171         end = System.currentTimeMillis();
172         if (displayResult)
173           console.println(ConsoleTranslate.get("sql.display.affected.rows",
174               result));
175       }
176       console.println(ConsoleTranslate.get("sql.display.query.time",
177           new Long JavaDoc[]{new Long JavaDoc((end - start) / 1000),
178               new Long JavaDoc((end - start) % 1000)}));
179     }
180     catch (Exception JavaDoc e)
181     {
182       console.printError(ConsoleTranslate.get("sql.command.sqlquery.error", e),
183           e);
184     }
185     finally
186     {
187       try
188       {
189         stmt.close();
190       }
191       catch (Exception JavaDoc ignore)
192       {
193       }
194     }
195   }
196
197   /**
198    * Connects to a virtual database.
199    */

200   public void handlePrompt()
201   {
202     loadHistory();
203
204     while (!quit)
205     {
206       try
207       {
208         String JavaDoc cmd = console.readLine(this.getPromptString());
209         if (cmd == null)
210           cmd = "";
211
212         if (cmd.length() == 0)
213           continue;
214
215         manageHistory(cmd);
216
217         ConsoleCommand currentCommand = findConsoleCommand(cmd,
218             getHashCommands());
219
220         if (currentCommand == null)
221         {
222           execSQL(cmd, true);
223         }
224         else
225         {
226           currentCommand.execute(cmd.substring(
227               currentCommand.getCommandName().length()).trim());
228         }
229
230       }
231       catch (Exception JavaDoc e)
232       {
233         console.printError(ConsoleTranslate.get("sql.display.exception", e), e);
234         if (e instanceof RuntimeException JavaDoc)
235         {
236           System.exit(0);
237         }
238       }
239     }
240   }
241
242   /**
243    * @see org.objectweb.cjdbc.console.text.module.AbstractConsoleModule#getDescriptionString()
244    */

245   public String JavaDoc getDescriptionString()
246   {
247     return "SQL Console";
248   }
249
250   /**
251    * @see org.objectweb.cjdbc.console.text.module.AbstractConsoleModule#getPromptString()
252    */

253   public String JavaDoc getPromptString()
254   {
255     int ind1 = url.lastIndexOf('?');
256     int ind2 = url.lastIndexOf(';');
257     if (ind1 != -1 || ind2 != -1)
258     {
259       String JavaDoc prompt;
260       prompt = (ind1 != -1) ? url.substring(0, ind1) : url;
261       prompt = (ind2 != -1) ? url.substring(0, ind2) : url;
262       return prompt + " (" + login + ")";
263     }
264     else
265       return url + " (" + login + ")";
266   }
267   
268   /**
269    * Get a <code>SavePoint</code> identified by its <code>name</code>
270    *
271    * @param name name fo the <code>SavePoint</code>
272    * @return a <code>SavePoint</code> or <code>null</code> if no <code>SavePoint</code> with
273    * such a name has been previously added
274    */

275   public Savepoint JavaDoc getSavePoint(String JavaDoc name)
276   {
277     return (Savepoint JavaDoc) savePoints.get(name);
278   }
279   
280   /**
281    * add a <code>SavePoint</code>
282    *
283    * @param savePoint the <code>SavePoint</code> to add
284    * @throws SQLException if the <code>savePoint</code> is unnamed
285    */

286   public void addSavePoint(Savepoint JavaDoc savePoint) throws SQLException JavaDoc
287   {
288     savePoints.put(savePoint.getSavepointName(), savePoint);
289   }
290
291   /**
292    * Get the timeout value (in seconds)
293    *
294    * @return the timeout value (in seconds)
295    */

296   public int getTimeout()
297   {
298     return timeout;
299   }
300
301   /**
302    * Set the timeout value (in seconds)
303    *
304    * @param timeout new timeout value (in seconds)
305    */

306   public void setTimeout(int timeout)
307   {
308     this.timeout = timeout;
309   }
310
311   /**
312    * Get the fetchsize value
313    *
314    * @return the fetchsize value
315    */

316   public int getFetchsize()
317   {
318     return fetchsize;
319   }
320
321   /**
322    * Set the fetchsize
323    *
324    * @param fetchsize new fetchsize value
325    */

326   public void setFetchsize(int fetchsize)
327   {
328     this.fetchsize = fetchsize;
329   }
330
331   /**
332    * Set the maxrows
333    *
334    * @param maxrows new maxrows value
335    */

336   public void setMaxrows(int maxrows)
337   {
338     this.maxrows = maxrows;
339   }
340
341   /**
342    * @see org.objectweb.cjdbc.console.text.module.AbstractConsoleModule#loadCommands()
343    */

344   protected void loadCommands()
345   {
346     commands.add(new Begin(this));
347     commands.add(new CallStoredProcedure(this));
348     commands.add(new Commit(this));
349     commands.add(new SetFetchSize(this));
350     commands.add(new Help(this));
351     commands.add(new Load(this));
352     commands.add(new SetMaxRows(this));
353     commands.add(new SetSavePoint(this));
354     commands.add(new Rollback(this));
355     commands.add(new SetIsolation(this));
356     commands.add(new ShowTables(this));
357     commands.add(new SetTimeout(this));
358     commands.add(new Quit(this));
359     commands.add(new History(this));
360   }
361
362   /**
363    * @see org.objectweb.cjdbc.console.text.module.AbstractConsoleModule#login(java.lang.String[])
364    */

365   public void login(String JavaDoc[] params) throws Exception JavaDoc
366   {
367     login = null;
368     url = (params.length > 0 && params[0] != null) ? params[0].trim() : null;
369     try
370     {
371       if ((url == null) || url.trim().equals(""))
372       {
373         url = console.readLine(ConsoleTranslate.get("sql.login.prompt.url"));
374         if (url == null)
375           return;
376       }
377       login = console.readLine(ConsoleTranslate.get("sql.login.prompt.user"));
378       if (login == null)
379         return;
380       String JavaDoc password = console.readPassword(ConsoleTranslate
381           .get("sql.login.prompt.password"));
382       if (password == null)
383         return;
384
385       connection = createConnection(url, login, password);
386       
387       // Change console reader completor
388
console.getConsoleReader().removeCompletor(
389           console.getControllerModule().getCompletor());
390       console.getConsoleReader().addCompletor(this.getCompletor());
391     }
392     catch (Exception JavaDoc e)
393     {
394       throw new ConsoleException(ConsoleTranslate.get("sql.login.exception", e));
395     }
396   }
397
398   /**
399    * @see org.objectweb.cjdbc.console.text.module.AbstractConsoleModule#quit()
400    */

401   public void quit()
402   {
403     if (connection != null)
404     {
405       try
406       {
407         connection.close();
408       }
409       catch (Exception JavaDoc e)
410       {
411         // ignore
412
}
413     }
414     super.quit();
415   }
416
417   /**
418    * @see org.objectweb.cjdbc.console.text.module.AbstractConsoleModule#help()
419    */

420   public void help()
421   {
422     super.help();
423     console.println();
424     console.println(ConsoleTranslate.get("sql.command.description"));
425   }
426 }
427
Popular Tags