KickJava   Java API By Example, From Geeks To Geeks.

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


1 /* Copyright (c) 1995-2000, The Hypersonic SQL 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 Hypersonic SQL 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 THE HYPERSONIC SQL GROUP,
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  * This software consists of voluntary contributions made by many individuals
31  * on behalf of the Hypersonic SQL Group.
32  *
33  *
34  * For work added by the HSQL Development Group:
35  *
36  * Copyright (c) 2001-2005, The HSQL Development Group
37  * All rights reserved.
38  *
39  * Redistribution and use in source and binary forms, with or without
40  * modification, are permitted provided that the following conditions are met:
41  *
42  * Redistributions of source code must retain the above copyright notice, this
43  * list of conditions and the following disclaimer.
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.
48  *
49  * Neither the name of the HSQL Development Group nor the names of its
50  * contributors may be used to endorse or promote products derived from this
51  * software without specific prior written permission.
52  *
53  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
54  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56  * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
57  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
58  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
59  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
60  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
61  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
62  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
63  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
64  */

65
66
67 package org.hsqldb.util;
68
69 import java.io.File JavaDoc;
70 import java.io.FileInputStream JavaDoc;
71 import java.io.FileOutputStream JavaDoc;
72 import java.io.IOException JavaDoc;
73 import java.lang.reflect.Constructor JavaDoc;
74 import java.lang.reflect.InvocationTargetException JavaDoc;
75 import java.sql.Connection JavaDoc;
76 import java.sql.DatabaseMetaData JavaDoc;
77 import java.sql.Driver JavaDoc;
78 import java.sql.DriverManager JavaDoc;
79 import java.sql.ResultSet JavaDoc;
80 import java.sql.ResultSetMetaData JavaDoc;
81 import java.sql.SQLException JavaDoc;
82 import java.sql.Statement JavaDoc;
83 import java.text.DecimalFormat JavaDoc;
84 import java.util.ArrayList JavaDoc;
85 import java.util.HashMap JavaDoc;
86 import java.util.HashSet JavaDoc;
87 import java.util.Hashtable JavaDoc;
88 import java.util.Iterator JavaDoc;
89 import java.util.Locale JavaDoc;
90 import java.util.Properties JavaDoc;
91 import java.util.Vector JavaDoc;
92 import java.awt.BorderLayout JavaDoc;
93 import java.awt.Cursor JavaDoc;
94 import java.awt.Dimension JavaDoc;
95 import java.awt.Event JavaDoc;
96 import java.awt.Font JavaDoc;
97 import java.awt.Insets JavaDoc;
98 import java.awt.Toolkit JavaDoc;
99 import java.awt.event.ActionEvent JavaDoc;
100 import java.awt.event.ActionListener JavaDoc;
101 import java.awt.event.KeyEvent JavaDoc;
102 import java.awt.event.KeyListener JavaDoc;
103 import java.awt.event.WindowEvent JavaDoc;
104 import java.awt.event.WindowListener JavaDoc;
105 import java.awt.Component JavaDoc;
106 import java.awt.Container JavaDoc;
107
108 import javax.swing.ButtonGroup JavaDoc;
109 import javax.swing.ImageIcon JavaDoc;
110 import javax.swing.JApplet JavaDoc;
111 import javax.swing.JButton JavaDoc;
112 import javax.swing.JCheckBoxMenuItem JavaDoc;
113 import javax.swing.JComponent JavaDoc;
114 import javax.swing.JFileChooser JavaDoc;
115 import javax.swing.JFrame JavaDoc;
116 import javax.swing.JLabel JavaDoc;
117 import javax.swing.JMenu JavaDoc;
118 import javax.swing.JMenuBar JavaDoc;
119 import javax.swing.JMenuItem JavaDoc;
120 import javax.swing.JOptionPane JavaDoc;
121 import javax.swing.JPanel JavaDoc;
122 import javax.swing.JRadioButtonMenuItem JavaDoc;
123 import javax.swing.JScrollPane JavaDoc;
124 import javax.swing.JSplitPane JavaDoc;
125 import javax.swing.JTable JavaDoc;
126 import javax.swing.JTextArea JavaDoc;
127 import javax.swing.JToolBar JavaDoc;
128 import javax.swing.JTree JavaDoc;
129 import javax.swing.KeyStroke JavaDoc;
130 import javax.swing.SwingUtilities JavaDoc;
131 import javax.swing.table.TableModel JavaDoc;
132 import javax.swing.tree.DefaultMutableTreeNode JavaDoc;
133 import javax.swing.tree.DefaultTreeModel JavaDoc;
134 import javax.swing.tree.MutableTreeNode JavaDoc;
135 import javax.swing.RootPaneContainer JavaDoc;
136
137 import java.security.AccessControlException JavaDoc;
138
139 import org.hsqldb.lib.java.JavaSystem;
140
141 //dmarshall@users - 20020101 - original swing port of DatabaseManager
142
//sqlbob@users 20020401 - patch 537501 by ulrivo - commandline arguments
143
//sqlbob@users 20020407 - patch 1.7.0 - reengineering and enhancements
144
//nickferguson@users 20021005 - patch 1.7.1 - enhancements
145
//deccles@users 20040412 - patch 933671 - various bug fixes
146
//deccles@users 2004xxxx - enhancements
147
//weconsultants@users 20041109 - version 1.8.0 - reengineering and enhancements:
148
// Added: Goodies 'Look and Feel'.
149
// Added: a Font Changer(Font Type\Style).
150
// Added: a Color Changer (foreground\bckground).
151
// Added: RowCounts for each JTree table nodes.
152
// Added: OneTouchExpandable attribute to JSplitPanes.
153
// Moved: setFramePositon code to a CommonSwing.setFramePositon() Method.
154
// Added: call to new method to handle exception processing (CommonSwing.errorMessage());
155
// Added: Added a new pane added at the bottom of the Frame. (Status Icon and StatusLine).
156
// Added: 2 Methods (setStatusMessage()), one overrides the other. One to change the ruung status
157
// another to allow a message to be posted without changing the Status Icon if needed.
158
// Added: Added a customCursor for the current wait cursor
159
// Added: Ability to switch the current LAF while runing (Native,Java or Motif)
160
//unsaved@users 2005xxxx - improvements and bug fixes
161

162 /**
163  * Swing Tool for managing a JDBC database.<p>
164  * <pre>
165  * Usage: java DatabaseManagerSwing [--options]
166  * where options include:
167  * --driver <classname> jdbc driver class
168  * --url <name> jdbc url
169  * --user <name> username used for connection
170  * --password <password> password for this user
171  * --dir <path> default directory
172  * --script <file> reads from script file
173  * --urlid <urlid> get connection info from RC file
174  * --rcfile <file> use instead of default (with urlid)
175  * --noexit Don't exit JVM
176  * </pre>
177  *
178  * Note that the sys-table switch will not work for Oracle, because Oracle
179  * does not categorize their system tables correctly in the JDBC Metadata.
180  *
181  * New class based on Hypersonic SQL original
182  *
183  * @author dmarshall@users
184  * @version 1.8.0
185  * @since 1.7.0
186  */

