KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > hsqldb > util > DatabaseManager


1 /* Copyright (c) 2001-2005, The HSQL Development Group
2  * All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are met:
6  *
7  * Redistributions of source code must retain the above copyright notice, this
8  * list of conditions and the following disclaimer.
9  *
10  * Redistributions in binary form must reproduce the above copyright notice,
11  * this list of conditions and the following disclaimer in the documentation
12  * and/or other materials provided with the distribution.
13  *
14  * Neither the name of the HSQL Development Group nor the names of its
15  * contributors may be used to endorse or promote products derived from this
16  * software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
22  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (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  */

30
31
32 package org.hsqldb.util;
33
34 import java.applet.Applet JavaDoc;
35 import java.io.File JavaDoc;
36 import java.io.IOException JavaDoc;
37 import java.sql.Connection JavaDoc;
38 import java.sql.DatabaseMetaData JavaDoc;
39 import java.sql.ResultSet JavaDoc;
40 import java.sql.ResultSetMetaData JavaDoc;
41 import java.sql.SQLException JavaDoc;
42 import java.sql.Statement JavaDoc;
43 import java.util.Vector JavaDoc;
44 import java.awt.BorderLayout JavaDoc;
45 import java.awt.Button JavaDoc;
46 import java.awt.Color JavaDoc;
47 import java.awt.Dimension JavaDoc;
48 import java.awt.FileDialog JavaDoc;
49 import java.awt.Font JavaDoc;
50 import java.awt.Frame JavaDoc;
51 import java.awt.Image JavaDoc;
52 import java.awt.Menu JavaDoc;
53 import java.awt.MenuBar JavaDoc;
54 import java.awt.MenuItem JavaDoc;
55 import java.awt.MenuShortcut JavaDoc;
56 import java.awt.Panel JavaDoc;
57 import java.awt.TextArea JavaDoc;
58 import java.awt.Toolkit JavaDoc;
59 import java.awt.event.ActionEvent JavaDoc;
60 import java.awt.event.ActionListener JavaDoc;
61 import java.awt.event.KeyEvent JavaDoc;
62 import java.awt.event.KeyListener JavaDoc;
63 import java.awt.event.WindowEvent JavaDoc;
64 import java.awt.event.WindowListener JavaDoc;
65 import java.awt.image.MemoryImageSource JavaDoc;
66
67 import org.hsqldb.lib.java.JavaSystem;
68
69 // sqlbob@users 20020401 - patch 1.7.0 by sqlbob (RMP) - enhancements
70
// sqlbob@users 20020401 - patch 537501 by ulrivo - command line arguments
71
// sqlbob@users 20020407 - patch 1.7.0 - reengineering
72
// nickferguson@users 20021005 - patch 1.7.1 - enhancements
73

74 /**
75  * AWT Tool for manageing a JDBC database.<p>
76  * <pre>
77  * Usage: java DatabaseManagerSwing [--options]
78  * where options include:
79  * --driver <classname> jdbc driver class
80  * --url <name> jdbc url
81  * --user <name> username used for connection
82  * --password <password> password for this user
83  * --urlid <urlid> get connection info from RC file
84  * --rcfile <file> use instead of default (with urlid)
85  * --dir <path> default directory
86  * --script <file> reads from script file
87  *</pre>
88  * Tue Apr 26 16:38:54 EDT 2005
89  * Switched default switch method from "-switch" to "--switch" because
90  * "-switch" usage is ambiguous as used here. Single switches should
91  * be reserved for single-letter switches which can be mixed like
92  * "-u -r -l" = "-url". -blaine
93  *
94  * @author Thomas Mueller (Hypersonic SQL Group)
95  * @version 1.8.0
96  * @since Hypersonic SQL
97  */

