KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > protomatter > jdbc > sl > SimpleListener


1 package com.protomatter.jdbc.sl;
2
3 /**
4  * {{{ The Protomatter Software License, Version 1.0
5  * derived from The Apache Software License, Version 1.1
6  *
7  * Copyright (c) 1998-2002 Nate Sammons. All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  * notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  * notice, this list of conditions and the following disclaimer in
18  * the documentation and/or other materials provided with the
19  * distribution.
20  *
21  * 3. The end-user documentation included with the redistribution,
22  * if any, must include the following acknowledgment:
23  * "This product includes software developed for the
24  * Protomatter Software Project
25  * (http://protomatter.sourceforge.net/)."
26  * Alternately, this acknowledgment may appear in the software itself,
27  * if and wherever such third-party acknowledgments normally appear.
28  *
29  * 4. The names "Protomatter" and "Protomatter Software Project" must
30  * not be used to endorse or promote products derived from this
31  * software without prior written permission. For written
32  * permission, please contact support@protomatter.com.
33  *
34  * 5. Products derived from this software may not be called "Protomatter",
35  * nor may "Protomatter" appear in their name, without prior written
36  * permission of the Protomatter Software Project
37  * (support@protomatter.com).
38  *
39  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
40  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
41  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
42  * DISCLAIMED. IN NO EVENT SHALL THE PROTOMATTER SOFTWARE PROJECT OR
43  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
45  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
46  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
47  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
48  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
49  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE. }}}
51  */

52
53 import java.sql.*;
54 import java.text.*;
55 import java.io.*;
56 import java.util.*;
57 import java.lang.reflect.*;
58 import com.protomatter.Protomatter;
59
60 /**
61  * A simple SQL tool. Run it, and type "help".
62  * A list of files are taken as command line arguments -- each
63  * of these files are run as command files at startup.
64  */