187 public class DatabaseManagerSwing extends JApplet JavaDoc
188 implements ActionListener JavaDoc, WindowListener JavaDoc, KeyListener JavaDoc {
189
190     /*
191      * This is down here because it is an implementation note, not a
192      * Javadoc comment!
193      * Tue Apr 26 16:38:54 EDT 2005
194      * Switched default switch method from "-switch" to "--switch" because
195      * "-switch" usage is ambiguous as used here. Single switches should
196      * be reserved for single-letter switches which can be mixed like
197      * "-u -r -l" = "-url". -blaine
198      */

199     private static String JavaDoc homedir = null;
200
201     static {
202         try {
203             Class JavaDoc c = Class.forName("sun.security.action.GetPropertyAction");
204             Constructor JavaDoc constructor = c.getConstructor(new Class JavaDoc[]{
205                 String JavaDoc.class });
206             java.security.PrivilegedAction JavaDoc a =
207                 (java.security.PrivilegedAction JavaDoc) constructor.newInstance(
208                     new Object JavaDoc[]{ "user.home" });
209
210             homedir = (String JavaDoc) java.security.AccessController.doPrivileged(a);
211         } catch (IllegalAccessException JavaDoc e) {
212             System.err.println(
213                 "Failed to get home directory.\n"
214                 + "Therefore not retrieving/storing user preferences.\n("
215                 + e.getMessage() + ')');
216         } catch (NoSuchMethodException JavaDoc e) {
217             System.err.println(
218                 "Failed to get home directory.\n"
219                 + "Therefore not retrieving/storing user preferences.\n("
220                 + e.getMessage() + ')');
221         } catch (ClassNotFoundException JavaDoc e) {
222             System.err.println(
223                 "Failed to get home directory.\n"
224                 + "Therefore not retrieving/storing user preferences.\n("
225                 + e.getMessage() + ')');
226         } catch (InstantiationException JavaDoc e) {
227             System.err.println(
228                 "Failed to get home directory.\n"
229                 + "Therefore not retrieving/storing user preferences.\n("
230                 + e.getMessage() + ')');
231         } catch (InvocationTargetException JavaDoc e) {
232             System.err.println(
233                 "Failed to get home directory.\n"
234                 + "Therefore not retrieving/storing user preferences.\n("
235                 + e.getMessage() + ')');
236         } catch (AccessControlException JavaDoc e) {
237             System.err.println(
238                 "Failed to get home directory.\n"
239                 + "Therefore not retrieving/storing user preferences.\n("
240                 + e.getMessage() + ')');
241         }
242     }
243
244     ArrayList JavaDoc localActionList = new ArrayList JavaDoc();
245     private JFrame JavaDoc jframe = null;
246     private static final String JavaDoc DEFAULT_RCFILE = homedir + "/dbmanager.rc";
247     private static final String JavaDoc HELP_TEXT =
248         "See the forums, mailing lists, and HSQLDB User Guide\n"
249         + "at http://hsqldb.org.\n\n"
250         + "Please paste the following version identifier with any\n"
251         + "problem reports or help requests: $Revision: 1.69 $";
252     private static final String JavaDoc ABOUT_TEXT =
253         "$Revision: 1.69 $ of DatabaseManagerSwing\n\n"
254         + "Copyright (c) 1995-2000, The Hypersonic SQL Group.\n"
255         + "Copyright (c) 2001-2005, The HSQL Development Group.\n"
256         + "http://hsqldb.org\n\n\n"
257         + "You may use and redistribute according to the HSQLDB\n"
258         + "license documented in the source code and at the web\n"
259         + "site above.";
260     static final String JavaDoc NL = System.getProperty("line.separator");
261     static final String JavaDoc NULL_STR = "[null]";
262     static int iMaxRecent = 24;
263     Connection JavaDoc cConn;
264     Connection JavaDoc rowConn; // holds the connetion for getting table row counts
265
DatabaseMetaData JavaDoc dMeta;
266     Statement JavaDoc sStatement;
267     JMenu JavaDoc mRecent;
268     String JavaDoc[] sRecent;
269     int iRecent;
270     JTextArea JavaDoc txtCommand;
271     JScrollPane JavaDoc txtCommandScroll;
272     JButton JavaDoc butExecute;
273     JTree JavaDoc tTree;
274     JScrollPane JavaDoc tScrollPane;
275     DefaultTreeModel JavaDoc treeModel;
276     TableModel JavaDoc tableModel;
277     DefaultMutableTreeNode JavaDoc rootNode;
278     JPanel JavaDoc pResult;
279     long lTime;
280     GridSwing gResult;
281
282     /**
283      * I think this is used to store model info whether we're using Grid
284      * output or not (this object is queried for data to display for
285      * text output mode).
286      * If so, the presentation-independent model part should be moved
287      * to an appropriately-named class instead of storing pure data in
288      * a Swing-specific class.
289      */

290     JTable JavaDoc gResultTable;
291     JScrollPane JavaDoc gScrollPane;
292     JTextArea JavaDoc txtResult;
293     JScrollPane JavaDoc txtResultScroll;
294     JSplitPane JavaDoc nsSplitPane; // Contains query over results
295
JSplitPane JavaDoc ewSplitPane; // Contains tree beside nsSplitPane
296
boolean bHelp;
297     RootPaneContainer JavaDoc fMain;
298     static boolean bMustExit;
299
300     /** Value of this variable only retained if huge input script read in. */
301     String JavaDoc sqlScriptBuffer = null;
302     JToolBar JavaDoc jtoolbar;
303     private boolean showSchemas = true;
304     private boolean showTooltips = true;
305     private boolean autoRefresh = true;
306     private boolean gridFormat = true;
307
308     // Added: (weconsultants@users)
309
static DatabaseManagerSwing refForFontDialogSwing;
310     boolean displayRowCounts = false;
311     boolean showSys = false;
312     boolean showIndexDetails = true;
313     String JavaDoc currentLAF = null;
314     JPanel JavaDoc pStatus;
315     static JButton JavaDoc iReadyStatus;
316     JRadioButtonMenuItem JavaDoc rbAllSchemas = new JRadioButtonMenuItem JavaDoc("*");
317     JMenuItem JavaDoc mitemAbout = new JMenuItem JavaDoc("About", 'A');
318     JMenuItem JavaDoc mitemHelp = new JMenuItem JavaDoc("Help", 'H');
319     JMenuItem JavaDoc mitemUpdateSchemas = new JMenuItem JavaDoc("Update Schemas");
320     JCheckBoxMenuItem JavaDoc boxAutoCommit =
321         new JCheckBoxMenuItem JavaDoc(AUTOCOMMIT_BOX_TEXT);
322     JCheckBoxMenuItem JavaDoc boxLogging = new JCheckBoxMenuItem JavaDoc(LOGGING_BOX_TEXT);
323     JCheckBoxMenuItem JavaDoc boxShowSchemas =
324         new JCheckBoxMenuItem JavaDoc(SHOWSCHEMAS_BOX_TEXT);
325     JCheckBoxMenuItem JavaDoc boxAutoRefresh =
326         new JCheckBoxMenuItem JavaDoc(AUTOREFRESH_BOX_TEXT);
327     JCheckBoxMenuItem JavaDoc boxTooltips = new JCheckBoxMenuItem JavaDoc(SHOWTIPS_BOX_TEXT);
328     JCheckBoxMenuItem JavaDoc boxRowCounts =
329         new JCheckBoxMenuItem JavaDoc(ROWCOUNTS_BOX_TEXT);
330     JCheckBoxMenuItem JavaDoc boxShowGrid = new JCheckBoxMenuItem JavaDoc(GRID_BOX_TEXT);
331     JCheckBoxMenuItem JavaDoc boxShowSys = new JCheckBoxMenuItem JavaDoc(SHOWSYS_BOX_TEXT);
332
333     // Consider adding GTK and Plaf L&Fs.
334
JRadioButtonMenuItem JavaDoc rbNativeLF =
335         new JRadioButtonMenuItem JavaDoc("Native Look & Feel");
336     JRadioButtonMenuItem JavaDoc rbJavaLF =
337         new JRadioButtonMenuItem JavaDoc("Java Look & Feel");
338     JRadioButtonMenuItem JavaDoc rbMotifLF =
339         new JRadioButtonMenuItem JavaDoc("Motif Look & Feel");
340     JLabel JavaDoc jStatusLine;
341     static String JavaDoc READY_STATUS = "Ready";
342     private static final String JavaDoc AUTOCOMMIT_BOX_TEXT = "Autocommit mode";
343     private static final String JavaDoc LOGGING_BOX_TEXT = "Logging mode";
344     private static final String JavaDoc SHOWSCHEMAS_BOX_TEXT = "Show schemas";
345     private static final String JavaDoc AUTOREFRESH_BOX_TEXT = "Auto-refresh tree";
346     private static final String JavaDoc SHOWTIPS_BOX_TEXT = "Show Tooltips";
347     private static final String JavaDoc ROWCOUNTS_BOX_TEXT = "Show row counts";
348     private static final String JavaDoc SHOWSYS_BOX_TEXT = "Show system tables";
349     private static final String JavaDoc GRID_BOX_TEXT =
350         "Show results in Grid (a.o.t. Text)";
351
352     // variables to hold the default cursors for these top level swing objects
353
// so we can restore them when we exit our thread
354
Cursor JavaDoc fMainCursor;
355     Cursor JavaDoc txtCommandCursor;
356     Cursor JavaDoc txtResultCursor;
357     HashMap JavaDoc tipMap = new HashMap JavaDoc();
358     private JMenu JavaDoc mnuSchemas = new JMenu JavaDoc("Schemas");
359
360     /**
361      * Wait Cursor
362      */

363
364     // Changed: (weconsultants@users): commonted out the, out of the box, cursor to use a custom cursor
365
private final Cursor JavaDoc waitCursor = new Cursor JavaDoc(Cursor.WAIT_CURSOR);
366
367     //getToolkit().createCustomCursor(CommonSwing.getIcon("SystemCursor"),
368
// new Point(4, 4), "HourGlass cursor");
369
// (ulrivo): variables set by arguments from the commandline
370
static String JavaDoc defDriver = "org.hsqldb.jdbcDriver";
371     static String JavaDoc defURL = "jdbc:hsqldb:.";
372     static String JavaDoc defUser = "sa";
373     static String JavaDoc defPassword = "";
374     static String JavaDoc defScript;
375     static String JavaDoc defDirectory;
376     private String JavaDoc schemaFilter = null;
377
378     public DatabaseManagerSwing() {
379         jframe = new JFrame JavaDoc("HSQLDB DatabaseManager");
380         fMain = jframe;
381     }
382     ;
383
384     public DatabaseManagerSwing(JFrame JavaDoc frameIn) {
385         jframe = frameIn;
386         fMain = jframe;
387     }
388     ;
389
390     public void init() {
391
392         javax.swing.AbstractButton JavaDoc btn;
393
394         fMain = this;
395
396         main();
397
398         for (int i = 0; i < localActionList.size(); i++) {
399             btn = (javax.swing.AbstractButton JavaDoc) localActionList.get(i);
400
401             btn.setEnabled(false);
402         }
403
404         Connection JavaDoc c = null;
405         boolean auto = false;
406
407         if (getParameter("jdbcDriver") != null) {
408             auto = true;
409             defDriver = getParameter("jdbcDriver");
410         }
411
412         if (getParameter("jdbcUrl") != null) {
413             auto = true;
414             defURL = getParameter("jdbcUrl");
415         }
416
417         if (getParameter("jdbcUser") != null) {
418             auto = true;
419             defUser = getParameter("jdbcUser");
420         }
421
422         if (getParameter("jdbcPassword") != null) {
423             auto = true;
424             defPassword = getParameter("jdbcPassword");
425         }
426
427         try {
428             setWaiting("Initializing");
429
430             //insertTestData();
431
//updateAutoCommitBox();
432
c = (auto
433                  ? ConnectionDialogSwing.createConnection(defDriver, defURL,
434                      defUser, defPassword)
435                  : ConnectionDialogSwing.createConnection(jframe, "Connect"));
436         } catch (Exception JavaDoc e) {
437
438             // Added: (weconsultants@users)
439
CommonSwing.errorMessage(e);
440         } finally {
441             setWaiting(null);
442         }
443
444         if (c != null) {
445             connect(c);
446         }
447
448         if (getParameter("loadSampleData") != null
449                 && getParameter("loadSampleData").equals("true")) {
450             insertTestData();
451
452             try {
453                 Thread.sleep(1000);
454             } catch (InterruptedException JavaDoc ie) {}
455             ;
456
457             // I don't know why, but the tree refresh below sometimes
458
// doesn't show all tables unless I put this delay here.
459
refreshTree();
460         }
461
462         if (getParameter("schemaFilter") != null) {
463             schemaFilter = getParameter("schemaFilter");
464         }
465     }
466
467     public static void main(String JavaDoc[] arg) {
468
469         System.getProperties().put("sun.java2d.noddraw", "true");
470
471         // (ulrivo): read all arguments from the command line
472
String JavaDoc lowerArg;
473         String JavaDoc urlid = null;
474         String JavaDoc rcFile = null;
475         boolean autoConnect = false;
476         boolean urlidConnect = false;
477
478         bMustExit = true;
479
480         for (int i = 0; i < arg.length; i++) {
481             lowerArg = arg[i].toLowerCase();
482
483             if (lowerArg.length() > 1 && lowerArg.charAt(1) == '-') {
484                 lowerArg = lowerArg.substring(1);
485             }
486
487             i++;
488
489             if (lowerArg.equals("-driver")) {
490                 defDriver = arg[i];
491                 autoConnect = true;
492             } else if (lowerArg.equals("-url")) {
493                 defURL = arg[i];
494                 autoConnect = true;
495             } else if (lowerArg.equals("-user")) {
496                 defUser = arg[i];
497                 autoConnect = true;
498             } else if (lowerArg.equals("-password")) {
499                 defPassword = arg[i];
500                 autoConnect = true;
501             } else if (lowerArg.equals("-urlid")) {
502                 urlid = arg[i];
503                 urlidConnect = true;
504             } else if (lowerArg.equals("-rcfile")) {
505                 rcFile = arg[i];
506                 urlidConnect = true;
507             } else if (lowerArg.equals("-dir")) {
508                 defDirectory = arg[i];
509             } else if (lowerArg.equals("-script")) {
510                 defScript = arg[i];
511             } else if (lowerArg.equals("-noexit")) {
512                 bMustExit = false;
513
514                 i--;
515             } else {
516                 showUsage();
517
518                 return;
519             }
520         }
521
522         DatabaseManagerSwing m =
523             new DatabaseManagerSwing(new JFrame JavaDoc("HSQL Database Manager"));
524
525         // Added: (weconsultants@users): Need databaseManagerSwing for later Reference
526
refForFontDialogSwing = m;
527
528         m.main();
529
530         Connection JavaDoc c = null;
531
532         m.setWaiting("Initializing");
533
534         try {
535             if (autoConnect && urlidConnect) {
536                 throw new IllegalArgumentException JavaDoc(
537                     "You may not specify both (urlid) AND (url/user/password).");
538             }
539
540             if (autoConnect) {
541                 c = ConnectionDialogSwing.createConnection(defDriver, defURL,
542                         defUser, defPassword);
543             } else if (urlidConnect) {
544                 if (urlid == null) {
545                     throw new IllegalArgumentException JavaDoc(
546                         "You must specify an 'urlid' to use an RC file");
547                 }
548
549                 autoConnect = true;
550
551                 String JavaDoc rcfilepath = (rcFile == null) ? DEFAULT_RCFILE
552                                                      : rcFile;
553                 RCData rcdata = new RCData(new File JavaDoc(rcfilepath), urlid);
554
555                 c = rcdata.getConnection(
556                     null, System.getProperty("sqlfile.charset"),
557                     System.getProperty("javax.net.ssl.trustStore"));
558             } else {
559                 c = ConnectionDialogSwing.createConnection(m.jframe,
560                         "Connect");
561             }
562         } catch (Exception JavaDoc e) {
563
564             // Added: (weconsultants@users)
565
CommonSwing.errorMessage(e);
566         } finally {
567             m.setWaiting(null);
568         }
569
570         if (c != null) {
571             m.connect(c);
572         }
573
574         // Added: (weconsultants@users): For preloadng FontDialogSwing
575
FontDialogSwing.CreatFontDialog(refForFontDialogSwing);
576         m.start();
577     }
578
579     /**
580      * This stuff is all quick, except for the refreshTree().
581      * This unit can be kicked off in main Gui thread. The refreshTree
582      * will be backgrounded and this method will return.
583      */

584     public void connect(Connection JavaDoc c) {
585
586         schemaFilter = null;
587
588         if (c == null) {
589             return;
590         }
591
592         if (cConn != null) {
593             try {
594                 cConn.close();
595             } catch (SQLException JavaDoc e) {
596
597                 // Added: (weconsultants@users)
598
CommonSwing.errorMessage(e);
599             }
600         }
601
602         cConn = c;
603
604         // Added: (weconsultants@users) Need to barrow to get the table rowcounts
605
rowConn = c;
606
607         try {
608             dMeta = cConn.getMetaData();
609             sStatement = cConn.createStatement();
610
611             updateAutoCommitBox();
612
613             // Workaround for EXTREME SLOWNESS getting this info from O.
614
showIndexDetails =
615                 (dMeta.getDatabaseProductName().indexOf("Oracle") < 0);
616
617             Driver JavaDoc driver = DriverManager.getDriver(dMeta.getURL());
618             ConnectionSetting newSetting = new ConnectionSetting(
619                 dMeta.getDatabaseProductName(), driver.getClass().getName(),
620                 dMeta.getURL(),
621                 dMeta.getUserName().replaceAll("@localhost", ""), "");
622             Hashtable JavaDoc settings =
623                 ConnectionDialogCommon.loadRecentConnectionSettings();
624
625             ConnectionDialogCommon.addToRecentConnectionSettings(settings,
626                     newSetting);
627             ConnectionDialogSwing.setConnectionSetting(newSetting);
628             refreshTree();
629             clearResultPanel();
630
631             if (fMain instanceof JApplet JavaDoc) {
632                 getAppletContext().showStatus(
633                     "JDBC Connection established to a "
634                     + dMeta.getDatabaseProductName() + " v. "
635                     + dMeta.getDatabaseProductVersion() + " database as '"
636                     + dMeta.getUserName() + "'.");
637             }
638         } catch (SQLException JavaDoc e) {
639
640             // Added: (weconsultants@users)
641
CommonSwing.errorMessage(e);
642         } catch (IOException JavaDoc e) {
643
644             // Added: (weconsultants@users)
645
CommonSwing.errorMessage(e);
646         } catch (Exception JavaDoc e) {
647             CommonSwing.errorMessage(e);
648         }
649     }
650
651     private static void showUsage() {
652
653         System.out.println(
654             "Usage: java DatabaseManagerSwing [--options]\n"
655             + "where options include:\n"
656             + " --driver <classname> jdbc driver class\n"
657             + " --url <name> jdbc url\n"
658             + " --user <name> username used for connection\n"
659             + " --password <password> password for this user\n"
660             + " --urlid <urlid> use url/user/password/driver in rc file\n"
661             + " --rcfile <file> (defaults to 'dbmanager.rc' in home dir)\n"
662             + " --dir <path> default directory\n"
663             + " --script <file> reads from script file\n"
664             + " --noexit do not call system.exit()\n"
665             + "(Single-hypen switches like '-driver' are also supported)");
666     }
667
668     private void insertTestData() {
669
670         try {
671             DatabaseManagerCommon.createTestTables(sStatement);
672             txtCommand.setText(
673                 DatabaseManagerCommon.createTestData(sStatement));
674
675             for (int i = 0; i < DatabaseManagerCommon.testDataSql.length;
676                     i++) {
677                 addToRecent(DatabaseManagerCommon.testDataSql[i]);
678             }
679
680             executeCurrentSQL();
681         } catch (SQLException JavaDoc e) {
682
683             // Added: (weconsultants@users)
684
CommonSwing.errorMessage(e);
685         }
686     }
687
688     public void setMustExit(boolean b) {
689         this.bMustExit = b;
690     }
691
692     private DBMPrefs prefs = null;
693
694     public void main() {
695
696         JMenu JavaDoc jmenu;
697         JMenuItem JavaDoc mitem;
698
699         try {
700             prefs = new DBMPrefs(fMain instanceof JApplet JavaDoc);
701         } catch (Exception JavaDoc e) {
702             System.err.println(
703                 "Failed to load preferences. Proceeding with defaults:\n");
704         }
705
706         if (prefs == null) {
707             setLF(CommonSwing.Native);
708         } else {
709             autoRefresh = prefs.autoRefresh;
710             displayRowCounts = prefs.showRowCounts;
711             showSys = prefs.showSysTables;
712             showSchemas = prefs.showSchemas;
713             gridFormat = prefs.resultGrid;
714             showTooltips = prefs.showTooltips;
715
716             setLF(prefs.laf);
717         }
718
719         // (ulrivo): An actual icon. N.b., this adds some tips to the tip map
720
fMain.getContentPane().add(createToolBar(), "North");
721
722         if (fMain instanceof java.awt.Frame JavaDoc) {
723             ((java.awt.Frame JavaDoc) fMain).setIconImage(
724                 CommonSwing.getIcon("Frame"));
725         }
726
727         if (fMain instanceof java.awt.Window JavaDoc) {
728             ((java.awt.Window JavaDoc) fMain).addWindowListener(this);
729         }
730
731         JMenuBar JavaDoc bar = new JMenuBar JavaDoc();
732
733         // used shortcuts: CERGTSIUDOLM
734
String JavaDoc[] fitems = {
735             "-Connect...", "--", "OOpen Script...", "-Save Script...",
736             "-Save Result...", "--", "-Exit"
737         };
738
739         jmenu = addMenu(bar, "File", fitems);
740
741         // All actions after Connect and the divider are local.
742
for (int i = 2; i < jmenu.getItemCount(); i++) {
743             mitem = jmenu.getItem(i);
744
745             if (mitem != null) {
746                 localActionList.add(mitem);
747             }
748         }
749
750         Object JavaDoc[] vitems = {
751             "RRefresh Tree", boxAutoRefresh, "--", boxRowCounts, boxShowSys,
752             boxShowSchemas, boxShowGrid
753         };
754
755         addMenu(bar, "View", vitems);
756
757         String JavaDoc[] sitems = {
758             "SSELECT", "IINSERT", "UUPDATE", "DDELETE", "EEXECUTE", "---",
759             "-CREATE TABLE", "-DROP TABLE", "-CREATE INDEX", "-DROP INDEX",
760             "--", "-CHECKPOINT", "-SCRIPT", "-SET", "-SHUTDOWN", "--",
761             "-Test Script"
762         };
763
764         addMenu(bar, "Command", sitems);
765
766         mRecent = new JMenu JavaDoc("Recent");
767
768         mRecent.setMnemonic(KeyEvent.VK_R);
769         bar.add(mRecent);
770
771         ButtonGroup JavaDoc lfGroup = new ButtonGroup JavaDoc();
772
773         lfGroup.add(rbNativeLF);
774         lfGroup.add(rbJavaLF);
775         lfGroup.add(rbMotifLF);
776         boxShowSchemas.setSelected(showSchemas);
777         boxShowGrid.setSelected(gridFormat);
778         boxTooltips.setSelected(showTooltips);
779         boxShowGrid.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G,
780                 Event.CTRL_MASK));
781         boxAutoRefresh.setSelected(autoRefresh);
782         boxRowCounts.setSelected(displayRowCounts);
783         boxShowSys.setSelected(showSys);
784         rbNativeLF.setActionCommand("LFMODE:" + CommonSwing.Native);
785         rbJavaLF.setActionCommand("LFMODE:" + CommonSwing.Java);
786         rbMotifLF.setActionCommand("LFMODE:" + CommonSwing.Motif);
787         tipMap.put(mitemUpdateSchemas,
788                    "Refresh the schema list in this menu");
789         tipMap.put(rbAllSchemas, "Display items in all schemas");
790         tipMap.put(mitemAbout, "Display product information");
791         tipMap.put(mitemHelp, "Display advice for obtaining help");
792         tipMap.put(boxAutoRefresh,
793                    "Refresh tree (and schema list) automatically"
794                    + "when YOU modify database objects");
795         tipMap.put(boxShowSchemas,
796                    "Display object names in tree like schemaname.basename");
797         tipMap.put(rbNativeLF,
798                    "Set Look and Feel to Native for your platform");
799         tipMap.put(rbJavaLF, "Set Look and Feel to Java");
800         tipMap.put(rbMotifLF, "Set Look and Feel to Motif");
801         boxTooltips.setToolTipText(
802             "Display tooltips (hover text), like this");
803         tipMap.put(boxAutoCommit,
804                    "Shows current Auto-commit mode. Click to change");
805         tipMap.put(
806             boxLogging,
807             "Shows current JDBC DriverManager logging mode. Click to change");
808         tipMap.put(boxShowSys,
809                    "Show system tables in table tree to the left");
810         tipMap.put(boxShowGrid,
811                    "Show query results in grid (in text if off)");
812         tipMap.put(boxRowCounts, "Show row counts with table names in tree");
813         boxAutoRefresh.setMnemonic(KeyEvent.VK_C);
814         boxShowSchemas.setMnemonic(KeyEvent.VK_Y);
815         boxAutoCommit.setMnemonic(KeyEvent.VK_A);
816         boxShowSys.setMnemonic(KeyEvent.VK_Y);
817         boxShowGrid.setMnemonic(KeyEvent.VK_G);
818         boxRowCounts.setMnemonic(KeyEvent.VK_C);
819         boxLogging.setMnemonic(KeyEvent.VK_L);
820         rbAllSchemas.setMnemonic(KeyEvent.VK_ASTERISK);
821         rbNativeLF.setMnemonic(KeyEvent.VK_N);
822         rbJavaLF.setMnemonic(KeyEvent.VK_J);
823         rbMotifLF.setMnemonic(KeyEvent.VK_M);
824         mitemUpdateSchemas.setMnemonic(KeyEvent.VK_U);
825
826         Object JavaDoc[] soptions = {
827
828             // Added: (weconsultants@users) New menu options
829
rbNativeLF, rbJavaLF, rbMotifLF, "--", "-Set Fonts", "--",
830             boxAutoCommit, "CCommit", "LRollback", "--", "-Disable MaxRows",
831             "-Set MaxRows to 100", "--", boxLogging, "--", "-Insert test data"
832         };
833
834         addMenu(bar, "Options", soptions);
835
836         String JavaDoc[] stools = {
837             "-Dump", "-Restore", "-Transfer"
838         };
839
840         jmenu = addMenu(bar, "Tools", stools);
841
842         localActionList.add(jmenu);
843
844         for (int i = 0; i < jmenu.getItemCount(); i++) {
845             mitem = jmenu.getItem(i);
846
847             if (mitem != null) {
848                 localActionList.add(mitem);
849             }
850         }
851
852         mnuSchemas.setMnemonic(KeyEvent.VK_S);
853         bar.add(mnuSchemas);
854
855         JMenu JavaDoc mnuHelp = new JMenu JavaDoc("Help");
856
857         mnuHelp.setMnemonic(KeyEvent.VK_H);
858         mnuHelp.add(mitemAbout);
859         mnuHelp.add(mitemHelp);
860         mnuHelp.add(boxTooltips);
861         rbAllSchemas.addActionListener(schemaListListener);
862
863         // May be illegal:
864
mitemUpdateSchemas.addActionListener(new ActionListener JavaDoc() {
865
866             public void actionPerformed(ActionEvent JavaDoc actionevent) {
867                 updateSchemaList();
868             }
869         });
870         mitemHelp.addActionListener(new ActionListener JavaDoc() {
871
872             public void actionPerformed(ActionEvent JavaDoc actionevent) {
873
874                 JOptionPane.showMessageDialog(
875                     fMain.getContentPane(), HELP_TEXT, "HELP",
876                     JOptionPane.INFORMATION_MESSAGE);
877             }
878         });
879         mitemAbout.addActionListener(new ActionListener JavaDoc() {
880
881             public void actionPerformed(ActionEvent JavaDoc actionevent) {
882
883                 JOptionPane.showMessageDialog(
884                     fMain.getContentPane(), ABOUT_TEXT, "About",
885                     JOptionPane.INFORMATION_MESSAGE);
886             }
887         });
888         boxTooltips.addActionListener(new ActionListener JavaDoc() {
889
890             public void actionPerformed(ActionEvent JavaDoc actionevent) {
891
892                 showTooltips = boxTooltips.isSelected();
893
894                 resetTooltips();
895             }
896         });
897         bar.add(mnuHelp);
898
899         if (fMain instanceof JApplet JavaDoc) {
900             ((JApplet JavaDoc) fMain).setJMenuBar(bar);
901         } else if (fMain instanceof JFrame JavaDoc) {
902             ((JFrame JavaDoc) fMain).setJMenuBar(bar);
903         }
904
905         initGUI();
906
907         sRecent = new String JavaDoc[iMaxRecent];
908
909         // Modified: (weconsultants@users)Mode code to CommonSwing for general use
910
if (!(fMain instanceof JApplet JavaDoc)) {
911             CommonSwing.setFramePositon((JFrame JavaDoc) fMain);
912         }
913
914         // Modified: (weconsultants@users) Changed from deprecated show()
915
((Component JavaDoc) fMain).setVisible(true);
916
917         // (ulrivo): load query from command line
918
if (defScript != null) {
919             if (defDirectory != null) {
920                 defScript = defDirectory + File.separator + defScript;
921             }
922
923             // if insert stmet is thousands of records...skip showing it
924
// as text. Too huge.
925
sqlScriptBuffer = DatabaseManagerCommon.readFile(defScript);
926
927             if (4096 <= sqlScriptBuffer.length()) {
928                 int eoThirdLine = sqlScriptBuffer.indexOf('\n');
929
930                 if (eoThirdLine > 0) {
931                     eoThirdLine = sqlScriptBuffer.indexOf('\n',
932                                                           eoThirdLine + 1);
933                 }
934
935                 if (eoThirdLine > 0) {
936                     eoThirdLine = sqlScriptBuffer.indexOf('\n',
937                                                           eoThirdLine + 1);
938                 }
939
940                 if (eoThirdLine < 1) {
941                     eoThirdLine = 100;
942                 }
943
944                 txtCommand.setText(
945                     "............... Script File loaded: " + defScript
946                     + " ..................... \n"
947                     + "............... Click Execute or Clear "
948                     + "...................\n"
949                     + sqlScriptBuffer.substring(0, eoThirdLine + 1)
950                     + "..........................................."
951                     + "..............................\n"
952                     + "............................................."
953                     + "............................\n");
954                 txtCommand.setEnabled(false);
955             } else {
956                 txtCommand.setText(sqlScriptBuffer);
957
958                 sqlScriptBuffer = null;
959
960                 txtCommand.setEnabled(true);
961             }
962         }
963
964         // This must be done AFTER all tip texts are put into the map
965
resetTooltips();
966         txtCommand.requestFocus();
967     }
968
969     private JMenu JavaDoc addMenu(JMenuBar JavaDoc b, String JavaDoc name, Object JavaDoc[] items) {
970
971         JMenu JavaDoc menu = new JMenu JavaDoc(name);
972
973         menu.setMnemonic(name.charAt(0));
974         addMenuItems(menu, items);
975         b.add(menu);
976
977         return menu;
978     }
979
980     private void addMenuItems(JMenu JavaDoc f, Object JavaDoc[] m) {
981
982         /*
983          * This method needs to be completely written or just
984          * obliterated and we'll use the Menu objects directly.
985          * Problem is, passing in Strings for menu elements makes it
986          * extremely difficult to use non-text menu items (an important
987          * part of a good Gui), hot-keys, mnemonic keys, tooltips.
988          * Note the "trick" required here to set hot-keys.
989          */

990         Dimension JavaDoc d = Toolkit.getDefaultToolkit().getScreenSize();
991
992         for (int i = 0; i < m.length; i++) {
993             if (m[i].equals("--")) {
994                 f.addSeparator();
995             } else if (m[i].equals("---")) {
996
997                 // (ulrivo): full size on screen with less than 640 width
998
if (d.width >= 640) {
999                     f.addSeparator();
1000                } else {
1001                    return;
1002                }
1003            } else {
1004                JMenuItem JavaDoc item;
1005
1006                if (m[i] instanceof JMenuItem JavaDoc) {
1007                    item = (JMenuItem JavaDoc) m[i];
1008                } else if (m[i] instanceof String JavaDoc) {
1009                    item = new JMenuItem JavaDoc(((String JavaDoc) m[i]).substring(1));
1010
1011                    char c = ((String JavaDoc) m[i]).charAt(0);
1012
1013                    if (c != '-') {
1014                        KeyStroke JavaDoc key =
1015                            KeyStroke.getKeyStroke(c, Event.CTRL_MASK);
1016
1017                        item.setAccelerator(key);
1018                    }
1019                } else {
1020                    throw new RuntimeException JavaDoc(
1021                        "Unexpected element for menu item creation: "
1022                        + m[i].getClass().getName());
1023                }
1024
1025                item.addActionListener(this);
1026                f.add(item);
1027            }
1028        }
1029    }
1030
1031    public void keyPressed(KeyEvent JavaDoc k) {}
1032
1033    public void keyReleased(KeyEvent JavaDoc k) {}
1034
1035    public void keyTyped(KeyEvent JavaDoc k) {
1036
1037        if (k.getKeyChar() == '\n' && k.isControlDown()) {
1038            k.consume();
1039            executeCurrentSQL();
1040        }
1041    }
1042
1043    Thread JavaDoc dummyThread = new Thread JavaDoc("dummy");
1044
1045    public void actionPerformed(ActionEvent JavaDoc ev) {
1046
1047        String JavaDoc s = ev.getActionCommand();
1048
1049        if (s == null) {
1050            if (ev.getSource() instanceof JMenuItem JavaDoc) {
1051                s = ((JMenuItem JavaDoc) ev.getSource()).getText();
1052            }
1053        }
1054
1055        if (s == null) {}
1056        else if (s.equals("Exit")) {
1057            windowClosing(null);
1058        } else if (s.equals("Transfer")) {
1059            Transfer.work(null);
1060        } else if (s.equals("Dump")) {
1061            Transfer.work(new String JavaDoc[]{ "-d" });
1062        } else if (s.equals("Restore")) {
1063            Transfer.work(new String JavaDoc[]{ "-r" });
1064        } else if (s.equals(LOGGING_BOX_TEXT)) {
1065            JavaSystem.setLogToSystem(boxLogging.isSelected());
1066        } else if (s.equals(AUTOREFRESH_BOX_TEXT)) {
1067            autoRefresh = boxAutoRefresh.isSelected();
1068
1069            refreshTree();
1070        } else if (s.equals("Refresh Tree")) {
1071            refreshTree();
1072        } else if (s.startsWith("#")) {
1073            int i = Integer.parseInt(s.substring(1));
1074
1075            txtCommand.setText(sRecent[i]);
1076        } else if (s.equals("Connect...")) {
1077            Connection JavaDoc newCon = null;
1078
1079            try {
1080                setWaiting("Connecting");
1081
1082                newCon = ConnectionDialogSwing.createConnection(jframe,
1083                        "Connect");
1084            } finally {
1085                setWaiting(null);
1086            }
1087
1088            connect(newCon);
1089        } else if (s.equals(GRID_BOX_TEXT)) {
1090            gridFormat = boxShowGrid.isSelected();
1091
1092            displayResults();
1093        } else if (s.equals("Open Script...")) {
1094            JFileChooser JavaDoc f = new JFileChooser JavaDoc(".");
1095
1096            f.setDialogTitle("Open Script...");
1097
1098            // (ulrivo): set default directory if set from command line
1099
if (defDirectory != null) {
1100                f.setCurrentDirectory(new File JavaDoc(defDirectory));
1101            }
1102
1103            int option = f.showOpenDialog((Component JavaDoc) fMain);
1104
1105            if (option == JFileChooser.APPROVE_OPTION) {
1106                File JavaDoc file = f.getSelectedFile();
1107
1108                if (file != null) {
1109                    sqlScriptBuffer = DatabaseManagerCommon.readFile(
1110                        file.getAbsolutePath());
1111
1112                    if (4096 <= sqlScriptBuffer.length()) {
1113                        int eoThirdLine = sqlScriptBuffer.indexOf('\n');
1114
1115                        if (eoThirdLine > 0) {
1116                            eoThirdLine = sqlScriptBuffer.indexOf('\n',
1117                                                                  eoThirdLine
1118                                                                  + 1);
1119                        }
1120
1121                        if (eoThirdLine > 0) {
1122                            eoThirdLine = sqlScriptBuffer.indexOf('\n',
1123                                                                  eoThirdLine
1124                                                                  + 1);
1125                        }
1126
1127                        if (eoThirdLine < 1) {
1128                            eoThirdLine = 100;
1129                        }
1130
1131                        txtCommand.setText(
1132                            "............... Script File loaded: " + file
1133                            + " ..................... \n"
1134                            + "............... Click Execute or Clear "
1135                            + "...................\n"
1136                            + sqlScriptBuffer.substring(0, eoThirdLine + 1)
1137                            + "........................................."
1138                            + "................................\n"
1139                            + "..........................................."
1140                            + "..............................\n");
1141                        txtCommand.setEnabled(false);
1142                    } else {
1143                        txtCommand.setText(sqlScriptBuffer);
1144
1145                        sqlScriptBuffer = null;
1146
1147                        txtCommand.setEnabled(true);
1148                    }
1149                }
1150            }
1151        } else if (s.equals("Save Script...")) {
1152            JFileChooser JavaDoc f = new JFileChooser JavaDoc(".");
1153
1154            f.setDialogTitle("Save Script");
1155
1156            // (ulrivo): set default directory if set from command line
1157
if (defDirectory != null) {
1158                f.setCurrentDirectory(new File JavaDoc(defDirectory));
1159            }
1160
1161            int option = f.showSaveDialog((Component JavaDoc) fMain);
1162
1163            if (option == JFileChooser.APPROVE_OPTION) {
1164                File JavaDoc file = f.getSelectedFile();
1165
1166                if (file != null) {
1167                    DatabaseManagerCommon.writeFile(file.getAbsolutePath(),
1168                                                    txtCommand.getText());
1169                }
1170            }
1171        } else if (s.equals("Save Result...")) {
1172            JFileChooser JavaDoc f = new JFileChooser JavaDoc(".");
1173
1174            f.setDialogTitle("Save Result...");
1175
1176            // (ulrivo): set default directory if set from command line
1177
if (defDirectory != null) {
1178                f.setCurrentDirectory(new File JavaDoc(defDirectory));
1179            }
1180
1181            int option = f.showSaveDialog((Component JavaDoc) fMain);
1182
1183            if (option == JFileChooser.APPROVE_OPTION) {
1184                File JavaDoc file = f.getSelectedFile();
1185
1186                if (file != null) {
1187                    showResultInText();
1188                    DatabaseManagerCommon.writeFile(file.getAbsolutePath(),
1189                                                    txtResult.getText());
1190                }
1191            }
1192        } else if (s.equals(SHOWSYS_BOX_TEXT)) {
1193            showSys = boxShowSys.isSelected();
1194
1195            refreshTree();
1196        } else if (s.equals(ROWCOUNTS_BOX_TEXT)) {
1197            displayRowCounts = boxRowCounts.isSelected();
1198
1199            refreshTree();
1200        } else if (s.startsWith("LFMODE:")) {
1201            setLF(s.substring("LFMODE:".length()));
1202        } else if (s.equals("Set Fonts")) {
1203
1204            // Added: (weconsultants@users)
1205
FontDialogSwing.CreatFontDialog(refForFontDialogSwing);
1206        } else if (s.equals(AUTOCOMMIT_BOX_TEXT)) {
1207            try {
1208                cConn.setAutoCommit(boxAutoCommit.isSelected());
1209            } catch (SQLException JavaDoc e) {
1210                boxAutoCommit.setSelected(!boxAutoCommit.isSelected());
1211
1212                // Added: (weconsultants@users)
1213
CommonSwing.errorMessage(e);
1214            }
1215        } else if (s.equals("Commit")) {
1216            try {
1217                cConn.commit();
1218            } catch (SQLException JavaDoc e) {
1219
1220                // Added: (weconsultants@users)
1221
CommonSwing.errorMessage(e);
1222            }
1223        } else if (s.equals("Insert test data")) {
1224            insertTestData();
1225            refreshTree();
1226        } else if (s.equals("Rollback")) {
1227            try {
1228                cConn.rollback();
1229            } catch (SQLException JavaDoc e) {
1230
1231                // Added: (weconsultants@users)
1232
CommonSwing.errorMessage(e);
1233            }
1234        } else if (s.equals("Disable MaxRows")) {
1235            try {
1236                sStatement.setMaxRows(0);
1237            } catch (SQLException JavaDoc e) {
1238
1239                // Added: (weconsultants@users)
1240
CommonSwing.errorMessage(e);
1241            }
1242        } else if (s.equals("Set MaxRows to 100")) {
1243            try {
1244                sStatement.setMaxRows(100);
1245            } catch (SQLException JavaDoc e) {
1246                CommonSwing.errorMessage(e);
1247            }
1248        } else if (s.equals("SELECT")) {
1249            showHelp(DatabaseManagerCommon.selectHelp);
1250        } else if (s.equals("INSERT")) {
1251            showHelp(DatabaseManagerCommon.insertHelp);
1252        } else if (s.equals("UPDATE")) {
1253            showHelp(DatabaseManagerCommon.updateHelp);
1254        } else if (s.equals("DELETE")) {
1255            showHelp(DatabaseManagerCommon.deleteHelp);
1256        } else if (s.equals("EXECUTE")) {
1257            executeCurrentSQL();
1258        } else if (s.equals("CREATE TABLE")) {
1259            showHelp(DatabaseManagerCommon.createTableHelp);
1260        } else if (s.equals("DROP TABLE")) {
1261            showHelp(DatabaseManagerCommon.dropTableHelp);
1262        } else if (s.equals("CREATE INDEX")) {
1263            showHelp(DatabaseManagerCommon.createIndexHelp);
1264        } else if (s.equals("DROP INDEX")) {
1265            showHelp(DatabaseManagerCommon.dropIndexHelp);
1266        } else if (s.equals("CHECKPOINT")) {
1267            showHelp(DatabaseManagerCommon.checkpointHelp);
1268        } else if (s.equals("SCRIPT")) {
1269            showHelp(DatabaseManagerCommon.scriptHelp);
1270        } else if (s.equals("SHUTDOWN")) {
1271            showHelp(DatabaseManagerCommon.shutdownHelp);
1272        } else if (s.equals("SET")) {
1273            showHelp(DatabaseManagerCommon.setHelp);
1274        } else if (s.equals("Test Script")) {
1275            showHelp(DatabaseManagerCommon.testHelp);
1276        } else if (s.equals(SHOWSCHEMAS_BOX_TEXT)) {
1277            showSchemas = boxShowSchemas.isSelected();
1278
1279            refreshTree();
1280        } else {
1281            throw new RuntimeException JavaDoc("Unexpected action triggered: " + s);
1282        }
1283    }
1284
1285    private void displayResults() {
1286
1287        if (gridFormat) {
1288            setResultsInGrid();
1289        } else {
1290            setResultsInText();
1291        }
1292    }
1293
1294    private void setResultsInGrid() {
1295
1296        pResult.removeAll();
1297        pResult.add(gScrollPane, BorderLayout.CENTER);
1298        pResult.doLayout();
1299        gResult.fireTableChanged(null);
1300        pResult.repaint();
1301    }
1302
1303    private void setResultsInText() {
1304
1305        pResult.removeAll();
1306        pResult.add(txtResultScroll, BorderLayout.CENTER);
1307        pResult.doLayout();
1308        showResultInText();
1309        pResult.repaint();
1310    }
1311
1312    private void showHelp(String JavaDoc[] help) {
1313
1314        txtCommand.setText(help[0]);
1315
1316        bHelp = true;
1317
1318        pResult.removeAll();
1319        pResult.add(txtResultScroll, BorderLayout.CENTER);
1320        pResult.doLayout();
1321        txtResult.setText(help[1]);
1322        pResult.repaint();
1323        txtCommand.requestFocus();
1324        txtCommand.setCaretPosition(help[0].length());
1325    }
1326
1327    public void windowActivated(WindowEvent JavaDoc e) {}
1328
1329    public void windowDeactivated(WindowEvent JavaDoc e) {}
1330
1331    public void windowClosed(WindowEvent JavaDoc e) {}
1332
1333    public void windowDeiconified(WindowEvent JavaDoc e) {}
1334
1335    public void windowIconified(WindowEvent JavaDoc e) {}
1336
1337    public void windowOpened(WindowEvent JavaDoc e) {}
1338
1339    public void windowClosing(WindowEvent JavaDoc ev) {
1340
1341        stop();
1342
1343        try {
1344            if (cConn != null) {
1345                cConn.close();
1346            }
1347
1348            if (prefs != null) {
1349                prefs.autoRefresh = autoRefresh;
1350                prefs.showRowCounts = displayRowCounts;
1351                prefs.showSysTables = showSys;
1352                prefs.showSchemas = showSchemas;
1353                prefs.resultGrid = gridFormat;
1354                prefs.showTooltips = showTooltips;
1355                prefs.laf = currentLAF;
1356
1357                prefs.store();
1358            }
1359        } catch (Exception JavaDoc e) {
1360
1361            // Added: (weconsultants@users)
1362
CommonSwing.errorMessage(e);
1363        }
1364
1365        if (fMain instanceof java.awt.Window JavaDoc) {
1366            ((java.awt.Window JavaDoc) fMain).dispose();
1367        }
1368
1369        if (bMustExit) {
1370            System.exit(0);
1371        }
1372    }
1373
1374    private void clear() {
1375
1376        sqlScriptBuffer = null;
1377
1378        txtCommand.setText("");
1379        txtCommand.setEnabled(true);
1380    }
1381
1382    private String JavaDoc busyText = null;
1383
1384    private void backgroundIt(Runnable JavaDoc r, String JavaDoc description) {
1385
1386        if (busyText != null) {
1387            Toolkit.getDefaultToolkit().beep();
1388
1389            return;
1390        }
1391
1392        // set Waiting mode here. Inverse op must be called by final()
1393
// in the Thread.run() of every background thread.
1394
setWaiting(description);
1395        SwingUtilities.invokeLater(r);
1396    }
1397
1398    private void clearResultPanel() {
1399
1400        gResult.setHead(new Object JavaDoc[0]);
1401        gResult.clear();
1402
1403        if (gridFormat) {
1404            gResult.fireTableChanged(null);
1405        } else {
1406            showResultInText();
1407        }
1408    }
1409
1410    public void setWaiting(String JavaDoc description) {
1411
1412        busyText = description;
1413
1414        if (busyText == null) {
1415
1416            // restore the cursors we saved
1417
if (fMain instanceof java.awt.Frame JavaDoc) {
1418                ((java.awt.Frame JavaDoc) fMain).setCursor(fMainCursor);
1419            } else {
1420                ((Component JavaDoc) fMain).setCursor(fMainCursor);
1421            }
1422
1423            txtCommand.setCursor(txtCommandCursor);
1424            txtResult.setCursor(txtResultCursor);
1425
1426            //TODO: Enable actionButtons
1427
} else {
1428
1429            // save the old cursors
1430
if (fMainCursor == null) {
1431                fMainCursor = ((fMain instanceof java.awt.Frame JavaDoc)
1432                               ? (((java.awt.Frame JavaDoc) fMain).getCursor())
1433                               : (((Component JavaDoc) fMain).getCursor()));
1434                txtCommandCursor = txtCommand.getCursor();
1435                txtResultCursor = txtResult.getCursor();
1436            }
1437
1438            // set the cursors to the wait cursor
1439
if (fMain instanceof java.awt.Frame JavaDoc) {
1440                ((java.awt.Frame JavaDoc) fMain).setCursor(waitCursor);
1441            } else {
1442                ((Component JavaDoc) fMain).setCursor(waitCursor);
1443            }
1444
1445            txtCommand.setCursor(waitCursor);
1446            txtResult.setCursor(waitCursor);
1447
1448            //TODO: Disable actionButtons
1449
}
1450
1451        setStatusLine(busyText, ((busyText == null) ? gResult.getRowCount()
1452                                                    : 0));
1453    }
1454
1455    private Runnable JavaDoc enableButtonRunnable = new Runnable JavaDoc() {
1456
1457        public void run() {
1458            jbuttonClear.setEnabled(true);
1459            jbuttonExecute.setEnabled(true);
1460        }
1461    };
1462    private Runnable JavaDoc disableButtonRunnable = new Runnable JavaDoc() {
1463
1464        public void run() {
1465            jbuttonClear.setEnabled(false);
1466            jbuttonExecute.setEnabled(false);
1467        }
1468    };
1469    private Thread JavaDoc buttonUpdaterThread = null;
1470    private static final int BUTTON_CHECK_PERIOD = 500;
1471    private Runnable JavaDoc buttonUpdater = new Runnable JavaDoc() {
1472
1473        public void run() {
1474
1475            boolean havesql;
1476
1477            while (true) {
1478                try {
1479                    Thread.sleep(BUTTON_CHECK_PERIOD);
1480                } catch (InterruptedException JavaDoc ie) {}
1481
1482                if (buttonUpdaterThread == null) { // Pointer to me
1483
return;
1484                }
1485
1486                havesql = (txtCommand.getText().length() > 0);
1487
1488                if (jbuttonClear.isEnabled() != havesql) {
1489                    SwingUtilities.invokeLater(havesql ? enableButtonRunnable
1490                                                       : disableButtonRunnable);
1491                }
1492            }
1493        }
1494    };
1495    private JButton JavaDoc jbuttonClear;
1496    private JButton JavaDoc jbuttonExecute;
1497
1498    public void start() {
1499
1500        if (buttonUpdaterThread == null) {
1501            buttonUpdaterThread = new Thread JavaDoc(buttonUpdater);
1502        }
1503
1504        buttonUpdaterThread.start();
1505    }
1506
1507    public void stop() {
1508
1509        System.err.println("Stopping");
1510
1511        buttonUpdaterThread = null;
1512    }
1513
1514    private Runnable JavaDoc treeRefreshRunnable = new Runnable JavaDoc() {
1515
1516        public void run() {
1517
1518            try {
1519                directRefreshTree();
1520            } catch (RuntimeException JavaDoc re) {
1521                CommonSwing.errorMessage(re);
1522
1523                throw re;
1524            } finally {
1525                setWaiting(null);
1526            }
1527        }
1528    };
1529
1530    /**
1531     * Schedules to run in a Gui-safe thread
1532     */

