Docjar: A Java Source and Docuemnt Enginecom.*    java.*    javax.*    org.*    all    new    plug-in

Quick Search    Search Deep

Source code: org/hsqldb/util/DatabaseManager.java


1   /* Copyrights and Licenses
2    *
3    * This product includes Hypersonic SQL.
4    * Originally developed by Thomas Mueller and the Hypersonic SQL Group. 
5    *
6    * Copyright (c) 1995-2000 by the Hypersonic SQL Group. All rights reserved. 
7    * Redistribution and use in source and binary forms, with or without modification, are permitted
8    * provided that the following conditions are met: 
9    *     -  Redistributions of source code must retain the above copyright notice, this list of conditions
10   *         and the following disclaimer. 
11   *     -  Redistributions in binary form must reproduce the above copyright notice, this list of
12   *         conditions and the following disclaimer in the documentation and/or other materials
13   *         provided with the distribution. 
14   *     -  All advertising materials mentioning features or use of this software must display the
15   *        following acknowledgment: "This product includes Hypersonic SQL." 
16   *     -  Products derived from this software may not be called "Hypersonic SQL" nor may
17   *        "Hypersonic SQL" appear in their names without prior written permission of the
18   *         Hypersonic SQL Group. 
19   *     -  Redistributions of any form whatsoever must retain the following acknowledgment: "This
20   *          product includes Hypersonic SQL." 
21   * This software is provided "as is" and any expressed or implied warranties, including, but
22   * not limited to, the implied warranties of merchantability and fitness for a particular purpose are
23   * disclaimed. In no event shall the Hypersonic SQL Group or its contributors be liable for any
24   * direct, indirect, incidental, special, exemplary, or consequential damages (including, but
25   * not limited to, procurement of substitute goods or services; loss of use, data, or profits;
26   * or business interruption). However caused any on any theory of liability, whether in contract,
27   * strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this
28   * software, even if advised of the possibility of such damage. 
29   * This software consists of voluntary contributions made by many individuals on behalf of the
30   * Hypersonic SQL Group.
31   *
32   *
33   * For work added by the HSQL Development Group:
34   *
35   * Copyright (c) 2001-2002, The HSQL Development Group
36   * All rights reserved.
37   *
38   * Redistribution and use in source and binary forms, with or without
39   * modification, are permitted provided that the following conditions are met:
40   *
41   * Redistributions of source code must retain the above copyright notice, this
42   * list of conditions and the following disclaimer, including earlier
43   * license statements (above) and comply with all above license conditions.
44   *
45   * Redistributions in binary form must reproduce the above copyright notice,
46   * this list of conditions and the following disclaimer in the documentation
47   * and/or other materials provided with the distribution, including earlier
48   * license statements (above) and comply with all above license conditions.
49   *
50   * Neither the name of the HSQL Development Group nor the names of its
51   * contributors may be used to endorse or promote products derived from this
52   * software without specific prior written permission.
53   *
54   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
55   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57   * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG, 
58   * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
59   * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
60   * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
61   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
62   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
63   * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
64   * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
65   */
66  
67  
68  package org.hsqldb.util;
69  
70  import java.awt.*;
71  import java.awt.event.*;
72  import java.awt.image.*;
73  import java.applet.*;
74  import java.sql.*;
75  import java.io.File;
76  import java.util.*;
77  
78  // sqlbob@users 20020401 - patch 1.7.0 by sqlbob (RMP) - enhancements
79  // sqlbob@users 20020401 - patch 537501 by ulrivo - command line arguments
80  // sqlbob@users 20020407 - patch 1.7.0 - reengineering
81  // nickferguson@users 20021005 - patch 1.7.1 - enhancements
82  
83  /**
84   * AWT Tool for manageing a JDBC database.<p>
85   * <pre>
86   *             Usage: java DatabaseManagerSwing [-options]
87   *             where options include:
88   *              -driver <classname>  jdbc driver class
89   *              -url <name>          jdbc url
90   *              -user <name>         username used for connection
91   *              -password <password> password for this user
92   *              -dir <path>          default directory
93   *              -script <file>       reads from script file
94   *</pre>
95   * @version 1.7.0
96   */
97  public class DatabaseManager extends Applet
98  implements ActionListener, WindowListener, KeyListener {
99  
100     final static String NL         = System.getProperty("line.separator");
101     final static int    iMaxRecent = 24;
102     Connection          cConn;
103     DatabaseMetaData    dMeta;
104     Statement           sStatement;
105     Menu                mRecent;
106     String              sRecent[];
107     int                 iRecent;
108     TextArea            txtCommand;
109     Button              butExecute;
110     Button              butClear;
111     Tree                tTree;
112     Panel               pResult;
113     long                lTime;
114     int                 iResult;    // 0: grid; 1: text
115     Grid                gResult;
116     TextArea            txtResult;
117     boolean             bHelp;
118     Frame               fMain;
119     Image               imgEmpty;
120     static boolean      bMustExit;
121     String              ifHuge = "";
122 
123     // (ulrivo): variables set by arguments from the commandline
124     static String defDriver   = "org.hsqldb.jdbcDriver";
125     static String defURL      = "jdbc:hsqldb:.";
126     static String defUser     = "sa";
127     static String defPassword = "";
128     static String defScript;
129     static String defDirectory;
130 
131     /**
132      * Method declaration
133      *
134      *
135      * @param c
136      */
137     void connect(Connection c) {
138 
139         if (c == null) {
140             return;
141         }
142 
143         if (cConn != null) {
144             try {
145                 cConn.close();
146             } catch (SQLException e) {}
147         }
148 
149         cConn = c;
150 
151         try {
152             dMeta      = cConn.getMetaData();
153             sStatement = cConn.createStatement();
154 
155             refreshTree();
156         } catch (SQLException e) {
157             e.printStackTrace();
158         }
159     }
160 
161     /**
162      * Method declaration
163      *
164      */
165     public void init() {
166 
167         DatabaseManager m = new DatabaseManager();
168 
169         m.main();
170 
171         try {
172             m.connect(ConnectionDialog.createConnection(defDriver, defURL,
173                     defUser, defPassword));
174             m.insertTestData();
175             m.refreshTree();
176         } catch (Exception e) {
177             e.printStackTrace();
178         }
179     }
180 
181     /**
182      * Method declaration
183      *
184      *
185      * @param arg
186      */
187     public static void main(String arg[]) {
188 
189         System.getProperties().put("sun.java2d.noddraw", "true");
190 
191         // (ulrivo): read all arguments from the command line
192         String  lowerArg;
193         boolean autoConnect = false;
194 
195         for (int i = 0; i < arg.length; i++) {
196             lowerArg = arg[i].toLowerCase();
197 
198             i++;
199 
200             if (i == arg.length) {
201                 showUsage();
202 
203                 return;
204             }
205 
206             if (lowerArg.equals("-driver")) {
207                 defDriver   = arg[i];
208                 autoConnect = true;
209             } else if (lowerArg.equals("-url")) {
210                 defURL      = arg[i];
211                 autoConnect = true;
212             } else if (lowerArg.equals("-user")) {
213                 defUser     = arg[i];
214                 autoConnect = true;
215             } else if (lowerArg.equals("-password")) {
216                 defPassword = arg[i];
217                 autoConnect = true;
218             } else if (lowerArg.equals("-dir")) {
219                 defDirectory = arg[i];
220             } else if (lowerArg.equals("-script")) {
221                 defScript = arg[i];
222             } else {
223                 showUsage();
224 
225                 return;
226             }
227         }
228 
229         bMustExit = true;
230 
231         DatabaseManager m = new DatabaseManager();
232 
233         m.main();
234 
235         Connection c = null;
236 
237         try {
238             if (autoConnect) {
239                 c = ConnectionDialog.createConnection(defDriver, defURL,
240                                                       defUser, defPassword);
241             } else {
242                 c = ConnectionDialog.createConnection(m.fMain, "Connect");
243             }
244         } catch (Exception e) {
245             e.printStackTrace();
246         }
247 
248         if (c == null) {
249             return;
250         }
251 
252         m.connect(c);
253     }
254 
255     private static void showUsage() {
256 
257         System.out.println(
258             "Usage: java DatabaseManager [-options]\n"
259             + "where options include:\n"
260             + "    -driver <classname>  jdbc driver class\n"
261             + "    -url <name>          jdbc url\n"
262             + "    -user <name>         username used for connection\n"
263             + "    -password <password> password for this user\n"
264             + "    -dir <path>          default directory\n"
265             + "    -script <file>       reads from script file\n");
266     }
267 
268     /**
269      * Method declaration
270      *
271      */
272     void insertTestData() {
273 
274         try {
275             DatabaseManagerCommon.createTestTables(sStatement);
276             refreshTree();
277             txtCommand.setText(
278                 DatabaseManagerCommon.createTestData(sStatement));
279             refreshTree();
280 
281             for (int i = 0; i < DatabaseManagerCommon.testDataSql.length;
282                     i++) {
283                 addToRecent(DatabaseManagerCommon.testDataSql[i]);
284             }
285 
286             execute();
287         } catch (SQLException e) {
288             e.printStackTrace();
289         }
290     }
291 
292     /**
293      * Method declaration
294      *
295      */
296     void main() {
297 
298         fMain = new Frame("HSQL Database Manager");
299         imgEmpty = createImage(new MemoryImageSource(2, 2, new int[4 * 4], 2,
300                 2));
301 
302         fMain.setIconImage(imgEmpty);
303         fMain.addWindowListener(this);
304 
305         MenuBar bar = new MenuBar();
306 
307         // used shortcuts: CERGTSIUDOLM
308         String fitems[] = {
309             "-Connect...", "--", "-Open Script...", "-Save Script...",
310             "-Save Result...", "--", "-Exit"
311         };
312 
313         addMenu(bar, "File", fitems);
314 
315         String vitems[] = {
316             "RRefresh Tree", "--", "GResults in Grid", "TResults in Text",
317             "--", "1Shrink Tree", "2Enlarge Tree", "3Shrink Command",
318             "4Enlarge Command"
319         };
320 
321         addMenu(bar, "View", vitems);
322 
323         String sitems[] = {
324             "SSELECT", "IINSERT", "UUPDATE", "DDELETE", "--", "-CREATE TABLE",
325             "-DROP TABLE", "-CREATE INDEX", "-DROP INDEX", "--",
326             "-CHECKPOINT", "-SCRIPT", "-SET", "-SHUTDOWN", "--",
327             "-Test Script"
328         };
329 
330         addMenu(bar, "Command", sitems);
331 
332         Menu recent = new Menu("Recent");
333 
334         mRecent = new Menu("Recent");
335 
336         bar.add(mRecent);
337 
338         String soptions[] = {
339             "-AutoCommit on", "-AutoCommit off", "OCommit", "LRollback", "--",
340             "-Disable MaxRows", "-Set MaxRows to 100", "--", "-Logging on",
341             "-Logging off", "--", "-Insert test data"
342         };
343 
344         addMenu(bar, "Options", soptions);
345 
346         String stools[] = {
347             "-Dump", "-Restore", "-Transfer"
348         };
349 
350         addMenu(bar, "Tools", stools);
351         fMain.setMenuBar(bar);
352         fMain.setSize(640, 480);
353         fMain.add("Center", this);
354         initGUI();
355 
356         sRecent = new String[iMaxRecent];
357 
358         Dimension d    = Toolkit.getDefaultToolkit().getScreenSize();
359         Dimension size = fMain.getSize();
360 
361         // (ulrivo): full size on screen with less than 640 width
362         if (d.width >= 640) {
363             fMain.setLocation((d.width - size.width) / 2,
364                               (d.height - size.height) / 2);
365         } else {
366             fMain.setLocation(0, 0);
367             fMain.setSize(d);
368         }
369 
370         fMain.show();
371 
372         // (ulrivo): load query from command line
373         if (defScript != null) {
374             if (defDirectory != null) {
375                 defScript = defDirectory + File.separator + defScript;
376             }
377 
378             txtCommand.setText(DatabaseManagerCommon.readFile(defScript));
379         }
380 
381         txtCommand.requestFocus();
382     }
383 
384     /**
385      * Method declaration
386      *
387      *
388      * @param b
389      * @param name
390      * @param items
391      */
392     void addMenu(MenuBar b, String name, String items[]) {
393 
394         Menu menu = new Menu(name);
395 
396         addMenuItems(menu, items);
397         b.add(menu);
398     }
399 
400     /**
401      * Method declaration
402      *
403      *
404      * @param f
405      * @param m
406      */
407     void addMenuItems(Menu f, String m[]) {
408 
409         for (int i = 0; i < m.length; i++) {
410             MenuItem item = new MenuItem(m[i].substring(1));
411             char     c    = m[i].charAt(0);
412 
413             if (c != '-') {
414                 item.setShortcut(new MenuShortcut(c));
415             }
416 
417             item.addActionListener(this);
418             f.add(item);
419         }
420     }
421 
422     /**
423      * Method declaration
424      *
425      *
426      * @param k
427      */
428     public void keyPressed(KeyEvent k) {}
429 
430     /**
431      * Method declaration
432      *
433      *
434      * @param k
435      */
436     public void keyReleased(KeyEvent k) {}
437 
438     /**
439      * Method declaration
440      *
441      *
442      * @param k
443      */
444     public void keyTyped(KeyEvent k) {
445 
446         if (k.getKeyChar() == '\n' && k.isControlDown()) {
447             k.consume();
448             execute();
449         }
450     }
451 
452     /**
453      * Method declaration
454      *
455      *
456      * @param ev
457      */
458     public void actionPerformed(ActionEvent ev) {
459 
460         String s = ev.getActionCommand();
461 
462         if (s == null) {
463             if (ev.getSource() instanceof MenuItem) {
464                 MenuItem i;
465 
466                 s = ((MenuItem) ev.getSource()).getLabel();
467             }
468         }
469 
470         if (s.equals("Execute")) {
471             execute();
472         } else if (s.equals("Clear")) {
473             clear();
474         } else if (s.equals("Exit")) {
475             windowClosing(null);
476         } else if (s.equals("Transfer")) {
477             Transfer.work(null);
478         } else if (s.equals("Dump")) {
479             Transfer.work(new String[]{ "-d" });
480         } else if (s.equals("Restore")) {
481             Transfer.work(new String[]{ "-r" });
482         } else if (s.equals("Logging on")) {
483             jdbcSystem.setLogToSystem(true);
484         } else if (s.equals("Logging off")) {
485             jdbcSystem.setLogToSystem(false);
486         } else if (s.equals("Refresh Tree")) {
487             refreshTree();
488         } else if (s.startsWith("#")) {
489             int i = Integer.parseInt(s.substring(1));
490 
491             txtCommand.setText(sRecent[i]);
492         } else if (s.equals("Connect...")) {
493             connect(ConnectionDialog.createConnection(fMain, "Connect"));
494             refreshTree();
495         } else if (s.equals("Results in Grid")) {
496             iResult = 0;
497 
498             pResult.removeAll();
499             pResult.add("Center", gResult);
500             pResult.doLayout();
501         } else if (s.equals("Open Script...")) {
502             FileDialog f = new FileDialog(fMain, "Open Script",
503                                           FileDialog.LOAD);
504 
505             // (ulrivo): set default directory if set from command line
506             if (defDirectory != null) {
507                 f.setDirectory(defDirectory);
508             }
509 
510             f.show();
511 
512             String file = f.getFile();
513 
514             if (file != null) {
515                 StringBuffer buf = new StringBuffer();
516 
517                 ifHuge = DatabaseManagerCommon.readFile(f.getDirectory()
518                         + file);
519 
520                 if (4096 <= ifHuge.length()) {
521                     buf.append(
522                         "This huge file cannot be edited. Please execute\n");
523                     txtCommand.setText(buf.toString());
524                 } else {
525                     txtCommand.setText(ifHuge);
526                 }
527             }
528         } else if (s.equals("Save Script...")) {
529             FileDialog f = new FileDialog(fMain, "Save Script",
530                                           FileDialog.SAVE);
531 
532             // (ulrivo): set default directory if set from command line
533             if (defDirectory != null) {
534                 f.setDirectory(defDirectory);
535             }
536 
537             f.show();
538 
539             String file = f.getFile();
540 
541             if (file != null) {
542                 DatabaseManagerCommon.writeFile(f.getDirectory() + file,
543                                                 txtCommand.getText());
544             }
545         } else if (s.equals("Save Result...")) {
546             FileDialog f = new FileDialog(fMain, "Save Result",
547                                           FileDialog.SAVE);
548 
549             // (ulrivo): set default directory if set from command line
550             if (defDirectory != null) {
551                 f.setDirectory(defDirectory);
552             }
553 
554             f.show();
555 
556             String file = f.getFile();
557 
558             if (file != null) {
559                 showResultInText();
560                 DatabaseManagerCommon.writeFile(f.getDirectory() + file,
561                                                 txtResult.getText());
562             }
563         } else if (s.equals("Results in Text")) {
564             iResult = 1;
565 
566             pResult.removeAll();
567             pResult.add("Center", txtResult);
568             pResult.doLayout();
569             showResultInText();
570         } else if (s.equals("AutoCommit on")) {
571             try {
572                 cConn.setAutoCommit(true);
573             } catch (SQLException e) {}
574         } else if (s.equals("AutoCommit off")) {
575             try {
576                 cConn.setAutoCommit(false);
577             } catch (SQLException e) {}
578         } else if (s.equals("Enlarge Tree")) {
579             Dimension d = tTree.getMinimumSize();
580 
581             d.width += 20;
582 
583             tTree.setMinimumSize(d);
584             fMain.pack();
585         } else if (s.equals("Shrink Tree")) {
586             Dimension d = tTree.getMinimumSize();
587 
588             d.width -= 20;
589 
590             if (d.width >= 0) {
591                 tTree.setMinimumSize(d);
592             }
593 
594             fMain.pack();
595         } else if (s.equals("Enlarge Command")) {
596             txtCommand.setRows(txtCommand.getRows() + 1);
597             fMain.pack();
598         } else if (s.equals("Shrink Command")) {
599             int i = txtCommand.getRows() - 1;
600 
601             txtCommand.setRows(i < 1 ? 1
602                                      : i);
603             fMain.pack();
604         } else if (s.equals("Commit")) {
605             try {
606                 cConn.commit();
607             } catch (SQLException e) {}
608         } else if (s.equals("Insert test data")) {
609             insertTestData();
610         } else if (s.equals("Rollback")) {
611             try {
612                 cConn.rollback();
613             } catch (SQLException e) {}
614         } else if (s.equals("Disable MaxRows")) {
615             try {
616                 sStatement.setMaxRows(0);
617             } catch (SQLException e) {}
618         } else if (s.equals("Set MaxRows to 100")) {
619             try {
620                 sStatement.setMaxRows(100);
621             } catch (SQLException e) {}
622         } else if (s.equals("SELECT")) {
623             showHelp(DatabaseManagerCommon.selectHelp);
624         } else if (s.equals("INSERT")) {
625             showHelp(DatabaseManagerCommon.insertHelp);
626         } else if (s.equals("UPDATE")) {
627             showHelp(DatabaseManagerCommon.updateHelp);
628         } else if (s.equals("DELETE")) {
629             showHelp(DatabaseManagerCommon.deleteHelp);
630         } else if (s.equals("CREATE TABLE")) {
631             showHelp(DatabaseManagerCommon.createTableHelp);
632         } else if (s.equals("DROP TABLE")) {
633             showHelp(DatabaseManagerCommon.dropTableHelp);
634         } else if (s.equals("CREATE INDEX")) {
635             showHelp(DatabaseManagerCommon.createIndexHelp);
636         } else if (s.equals("DROP INDEX")) {
637             showHelp(DatabaseManagerCommon.dropIndexHelp);
638         } else if (s.equals("CHECKPOINT")) {
639             showHelp(DatabaseManagerCommon.checkpointHelp);
640         } else if (s.equals("SCRIPT")) {
641             showHelp(DatabaseManagerCommon.scriptHelp);
642         } else if (s.equals("SHUTDOWN")) {
643             showHelp(DatabaseManagerCommon.shutdownHelp);
644         } else if (s.equals("SET")) {
645             showHelp(DatabaseManagerCommon.setHelp);
646         } else if (s.equals("Test Script")) {
647             showHelp(DatabaseManagerCommon.testHelp);
648         }
649     }
650 
651     /**
652      * Method declaration
653      *
654      *
655      * @param s
656      * @param help
657      */
658     void showHelp(String help[]) {
659 
660         txtCommand.setText(help[0]);
661         txtResult.setText(help[1]);
662 
663         bHelp = true;
664 
665         pResult.removeAll();
666         pResult.add("Center", txtResult);
667         pResult.doLayout();
668         txtCommand.requestFocus();
669         txtCommand.setCaretPosition(help[0].length());
670     }
671 
672     /**
673      * Method declaration
674      *
675      *
676      * @param e
677      */
678     public void windowActivated(WindowEvent e) {}
679 
680     /**
681      * Method declaration
682      *
683      *
684      * @param e
685      */
686     public void windowDeactivated(WindowEvent e) {}
687 
688     /**
689      * Method declaration
690      *
691      *
692      * @param e
693      */
694     public void windowClosed(WindowEvent e) {}
695 
696     /**
697      * Method declaration
698      *
699      *
700      * @param ev
701      */
702     public void windowClosing(WindowEvent ev) {
703 
704         try {
705             cConn.close();
706         } catch (Exception e) {}
707 
708         fMain.dispose();
709 
710         if (bMustExit) {
711             System.exit(0);
712         }
713     }
714 
715     /**
716      * Method declaration
717      *
718      *
719      * @param e
720      */
721     public void windowDeiconified(WindowEvent e) {}
722 
723     /**
724      * Method declaration
725      *
726      *
727      * @param e
728      */
729     public void windowIconified(WindowEvent e) {}
730 
731     /**
732      * Method declaration
733      *
734      *
735      * @param e
736      */
737     public void windowOpened(WindowEvent e) {}
738 
739     /**
740      * Method declaration
741      * Clear SQL Statements.
742      */
743     void clear() {
744 
745         ifHuge = "";
746 
747         txtCommand.setText(ifHuge);
748     }
749 
750     /**
751      * Method declaration
752      * Adjust this method for large strings...ie multi megabtypes.
753      */
754     void execute() {
755 
756         String sCmd = null;
757 
758         if (4096 <= ifHuge.length()) {
759             sCmd = ifHuge;
760         } else {
761             sCmd = txtCommand.getText();
762         }
763 
764         if (sCmd.startsWith("-->>>TEST<<<--")) {
765             testPerformance();
766 
767             return;
768         }
769 
770         String g[] = new String[1];
771 
772         try {
773             lTime = System.currentTimeMillis();
774 
775             sStatement.execute(sCmd);
776 
777             int r = sStatement.getUpdateCount();
778 
779             if (r == -1) {
780                 formatResultSet(sStatement.getResultSet());
781             } else {
782                 g[0] = "update count";
783 
784                 gResult.setHead(g);
785 
786                 g[0] = String.valueOf(r);
787 
788                 gResult.addRow(g);
789             }
790 
791             lTime = System.currentTimeMillis() - lTime;
792 
793             addToRecent(txtCommand.getText());
794         } catch (SQLException e) {
795             lTime = System.currentTimeMillis() - lTime;
796             g[0]  = "SQL Error";
797 
798             gResult.setHead(g);
799 
800             String s = e.getMessage();
801 
802             s    += " / Error Code: " + e.getErrorCode();
803             s    += " / State: " + e.getSQLState();
804             g[0] = s;
805 
806             gResult.addRow(g);
807         }
808 
809         updateResult();
810         System.gc();
811     }
812 
813     /**
814      * Method declaration
815      *
816      */
817     void updateResult() {
818 
819         if (iResult == 0) {
820 
821             // in case 'help' has removed the grid
822             if (bHelp) {
823                 pResult.removeAll();
824                 pResult.add("Center", gResult);
825                 pResult.doLayout();
826 
827                 bHelp = false;
828             }
829 
830             gResult.update();
831             gResult.repaint();
832         } else {
833             showResultInText();
834         }
835 
836         txtCommand.selectAll();
837         txtCommand.requestFocus();
838     }
839 
840     /**
841      * Method declaration
842      *
843      *
844      * @param r
845      */
846     void formatResultSet(ResultSet r) {
847 
848         if (r == null) {
849             String g[] = new String[1];
850 
851             g[0] = "Result";
852 
853             gResult.setHead(g);
854 
855             g[0] = "(empty)";
856 
857             gResult.addRow(g);
858 
859             return;
860         }
861 
862         try {
863             ResultSetMetaData m   = r.getMetaData();
864             int               col = m.getColumnCount();
865             String            h[] = new String[col];
866 
867             for (int i = 1; i <= col; i++) {
868                 h[i - 1] = m.getColumnLabel(i);
869             }
870 
871             gResult.setHead(h);
872 
873             while (r.next()) {
874                 for (int i = 1; i <= col; i++) {
875                     h[i - 1] = r.getString(i);
876 
877                     if (r.wasNull()) {
878                         h[i - 1] = "(null)";
879                     }
880                 }
881 
882                 gResult.addRow(h);
883             }
884 
885             r.close();
886         } catch (SQLException e) {}
887     }
888 
889     /**
890      * Method declaration
891      *
892      */
893     void testPerformance() {
894 
895         String       all   = txtCommand.getText();
896         StringBuffer b     = new StringBuffer();
897         long         total = 0;
898 
899         for (int i = 0; i < all.length(); i++) {
900             char c = all.charAt(i);
901 
902             if (c != '\n') {
903                 b.append(c);
904             }
905         }
906 
907         all = b.toString();
908 
909         String g[] = new String[4];
910 
911         g[0] = "ms";
912         g[1] = "count";
913         g[2] = "sql";
914         g[3] = "error";
915 
916         gResult.setHead(g);
917 
918         int max = 1;
919 
920         lTime = System.currentTimeMillis() - lTime;
921 
922         while (!all.equals("")) {
923             int    i = all.indexOf(';');
924             String sql;
925 
926             if (i != -1) {
927                 sql = all.substring(0, i);
928                 all = all.substring(i + 1);
929             } else {
930                 sql = all;
931                 all = "";
932             }
933 
934             if (sql.startsWith("--#")) {
935                 max = Integer.parseInt(sql.substring(3));
936 
937                 continue;
938             } else if (sql.startsWith("--")) {
939                 continue;
940             }
941 
942             g[2] = sql;
943 
944             long l = 0;
945 
946             try {
947                 l = DatabaseManagerCommon.testStatement(sStatement, sql, max);
948                 total += l;
949                 g[0]  = String.valueOf(l);
950                 g[1]  = String.valueOf(max);
951                 g[3]  = "";
952             } catch (SQLException e) {
953                 g[0] = g[1] = "n/a";
954                 g[3] = e.toString();
955             }
956 
957             gResult.addRow(g);
958             System.out.println(l + " ms : " + sql);
959         }
960 
961         g[0] = "" + total;
962         g[1] = "total";
963         g[2] = "";
964 
965         gResult.addRow(g);
966 
967         lTime = System.currentTimeMillis() - lTime;
968 
969         updateResult();
970     }
971 
972     /**
973      * Method declaration
974      *
975      */
976     void showResultInText() {
977 
978         String col[]  = gResult.getHead();
979         int    width  = col.length;
980         int    size[] = new int[width];
981         Vector data   = gResult.getData();
982         String row[];
983         int    height = data.size();
984 
985         for (int i = 0; i < width; i++) {
986             size[i] = col[i].length();
987         }
988 
989         for (int i = 0; i < height; i++) {
990             row = (String[]) data.elementAt(i);
991 
992             for (int j = 0; j < width; j++) {
993                 int l = row[j].length();
994 
995                 if (l > size[j]) {
996                     size[j] = l;
997                 }
998             }
999         }
1000
1001        StringBuffer b = new StringBuffer();
1002
1003        for (int i = 0; i < width; i++) {
1004            b.append(col[i]);
1005
1006            for (int l = col[i].length(); l <= size[i]; l++) {
1007                b.append(' ');
1008            }
1009        }
1010
1011        b.append(NL);
1012
1013        for (int i = 0; i < width; i++) {
1014            for (int l = 0; l < size[i]; l++) {
1015                b.append('-');
1016            }
1017
1018            b.append(' ');
1019        }
1020
1021        b.append(NL);
1022
1023        for (int i = 0; i < height; i++) {
1024            row = (String[]) data.elementAt(i);
1025
1026            for (int j = 0; j < width; j++) {
1027                b.append(row[j]);
1028
1029                for (int l = row[j].length(); l <= size[j]; l++) {
1030                    b.append(' ');
1031                }
1032            }
1033
1034            b.append(NL);
1035        }
1036
1037        b.append(NL + height + " row(s) in " + lTime + " ms");
1038        txtResult.setText(b.toString());
1039    }
1040
1041    /**
1042     * Method declaration
1043     *
1044     *
1045     * @param s
1046     */
1047    private void addToRecent(String s) {
1048
1049        for (int i = 0; i < iMaxRecent; i++) {
1050            if (s.equals(sRecent[i])) {
1051                return;
1052            }
1053        }
1054
1055        if (sRecent[iRecent] != null) {
1056            mRecent.remove(iRecent);
1057        }
1058
1059        sRecent[iRecent] = s;
1060
1061        if (s.length() > 43) {
1062            s = s.substring(0, 40) + "...";
1063        }
1064
1065        MenuItem item = new MenuItem(s);
1066
1067        item.setActionCommand("#" + iRecent);
1068        item.addActionListener(this);
1069        mRecent.insert(item, iRecent);
1070
1071        iRecent = (iRecent + 1) % iMaxRecent;
1072    }
1073
1074    /**
1075     * Method declaration
1076     *
1077     */
1078    private void initGUI() {
1079
1080        Panel pQuery   = new Panel();
1081        Panel pCommand = new Panel();
1082
1083        pResult = new Panel();
1084
1085        pQuery.setLayout(new BorderLayout());
1086        pCommand.setLayout(new BorderLayout());
1087        pResult.setLayout(new BorderLayout());
1088
1089        Font fFont = new Font("Dialog", Font.PLAIN, 12);
1090
1091        txtCommand = new TextArea(5, 40);
1092
1093        txtCommand.addKeyListener(this);
1094
1095        txtResult = new TextArea(20, 40);
1096
1097        txtCommand.setFont(fFont);
1098        txtResult.setFont(new Font("Courier", Font.PLAIN, 12));
1099
1100        butExecute = new Button("Execute");
1101        butClear   = new Button("Clear");
1102
1103        butExecute.addActionListener(this);
1104        butClear.addActionListener(this);
1105        pCommand.add("East", butExecute);
1106        pCommand.add("West", butClear);
1107        pCommand.add("Center", txtCommand);
1108
1109        gResult = new Grid();
1110
1111        setLayout(new BorderLayout());
1112        pResult.add("Center", gResult);
1113        pQuery.add("North", pCommand);
1114        pQuery.add("Center", pResult);
1115        fMain.add("Center", pQuery);
1116
1117        tTree = new Tree();
1118
1119        // (ulrivo): screen with less than 640 width
1120        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
1121
1122        if (d.width >= 640) {
1123            tTree.setMinimumSize(new Dimension(200, 100));
1124        } else {
1125            tTree.setMinimumSize(new Dimension(80, 100));
1126        }
1127
1128        gResult.setMinimumSize(new Dimension(200, 300));
1129        fMain.add("West", tTree);
1130        doLayout();
1131        fMain.pack();
1132    }
1133
1134    /**
1135     * Method declaration
1136     *
1137     */
1138    protected void refreshTree() {
1139
1140        tTree.removeAll();
1141
1142        try {
1143            int color_table  = Color.yellow.getRGB();
1144            int color_column = Color.orange.getRGB();
1145            int color_index  = Color.red.getRGB();
1146
1147            tTree.addRow("", dMeta.getURL(), "-", 0);
1148
1149            String    usertables[] = {
1150                "TABLE", "GLOBAL TEMPORARY", "VIEW"
1151            };
1152            ResultSet result = dMeta.getTables(null, null, null, usertables);
1153            Vector    tables       = new Vector();
1154
1155            // sqlbob@users Added remarks.
1156            Vector remarks = new Vector();
1157
1158            while (result.next()) {
1159                tables.addElement(result.getString(3));
1160                remarks.addElement(result.getString(5));
1161            }
1162
1163            result.close();
1164
1165            for (int i = 0; i < tables.size(); i++) {
1166                String name = (String) tables.elementAt(i);
1167                String key  = "tab-" + name + "-";
1168
1169                tTree.addRow(key, name, "+", color_table);
1170
1171                // sqlbob@users Added remarks.
1172                String remark = (String) remarks.elementAt(i);
1173
1174                if ((remark != null) &&!remark.trim().equals("")) {
1175                    tTree.addRow(key + "r", " " + remark);
1176                }
1177
1178                ResultSet col = dMeta.getColumns(null, null, name, null);
1179
1180                while (col.next()) {
1181                    String c  = col.getString(4);
1182                    String k1 = key + "col-" + c + "-";
1183
1184                    tTree.addRow(k1, c, "+", color_column);
1185
1186                    String type = col.getString(6);
1187
1188                    tTree.addRow(k1 + "t", "Type: " + type);
1189
1190                    boolean nullable = col.getInt(11)
1191                                       != DatabaseMetaData.columnNoNulls;
1192
1193                    tTree.addRow(k1 + "n", "Nullable: " + nullable);
1194                }
1195
1196                col.close();
1197                tTree.addRow(key + "ind", "Indices", "+", 0);
1198
1199                ResultSet ind = dMeta.getIndexInfo(null, null, name, false,
1200                                                   false);
1201                String oldiname = null;
1202
1203                while (ind.next()) {
1204                    boolean nonunique = ind.getBoolean(4);
1205                    String  iname     = ind.getString(6);
1206                    String  k2        = key + "ind-" + iname + "-";
1207
1208                    if ((oldiname == null ||!oldiname.equals(iname))) {
1209                        tTree.addRow(k2, iname, "+", color_index);
1210                        tTree.addRow(k2 + "u", "Unique: " + !nonunique);
1211
1212                        oldiname = iname;
1213                    }
1214
1215                    String c = ind.getString(9);
1216
1217                    tTree.addRow(k2 + "c-" + c + "-", c);
1218                }
1219
1220                ind.close();
1221            }
1222
1223            tTree.addRow("p", "Properties", "+", 0);
1224            tTree.addRow("pu", "User: " + dMeta.getUserName());
1225            tTree.addRow("pr", "ReadOnly: " + cConn.isReadOnly());
1226            tTree.addRow("pa", "AutoCommit: " + cConn.getAutoCommit());
1227            tTree.addRow("pd", "Driver: " + dMeta.getDriverName());
1228            tTree.addRow("pp", "Product: " + dMeta.getDatabaseProductName());
1229            tTree.addRow("pv",
1230                         "Version: " + dMeta.getDatabaseProductVersion());
1231        } catch (SQLException e) {
1232            tTree.addRow("", "Error getting metadata:", "-", 0);
1233            tTree.addRow("-", e.getMessage());
1234            tTree.addRow("-", e.getSQLState());
1235        }
1236
1237        tTree.update();
1238    }
1239}