65 public class SimpleListener
66 {
67   private Connection connection;
68   private Driver driver;
69   private String JavaDoc url;
70   private Properties props;
71
72   private String JavaDoc lastCommandLine = "";
73   private Vector history = new Vector();
74   private int historySize = 20;
75   private String JavaDoc prompt = "SL> ";
76   private String JavaDoc morePrompt = "";
77   private boolean showStackTrace = false;
78   private boolean showQuotes = false;
79   private String JavaDoc defaultSchema = null;
80
81   private SimpleListener()
82   {
83     super();
84   }
85
86   public static void main(String JavaDoc args[])
87   {
88     SimpleListener s = new SimpleListener();
89     try
90     {
91       if (args.length > 0)
92       {
93         for (int i=0; i<args.length; i++)
94         {
95           String JavaDoc file = args[i];
96           Vector theArgs = new Vector();
97           theArgs.addElement(file);
98           s.handleCommand_run(theArgs);
99         }
100       }
101       s.commandLoop();
102     }
103     catch (Exception JavaDoc x)
104     {
105       x.printStackTrace();
106     }
107   }
108
109   private void commandLoop()
110   throws IOException
111   {
112     // try a statement
113
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
114     String JavaDoc line = "";
115     System.out.print(prompt);
116     System.out.flush();
117     while ((line = reader.readLine()) != null)
118     {
119       StringBuffer JavaDoc cmd = new StringBuffer JavaDoc();
120       while (!line.equals("") && !line.endsWith(";") && !line.endsWith("/"))
121       {
122         if (!line.startsWith("#") && !line.startsWith("--"))
123         {
124           cmd.append(line);
125           cmd.append(" ");
126         }
127         System.out.print(morePrompt);
128         System.out.flush();
129         line = reader.readLine();
130       }
131       if (!line.equals("") && !line.startsWith("#") && !line.startsWith("--"))
132         cmd.append(line.substring(0, line.length() -1));
133       executeCommand(cmd.toString());
134       System.out.print(prompt);
135       System.out.flush();
136     }
137   }
138
139   private void executeCommand(String JavaDoc line)
140   throws IOException
141   {
142       if (line.equals("/"))
143       {
144         line = lastCommandLine;
145         System.out.println("");
146         System.out.println("Executing last command:");
147         System.out.println(" " + lastCommandLine);
148         System.out.println("");
149       }
150
151       if (line.startsWith("!"))
152       {
153         int index = 0;
154         try
155         {
156           index = Integer.parseInt(line.substring(1));
157           line = getHistoryCommand(index);
158           System.out.println("");
159           System.out.println("Executing command from history:");
160           System.out.println(" " + line);
161           System.out.println("");
162         }
163         catch (Exception JavaDoc x)
164         {
165           System.out.println("What?");
166           line = "";
167         }
168       }
169
170       if (!line.equals(""))
171       {
172         lastCommandLine = line;
173         addToHistory(line);
174         try
175         {
176           StringTokenizer st = new StringTokenizer(line);
177           String JavaDoc commandName = st.nextToken();
178           if (commandName.equals("connect"))
179           {
180             // different handling here for "connect" because
181
// some drivers put spaces into their URLs. Bah!
182
long time = System.currentTimeMillis();
183             handleCommand_connect(line.substring(7).trim());
184             time = System.currentTimeMillis() - time;
185             System.out.println("Command took " + time + "ms");
186           }
187           else
188           {
189             Class JavaDoc c = this.getClass();
190             Class JavaDoc params[] = new Class JavaDoc[1];
191             Vector args = new Vector();
192             String JavaDoc s = null;
193             while (st.hasMoreTokens())
194             {
195               args.addElement(st.nextToken());
196             }
197             try
198             {
199               params[0] = Class.forName("java.util.Vector");
200             }
201             catch (ClassNotFoundException JavaDoc e)
202             {
203               throw new InternalError JavaDoc("Can't find java.util.Vector! Doh!");
204             }
205             Method method = null;
206             try
207             {
208               method = c.getMethod("handleCommand_" + commandName, params);
209               System.out.println("");
210             }
211             catch (Exception JavaDoc e)
212             {
213               handleCommandDefault(commandName, args);
214               return;
215             }
216             Object JavaDoc methodArguments[] = new Object JavaDoc[1];
217             try
218             {
219               methodArguments[0] = args;
220               long time = System.currentTimeMillis();
221               method.invoke(this, methodArguments);
222               time = System.currentTimeMillis() - time;
223               System.out.println("Command took " + time + "ms");
224             }
225             catch (InvocationTargetException e)
226             {
227               System.out.println("Exception calling method:");
228               Throwable JavaDoc x = e.getTargetException();
229
230               if (showStackTrace)
231                 x.printStackTrace();
232               else
233                 System.out.println("Exception: " + x);
234               System.out.println("");
235               return;
236             }
237           }
238         }
239         catch (Exception JavaDoc e)
240         {
241           if (showStackTrace)
242             e.printStackTrace();
243           else
244             System.out.println("Exception: " + e);
245         }
246       }
247     }
248
249   private void handleCommandDefault(String JavaDoc cmdName, Vector args)
250   throws SQLException
251   {
252     System.out.println("Executing sql");
253     if (checkConnected())
254     {
255       String JavaDoc line = cmdName;
256
257       boolean query = false;
258       if (cmdName.equalsIgnoreCase("select"))
259         query = true;
260
261       Enumeration e = args.elements();
262       while (e.hasMoreElements())
263       {
264         line += " " + e.nextElement();
265       }
266
267       PreparedStatement s = connection.prepareStatement(line);
268       long time = System.currentTimeMillis();
269
270       ResultSet r = null;
271       int rows = 0;
272
273       if (query)
274         r = s.executeQuery();
275       else
276         rows = s.executeUpdate();
277
278       time = System.currentTimeMillis() - time;
279       if (query)
280       {
281         System.out.println("PreparedStatement.executeQuery() took " + time + "ms");
282         ResultSetUtil.formatResultSet(r, System.out, showQuotes);
283       }
284       else
285       {
286         System.out.println("PreparedStatement.executeUpdate() took " + time + "ms");
287         System.out.println("Affected " + rows + " row" + (rows == 1 ? "" : "s"));
288       }
289       if (r != null)
290         r.close();
291       if (s != null)
292         s.close();
293     }
294   }
295
296   public void handleCommand_quit(Vector args)
297   {
298     if (connection != null)
299     {
300       try
301       {
302         System.out.println("Disconnecting...");
303         connection.close();
304       }
305       catch (Exception JavaDoc x)
306       {
307         System.out.println("Exception closing connection...");
308         if (showStackTrace)
309           x.printStackTrace();
310         else
311           System.out.println("Exception: " + x);
312       }
313     }
314     System.out.println("See ya, sucker!");
315     System.exit(0);
316   }
317
318   public void handleCommand_disconnect(Vector args)
319   throws Exception JavaDoc
320   {
321     if (!checkConnected())
322       return;
323     connection.close();
324     connection = null;
325     this.url = null;
326     this.props = null;
327   }
328
329   public void handleCommand_commit(Vector args)
330   throws Exception JavaDoc
331   {
332     if (!checkConnected())
333       return;
334     connection.commit();
335   }
336
337   public void handleCommand_rollback(Vector args)
338   throws Exception JavaDoc
339   {
340     if (!checkConnected())
341       return;
342     connection.rollback();
343   }
344
345   public void handleCommand_driver(Vector args)
346   throws Exception JavaDoc
347   {
348     try
349     {
350       driver = (Driver)Class.forName((String JavaDoc)args.firstElement()).newInstance();
351     }
352     catch (Exception JavaDoc x)
353     {
354       if (showStackTrace)
355         x.printStackTrace();
356       else
357         System.out.println("Exception: " + x);
358       throw x;
359     }
360   }
361
362   public void handleCommand_connect(String JavaDoc args)
363   throws Exception JavaDoc
364   {
365     if (!checkDriver()) return;
366     try
367     {
368       // the argument should be:
369
//
370
// URL [username [password [key=val ...]]]
371
//
372
if (args.equals(""))
373       {
374         System.out.println("Usage: connect URL [username [password [key=val ...]]]");
375         System.out.println(" You can use double-quotes to quote things.");
376         System.out.println("");
377         return;
378       }
379
380       String JavaDoc url = null;
381       String JavaDoc user = null;
382       String JavaDoc pass = null;
383       Properties props = new Properties();
384
385       // parse things out and pay attention to double quotes.
386
Vector list = new Vector();
387       boolean inQuote = false;
388       StringBuffer JavaDoc currString = new StringBuffer JavaDoc();
389       for (int i=0; i<args.length(); i++)
390       {
391         char c = args.charAt(i);
392         if (c == '"')
393         {
394           if (inQuote)
395           {
396             list.add(currString.toString());
397             currString = new StringBuffer JavaDoc();
398             inQuote = false;
399           }
400           else
401           {
402             inQuote = true;
403           }
404         }
405         else if (c == ' ')
406         {
407           if (inQuote)
408           {
409             currString.append(c);
410           }
411           else
412           {
413             if (currString.length() != 0)
414             {
415               list.add(currString.toString());
416               currString = new StringBuffer JavaDoc();
417             }
418           }
419         }
420         else
421         {
422           currString.append(c);
423         }
424       }
425       if (currString.length() != 0)
426         list.add(currString.toString());
427
428
429       Enumeration e = list.elements();
430       if (e.hasMoreElements())
431         url = (String JavaDoc)e.nextElement();
432       if (e.hasMoreElements())
433         user = (String JavaDoc)e.nextElement();
434       if (e.hasMoreElements())
435         pass = (String JavaDoc)e.nextElement();
436
437       Properties p = new Properties();
438       if (user != null)
439         p.put("user", user);
440       if (pass != null)
441         p.put("password", pass);
442       while (e.hasMoreElements())
443       {
444         String JavaDoc tok = (String JavaDoc)e.nextElement();
445         StringTokenizer st = new StringTokenizer(tok, "=");
446         p.put(st.nextToken(), st.nextToken());
447       }
448
449       System.out.println("Connecting....");
450       System.out.println(" URL: \"" + url + "\"");
451       System.out.println(" Properties:");
452       Enumeration en = p.keys();
453       int width = 0;
454       while (en.hasMoreElements())
455       {
456         String JavaDoc key = (String JavaDoc)en.nextElement();
457         if (key.length() > width)
458           width = key.length();
459       }
460
461       en = p.keys();
462       while (en.hasMoreElements())
463       {
464         String JavaDoc key = (String JavaDoc)en.nextElement();
465         String JavaDoc val = p.getProperty(key);
466         int size = key.length();
467         System.out.print(" ");
468         System.out.print(key);
469         for (int i=0; i<(width-size); i++)
470           System.out.print(" ");
471         System.out.println(" = " + val);
472       }
473
474       this.url = url;
475       this.props = p;
476       connection = DriverManager.getConnection(url, p);
477     }
478     catch (Exception JavaDoc x)
479     {
480       if (showStackTrace)
481         x.printStackTrace();
482       else
483         System.out.println("Exception: " + x);
484       throw x;
485     }
486   }
487
488   private String JavaDoc getIsolationString(int isolation)
489   {
490     switch (isolation)
491     {
492       case Connection.TRANSACTION_NONE:
493         return "None";
494       case Connection.TRANSACTION_READ_COMMITTED:
495         return "Read Committed";
496       case Connection.TRANSACTION_READ_UNCOMMITTED:
497         return "Read Uncommitted";
498       case Connection.TRANSACTION_REPEATABLE_READ:
499         return "Repeatable Read";
500       case Connection.TRANSACTION_SERIALIZABLE:
501         return "Serializable";
502     }
503     return "Unknown";
504   }
505
506   public void handleCommand_isolation(Vector args)
507   throws SQLException
508   {
509     if (!checkConnected())
510       return;
511
512     if (args.size() == 1)
513     {
514       String JavaDoc l = (String JavaDoc)args.elementAt(0);
515       if (l.equalsIgnoreCase("none"))
516         connection.setTransactionIsolation(Connection.TRANSACTION_NONE);
517       else if (l.equalsIgnoreCase("read_committed"))
518         connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
519       else if (l.equalsIgnoreCase("read_uncommitted"))
520         connection.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
521       else if (l.equalsIgnoreCase("repeatable_read"))
522         connection.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
523       else if (l.equalsIgnoreCase("serializable"))
524         connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
525       else
526       {
527         System.out.println(" You must specify one of the following levels:");
528         System.out.println(" NONE");
529         System.out.println(" READ_COMMITTED");
530         System.out.println(" READ_UNCOMMITTED");
531         System.out.println(" REPEATABLE_READ");
532         System.out.println(" SERIALIZABLE");
533         System.out.println("");
534       }
535     }
536     System.out.println("Current isolation level: "
537       + getIsolationString(connection.getTransactionIsolation()));
538     System.out.println("");
539   }
540
541   public void handleCommand_metadata(Vector args)
542   throws SQLException
543   {
544     if (!checkConnected())
545       return;
546     DatabaseMetaData m = connection.getMetaData();
547     System.out.println("Connection Class name = " + connection.getClass().getName());
548     System.out.println("Driver Name = " + m.getDriverName());
549     System.out.println("Driver Version = " + m.getDriverVersion());
550     System.out.println("Database Product Name = " + m.getDatabaseProductName());
551     System.out.println("Database Product Version = " + m.getDatabaseProductVersion());
552
553     System.out.println("");
554     System.out.println("Default Isolation = " + getIsolationString(m.getDefaultTransactionIsolation()));
555
556     System.out.println("");
557     System.out.println("Maximum length for:");
558     System.out.println(" Catalog name = " + m.getMaxCatalogNameLength());
559     System.out.println(" Schema name = " + m.getMaxSchemaNameLength());
560     System.out.println(" Table name = " + m.getMaxTableNameLength());
561     System.out.println(" Column name = " + m.getMaxColumnNameLength());
562     System.out.println(" Procedure name = " + m.getMaxProcedureNameLength());
563     System.out.println(" Binary literal = " + m.getMaxBinaryLiteralLength());
564     System.out.println("");
565     System.out.println("Other misc maximums:");
566     System.out.println(" Columns in table = " + m.getMaxColumnsInTable());
567     System.out.println(" Connections = " + m.getMaxConnections());
568     System.out.println(" Row size = " + m.getMaxRowSize());
569     System.out.println(" Open statements = " + m.getMaxStatements());
570     System.out.println("");
571     System.out.println("ANSI Support declared:");
572     System.out.println(" Entry-Level SQL92: " + m.supportsANSI92EntryLevelSQL());
573     System.out.println(" Full SQL92: " + m.supportsANSI92FullSQL());
574     System.out.println(" Intermediate SQL92: " + m.supportsANSI92IntermediateSQL());
575     System.out.println(" Integrity Enhancement Facility: " + m.supportsIntegrityEnhancementFacility());
576     System.out.println("");
577   }
578
579   public void handleCommand_catalogs(Vector args)
580   throws SQLException
581   {
582     if (!checkConnected()) return;
583     ResultSet r = connection.getMetaData().getCatalogs();
584     System.out.println("Available catalogs:");
585     String JavaDoc current = connection.getCatalog();
586     while (r.next())
587     {
588       String JavaDoc cname = r.getString(1);
589       System.out.println(" " + cname + (cname.equals(current) ? " <== current catalog" : ""));
590     }
591     r.close();
592     System.out.println("");
593   }
594
595   public void handleCommand_catalog(Vector args)
596   throws SQLException
597   {
598     if (!checkConnected()) return;
599     if (args.size() != 1)
600     {
601       System.out.println("Usage: catalog <catalogname>");
602     }
603     else
604     {
605       connection.setCatalog((String JavaDoc)args.firstElement());
606       System.out.println("Changed catalogs to " + args.firstElement());
607     }
608   }
609
610   public void handleCommand_schema(Vector args)
611   throws SQLException
612   {
613     if (!checkConnected()) return;
614     if (args.size() != 1)
615     {
616       System.out.println("Usage: schema <schema>");
617       System.out.println("Current default schema is \"" + defaultSchema + "\"");
618     }
619     else
620     {
621       String JavaDoc schema = (String JavaDoc)args.firstElement();
622       if ("null".equals(schema))
623           defaultSchema = null;
624       else
625           defaultSchema = schema;
626       System.out.println("Changed default schema to " + args.firstElement());
627     }
628   }
629
630   public void handleCommand_schemas(Vector args)
631   throws SQLException
632   {
633     if (!checkConnected()) return;
634     if (args.size() != 0)
635     {
636       System.out.println("Usage: schemas");
637       return;
638     }
639
640     ResultSet r = connection.getMetaData().getSchemas();
641     while (r.next())
642     {
643       System.out.println(" " + r.getString("TABLE_SCHEM"));
644     }
645     System.out.println("");
646     r.close();
647   }
648
649   public void handleCommand_procedures(Vector args)
650   throws SQLException
651   {
652     if (!checkConnected()) return;
653     String JavaDoc catalog = connection.getCatalog();
654     if (args.size() > 1)
655     {
656       System.out.println("Usage: procedures [<schemaname>]");
657       return;
658     }
659     String JavaDoc schema = null;
660     if (args.size() == 1)
661     {
662       schema = (String JavaDoc)args.firstElement();
663     }
664
665     ResultSet r = connection.getMetaData().getProcedures(catalog, schema, null);
666     System.out.println("Schema Procedure");
667     System.out.println("-------------------------------------------------");
668     // xxxxxxxxxxxxxxxx xxxxxxxxxxxxx...
669
while (r.next())
670     {
671       System.out.println(" " +
672         format(r.getString("PROCEDURE_SCHEM"), 16) + " " +
673         r.getString("PROCEDURE_NAME"));
674     }
675     r.close();
676     System.out.println("");
677   }
678
679   public void handleCommand_tables(Vector args)
680   throws SQLException
681   {
682     if (!checkConnected()) return;
683     String JavaDoc catalog = connection.getCatalog();
684     String JavaDoc schema = null;
685     String JavaDoc tablename = null;
686     if (args.size() > 0)
687     {
688       schema = (String JavaDoc)args.firstElement();
689     }
690     if (args.size() > 1)
691     {
692       tablename = ((String JavaDoc)args.elementAt(1)).toUpperCase();
693     }
694
695     ResultSet r = connection.getMetaData().getTables(catalog, schema, null, null);
696     //System.out.println(ResultSetUtil.formatResultSet(r));
697

698     System.out.println("Schema Tablename");
699     System.out.println("-------------------------------------------------");
700     // xxxxxxxxxxxxxxxx xxxxxxxxxxxxx...
701
while (r.next())
702     {
703       String JavaDoc name = r.getString("TABLE_NAME");
704       if (tablename == null || (name.toUpperCase().indexOf(tablename) != -1))
705         System.out.println(" " + format(r.getString("TABLE_SCHEM"), 16) + " " + name);
706     }
707     r.close();
708
709     System.out.println("");
710   }
711
712   public void handleCommand_indexes(Vector args)
713   throws SQLException
714   {
715     if (!checkConnected()) return;
716     String JavaDoc catalog = connection.getCatalog();
717     if (args.size() != 1)
718     {
719       System.out.println("Usage: indexes [<schema>.]<tablename>");
720       return;
721     }
722     String JavaDoc table = (String JavaDoc)args.firstElement();
723     String JavaDoc schema = null;
724     if (table.indexOf(".") != -1)
725     {
726       StringTokenizer st = new StringTokenizer(table, ".");
727       schema = st.nextToken();
728       table = st.nextToken();
729     }
730
731     ResultSet r = connection.getMetaData().getIndexInfo(catalog, schema, table, false, true);
732     boolean first = true;
733     while (r.next())
734     {
735       if (first)
736       {
737         System.out.println("Schema: " + r.getString("TABLE_SCHEM"));
738         System.out.println("Table: " + r.getString("TABLE_NAME"));
739         first = false;
740       }
741
742       String JavaDoc indexName = r.getString("INDEX_NAME");
743       boolean nonUnique = r.getBoolean("NON_UNIQUE");
744       String JavaDoc qualifier = r.getString("INDEX_QUALIFIER");
745       short indexType = r.getShort("TYPE");
746       short position = r.getShort("ORDINAL_POSITION");
747       String JavaDoc column = r.getString("COLUMN_NAME");
748       String JavaDoc ascDesc = r.getString("ASC_OR_DESC");
749       int cardinality = r.getInt("CARDINALITY");
750       int pages = r.getInt("PAGES");
751       String JavaDoc filter = r.getString("FILTER_CONDITION");
752
753       System.out.println(" Index name: " + indexName);
754       System.out.println(" Non unique vals?: " + nonUnique);
755       System.out.println(" Column: " + column);
756       System.out.println(" Qualifier: " + qualifier);
757       System.out.print(" Type: ");
758       switch (indexType)
759       {
760         case DatabaseMetaData.tableIndexStatistic:
761           System.out.println("Statistic");
762           break;
763         case DatabaseMetaData.tableIndexClustered:
764           System.out.println("Clustered");
765           break;
766         case DatabaseMetaData.tableIndexHashed:
767           System.out.println("Hashed");
768           break;
769         case DatabaseMetaData.tableIndexOther:
770           System.out.println("Other");
771           break;
772         default:
773           System.out.println("Unknown");
774       }
775       System.out.println(" Positon: " + position);
776       System.out.println(" Asc/Desc: " + ascDesc);
777       System.out.println(" Cardinality: " + cardinality);
778       System.out.println(" Pages: " + pages);
779       System.out.println(" Filter: " + filter);
780       System.out.println("");
781     }
782
783     if (first) // no rows
784
{
785       System.out.println(" Table \"" + table + "\" does not appear to have any indexes.");
786       System.out.println("");
787     }
788
789     r.close();
790   }
791
792   public void handleCommand_run(Vector args)
793   throws SQLException, IOException
794   {
795     if (args.size() != 1)
796     {
797       System.out.println("Usage: run <filename>");
798       System.out.println(" (executes commands from the given file)");
799       return;
800     }
801     String JavaDoc file = (String JavaDoc)args.elementAt(0);
802     System.out.println("Processing commands from file:");
803     System.out.println(" file=" + file);
804     BufferedReader r = new BufferedReader(new FileReader(new File(file)));
805     String JavaDoc line = "";
806     while ((line = r.readLine()) != null)
807     {
808       StringBuffer JavaDoc cmd = new StringBuffer JavaDoc();
809       while (!line.equals("") && !line.endsWith(";") && !line.endsWith("/"))
810       {
811         if (!line.startsWith("#") && !line.startsWith("--"))
812         {
813           cmd.append(line);
814           cmd.append(" ");
815         }
816         line = r.readLine();
817       }
818       if (!line.equals(""))
819         cmd.append(line.substring(0, line.length() -1));
820       if (!cmd.toString().startsWith("#") && !cmd.toString().startsWith("--") && !cmd.toString().trim().equals(""))
821       {
822         System.out.println(" cmd=\"" + cmd + "\"");
823         executeCommand(cmd.toString());
824       }
825     }
826     r.close();
827   }
828
829   public void handleCommand_desc(Vector args)
830   throws SQLException
831   {
832     if (!checkConnected()) return;
833     String JavaDoc catalog = connection.getCatalog();
834     if (args.size() != 1)
835     {
836       System.out.println("Usage: desc [<schema>.]<tablename>");
837       return;
838     }
839     String JavaDoc table = (String JavaDoc)args.firstElement();
840     String JavaDoc schema = defaultSchema;
841     if (table.indexOf(".") != -1)
842     {
843       StringTokenizer st = new StringTokenizer(table, ".");
844       schema = st.nextToken();
845       table = st.nextToken();
846     }
847
848     // get PK info
849
Hashtable pks = new Hashtable();
850     ResultSet r = connection.getMetaData().getPrimaryKeys(catalog, schema, table);
851     while (r.next())
852       pks.put(r.getString("COLUMN_NAME"), "blah");
853     r.close();
854
855     r = connection.getMetaData().getColumns(catalog, schema, table, null);
856     //System.out.println(ResultSetUtil.formatResultSet(r));
857
boolean first = true;
858     while (r.next())
859     {
860       if (first)
861       {
862         if (schema == null)
863         {
864             schema = r.getString("TABLE_SCHEM");
865         }
866         System.out.println("Schema: " + r.getString("TABLE_SCHEM"));
867         System.out.println("Column Name Type Size Null? PK");
868         System.out.println("------------------------------------------------------------------------");
869         // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxx xxxxxxxxxxxxxxx xxxxx xx
870
// 30 13 15 5
871
first = false;
872       }
873       String JavaDoc colSchema = r.getString("TABLE_SCHEM");
874       if ((schema == null) || (schema != null && schema.equals(colSchema)))
875       {
876         String JavaDoc colName = r.getString("COLUMN_NAME");
877         System.out.print(
878           " " +
879           format(colName, 30) + " " +
880           format(r.getString("TYPE_NAME"), 13) + " " +
881           format(String.valueOf(r.getInt("COLUMN_SIZE")), 15) + " " +
882           format(r.getString("IS_NULLABLE"), 6)
883           );
884         if (pks.containsKey(colName))
885           System.out.println("Y");
886         else
887           System.out.println("");
888       }
889     }
890
891     if (first) // no rows
892
{
893       System.out.println(" Table \"" + table + "\" does not appear to exist.");
894     }
895
896     r.close();
897     System.out.println("");
898   }
899
900   public void handleCommand_fkdesc(Vector args)
901   throws SQLException
902   {
903     if (!checkConnected()) return;
904     String JavaDoc catalog = connection.getCatalog();
905     if (args.size() != 1)
906     {
907       System.out.println("Usage: fkdesc [<schema>.]<tablename>");
908       return;
909     }
910     String JavaDoc table = (String JavaDoc)args.firstElement();
911     String JavaDoc schema = defaultSchema;
912     if (table.indexOf(".") != -1)
913     {
914       StringTokenizer st = new StringTokenizer(table, ".");
915       schema = st.nextToken();
916       table = st.nextToken();
917     }
918
919     DatabaseMetaData md = connection.getMetaData();
920
921     System.out.println("Exported keys:");
922     ResultSet fkr = md.getCrossReference(catalog, schema, table, null, null, null);
923     while (fkr.next())
924     {
925       System.out.print(" " + fkr.getString("PKCOLUMN_NAME"));
926       System.out.print(" is referenced by ");
927       System.out.println(fkr.getString("FKTABLE_NAME") + "." + fkr.getString("FKCOLUMN_NAME"));
928     }
929     System.out.println("");
930     fkr.close();
931
932
933     System.out.println("Imported keys:");
934     fkr = md.getCrossReference(null, null, null, catalog, schema, table);
935     while (fkr.next())
936     {
937       System.out.print(" " + fkr.getString("FKCOLUMN_NAME"));
938       System.out.print(" references ");
939       System.out.println(fkr.getString("PKTABLE_NAME") + "." + fkr.getString("PKCOLUMN_NAME"));
940     }
941     System.out.println("");
942     fkr.close();
943   }
944
945   public void handleCommand_jdesc(Vector args)
946   throws SQLException
947   {
948     if (!checkConnected()) return;
949     String JavaDoc catalog = connection.getCatalog();
950     if (args.size() != 1)
951     {
952       System.out.println("Usage: jdesc [<schema>.]<tablename>");
953       return;
954     }
955     String JavaDoc table = (String JavaDoc)args.firstElement();
956     String JavaDoc schema = defaultSchema;
957     if (table.indexOf(".") != -1)
958     {
959       StringTokenizer st = new StringTokenizer(table, ".");
960       schema = st.nextToken();
961       table = st.nextToken();
962     }
963
964     // get PK info
965
Hashtable pks = new Hashtable();
966     ResultSet r = connection.getMetaData().getPrimaryKeys(catalog, schema, table);
967     while (r.next())
968       pks.put(r.getString("COLUMN_NAME"), "blah");
969     r.close();
970
971     r = connection.getMetaData().getColumns(catalog, schema, table, null);
972     boolean first = true;
973     while (r.next())
974     {
975       if (first)
976       {
977         if (schema == null)
978         {
979             schema = r.getString("TABLE_SCHEM");
980         }
981         //System.out.println(ResultSetUtil.formatResultSet(r));
982
System.out.println("Schema: " + r.getString("TABLE_SCHEM"));
983         System.out.println("Column Name java.sql.Types Size Null? PK");
984         System.out.println("------------------------------------------------------------------------");
985         // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxx xxxxxxxxxxxx xxxxx xx
986
// 30 16 12 5
987
first = false;
988       }
989       String JavaDoc colSchema = r.getString("TABLE_SCHEM");
990
991       if ((schema == null) || (schema.equals(colSchema)))
992       {
993         String JavaDoc nullable = r.getString("IS_NULLABLE");
994         if (nullable.equalsIgnoreCase("YES"))
995           nullable = "YES";
996         else
997           nullable = "NO";
998         String JavaDoc colName = r.getString("COLUMN_NAME");
999         System.out.print(
1000          " " +
1001          format(colName, 30) + " " +
1002          format(getType(r.getInt("DATA_TYPE")), 16) + " " +
1003          format(String.valueOf(r.getInt("COLUMN_SIZE")), 12) + " " +
1004          format(nullable, 6)
1005          );
1006        if (pks.containsKey(colName))
1007          System.out.println("Y");
1008        else
1009          System.out.println("");
1010      }
1011    }
1012
1013    if (first) // no rows
1014
{
1015      System.out.println(" Table \"" + table + "\" does not appear to exist.");
1016    }
1017
1018    r.close();
1019    System.out.println("");
1020  }
1021
1022  public void handleCommand_driverdata(Vector args)
1023  throws SQLException
1024  {
1025    if (!checkDriver()) return;
1026    System.out.println("Class name: " + driver.getClass().getName());
1027    System.out.println("Driver Major Version: " + driver.getMajorVersion());
1028    System.out.println("Driver Minor Version: " + driver.getMinorVersion());
1029  }
1030
1031  public void handleCommand_about(Vector args)
1032  {
1033    System.out.println("");
1034    System.out.println("SimpleListener -- a (very) simple SQL tool");
1035    System.out.println("");
1036  }
1037
1038  private boolean checkDriver()
1039  {
1040    if (driver == null)
1041    {
1042      System.out.println("No driver loaded -- use \"driver drivername\"");
1043      return false;
1044    }
1045    return true;
1046  }
1047
1048  private boolean checkConnected()
1049  {
1050    if (!checkDriver())
1051      return false;
1052    else if (connection == null)
1053    {
1054      System.out.println("Not connected -- use \"connect\"");
1055      return false;
1056    }
1057    return true;
1058  }
1059
1060  private String JavaDoc format(String JavaDoc s, int length)
1061  {
1062    StringBuffer JavaDoc b = new StringBuffer JavaDoc(length);
1063    b.append(s);
1064    for (int i=0; i<length-s.length(); i++)
1065      b.append(" ");
1066    return b.toString();
1067  }
1068
1069  public void handleCommand_h(Vector args)
1070  {
1071    handleCommand_history(args);
1072  }
1073
1074  public void handleCommand_history(Vector args)
1075  {
1076    if (args.size() > 0)
1077    {
1078      try
1079      {
1080        historySize = Integer.parseInt((String JavaDoc)args.elementAt(0));
1081        trimHistory();
1082      }
1083      catch (Exception JavaDoc x) { ; }
1084    }
1085    System.out.println("Command history (max size = " + historySize + "):");
1086    System.out.println("");
1087    Enumeration e = history.elements();
1088    int index = 0;
1089
1090    while (e.hasMoreElements())
1091    {
1092      System.out.println(" " + format(String.valueOf(index), 2) + ": " + e.nextElement());
1093      index++;
1094    }
1095    System.out.println("");
1096    System.out.println(" Type \"!X\" to execute command number X.");
1097    System.out.println("");
1098    System.out.println(" Type \"history n\" to set the length.");
1099    System.out.println("");
1100  }
1101
1102  public void handleCommand_help(Vector args)
1103  {
1104    System.out.println("");
1105    System.out.println("Protomatter SimpleListener -- a simple SQL client.");
1106    System.out.println(" version " + Protomatter.VERSION);
1107    System.out.println("");
1108    System.out.println("Available commands: (in addition to normal SQL)");
1109    System.out.println(" about");
1110    System.out.println(" driver <drivername>");
1111    System.out.println(" connect <URL> [<username> [<password> [ key=val ... key=val ]]]");
1112    System.out.println(" (note: double-quotes are interpreted as you expect in \"connect\")");
1113    System.out.println(" disconnect");
1114    System.out.println(" commit");
1115    System.out.println(" rollback");
1116    System.out.println(" help");
1117    System.out.println(" metadata");
1118    System.out.println(" driverdata");
1119    System.out.println(" connectioninfo");
1120    System.out.println(" autocommit [on|off]");
1121    System.out.println(" showstacktrace [on|off]");
1122    System.out.println(" showquotes [on|off]");
1123    System.out.println(" isolation [level]");
1124    System.out.println(" run <filename>");
1125    System.out.println(" schemas");
1126    System.out.println(" schema <schema>");
1127    System.out.println(" catalogs");
1128    System.out.println(" catalog <catalogname>");
1129    System.out.println(" tables [<schema> [<table_name_substring>]]");
1130    System.out.println(" procedures [<schema>]");
1131    System.out.println(" indexes [<schema>.]<tablename>");
1132    System.out.println(" desc [<schema>.]<tablename>");
1133    System.out.println(" jdesc [<schema>.]<tablename> (describe table in terms of Java types)");
1134    System.out.println(" fkdesc [<schema>.]<tablename> (describe foreign keys on table)");
1135    System.out.println(" history ('h' works too) (display command history)");
1136    System.out.println(" / (executes last command again)");
1137    System.out.println(" quit");
1138    System.out.println("");
1139    System.out.println(" Note: commands can be spread over multiple lines");
1140    System.out.println(" if the last character on each line is a \"\\\"");
1141    System.out.println("");
1142  }
1143
1144  public void handleCommand_connectioninfo(Vector args)
1145  throws SQLException
1146  {
1147    if (checkConnected())
1148    {
1149      System.out.println("");
1150      System.out.println("Connection information:");
1151      System.out.println(" URL: " + this.url);
1152      System.out.println(" Properties:");
1153      int maxlen = 0;
1154      Enumeration e = this.props.keys();
1155      while (e.hasMoreElements())
1156      {
1157        String JavaDoc key = (String JavaDoc)e.nextElement();
1158        if (key.length() > maxlen)
1159          maxlen = key.length();
1160      }
1161
1162      e = this.props.keys();
1163      while (e.hasMoreElements())
1164      {
1165        String JavaDoc key = (String JavaDoc)e.nextElement();
1166        System.out.println(" " + format(key, maxlen) + " = " + this.props.get(key));
1167      }
1168      System.out.println("");
1169      System.out.println(" Isolation level: " + getIsolationString(connection.getTransactionIsolation()));
1170      System.out.println(" Read Only: " + connection.isReadOnly());
1171      System.out.println(" Auto Commit: " + connection.getAutoCommit());
1172      System.out.println("");
1173    }
1174    else
1175    {
1176      System.out.println("");
1177      System.out.println("You are not connected to a database at this time.");
1178      System.out.println("");
1179    }
1180  }
1181
1182  public void handleCommand_autocommit(Vector args)
1183  throws SQLException
1184  {
1185    if (checkConnected())
1186    {
1187      boolean b = false;
1188      if (args.isEmpty())
1189      {
1190        b = connection.getAutoCommit();
1191      }
1192      else
1193      {
1194        String JavaDoc value = (String JavaDoc)args.firstElement();
1195        if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("on"))
1196          b = true;
1197        connection.setAutoCommit(b);
1198      }
1199      System.out.println("Auto-Commit set to " + b);
1200      System.out.println("");
1201    }
1202    else
1203    {
1204      System.out.println("");
1205      System.out.println("You are not connected to a database at this time.");
1206      System.out.println("");
1207    }
1208  }
1209
1210  public void handleCommand_showstacktrace(Vector args)
1211  throws SQLException
1212  {
1213    boolean b = false;
1214    if (args.isEmpty())
1215    {
1216      b = showStackTrace;
1217    }
1218    else
1219    {
1220      String JavaDoc value = (String JavaDoc)args.firstElement();
1221      if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("on"))
1222        b = true;
1223      showStackTrace = b;
1224    }
1225    System.out.println("Show stack trace set to " + b);
1226    System.out.println("");
1227  }
1228
1229  public void handleCommand_showquotes(Vector args)
1230  throws SQLException
1231  {
1232    boolean b = false;
1233    if (args.isEmpty())
1234    {
1235      b = showQuotes;
1236    }
1237    else
1238    {
1239      String JavaDoc value = (String JavaDoc)args.firstElement();
1240      if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("on"))
1241        b = true;
1242      showQuotes = b;
1243    }
1244    System.out.println("Show quotes set to " + b);
1245    System.out.println("");
1246  }
1247
1248  private static final String JavaDoc getType(int type)
1249  {
1250    // look for a type of that value on the Types object
1251
try
1252    {
1253      Field fields[] = Types.class.getFields();
1254      for (int i=0; i<fields.length; i++)
1255      {
1256        Number JavaDoc n = (Number JavaDoc)fields[i].get(null);
1257        int val = n.intValue();
1258        if (val == type)
1259          return fields[i].getName();
1260      }
1261    }
1262    catch (Exception JavaDoc x)
1263    {
1264      ;
1265    }
1266    return null;
1267  }
1268
1269  private void addToHistory(String JavaDoc command)
1270  {
1271    if (!history.contains(command))
1272      history.addElement(command);
1273    trimHistory();
1274  }
1275
1276  private String JavaDoc getHistoryCommand(int index)
1277  {
1278    return (String JavaDoc)history.elementAt(index);
1279  }
1280
1281  private void trimHistory()
1282  {
1283    if (history.size() > historySize)
1284    {
1285      int remove = history.size() - historySize;
1286      for (int i=0; i<remove; i++)
1287        history.removeElementAt(i);
1288    }
1289  }
1290}
1291
Popular Tags