1533    protected void executeCurrentSQL() {
1534
1535        if (txtCommand.getText().length() < 1) {
1536            CommonSwing.errorMessage("No SQL to execute");
1537
1538            return;
1539        }
1540
1541        backgroundIt(new StatementExecRunnable(), "Executing SQL");
1542    }
1543
1544    protected class StatementExecRunnable implements Runnable JavaDoc {
1545
1546        public void run() {
1547
1548            gResult.clear();
1549
1550            try {
1551                if (txtCommand.getText().startsWith("-->>>TEST<<<--")) {
1552                    testPerformance();
1553                } else {
1554                    executeSQL();
1555                }
1556
1557                updateResult();
1558                displayResults();
1559                updateAutoCommitBox();
1560                System.gc();
1561            } catch (RuntimeException JavaDoc re) {
1562                CommonSwing.errorMessage(re);
1563
1564                throw re;
1565            } finally {
1566                setWaiting(null);
1567            }
1568        }
1569    }
1570    ;
1571
1572    private void executeSQL() {
1573
1574        String JavaDoc[] g = new String JavaDoc[1];
1575        String JavaDoc sql = null;
1576
1577        try {
1578            lTime = System.currentTimeMillis();
1579            sql = ((sqlScriptBuffer == null ? txtCommand.getText()
1580                                              : sqlScriptBuffer));
1581
1582            sStatement.execute(sql);
1583
1584            int r = sStatement.getUpdateCount();
1585
1586            if (r == -1) {
1587                formatResultSet(sStatement.getResultSet());
1588            } else {
1589                g[0] = "update count";
1590
1591                gResult.setHead(g);
1592
1593                g[0] = "" + r;
1594
1595                gResult.addRow(g);
1596            }
1597
1598            lTime = System.currentTimeMillis() - lTime;
1599
1600            if (sqlScriptBuffer == null) {
1601                addToRecent(sql);
1602                txtCommand.setEnabled(true); // clear() does this otherwise
1603
} else {
1604                clear();
1605            }
1606        } catch (SQLException JavaDoc e) {
1607            lTime = System.currentTimeMillis() - lTime;
1608            g[0] = "SQL Error";
1609
1610            gResult.setHead(g);
1611
1612            String JavaDoc s = e.getMessage();
1613
1614            s += " / Error Code: " + e.getErrorCode();
1615            s += " / State: " + e.getSQLState();
1616            g[0] = s;
1617
1618            gResult.addRow(g);
1619
1620            // Added: (weconsultants@users)
1621
CommonSwing.errorMessage(e);
1622
1623            return;
1624        }
1625
1626        if (autoRefresh) {
1627
1628            // We're already running in a "busy" thread. Just update the
1629
// status text.
1630
setStatusLine("Refreshing object tree", 0);
1631
1632            String JavaDoc upper = sql.toUpperCase(Locale.ENGLISH);
1633
1634            // This test can be very liberal. Too liberal will just do
1635
// some extra refreshes. Too conservative will display
1636
// obsolete info.
1637
if (upper.indexOf("ALTER") > -1 || upper.indexOf("DROP") > -1
1638                    || upper.indexOf("CREATE") > -1) {
1639                directRefreshTree();
1640            }
1641        }
1642    }
1643
1644    /**
1645     * Could somebody explain what the purpose of this method is?
1646     * Contrary to the method name, it looks like it displays
1647     * results only if gridFormat is off (seems like it does
1648     * nothing otherwise, except for clearing help text and moving focus).
1649     */