98 public class DatabaseManager extends Applet JavaDoc
99 implements ActionListener JavaDoc, WindowListener JavaDoc, KeyListener JavaDoc {
100
101     private static final String JavaDoc DEFAULT_RCFILE =
102         System.getProperty("user.home") + "/dbmanager.rc";
103     static final String JavaDoc NL = System.getProperty("line.separator");
104     static final int iMaxRecent = 24;
105     Connection JavaDoc cConn;
106     DatabaseMetaData JavaDoc dMeta;
107     Statement JavaDoc sStatement;
108     Menu JavaDoc mRecent;
109     String JavaDoc[] sRecent;
110     int iRecent;
111     TextArea JavaDoc txtCommand;
112     Button JavaDoc butExecute;
113     Button JavaDoc butClear;
114     Tree tTree;
115     Panel JavaDoc pResult;
116     long lTime;
117     int iResult; // 0: grid; 1: text
118
Grid gResult;
119     TextArea JavaDoc txtResult;
120     boolean bHelp;
121     Frame JavaDoc fMain;
122     Image JavaDoc imgEmpty;
123     static boolean bMustExit;
124     String JavaDoc ifHuge = "";
125
126     // (ulrivo): variables set by arguments from the commandline
127
static String JavaDoc defDriver = "org.hsqldb.jdbcDriver";
128     static String JavaDoc defURL = "jdbc:hsqldb:.";
129     static String JavaDoc defUser = "sa";
130     static String JavaDoc defPassword = "";
131     static String JavaDoc defScript;
132     static String JavaDoc defDirectory;
133
134     /**
135      * Method declaration
136      *
137      *
138      * @param c
139      */

140     public void connect(Connection JavaDoc c) {
141
142         if (c == null) {
143             return;
144         }
145
146         if (cConn != null) {
147             try {
148                 cConn.close();
149             } catch (SQLException JavaDoc e) {}
150         }
151
152         cConn = c;
153
154         try {
155             dMeta = cConn.getMetaData();
156             sStatement = cConn.createStatement();
157
158             refreshTree();
159         } catch (SQLException JavaDoc e) {
160             e.printStackTrace();
161         }
162     }
163
164     /**
165      * Method declaration
166      *
167      */

168     public void init() {
169
170         DatabaseManager m = new DatabaseManager();
171
172         m.main();
173
174         try {
175             m.connect(ConnectionDialog.createConnection(defDriver, defURL,
176                     defUser, defPassword));
177             m.insertTestData();
178             m.refreshTree();
179         } catch (Exception JavaDoc e) {
180             e.printStackTrace();
181         }
182     }
183
184     /**
185      * Method declaration
186      *
187      *
188      * @param arg
189      */

190     public static void main(String JavaDoc[] arg) {
191
192         System.getProperties().put("sun.java2d.noddraw", "true");
193
194         // (ulrivo): read all arguments from the command line
195
String JavaDoc lowerArg;
196         String JavaDoc urlid = null;
197         String JavaDoc rcFile = null;
198         boolean autoConnect = false;
199         boolean urlidConnect = false;
200
201         bMustExit = true;
202
203         for (int i = 0; i < arg.length; i++) {
204             lowerArg = arg[i].toLowerCase();
205
206             if (lowerArg.length() > 1 && lowerArg.charAt(1) == '-') {
207                 lowerArg = lowerArg.substring(1);
208             }
209
210             i++;
211
212             if (i == arg.length) {
213                 showUsage();
214
215                 return;
216             }
217
218             if (lowerArg.equals("-driver")) {
219                 defDriver = arg[i];
220                 autoConnect = true;
221             } else if (lowerArg.equals("-url")) {
222                 defURL = arg[i];
223                 autoConnect = true;
224             } else if (lowerArg.equals("-user")) {
225                 defUser = arg[i];
226                 autoConnect = true;
227             } else if (lowerArg.equals("-password")) {
228                 defPassword = arg[i];
229                 autoConnect = true;
230             } else if (lowerArg.equals("-urlid")) {
231                 urlid = arg[i];
232                 urlidConnect = true;
233             } else if (lowerArg.equals("-rcfile")) {
234                 rcFile = arg[i];
235                 urlidConnect = true;
236             } else if (lowerArg.equals("-dir")) {
237                 defDirectory = arg[i];
238             } else if (lowerArg.equals("-script")) {
239                 defScript = arg[i];
240             } else if (lowerArg.equals("-noexit")) {
241                 bMustExit = false;
242
243                 i--;
244             } else {
245                 showUsage();
246
247                 return;
248             }
249         }
250
251         DatabaseManager m = new DatabaseManager();
252
253         m.main();
254
255         Connection JavaDoc c = null;
256
257         try {
258             if (autoConnect && urlidConnect) {
259                 throw new IllegalArgumentException JavaDoc(
260                     "You may not specify both (urlid) AND (url/user/password).");
261             }
262
263             if (autoConnect) {
264                 c = ConnectionDialog.createConnection(defDriver, defURL,
265                                                       defUser, defPassword);
266             } else if (urlidConnect) {
267                 if (urlid == null) {
268                     throw new IllegalArgumentException JavaDoc(
269                         "You must specify an 'urlid' to use an RC file");
270                 }
271
272                 autoConnect = true;
273                 c = (new RCData(new File JavaDoc((rcFile == null) ? DEFAULT_RCFILE
274                                                           : rcFile), urlid).getConnection(
275                                                           null, System.getProperty(
276                                                               "sqlfile.charset"), System.getProperty(
277                                                                   "javax.net.ssl.trustStore")));
278             } else {
279                 c = ConnectionDialog.createConnection(m.fMain, "Connect");
280             }
281         } catch (Exception JavaDoc e) {
282             e.printStackTrace();
283         }
284
285         if (c == null) {
286             return;
287         }
288
289         m.connect(c);
290     }
291
292     private static void showUsage() {
293
294         System.out.println(
295             "Usage: java DatabaseManager [--options]\n"
296             + "where options include:\n"
297             + " --driver <classname> jdbc driver class\n"
298             + " --url <name> jdbc url\n"
299             + " --user <name> username used for connection\n"
300             + " --password <password> password for this user\n"
301             + " --urlid <urlid> use url/user/password/driver in rc file\n"
302             + " --rcfile <file> (defaults to 'dbmanager.rc' in home dir)\n"
303             + " --dir <path> default directory\n"
304             + " --script <file> reads from script file\n"
305             + " --noexit do not call system.exit()\n"
306             + "(Single-hypen switches like '-driver' are also supported)");
307     }
308
309     /**
310      * Method declaration
311      *
312      */

313     void insertTestData() {
314
315         try {
316             DatabaseManagerCommon.createTestTables(sStatement);
317             refreshTree();
318             txtCommand.setText(
319                 DatabaseManagerCommon.createTestData(sStatement));
320             refreshTree();
321
322             for (int i = 0; i < DatabaseManagerCommon.testDataSql.length;
323                     i++) {
324                 addToRecent(DatabaseManagerCommon.testDataSql[i]);
325             }
326
327             execute();
328         } catch (SQLException JavaDoc e) {
329             e.printStackTrace();
330         }
331     }
332
333     /**
334      * Method declaration
335      *
336      */

337     public void main() {
338
339         fMain = new Frame JavaDoc("HSQL Database Manager");
340         imgEmpty = createImage(new MemoryImageSource JavaDoc(2, 2, new int[4 * 4], 2,
341                 2));
342
343         fMain.setIconImage(imgEmpty);
344         fMain.addWindowListener(this);
345
346         MenuBar JavaDoc bar = new MenuBar JavaDoc();
347
348         // used shortcuts: CERGTSIUDOLM
349
String JavaDoc[] fitems = {
350             "-Connect...", "--", "-Open Script...", "-Save Script...",
351             "-Save Result...", "-Save Result csv...", "--", "-Exit"
352         };
353
354         addMenu(bar, "File", fitems);
355
356         String JavaDoc[] vitems = {
357             "RRefresh Tree", "--", "GResults in Grid", "TResults in Text",
358             "--", "1Shrink Tree", "2Enlarge Tree", "3Shrink Command",
359             "4Enlarge Command"
360         };
361
362         addMenu(bar, "View", vitems);
363
364         String JavaDoc[] sitems = {
365             "SSELECT", "IINSERT", "UUPDATE", "DDELETE", "--", "-CREATE TABLE",
366             "-DROP TABLE", "-CREATE INDEX", "-DROP INDEX", "--",
367             "-CHECKPOINT", "-SCRIPT", "-SET", "-SHUTDOWN", "--",
368             "-Test Script"
369         };
370
371         addMenu(bar, "Command", sitems);
372
373         Menu JavaDoc recent = new Menu JavaDoc("Recent");
374
375         mRecent = new Menu JavaDoc("Recent");
376
377         bar.add(mRecent);
378
379         String JavaDoc[] soptions = {
380             "-AutoCommit on", "-AutoCommit off", "OCommit", "LRollback", "--",
381             "-Disable MaxRows", "-Set MaxRows to 100", "--", "-Logging on",
382             "-Logging off", "--", "-Insert test data"
383         };
384
385         addMenu(bar, "Options", soptions);
386
387         String JavaDoc[] stools = {
388             "-Dump", "-Restore", "-Transfer"
389         };
390
391         addMenu(bar, "Tools", stools);
392         fMain.setMenuBar(bar);
393         fMain.setSize(640, 480);
394         fMain.add("Center", this);
395         initGUI();
396
397         sRecent = new String JavaDoc[iMaxRecent];
398
399         Dimension JavaDoc d = Toolkit.getDefaultToolkit().getScreenSize();
400         Dimension JavaDoc size = fMain.getSize();
401
402         // (ulrivo): full size on screen with less than 640 width
403
if (d.width >= 640) {
404             fMain.setLocation((d.width - size.width) / 2,
405                               (d.height - size.height) / 2);
406         } else {
407             fMain.setLocation(0, 0);
408             fMain.setSize(d);
409         }
410
411         fMain.show();
412
413         // (ulrivo): load query from command line
414
if (defScript != null) {
415             if (defDirectory != null) {
416                 defScript = defDirectory + File.separator + defScript;
417             }
418
419             txtCommand.setText(DatabaseManagerCommon.readFile(defScript));
420         }
421
422         txtCommand.requestFocus();
423     }
424
425     /**
426      * Method declaration
427      *
428      *
429      * @param b
430      * @param name
431      * @param items
432      */

433     void addMenu(MenuBar JavaDoc b, String JavaDoc name, String JavaDoc[] items) {
434
435         Menu JavaDoc menu = new Menu JavaDoc(name);
436
437         addMenuItems(menu, items);
438         b.add(menu);
439     }
440
441     /**
442      * Method declaration
443      *
444      *
445      * @param f
446      * @param m
447      */

448     void addMenuItems(Menu JavaDoc f, String JavaDoc[] m) {
449
450         for (int i = 0; i < m.length; i++) {
451             MenuItem JavaDoc item = new MenuItem JavaDoc(m[i].substring(1));
452             char c = m[i].charAt(0);
453
454             if (c != '-') {
455                 item.setShortcut(new MenuShortcut JavaDoc(c));
456             }
457
458             item.addActionListener(this);
459             f.add(item);
460         }
461     }
462
463     /**
464      * Method declaration
465      *
466      *
467      * @param k
468      */

469     public void keyPressed(KeyEvent JavaDoc k) {}
470
471     /**
472      * Method declaration
473      *
474      *
475      * @param k
476      */

477     public void keyReleased(KeyEvent JavaDoc k) {}
478
479     /**
480      * Method declaration
481      *
482      *
483      * @param k
484      */

485     public void keyTyped(KeyEvent JavaDoc k) {
486
487         if (k.getKeyChar() == '\n' && k.isControlDown()) {
488             k.consume();
489             execute();
490         }
491     }
492
493     /**
494      * Method declaration
495      *
496      *
497      * @param ev
498      */

499     public void actionPerformed(ActionEvent JavaDoc ev) {
500
501         String JavaDoc s = ev.getActionCommand();
502
503         if (s == null) {
504             if (ev.getSource() instanceof MenuItem JavaDoc) {
505                 MenuItem JavaDoc i;
506
507                 s = ((MenuItem JavaDoc) ev.getSource()).getLabel();
508             }
509         }
510
511         if (s == null) {}
512         else if (s.equals("Execute")) {
513             execute();
514         } else if (s.equals("Clear")) {
515             clear();
516         } else if (s.equals("Exit")) {
517             windowClosing(null);
518         } else if (s.equals("Transfer")) {
519             Transfer.work(null);
520         } else if (s.equals("Dump")) {
521             Transfer.work(new String JavaDoc[]{ "-d" });
522         } else if (s.equals("Restore")) {
523             Transfer.work(new String JavaDoc[]{ "-r" });
524         } else if (s.equals("Logging on")) {
525             JavaSystem.setLogToSystem(true);
526         } else if (s.equals("Logging off")) {
527             JavaSystem.setLogToSystem(false);
528         } else if (s.equals("Refresh Tree")) {
529             refreshTree();
530         } else if (s.startsWith("#")) {
531             int i = Integer.parseInt(s.substring(1));
532
533             txtCommand.setText(sRecent[i]);
534         } else if (s.equals("Connect...")) {
535             connect(ConnectionDialog.createConnection(fMain, "Connect"));
536             refreshTree();
537         } else if (s.equals("Results in Grid")) {
538             iResult = 0;
539
540             pResult.removeAll();
541             pResult.add("Center", gResult);
542             pResult.doLayout();
543         } else if (s.equals("Open Script...")) {
544             FileDialog JavaDoc f = new FileDialog JavaDoc(fMain, "Open Script",
545                                           FileDialog.LOAD);
546
547             // (ulrivo): set default directory if set from command line
548
if (defDirectory != null) {
549                 f.setDirectory(defDirectory);
550             }
551
552             f.show();
553
554             String JavaDoc file = f.getFile();
555
556             if (file != null) {
557                 StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
558
559                 ifHuge = DatabaseManagerCommon.readFile(f.getDirectory()
560                         + file);
561
562                 if (4096 <= ifHuge.length()) {
563                     buf.append(
564                         "This huge file cannot be edited. Please execute\n");
565                     txtCommand.setText(buf.toString());
566                 } else {
567                     txtCommand.setText(ifHuge);
568                 }
569             }
570         } else if (s.equals("Save Script...")) {
571             FileDialog JavaDoc f = new FileDialog JavaDoc(fMain, "Save Script",
572                                           FileDialog.SAVE);
573
574             // (ulrivo): set default directory if set from command line
575
if (defDirectory != null) {
576                 f.setDirectory(defDirectory);
577             }
578
579             f.show();
580
581             String JavaDoc file = f.getFile();
582
583             if (file != null) {
584                 DatabaseManagerCommon.writeFile(f.getDirectory() + file,
585                                                 txtCommand.getText());
586             }
587         } else if (s.equals("Save Result csv...")) {
588             FileDialog JavaDoc f = new FileDialog JavaDoc(fMain, "Save Result CSV",
589                                           FileDialog.SAVE);
590
591             // (ulrivo): set default directory if set from command line
592
if (defDirectory != null) {
593                 f.setDirectory(defDirectory);
594             }
595
596             f.show();
597
598             String JavaDoc dir = f.getDirectory();
599             String JavaDoc file = f.getFile();
600
601             if (dir != null) {
602                 file = dir + "/" + file;
603             }
604
605             if (file != null) {
606                 showResultInText();
607                 saveAsCsv(file);
608             }
609         } else if (s.equals("Save Result...")) {
610             FileDialog JavaDoc f = new FileDialog JavaDoc(fMain, "Save Result",
611                                           FileDialog.SAVE);
612
613             // (ulrivo): set default directory if set from command line
614
if (defDirectory != null) {
615                 f.setDirectory(defDirectory);
616             }
617
618             f.show();
619
620             String JavaDoc file = f.getFile();
621
622             if (file != null) {
623                 showResultInText();
624                 DatabaseManagerCommon.writeFile(f.getDirectory() + file,
625                                                 txtResult.getText());
626             }
627         } else if (s.equals("Results in Text")) {
628             iResult = 1;
629
630             pResult.removeAll();
631             pResult.add("Center", txtResult);
632             pResult.doLayout();
633             showResultInText();
634         } else if (s.equals("AutoCommit on")) {
635             try {
636                 cConn.setAutoCommit(true);
637             } catch (SQLException JavaDoc e) {}
638         } else if (s.equals("AutoCommit off")) {
639             try {
640                 cConn.setAutoCommit(false);
641             } catch (SQLException JavaDoc e) {}
642         } else if (s.equals("Enlarge Tree")) {
643             Dimension JavaDoc d = tTree.getMinimumSize();
644
645             d.width += 20;
646
647             tTree.setMinimumSize(d);
648             fMain.pack();
649         } else if (s.equals("Shrink Tree")) {
650             Dimension JavaDoc d = tTree.getMinimumSize();
651
652             d.width -= 20;
653
654             if (d.width >= 0) {
655                 tTree.setMinimumSize(d);
656             }
657
658             fMain.pack();
659         } else if (s.equals("Enlarge Command")) {
660             txtCommand.setRows(txtCommand.getRows() + 1);
661             fMain.pack();
662         } else if (s.equals("Shrink Command")) {
663             int i = txtCommand.getRows() - 1;
664
665             txtCommand.setRows(i < 1 ? 1
666                                      : i);
667             fMain.pack();
668         } else if (s.equals("Commit")) {
669             try {
670                 cConn.commit();
671             } catch (SQLException JavaDoc e) {}
672         } else if (s.equals("Insert test data")) {
673             insertTestData();
674         } else if (s.equals("Rollback")) {
675             try {
676                 cConn.rollback();
677             } catch (SQLException JavaDoc e) {}
678         } else if (s.equals("Disable MaxRows")) {
679             try {
680                 sStatement.setMaxRows(0);
681             } catch (SQLException JavaDoc e) {}
682         } else if (s.equals("Set MaxRows to 100")) {
683             try {
684                 sStatement.setMaxRows(100);
685             } catch (SQLException JavaDoc e) {}
686         } else if (s.equals("SELECT")) {
687             showHelp(DatabaseManagerCommon.selectHelp);
688         } else if (s.equals("INSERT")) {
689             showHelp(DatabaseManagerCommon.insertHelp);
690         } else if (s.equals("UPDATE")) {
691             showHelp(DatabaseManagerCommon.updateHelp);
692         } else if (s.equals("DELETE")) {
693             showHelp(DatabaseManagerCommon.deleteHelp);
694         } else if (s.equals("CREATE TABLE")) {
695             showHelp(DatabaseManagerCommon.createTableHelp);
696         } else if (s.equals("DROP TABLE")) {
697             showHelp(DatabaseManagerCommon.dropTableHelp);
698         } else if (s.equals("CREATE INDEX")) {
699             showHelp(DatabaseManagerCommon.createIndexHelp);
700         } else if (s.equals("DROP INDEX")) {
701             showHelp(DatabaseManagerCommon.dropIndexHelp);
702         } else if (s.equals("CHECKPOINT")) {
703             showHelp(DatabaseManagerCommon.checkpointHelp);
704         } else if (s.equals("SCRIPT")) {
705             showHelp(DatabaseManagerCommon.scriptHelp);
706         } else if (s.equals("SHUTDOWN")) {
707             showHelp(DatabaseManagerCommon.shutdownHelp);
708         } else if (s.equals("SET")) {
709             showHelp(DatabaseManagerCommon.setHelp);
710         } else if (s.equals("Test Script")) {
711             showHelp(DatabaseManagerCommon.testHelp);
712         }
713     }
714
715     /**
716      * Method declaration
717      *
718      *
719      * @param s
720      * @param help
721      */

722     void showHelp(String JavaDoc[] help) {
723
724         txtCommand.setText(help[0]);
725         txtResult.setText(help[1]);
726
727         bHelp = true;
728
729         pResult.removeAll();
730         pResult.add("Center", txtResult);
731         pResult.doLayout();
732         txtCommand.requestFocus();
733         txtCommand.setCaretPosition(help[0].length());
734     }
735
736     /**
737      * Method declaration
738      *
739      *
740      * @param e
741      */

742     public void windowActivated(WindowEvent JavaDoc e) {}
743
744     /**
745      * Method declaration
746      *
747      *
748      * @param e
749      */

750     public void windowDeactivated(WindowEvent JavaDoc e) {}
751
752     /**
753      * Method declaration
754      *
755      *
756      * @param e
757      */

758     public void windowClosed(WindowEvent JavaDoc e) {}
759
760     /**
761      * Method declaration
762      *
763      *
764      * @param ev
765      */

766     public void windowClosing(WindowEvent JavaDoc ev) {
767
768         try {
769             cConn.close();
770         } catch (Exception JavaDoc e) {}
771
772         fMain.dispose();
773
774         if (bMustExit) {
775             System.exit(0);
776         }
777     }
778
779     /**
780      * Method declaration
781      *
782      *
783      * @param e
784      */

785     public void windowDeiconified(WindowEvent JavaDoc e) {}
786
787     /**
788      * Method declaration
789      *
790      *
791      * @param e
792      */

793     public void windowIconified(WindowEvent JavaDoc e) {}
794
795     /**
796      * Method declaration
797      *
798      *
799      * @param e
800      */

801     public void windowOpened(WindowEvent JavaDoc e) {}
802
803     /**
804      * Method declaration
805      * Clear SQL Statements.
806      */

807     void clear() {
808
809         ifHuge = "";
810
811         txtCommand.setText(ifHuge);
812     }
813
814     /**
815      * Method declaration
816      * Adjust this method for large strings...ie multi megabtypes.
817      */

818     void execute() {
819
820         String JavaDoc sCmd = null;
821
822         if (4096 <= ifHuge.length()) {
823             sCmd = ifHuge;
824         } else {
825             sCmd = txtCommand.getText();
826         }
827
828         if (sCmd.startsWith("-->>>TEST<<<--")) {
829             testPerformance();
830
831             return;
832         }
833
834         String JavaDoc[] g = new String JavaDoc[1];
835
836         lTime = System.currentTimeMillis();
837
838         try {
839             sStatement.execute(sCmd);
840
841             lTime = System.currentTimeMillis() - lTime;
842
843             int r = sStatement.getUpdateCount();
844
845             if (r == -1) {
846                 formatResultSet(sStatement.getResultSet());
847             } else {
848                 g[0] = "update count";
849
850                 gResult.setHead(g);
851
852                 g[0] = String.valueOf(r);
853
854                 gResult.addRow(g);
855             }
856
857             addToRecent(txtCommand.getText());
858         } catch (SQLException JavaDoc e) {
859             lTime = System.currentTimeMillis() - lTime;
860             g[0] = "SQL Error";
861
862             gResult.setHead(g);
863
864             String JavaDoc s = e.getMessage();
865
866             s += " / Error Code: " + e.getErrorCode();
867             s += " / State: " + e.getSQLState();
868             g[0] = s;
869
870             gResult.addRow(g);
871         }
872
873         updateResult();
874         System.gc();
875     }
876
877     /**
878      * Method declaration
879      *
880      */

881     void updateResult() {
882
883         if (iResult == 0) {
884
885             // in case 'help' has removed the grid
886
if (bHelp) {
887                 pResult.removeAll();
888                 pResult.add("Center", gResult);
889                 pResult.doLayout();
890
891                 bHelp = false;
892             }
893
894             gResult.update();
895             gResult.repaint();
896         } else {
897             showResultInText();
898         }
899
900         txtCommand.selectAll();
901         txtCommand.requestFocus();
902     }
903
904     /**
905      * Method declaration
906      *
907      *
908      * @param r
909      */

910     void formatResultSet(ResultSet JavaDoc r) {
911
912         if (r == null) {
913             String JavaDoc[] g = new String JavaDoc[1];
914
915             g[0] = "Result";
916
917             gResult.setHead(g);
918
919             g[0] = "(empty)";
920
921             gResult.addRow(g);
922
923             return;
924         }
925
926         try {
927             ResultSetMetaData JavaDoc m = r.getMetaData();
928             int col = m.getColumnCount();
929             String JavaDoc[] h = new String JavaDoc[col];
930
931             for (int i = 1; i <= col; i++) {
932                 h[i - 1] = m.getColumnLabel(i);
933             }
934
935             gResult.setHead(h);
936
937             while (r.next()) {
938                 for (int i = 1; i <= col; i++) {
939                     try {
940                         h[i - 1] = r.getString(i);
941
942                         if (r.wasNull()) {
943                             h[i - 1] = "(null)";
944                         }
945                     } catch (SQLException JavaDoc e) {}
946                 }
947
948                 gResult.addRow(h);
949             }
950
951             r.close();
952         } catch (SQLException JavaDoc e) {}
953     }
954
955     /**
956      * Method declaration
957      *
958      */

959     void testPerformance() {
960
961         String JavaDoc all = txtCommand.getText();
962         StringBuffer JavaDoc b = new StringBuffer JavaDoc();
963         long total = 0;
964
965         for (int i = 0; i < all.length(); i++) {
966             char c = all.charAt(i);
967
968             if (c != '\n') {
969                 b.append(c);
970             }
971         }
972
973         all = b.toString();
974
975         String JavaDoc[] g = new String JavaDoc[4];
976
977         g[0] = "ms";
978         g[1] = "count";
979         g[2] = "sql";
980         g[3] = "error";
981
982         gResult.setHead(g);
983
984         int max = 1;
985
986         lTime = System.currentTimeMillis() - lTime;
987
988         while (!all.equals("")) {
989             int i = all.indexOf(';');
990             String JavaDoc sql;
991
992             if (i != -1) {
993                 sql = all.substring(0, i);
994                 all = all.substring(i + 1);
995             } else {
996                 sql = all;
997                 all = "";
998             }
999
1000            if (sql.startsWith("--#")) {
1001                max = Integer.parseInt(sql.substring(3));
1002
1003                continue;
1004            } else if (sql.startsWith("--")) {
1005                continue;
1006            }
1007
1008            g[2] = sql;
1009
1010            long l = 0;
1011
1012            try {
1013                l = DatabaseManagerCommon.testStatement(sStatement, sql, max);
1014                total += l;
1015                g[0] = String.valueOf(l);
1016                g[1] = String.valueOf(max);
1017                g[3] = "";
1018            } catch (SQLException JavaDoc e) {
1019                g[0] = g[1] = "n/a";
1020                g[3] = e.toString();
1021            }
1022
1023            gResult.addRow(g);
1024            System.out.println(l + " ms : " + sql);
1025        }
1026
1027        g[0] = "" + total;
1028        g[1] = "total";
1029        g[2] = "";
1030
1031        gResult.addRow(g);
1032
1033        lTime = System.currentTimeMillis() - lTime;
1034
1035        updateResult();
1036    }
1037
1038    void saveAsCsv(String JavaDoc filename) {
1039
1040        try {
1041            File JavaDoc file = new File JavaDoc(filename);
1042            CSVWriter writer = new CSVWriter(file, null);
1043            String JavaDoc[] col = gResult.getHead();
1044            int width = col.length;
1045            Vector JavaDoc data = gResult.getData();
1046            String JavaDoc[] row;
1047            int height = data.size();
1048
1049            writer.writeHeader(col);
1050
1051            for (int i = 0; i < height; i++) {
1052                row = (String JavaDoc[]) data.elementAt(i);
1053
1054                String JavaDoc[] myRow = new String JavaDoc[row.length];
1055
1056                for (int j = 0; j < row.length; j++) {
1057                    String JavaDoc r = row[j];
1058
1059                    if (r.equals("(null)")) {
1060
1061                        // null is formatted as (null)
1062
r = "";
1063                    }
1064
1065                    myRow[j] = r;
1066                }
1067
1068                writer.writeData(myRow);
1069            }
1070
1071            writer.close();
1072        } catch (IOException JavaDoc e) {
1073            throw new RuntimeException JavaDoc("IOError: " + e.getMessage());
1074        }
1075    }
1076
1077    /**
1078     * Method declaration
1079     *
1080     */

1081    void showResultInText() {
1082
1083        String JavaDoc[] col = gResult.getHead();
1084        int width = col.length;
1085        int[] size = new int[width];
1086        Vector JavaDoc data = gResult.getData();
1087        String JavaDoc[] row;
1088        int height = data.size();
1089
1090        for (int i = 0; i < width; i++) {
1091            size[i] = col[i].length();
1092        }
1093
1094        for (int i = 0; i < height; i++) {
1095            row = (String JavaDoc[]) data.elementAt(i);
1096
1097            for (int j = 0; j < width; j++) {
1098                int l = row[j].length();
1099
1100                if (l > size[j]) {
1101                    size[j] = l;
1102                }
1103            }
1104        }
1105
1106        StringBuffer JavaDoc b = new StringBuffer JavaDoc();
1107
1108        for (int i = 0; i < width; i++) {
1109            b.append(col[i]);
1110
1111            for (int l = col[i].length(); l <= size[i]; l++) {
1112                b.append(' ');
1113            }
1114        }
1115
1116        b.append(NL);
1117
1118        for (int i = 0; i < width; i++) {
1119            for (int l = 0; l < size[i]; l++) {
1120                b.append('-');
1121            }
1122
1123            b.append(' ');
1124        }
1125
1126        b.append(NL);
1127
1128        for (int i = 0; i < height; i++) {
1129            row = (String JavaDoc[]) data.elementAt(i);
1130
1131            for (int j = 0; j < width; j++) {
1132                b.append(row[j]);
1133
1134                for (int l = row[j].length(); l <= size[j]; l++) {
1135                    b.append(' ');
1136                }
1137            }
1138
1139            b.append(NL);
1140        }
1141
1142        b.append(NL + height + " row(s) in " + lTime + " ms");
1143        txtResult.setText(b.toString());
1144    }
1145
1146    /**
1147     * Method declaration
1148     *
1149     *
1150     * @param s
1151     */

1152    private void addToRecent(String JavaDoc s) {
1153
1154        for (int i = 0; i < iMaxRecent; i++) {
1155            if (s.equals(sRecent[i])) {
1156                return;
1157            }
1158        }
1159
1160        if (sRecent[iRecent] != null) {
1161            mRecent.remove(iRecent);
1162        }
1163
1164        sRecent[iRecent] = s;
1165
1166        if (s.length() > 43) {
1167            s = s.substring(0, 40) + "...";
1168        }
1169
1170        MenuItem JavaDoc item = new MenuItem JavaDoc(s);
1171
1172        item.setActionCommand("#" + iRecent);
1173        item.addActionListener(this);
1174        mRecent.insert(item, iRecent);
1175
1176        iRecent = (iRecent + 1) % iMaxRecent;
1177    }
1178
1179    /**
1180     * Method declaration
1181     *
1182     */

1183    private void initGUI() {
1184
1185        Panel JavaDoc pQuery = new Panel JavaDoc();
1186        Panel JavaDoc pCommand = new Panel JavaDoc();
1187
1188        pResult = new Panel JavaDoc();
1189
1190        pQuery.setLayout(new BorderLayout JavaDoc());
1191        pCommand.setLayout(new BorderLayout JavaDoc());
1192        pResult.setLayout(new BorderLayout JavaDoc());
1193
1194        Font JavaDoc fFont = new Font JavaDoc("Dialog", Font.PLAIN, 12);
1195
1196        txtCommand = new TextArea JavaDoc(5, 40);
1197
1198        txtCommand.addKeyListener(this);
1199
1200        txtResult = new TextArea JavaDoc(20, 40);
1201
1202        txtCommand.setFont(fFont);
1203        txtResult.setFont(new Font JavaDoc("Courier", Font.PLAIN, 12));
1204
1205        butExecute = new Button JavaDoc("Execute");
1206        butClear = new Button JavaDoc("Clear");
1207
1208        butExecute.addActionListener(this);
1209        butClear.addActionListener(this);
1210        pCommand.add("East", butExecute);
1211        pCommand.add("West", butClear);
1212        pCommand.add("Center", txtCommand);
1213
1214        gResult = new Grid();
1215
1216        setLayout(new BorderLayout JavaDoc());
1217        pResult.add("Center", gResult);
1218        pQuery.add("North", pCommand);
1219        pQuery.add("Center", pResult);
1220        fMain.add("Center", pQuery);
1221
1222        tTree = new Tree();
1223
1224        // (ulrivo): screen with less than 640 width
1225
Dimension JavaDoc d = Toolkit.getDefaultToolkit().getScreenSize();
1226
1227        if (d.width >= 640) {
1228            tTree.setMinimumSize(new Dimension JavaDoc(200, 100));
1229        } else {
1230            tTree.setMinimumSize(new Dimension JavaDoc(80, 100));
1231        }
1232
1233        gResult.setMinimumSize(new Dimension JavaDoc(200, 300));
1234        fMain.add("West", tTree);
1235        doLayout();
1236        fMain.pack();
1237    }
1238
1239    /**
1240     * Method declaration
1241     *
1242     */

1243    protected void refreshTree() {
1244
1245        tTree.removeAll();
1246
1247        try {
1248            int color_table = Color.yellow.getRGB();
1249            int color_column = Color.orange.getRGB();
1250            int color_index = Color.red.getRGB();
1251
1252            tTree.addRow("", dMeta.getURL(), "-", 0);
1253
1254            String JavaDoc[] usertables = {
1255                "TABLE", "GLOBAL TEMPORARY", "VIEW"
1256            };
1257
1258            // fredt@users Schema support
1259
Vector JavaDoc schemas = new Vector JavaDoc();
1260            Vector JavaDoc tables = new Vector JavaDoc();
1261
1262            // sqlbob@users Added remarks.
1263
Vector JavaDoc remarks = new Vector JavaDoc();
1264            ResultSet JavaDoc result = dMeta.getTables(null, null, null, usertables);
1265
1266            try {
1267                while (result.next()) {
1268                    schemas.addElement(result.getString(2));
1269                    tables.addElement(result.getString(3));
1270                    remarks.addElement(result.getString(5));
1271                }
1272            } finally {
1273                result.close();
1274            }
1275
1276            for (int i = 0; i < tables.size(); i++) {
1277                String JavaDoc name = (String JavaDoc) tables.elementAt(i);
1278                String JavaDoc schema = (String JavaDoc) schemas.elementAt(i);
1279                String JavaDoc key = "tab-" + name + "-";
1280
1281                tTree.addRow(key, name, "+", color_table);
1282
1283                // sqlbob@users Added remarks.
1284
String JavaDoc remark = (String JavaDoc) remarks.elementAt(i);
1285
1286                if ((schema != null) &&!schema.trim().equals("")) {
1287                    tTree.addRow(key + "s", "schema: " + schema);
1288                }
1289
1290                if ((remark != null) &&!remark.trim().equals("")) {
1291                    tTree.addRow(key + "r", " " + remark);
1292                }
1293
1294                ResultSet JavaDoc col = dMeta.getColumns(null, schema, name, null);
1295
1296                try {
1297                    while (col.next()) {
1298                        String JavaDoc c = col.getString(4);
1299                        String JavaDoc k1 = key + "col-" + c + "-";
1300
1301                        tTree.addRow(k1, c, "+", color_column);
1302
1303                        String JavaDoc type = col.getString(6);
1304
1305                        tTree.addRow(k1 + "t", "Type: " + type);
1306
1307                        boolean nullable = col.getInt(11)
1308                                           != DatabaseMetaData.columnNoNulls;
1309
1310                        tTree.addRow(k1 + "n", "Nullable: " + nullable);
1311                    }
1312                } finally {
1313                    col.close();
1314                }
1315
1316                tTree.addRow(key + "ind", "Indices", "+", 0);
1317
1318                ResultSet JavaDoc ind = dMeta.getIndexInfo(null, schema, name, false,
1319                                                   false);
1320                String JavaDoc oldiname = null;
1321
1322                try {
1323                    while (ind.next()) {
1324                        boolean nonunique = ind.getBoolean(4);
1325                        String JavaDoc iname = ind.getString(6);
1326                        String JavaDoc k2 = key + "ind-" + iname + "-";
1327
1328                        if ((oldiname == null ||!oldiname.equals(iname))) {
1329                            tTree.addRow(k2, iname, "+", color_index);
1330                            tTree.addRow(k2 + "u", "Unique: " + !nonunique);
1331
1332                            oldiname = iname;
1333                        }
1334
1335                        String JavaDoc c = ind.getString(9);
1336
1337                        tTree.addRow(k2 + "c-" + c + "-", c);
1338                    }
1339                } finally {
1340                    ind.close();
1341                }
1342            }
1343
1344            tTree.addRow("p", "Properties", "+", 0);
1345            tTree.addRow("pu", "User: " + dMeta.getUserName());
1346            tTree.addRow("pr", "ReadOnly: " + cConn.isReadOnly());
1347            tTree.addRow("pa", "AutoCommit: " + cConn.getAutoCommit());
1348            tTree.addRow("pd", "Driver: " + dMeta.getDriverName());
1349            tTree.addRow("pp", "Product: " + dMeta.getDatabaseProductName());
1350            tTree.addRow("pv",
1351                         "Version: " + dMeta.getDatabaseProductVersion());
1352        } catch (SQLException JavaDoc e) {
1353            tTree.addRow("", "Error getting metadata:", "-", 0);
1354            tTree.addRow("-", e.getMessage());
1355            tTree.addRow("-", e.getSQLState());
1356        }
1357
1358        tTree.update();
1359    }
1360}
1361
Popular Tags