1650    private void updateResult() {
1651
1652        if (gridFormat) {
1653
1654            // in case 'help' has removed the grid
1655
if (bHelp) {
1656                pResult.removeAll();
1657                pResult.add(gScrollPane, BorderLayout.CENTER);
1658                pResult.doLayout();
1659                gResult.fireTableChanged(null);
1660                pResult.repaint();
1661
1662                bHelp = false;
1663            }
1664        } else {
1665            showResultInText();
1666        }
1667
1668        txtCommand.selectAll();
1669        txtCommand.requestFocus();
1670    }
1671
1672    /**
1673     * We let Swing handle displaying nulls (which it generally does by
1674     * printing nothing for them), except for the case of database
1675     * VARCHARs, because this is the only class where there is any
1676     * ambiguity about whether there is a null stored or not.
1677     */

1678    private void formatResultSet(ResultSet JavaDoc r) {
1679
1680        if (r == null) {
1681            String JavaDoc[] g = new String JavaDoc[1];
1682
1683            g[0] = "Result";
1684
1685            gResult.setHead(g);
1686
1687            g[0] = "(empty)";
1688
1689            gResult.addRow(g);
1690
1691            return;
1692        }
1693
1694        try {
1695            ResultSetMetaData JavaDoc m = r.getMetaData();
1696            int col = m.getColumnCount();
1697            Object JavaDoc[] h = new Object JavaDoc[col];
1698            boolean[] isVarChar = new boolean[col];
1699
1700            for (int i = 1; i <= col; i++) {
1701                h[i - 1] = m.getColumnLabel(i);
1702                isVarChar[i - 1] = (m.getColumnType(i)
1703                                    == java.sql.Types.VARCHAR);
1704            }
1705
1706            gResult.setHead(h);
1707
1708            while (r.next()) {
1709                for (int i = 1; i <= col; i++) {
1710                    try {
1711                        h[i - 1] = r.getObject(i);
1712
1713                        if (r.wasNull()) {
1714                            h[i - 1] = (isVarChar[i - 1] ? NULL_STR
1715                                                         : null);
1716                        }
1717                    } catch (SQLException JavaDoc e) {}
1718                }
1719
1720                gResult.addRow(h);
1721            }
1722
1723            r.close();
1724        } catch (SQLException JavaDoc e) {
1725
1726            // Added: (weconsultants@users)
1727
CommonSwing.errorMessage(e);
1728        }
1729    }
1730
1731    private void testPerformance() {
1732
1733        String JavaDoc all = txtCommand.getText();
1734        StringBuffer JavaDoc b = new StringBuffer JavaDoc();
1735        long total = 0;
1736
1737        for (int i = 0; i < all.length(); i++) {
1738            char c = all.charAt(i);
1739
1740            if (c != '\n') {
1741                b.append(c);
1742            }
1743        }
1744
1745        all = b.toString();
1746
1747        String JavaDoc[] g = new String JavaDoc[4];
1748
1749        g[0] = "ms";
1750        g[1] = "count";
1751        g[2] = "sql";
1752        g[3] = "error";
1753
1754        gResult.setHead(g);
1755
1756        int max = 1;
1757
1758        lTime = System.currentTimeMillis() - lTime;
1759
1760        while (!all.equals("")) {
1761            int i = all.indexOf(';');
1762            String JavaDoc sql;
1763
1764            if (i != -1) {
1765                sql = all.substring(0, i);
1766                all = all.substring(i + 1);
1767            } else {
1768                sql = all;
1769                all = "";
1770            }
1771
1772            if (sql.startsWith("--#")) {
1773                max = Integer.parseInt(sql.substring(3));
1774
1775                continue;
1776            } else if (sql.startsWith("--")) {
1777                continue;
1778            }
1779
1780            g[2] = sql;
1781
1782            long l = 0;
1783
1784            try {
1785                l = DatabaseManagerCommon.testStatement(sStatement, sql, max);
1786                total += l;
1787                g[0] = "" + l;
1788                g[1] = "" + max;
1789                g[3] = "";
1790            } catch (SQLException JavaDoc e) {
1791                g[0] = g[1] = "n/a";
1792                g[3] = e.toString();
1793
1794                // Added: (weconsultants@users)
1795
CommonSwing.errorMessage(e);
1796            }
1797
1798            gResult.addRow(g);
1799            System.out.println(l + " ms : " + sql);
1800        }
1801
1802        g[0] = "" + total;
1803        g[1] = "total";
1804        g[2] = "";
1805
1806        gResult.addRow(g);
1807
1808        lTime = System.currentTimeMillis() - lTime;
1809    }
1810
1811    /**
1812     * Method declaration
1813     *
1814     */

1815    private void showResultInText() {
1816
1817        Object JavaDoc[] col = gResult.getHead();
1818        int width = col.length;
1819        int[] size = new int[width];
1820        Vector JavaDoc data = gResult.getData();
1821        Object JavaDoc[] row;
1822        int height = data.size();
1823
1824        for (int i = 0; i < width; i++) {
1825            size[i] = col[i].toString().length();
1826        }
1827
1828        for (int i = 0; i < height; i++) {
1829            row = (Object JavaDoc[]) data.elementAt(i);
1830
1831            for (int j = 0; j < width; j++) {
1832                String JavaDoc item = ((row[j] == null) ? ""
1833                                                : row[j].toString());
1834                int l = item.length();
1835
1836                if (l > size[j]) {
1837                    size[j] = l;
1838                }
1839            }
1840        }
1841
1842        StringBuffer JavaDoc b = new StringBuffer JavaDoc();
1843
1844        for (int i = 0; i < width; i++) {
1845            b.append(col[i]);
1846
1847            for (int l = col[i].toString().length(); l <= size[i]; l++) {
1848                b.append(' ');
1849            }
1850        }
1851
1852        b.append(NL);
1853
1854        for (int i = 0; i < width; i++) {
1855            for (int l = 0; l < size[i]; l++) {
1856                b.append('-');
1857            }
1858
1859            b.append(' ');
1860        }
1861
1862        b.append(NL);
1863
1864        for (int i = 0; i < height; i++) {
1865            row = (Object JavaDoc[]) data.elementAt(i);
1866
1867            for (int j = 0; j < width; j++) {
1868                String JavaDoc item = ((row[j] == null) ? ""
1869                                                : row[j].toString());
1870
1871                b.append(item);
1872
1873                for (int l = item.length(); l <= size[j]; l++) {
1874                    b.append(' ');
1875                }
1876            }
1877
1878            b.append(NL);
1879        }
1880
1881        // b.append(NL + height + " row(s) in " + lTime + " ms");
1882
// There is no reason why this report should be text-output-specific.
1883
// Moving it to bottom of the setWaiting method (where the report
1884
// gets written to the status line).
1885
// I'm only doing the rowcount now. Add the time report there if
1886
// you are so inclined.
1887
txtResult.setText(b.toString());
1888    }
1889
1890    private void addToRecent(String JavaDoc s) {
1891
1892        for (int i = 0; i < iMaxRecent; i++) {
1893            if (s.equals(sRecent[i])) {
1894                return;
1895            }
1896        }
1897
1898        if (sRecent[iRecent] != null) {
1899            mRecent.remove(iRecent);
1900        }
1901
1902        sRecent[iRecent] = s;
1903
1904        if (s.length() > 43) {
1905            s = s.substring(0, 40) + "...";
1906        }
1907
1908        JMenuItem JavaDoc item = new JMenuItem JavaDoc(s);
1909
1910        item.setActionCommand("#" + iRecent);
1911        item.addActionListener(this);
1912        mRecent.insert(item, iRecent);
1913
1914        iRecent = (iRecent + 1) % iMaxRecent;
1915    }
1916
1917    private void initGUI() {
1918
1919        JPanel JavaDoc pCommand = new JPanel JavaDoc();
1920
1921        pResult = new JPanel JavaDoc();
1922        nsSplitPane = new JSplitPane JavaDoc(JSplitPane.VERTICAL_SPLIT, pCommand,
1923                                     pResult);
1924
1925        // Added: (weconsultants@users)
1926
nsSplitPane.setOneTouchExpandable(true);
1927        pCommand.setLayout(new BorderLayout JavaDoc());
1928        pResult.setLayout(new BorderLayout JavaDoc());
1929
1930        Font JavaDoc fFont = new Font JavaDoc("Dialog", Font.PLAIN, 12);
1931
1932        txtCommand = new JTextArea JavaDoc(5, 40);
1933
1934        txtCommand.setMargin(new Insets JavaDoc(5, 5, 5, 5));
1935        txtCommand.addKeyListener(this);
1936
1937        txtCommandScroll = new JScrollPane JavaDoc(txtCommand);
1938        txtResult = new JTextArea JavaDoc(20, 40);
1939
1940        txtResult.setMargin(new Insets JavaDoc(5, 5, 5, 5));
1941
1942        txtResultScroll = new JScrollPane JavaDoc(txtResult);
1943
1944        txtCommand.setFont(fFont);
1945        txtResult.setFont(new Font JavaDoc("Courier", Font.PLAIN, 12));
1946        pCommand.add(txtCommandScroll, BorderLayout.CENTER);
1947
1948        gResult = new GridSwing();
1949
1950        TableSorter sorter = new TableSorter(gResult);
1951
1952        tableModel = sorter;
1953        gResultTable = new JTable JavaDoc(sorter);
1954
1955        sorter.setTableHeader(gResultTable.getTableHeader());
1956
1957        gScrollPane = new JScrollPane JavaDoc(gResultTable);
1958
1959        gResultTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
1960        gResult.setJTable(gResultTable);
1961
1962        //getContentPane().setLayout(new BorderLayout());
1963
pResult.add(gScrollPane, BorderLayout.CENTER);
1964
1965        // Set up the tree
1966
rootNode = new DefaultMutableTreeNode JavaDoc("Connection");
1967        treeModel = new DefaultTreeModel JavaDoc(rootNode);
1968        tTree = new JTree JavaDoc(treeModel);
1969        tScrollPane = new JScrollPane JavaDoc(tTree);
1970
1971        tScrollPane.setPreferredSize(new Dimension JavaDoc(120, 400));
1972        tScrollPane.setMinimumSize(new Dimension JavaDoc(70, 100));
1973        txtCommandScroll.setPreferredSize(new Dimension JavaDoc(360, 100));
1974        txtCommandScroll.setMinimumSize(new Dimension JavaDoc(180, 100));
1975        gScrollPane.setPreferredSize(new Dimension JavaDoc(460, 300));
1976
1977        ewSplitPane = new JSplitPane JavaDoc(JSplitPane.HORIZONTAL_SPLIT,
1978                                     tScrollPane, nsSplitPane);
1979
1980        // Added: (weconsultants@users)
1981
ewSplitPane.setOneTouchExpandable(true);
1982        fMain.getContentPane().add(ewSplitPane, BorderLayout.CENTER);
1983
1984        // Added: (weconsultants@users)
1985
jStatusLine = new JLabel JavaDoc();
1986        iReadyStatus =
1987            new JButton JavaDoc(new ImageIcon JavaDoc(CommonSwing.getIcon("StatusReady")));
1988
1989        iReadyStatus.setSelectedIcon(
1990            new ImageIcon JavaDoc(CommonSwing.getIcon("StatusRunning")));
1991
1992        pStatus = new JPanel JavaDoc();
1993
1994        pStatus.setLayout(new BorderLayout JavaDoc());
1995        pStatus.add(iReadyStatus, BorderLayout.WEST);
1996        pStatus.add(jStatusLine, BorderLayout.CENTER);
1997        fMain.getContentPane().add(pStatus, "South");
1998        doLayout();
1999
2000        if (fMain instanceof java.awt.Window JavaDoc) {
2001            ((java.awt.Window JavaDoc) fMain).pack();
2002        } else {
2003            ((Container JavaDoc) fMain).validate();
2004        }
2005    }
2006
2007    /* Simple tree node factory method - set's parent and user object.
2008     */

2009    private DefaultMutableTreeNode JavaDoc makeNode(Object JavaDoc userObject,
2010            MutableTreeNode JavaDoc parent) {
2011
2012        DefaultMutableTreeNode JavaDoc node = new DefaultMutableTreeNode JavaDoc(userObject);
2013
2014        if (parent != null) {
2015            treeModel.insertNodeInto(node, parent, parent.getChildCount());
2016        }
2017
2018        return node;
2019    }
2020
2021    private static final String JavaDoc[] usertables = {
2022        "TABLE", "GLOBAL TEMPORARY", "VIEW", "SYSTEM TABLE"
2023    };
2024    private static final String JavaDoc[] nonSystables = {
2025        "TABLE", "GLOBAL TEMPORARY", "VIEW"
2026    };
2027    private static final HashSet JavaDoc oracleSysUsers = new HashSet JavaDoc();
2028    private static final String JavaDoc[] oracleSysSchemas = {
2029        "SYS", "SYSTEM", "OUTLN", "DBSNMP", "OUTLN", "MDSYS", "ORDSYS",
2030        "ORDPLUGINS", "CTXSYS", "DSSYS", "PERFSTAT", "WKPROXY", "WKSYS",
2031        "WMSYS", "XDB", "ANONYMOUS", "ODM", "ODM_MTR", "OLAPSYS", "TRACESVR",
2032        "REPADMIN"
2033    };
2034
2035    static {
2036        for (int i = 0; i < oracleSysSchemas.length; i++) {
2037            oracleSysUsers.add(oracleSysSchemas[i]);
2038        }
2039    }
2040
2041    /**
2042     * Schedules to run in a Gui-safe thread
2043     */

2044    protected void refreshTree() {
2045        backgroundIt(treeRefreshRunnable, "Refreshing object tree");
2046    }
2047
2048    /**
2049     * Clear all existing nodes from the tree model and rebuild from scratch.
2050     *
2051     * This method executes in current thread
2052     */

2053    protected void directRefreshTree() {
2054
2055        int[] rowCounts;
2056        DefaultMutableTreeNode JavaDoc propertiesNode;
2057
2058        // Added: (weconsultants@users) Moved tableNode here for visibiity nd new DECFM
2059
DefaultMutableTreeNode JavaDoc tableNode;
2060        DecimalFormat JavaDoc DECFMT = new DecimalFormat JavaDoc(" ( ####,###,####,##0 )");
2061
2062        // First clear the existing tree by simply enumerating
2063
// over the root node's children and removing them one by one.
2064
while (treeModel.getChildCount(rootNode) > 0) {
2065            DefaultMutableTreeNode JavaDoc child =
2066                (DefaultMutableTreeNode JavaDoc) treeModel.getChild(rootNode, 0);
2067
2068            treeModel.removeNodeFromParent(child);
2069            child.removeAllChildren();
2070            child.removeFromParent();
2071        }
2072
2073        treeModel.nodeStructureChanged(rootNode);
2074        treeModel.reload();
2075        tScrollPane.repaint();
2076
2077        ResultSet JavaDoc result = null;
2078
2079        // Now rebuild the tree below its root
2080
try {
2081
2082            // Start by naming the root node from its URL:
2083
rootNode.setUserObject(dMeta.getURL());
2084
2085            // get metadata about user tables by building a vector of table names
2086
result = dMeta.getTables(null, null, null, (showSys ? usertables
2087                                                                : nonSystables));
2088
2089            Vector JavaDoc tables = new Vector JavaDoc();
2090            Vector JavaDoc schemas = new Vector JavaDoc();
2091
2092            // sqlbob@users Added remarks.
2093
Vector JavaDoc remarks = new Vector JavaDoc();
2094            String JavaDoc schema;
2095
2096            while (result.next()) {
2097                schema = result.getString(2);
2098
2099                if ((!showSys)
2100                        && dMeta.getDatabaseProductName().indexOf("Oracle")
2101                           > -1 && oracleSysUsers.contains(schema)) {
2102                    continue;
2103                }
2104
2105                if (schemaFilter == null || schema.equals(schemaFilter)) {
2106                    schemas.addElement(schema);
2107                    tables.addElement(result.getString(3));
2108                    remarks.addElement(result.getString(5));
2109
2110                    continue;
2111                }
2112            }
2113
2114            result.close();
2115
2116            result = null;
2117
2118            // Added: (weconsultants@users)
2119
// Sort not to go into production. Have to sync with 'remarks Vector' for DBMS that has it
2120
// Collections.sort(tables);
2121
// Added: (weconsultants@users) - Add rowCounts if needed.
2122
rowCounts = new int[tables.size()];
2123
2124            try {
2125                rowCounts = getRowCounts(tables, schemas);
2126            } catch (Exception JavaDoc e) {
2127
2128                // Added: (weconsultants@users)
2129
CommonSwing.errorMessage(e);
2130            }
2131
2132            ResultSet JavaDoc col;
2133
2134            // For each table, build a tree node with interesting info
2135
for (int i = 0; i < tables.size(); i++) {
2136                col = null;
2137
2138                String JavaDoc name;
2139
2140                try {
2141                    name = (String JavaDoc) tables.elementAt(i);
2142                    schema = (String JavaDoc) schemas.elementAt(i);
2143
2144                    String JavaDoc schemaname = "";
2145
2146                    if (schema != null && showSchemas) {
2147                        schemaname = schema + '.';
2148                    }
2149
2150                    String JavaDoc rowcount = displayRowCounts
2151                                      ? (" " + DECFMT.format(rowCounts[i]))
2152                                      : "";
2153                    String JavaDoc displayedName = schemaname + name + rowcount;
2154
2155                    // weconsul@ptd.net Add rowCounts if needed.
2156
tableNode = makeNode(displayedName, rootNode);
2157                    col = dMeta.getColumns(null, schema, name, null);
2158
2159                    if ((schema != null) &&!schema.trim().equals("")) {
2160                        makeNode(schema, tableNode);
2161                    }
2162
2163                    // sqlbob@users Added remarks.
2164
String JavaDoc remark = (String JavaDoc) remarks.elementAt(i);
2165
2166                    if ((remark != null) &&!remark.trim().equals("")) {
2167                        makeNode(remark, tableNode);
2168                    }
2169
2170                    // This block is very slow for some Oracle tables.
2171
// With a child for each column containing pertinent attributes
2172
while (col.next()) {
2173                        String JavaDoc c = col.getString(4);
2174                        DefaultMutableTreeNode JavaDoc columnNode = makeNode(c,
2175                            tableNode);
2176                        String JavaDoc type = col.getString(6);
2177
2178                        makeNode("Type: " + type, columnNode);
2179
2180                        boolean nullable = col.getInt(11)
2181                                           != DatabaseMetaData.columnNoNulls;
2182
2183                        makeNode("Nullable: " + nullable, columnNode);
2184                    }
2185                } finally {
2186                    if (col != null) {
2187                        try {
2188                            col.close();
2189                        } catch (SQLException JavaDoc se) {}
2190                    }
2191                }
2192
2193                DefaultMutableTreeNode JavaDoc indexesNode = makeNode("Indices",
2194                    tableNode);
2195
2196                if (showIndexDetails) {
2197                    ResultSet JavaDoc ind = null;
2198
2199                    try {
2200                        ind = dMeta.getIndexInfo(null, schema, name, false,
2201                                                 false);
2202
2203                        String JavaDoc oldiname = null;
2204                        DefaultMutableTreeNode JavaDoc indexNode = null;
2205
2206                        // A child node to contain each index - and its attributes
2207
while (ind.next()) {
2208                            boolean nonunique = ind.getBoolean(4);
2209                            String JavaDoc iname = ind.getString(6);
2210
2211                            if ((oldiname == null
2212                                    ||!oldiname.equals(iname))) {
2213                                indexNode = makeNode(iname, indexesNode);
2214
2215                                makeNode("Unique: " + !nonunique, indexNode);
2216
2217                                oldiname = iname;
2218                            }
2219
2220                            // And the ordered column list for index components
2221
makeNode(ind.getString(9), indexNode);
2222                        }
2223                    } catch (SQLException JavaDoc se) {
2224
2225                        // Workaround for Oracle
2226
if (se.getMessage() == null || ((!se.getMessage()
2227                                .startsWith("ORA-25191:")) && (!se
2228                                .getMessage().startsWith("ORA-01702:")) &&!se
2229                                    .getMessage().startsWith("ORA-01031:"))) {
2230                            throw se;
2231                        }
2232                    } finally {
2233                        if (ind != null) {
2234                            ind.close();
2235
2236                            ind = null;
2237                        }
2238                    }
2239                }
2240            }
2241
2242            // Finally - a little additional metadata on this connection
2243
propertiesNode = makeNode("Properties", rootNode);
2244
2245            makeNode("User: " + dMeta.getUserName(), propertiesNode);
2246            makeNode("ReadOnly: " + cConn.isReadOnly(), propertiesNode);
2247            makeNode("AutoCommit: " + cConn.getAutoCommit(), propertiesNode);
2248            makeNode("Driver: " + dMeta.getDriverName(), propertiesNode);
2249            makeNode("Product: " + dMeta.getDatabaseProductName(),
2250                     propertiesNode);
2251            makeNode("Version: " + dMeta.getDatabaseProductVersion(),
2252                     propertiesNode);
2253        } catch (SQLException JavaDoc se) {
2254            propertiesNode = makeNode("Error getting metadata:", rootNode);
2255
2256            makeNode(se.getMessage(), propertiesNode);
2257            makeNode(se.getSQLState(), propertiesNode);
2258            CommonSwing.errorMessage(se);
2259        } finally {
2260            if (result != null) {
2261                try {
2262                    result.close();
2263                } catch (SQLException JavaDoc se) {}
2264            }
2265        }
2266
2267        treeModel.nodeStructureChanged(rootNode);
2268        treeModel.reload();
2269        tScrollPane.repaint();
2270
2271        // We want the Schema List to always be in sync with the displayed tree
2272
updateSchemaList();
2273    }
2274
2275    // Added: (weconsultants@users) Sets up\changes the running status icon
2276
void setStatusLine(String JavaDoc busyBaseString, int rowCount) {
2277
2278        iReadyStatus.setSelected(busyBaseString != null);
2279
2280        if (busyBaseString == null) {
2281            String JavaDoc additionalMsg = "";
2282
2283            if (schemaFilter != null) {
2284                additionalMsg = " / Tree showing objects in schema '"
2285                                + schemaFilter + "'";
2286            }
2287
2288            if (rowCount > 1) {
2289                additionalMsg += " / " + rowCount + " rows retrieved";
2290            }
2291
2292            jStatusLine.setText(" " + READY_STATUS + additionalMsg);
2293        } else {
2294            jStatusLine.setText(" " + busyBaseString + "...");
2295        }
2296    }
2297
2298    // Added: (weconsultants@users) Needed to aggragate counts per table in jTree
2299
protected int[] getRowCounts(Vector JavaDoc inTable,
2300                                 Vector JavaDoc inSchema) throws Exception JavaDoc {
2301
2302        if (!displayRowCounts) {
2303            return (null);
2304        }
2305
2306        String JavaDoc rowCountSelect = "SELECT COUNT(*) FROM ";
2307        int[] counts;
2308        String JavaDoc name;
2309
2310        counts = new int[inTable.size()];
2311
2312        try {
2313            Statement JavaDoc select = rowConn.createStatement();
2314
2315            for (int i = 0; i < inTable.size(); i++) {
2316                try {
2317                    String JavaDoc schemaPart = (String JavaDoc) inSchema.elementAt(i);
2318
2319                    schemaPart = schemaPart == null ? ""
2320                                                    : (schemaPart + '.');
2321                    name = schemaPart + (String JavaDoc) inTable.elementAt(i);
2322
2323                    ResultSet JavaDoc resultSet = select.executeQuery(rowCountSelect
2324                        + name);
2325
2326                    while (resultSet.next()) {
2327                        counts[i] = resultSet.getInt(1);
2328                    }
2329                } catch (Exception JavaDoc e) {
2330                    System.err.println("Unable to get row count for table "
2331                                       + inSchema.elementAt(i) + '.'
2332                                       + inTable.elementAt(i)
2333                                       + ". Using value '0': " + e);
2334                }
2335            }
2336        } catch (Exception JavaDoc e) {
2337            CommonSwing.errorMessage(e);
2338        }
2339
2340        return (counts);
2341    }
2342
2343    protected JToolBar JavaDoc createToolBar() {
2344
2345        // Build jtoolbar and jtoolbar Buttons
2346
JToolBar JavaDoc jtoolbar = new JToolBar JavaDoc();
2347
2348        jtoolbar.putClientProperty("JToolBar.isRollover", Boolean.TRUE);
2349
2350        // I'm dropping "Statement" from "Execute SQL Statement", etc.,
2351
// because it may or may not be "one statement", but it is SQL.
2352
// Build jbuttonClear Buttons - blaine
2353
jbuttonClear =
2354            new JButton JavaDoc("Clear SQL",
2355                        new ImageIcon JavaDoc(CommonSwing.getIcon("Clear")));
2356
2357        jbuttonClear.putClientProperty("is3DEnabled", Boolean.TRUE);
2358        tipMap.put(jbuttonClear, "Clear SQL");
2359        jbuttonClear.addActionListener(new ActionListener JavaDoc() {
2360
2361            public void actionPerformed(ActionEvent JavaDoc actionevent) {
2362
2363                if (sqlScriptBuffer == null
2364                        && txtCommand.getText().length() < 1) {
2365                    CommonSwing.errorMessage("No SQL to clear");
2366
2367                    return;
2368                }
2369
2370                clear();
2371            }
2372        });
2373
2374        jbuttonExecute =
2375            new JButton JavaDoc("Execute SQL",
2376                        new ImageIcon JavaDoc(CommonSwing.getIcon("Execute")));
2377
2378        tipMap.put(jbuttonExecute, "Execute SQL");
2379        jbuttonExecute.putClientProperty("is3DEnabled", Boolean.TRUE);
2380        jbuttonExecute.addActionListener(new ActionListener JavaDoc() {
2381
2382            public void actionPerformed(ActionEvent JavaDoc actionevent) {
2383                executeCurrentSQL();
2384            }
2385        });
2386        jtoolbar.addSeparator();
2387        jtoolbar.add(jbuttonClear);
2388        jtoolbar.addSeparator();
2389        jtoolbar.add(jbuttonExecute);
2390        jtoolbar.addSeparator();
2391        jbuttonClear.setAlignmentY(0.5F);
2392        jbuttonClear.setAlignmentX(0.5F);
2393        jbuttonExecute.setAlignmentY(0.5F);
2394        jbuttonExecute.setAlignmentX(0.5F);
2395
2396        return jtoolbar;
2397    }
2398
2399    void updateAutoCommitBox() {
2400
2401        try {
2402            boxAutoCommit.setSelected(cConn.getAutoCommit());
2403        } catch (SQLException JavaDoc se) {
2404            CommonSwing.errorMessage(se);
2405        }
2406    }
2407
2408    private void setLF(String JavaDoc newLAF) {
2409
2410        if (currentLAF != null && currentLAF == newLAF) { // No change
2411
return;
2412        }
2413
2414        if (pResult != null && gridFormat) {
2415            pResult.removeAll();
2416        }
2417
2418        CommonSwing.setSwingLAF((Component JavaDoc) fMain, newLAF);
2419
2420        if (pResult != null && gridFormat) {
2421            setResultsInGrid();
2422        }
2423
2424        currentLAF = newLAF;
2425
2426        if (currentLAF.equals(CommonSwing.Native)) {
2427            rbNativeLF.setSelected(true);
2428        } else if (currentLAF.equals(CommonSwing.Java)) {
2429            rbJavaLF.setSelected(true);
2430        } else if (currentLAF.equals(CommonSwing.Motif)) {
2431            rbMotifLF.setSelected(true);
2432        }
2433    }
2434
2435    void resetTooltips() {
2436
2437        Iterator JavaDoc it = tipMap.keySet().iterator();
2438        JComponent JavaDoc component;
2439
2440        while (it.hasNext()) {
2441            component = (JComponent JavaDoc) it.next();
2442
2443            component.setToolTipText(showTooltips
2444                                     ? ((String JavaDoc) tipMap.get(component))
2445                                     : (String JavaDoc) null);
2446        }
2447    }
2448
2449    private void updateSchemaList() {
2450
2451        ButtonGroup JavaDoc group = new ButtonGroup JavaDoc();
2452        ArrayList JavaDoc list = new ArrayList JavaDoc();
2453        ResultSet JavaDoc result = null;
2454
2455        try {
2456            result = dMeta.getSchemas();
2457
2458            if (result == null) {
2459                throw new SQLException JavaDoc(
2460                    "Failed to get metadata from database");
2461            }
2462
2463            while (result.next()) {
2464                list.add(result.getString(1));
2465            }
2466        } catch (SQLException JavaDoc se) {
2467            CommonSwing.errorMessage(se);
2468        } finally {
2469            if (result != null) {
2470                try {
2471                    result.close();
2472                } catch (SQLException JavaDoc se) {}
2473            }
2474        }
2475
2476        mnuSchemas.removeAll();
2477        rbAllSchemas.setSelected(schemaFilter == null);
2478        group.add(rbAllSchemas);
2479        mnuSchemas.add(rbAllSchemas);
2480
2481        String JavaDoc s;
2482        JRadioButtonMenuItem JavaDoc radioButton;
2483
2484        for (int i = 0; i < list.size(); i++) {
2485            s = (String JavaDoc) list.get(i);
2486            radioButton = new JRadioButtonMenuItem JavaDoc(s);
2487
2488            group.add(radioButton);
2489            mnuSchemas.add(radioButton);
2490            radioButton.setSelected(schemaFilter != null
2491                                    && schemaFilter.equals(s));
2492            radioButton.addActionListener(schemaListListener);
2493            radioButton.setEnabled(list.size() > 1);
2494        }
2495
2496        mnuSchemas.addSeparator();
2497        mnuSchemas.add(mitemUpdateSchemas);
2498    }
2499
2500    ActionListener JavaDoc schemaListListener = (new ActionListener JavaDoc() {
2501
2502        public void actionPerformed(ActionEvent JavaDoc actionevent) {
2503
2504            schemaFilter = actionevent.getActionCommand();
2505
2506            if (schemaFilter.equals("*")) {
2507                schemaFilter = null;
2508            }
2509
2510            refreshTree();
2511        }
2512    });
2513
2514    /**
2515     * Persisted User Preferences for DatabaseManagerSwing.
2516     *
2517     * These are settings for items in the View and Options pulldown menus,
2518     * plus Help/Show Tooltips.
2519     */

2520    public class DBMPrefs {
2521
2522        public File JavaDoc prefsFile = null;
2523
2524        /**
2525         * The constructor guarantees that this will be null for Applet,
2526         * non-null if using a local preferences file
2527         */

2528
2529        // Set defaults from Data
2530
boolean autoRefresh = true;
2531        boolean showRowCounts = false;
2532        boolean showSysTables = false;
2533        boolean showSchemas = true;
2534        boolean resultGrid = true;
2535        String JavaDoc laf = CommonSwing.Native;
2536
2537        // Somebody with more time can store the font settings. IMO, that
2538
// menu item shouldn't even be there if the settings aren't persisted.
2539
boolean showTooltips = true;
2540
2541        public DBMPrefs(boolean isApplet) throws IOException JavaDoc {
2542
2543            if (isApplet) {}
2544            else {
2545                if (homedir == null) {
2546                    throw new IOException JavaDoc(
2547                        "Skipping preferences since do not know home dir");
2548                }
2549
2550                prefsFile = new File JavaDoc(homedir, "dbmprefs.properties");
2551            }
2552
2553            load();
2554        }
2555
2556        public void load() throws IOException JavaDoc {
2557
2558            String JavaDoc tmpString;
2559
2560            if (prefsFile == null) {
2561
2562                // LOAD PREFERENCES FROM APPLET PARAMS
2563
tmpString = getParameter("autoRefresh");
2564
2565                if (tmpString != null) {
2566                    autoRefresh = Boolean.valueOf(tmpString).booleanValue();
2567                }
2568
2569                tmpString = getParameter("showRowCounts");
2570
2571                if (tmpString != null) {
2572                    showRowCounts = Boolean.valueOf(tmpString).booleanValue();
2573                }
2574
2575                tmpString = getParameter("showSysTables");
2576
2577                if (tmpString != null) {
2578                    showSysTables = Boolean.valueOf(tmpString).booleanValue();
2579                }
2580
2581                tmpString = getParameter("showSchemas");
2582
2583                if (tmpString != null) {
2584                    showSchemas = Boolean.valueOf(tmpString).booleanValue();
2585                }
2586
2587                tmpString = getParameter("resultGrid");
2588
2589                if (tmpString != null) {
2590                    resultGrid = Boolean.valueOf(tmpString).booleanValue();
2591                }
2592
2593                tmpString = getParameter("laf");
2594                laf = ((tmpString == null) ? CommonSwing.Native
2595                                                 : tmpString);
2596                tmpString = getParameter("showTooltips");
2597
2598                if (tmpString != null) {
2599                    showTooltips = Boolean.valueOf(tmpString).booleanValue();
2600                }
2601            } else {
2602
2603                // LOAD PREFERENCES FROM LOCAL PREFERENCES FILE
2604
if (!prefsFile.exists()) {
2605                    throw new IOException JavaDoc("No such file: " + prefsFile);
2606                }
2607
2608                Properties JavaDoc props = new Properties JavaDoc();
2609
2610                try {
2611                    FileInputStream JavaDoc fis = new FileInputStream JavaDoc(prefsFile);
2612
2613                    props.load(fis);
2614                    fis.close();
2615                } catch (IOException JavaDoc ioe) {
2616                    throw new IOException JavaDoc("Failed to read preferences file '"
2617                                          + prefsFile + "': "
2618                                          + ioe.getMessage());
2619                }
2620
2621                tmpString = props.getProperty("autoRefresh");
2622
2623                if (tmpString != null) {
2624                    autoRefresh = Boolean.valueOf(tmpString).booleanValue();
2625                }
2626
2627                tmpString = props.getProperty("showRowCounts");
2628
2629                if (tmpString != null) {
2630                    showRowCounts = Boolean.valueOf(tmpString).booleanValue();
2631                }
2632
2633                tmpString = props.getProperty("showSysTables");
2634
2635                if (tmpString != null) {
2636                    showSysTables = Boolean.valueOf(tmpString).booleanValue();
2637                }
2638
2639                tmpString = props.getProperty("showSchemas");
2640
2641                if (tmpString != null) {
2642                    showSchemas = Boolean.valueOf(tmpString).booleanValue();
2643                }
2644
2645                tmpString = props.getProperty("resultGrid");
2646
2647                if (tmpString != null) {
2648                    resultGrid = Boolean.valueOf(tmpString).booleanValue();
2649                }
2650
2651                tmpString = props.getProperty("laf");
2652                laf = ((tmpString == null) ? CommonSwing.Native
2653                                                 : tmpString);
2654                tmpString = props.getProperty("showTooltips");
2655
2656                if (tmpString != null) {
2657                    showTooltips = Boolean.valueOf(tmpString).booleanValue();
2658                }
2659            }
2660        }
2661
2662        public void store() {
2663
2664            if (prefsFile == null) {
2665
2666                // Can't persist Applet settings.
2667
return;
2668            }
2669
2670            Properties JavaDoc props = new Properties JavaDoc();
2671
2672            // Boolean.toString(boolean) was new with Java 1.4, so don't use that.
2673
props.setProperty("autoRefresh", (autoRefresh ? tString
2674                                                          : fString));
2675            props.setProperty("showRowCounts", (showRowCounts ? tString
2676                                                              : fString));
2677            props.setProperty("showSysTables", (showSysTables ? tString
2678                                                              : fString));
2679            props.setProperty("showSchemas", (showSchemas ? tString
2680                                                          : fString));
2681            props.setProperty("resultGrid", (resultGrid ? tString
2682                                                        : fString));
2683            props.setProperty("laf", laf);
2684            props.setProperty("showTooltips", (showTooltips ? tString
2685                                                            : fString));
2686
2687            try {
2688                FileOutputStream JavaDoc fos = new FileOutputStream JavaDoc(prefsFile);
2689
2690                props.store(fos, "DatabaseManagerSwing user preferences");
2691                fos.flush();
2692                fos.close();
2693            } catch (IOException JavaDoc ioe) {
2694                throw new RuntimeException JavaDoc(
2695                    "Failed to prepare preferences file '" + prefsFile
2696                    + "': " + ioe.getMessage());
2697            }
2698        }
2699    }
2700
2701    private static final String JavaDoc tString = Boolean.TRUE.toString();
2702    private static final String JavaDoc fString = Boolean.FALSE.toString();
2703}
2704
Popular Tags