PageRenderTime 97ms CodeModel.GetById 20ms app.highlight 51ms RepoModel.GetById 19ms app.codeStats 1ms

/src/hsqldb19b3/org/hsqldb_voltpatches/util/ZaurusDatabaseManager.java

https://github.com/vkhoroshko/voltdb
Java | 670 lines | 469 code | 114 blank | 87 comment | 156 complexity | 0db1c033eb9c37c9f3e3a126f439ef31 MD5 | raw file
  1/* Copyright (c) 2001-2009, The HSQL Development Group
  2 * All rights reserved.
  3 *
  4 * Redistribution and use in source and binary forms, with or without
  5 * modification, are permitted provided that the following conditions are met:
  6 *
  7 * Redistributions of source code must retain the above copyright notice, this
  8 * list of conditions and the following disclaimer.
  9 *
 10 * Redistributions in binary form must reproduce the above copyright notice,
 11 * this list of conditions and the following disclaimer in the documentation
 12 * and/or other materials provided with the distribution.
 13 *
 14 * Neither the name of the HSQL Development Group nor the names of its
 15 * contributors may be used to endorse or promote products derived from this
 16 * software without specific prior written permission.
 17 *
 18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 19 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 21 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 22 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 23 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 24 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 25 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 26 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 28 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 29 */
 30
 31
 32package org.hsqldb_voltpatches.util;
 33
 34import java.io.IOException;
 35import java.sql.Connection;
 36import java.sql.DriverManager;
 37import java.sql.SQLException;
 38import java.awt.BorderLayout;
 39import java.awt.Button;
 40import java.awt.CardLayout;
 41import java.awt.Dimension;
 42import java.awt.FileDialog;
 43import java.awt.Font;
 44import java.awt.Frame;
 45import java.awt.GridLayout;
 46import java.awt.Insets;
 47import java.awt.Menu;
 48import java.awt.MenuBar;
 49import java.awt.MenuItem;
 50import java.awt.Panel;
 51import java.awt.TextArea;
 52import java.awt.Toolkit;
 53import java.awt.event.ActionEvent;
 54import java.awt.event.ActionListener;
 55import java.awt.event.KeyEvent;
 56import java.awt.event.KeyListener;
 57import java.awt.event.WindowListener;
 58import java.awt.image.MemoryImageSource;
 59
 60import org.hsqldb_voltpatches.lib.java.JavaSystem;
 61
 62/**
 63 * Class declaration
 64 *
 65 *
 66 * @version 1.0.0.1
 67 * @author ulrivo@users
 68 *
 69 */
 70public class ZaurusDatabaseManager extends DatabaseManager
 71implements ActionListener, WindowListener, KeyListener {
 72
 73    // (ulrivo): new buttons to switch the cards
 74    Button butTree;
 75    Button butCommand;
 76    Button butResult;
 77    Button butEditor;
 78
 79    // (ulrivo): Panel pCard with CardLayout inside Frame fMain
 80    Panel      pCard;
 81    CardLayout layoutCard;
 82
 83    // the editor/input form
 84    ZaurusEditor eEditor;
 85
 86    // (ulrivo): variables set by arguments from the commandline
 87    static String defDriver;
 88    static String defURL;
 89    static String defUser;
 90    static String defPassword;
 91    static String defQuery;
 92    static String defDirectory;
 93    static String defDatabase;
 94    static int    defWidth  = 237;
 95    static int    defHeight = 259;
 96    static int    defLocX   = 0;
 97    static int    defLocY   = 0;
 98
 99    /**
100     * Method declaration
101     *
102     *
103     * @param c
104     */
105    public void connect(Connection c) {
106
107        if (c == null) {
108            return;
109        }
110
111        if (cConn != null) {
112            try {
113                cConn.close();
114            } catch (SQLException e) {}
115        }
116
117        cConn = c;
118
119        try {
120            dMeta      = cConn.getMetaData();
121            sStatement = cConn.createStatement();
122        } catch (SQLException e) {
123            e.printStackTrace();
124        }
125
126        refreshTree();
127    }
128
129    /**
130     * Method declaration
131     *
132     *
133     * @param arg
134     */
135    public static void main(String[] arg) {
136
137        bMustExit = true;
138
139        // (ulrivo): read all arguments from the command line
140        int i = 0;
141
142        while (i < arg.length) {
143            if (arg[i].equalsIgnoreCase("-driver") && (i + 1 < arg.length)) {
144                i++;
145
146                defDriver = arg[i];
147            } else if (arg[i].equalsIgnoreCase("-url")
148                       && (i + 1 < arg.length)) {
149                i++;
150
151                defURL = arg[i];
152            } else if (arg[i].equalsIgnoreCase("-width")
153                       && (i + 1 < arg.length)) {
154                i++;
155
156                try {
157                    defWidth = Integer.parseInt(arg[i]);
158                } catch (Exception e) {}
159            } else if (arg[i].equalsIgnoreCase("-height")
160                       && (i + 1 < arg.length)) {
161                i++;
162
163                try {
164                    defHeight = Integer.parseInt(arg[i]);
165                } catch (Exception e) {}
166            } else if (arg[i].equalsIgnoreCase("-locx")
167                       && (i + 1 < arg.length)) {
168                i++;
169
170                try {
171                    defLocX = Integer.parseInt(arg[i]);
172                } catch (Exception e) {}
173            } else if (arg[i].equalsIgnoreCase("-locy")
174                       && (i + 1 < arg.length)) {
175                i++;
176
177                try {
178                    defLocY = Integer.parseInt(arg[i]);
179                } catch (Exception e) {}
180            } else if (arg[i].equalsIgnoreCase("-user")
181                       && (i + 1 < arg.length)) {
182                i++;
183
184                defUser = arg[i];
185            } else if (arg[i].equalsIgnoreCase("-password")
186                       && (i + 1 < arg.length)) {
187                i++;
188
189                defPassword = arg[i];
190            } else if (arg[i].equalsIgnoreCase("-query")
191                       && (i + 1 < arg.length)) {
192                i++;
193
194                defQuery = arg[i];
195            } else if (arg[i].equalsIgnoreCase("-defDirectory")
196                       && (i + 1 < arg.length)) {
197                i++;
198
199                defDirectory = arg[i];
200            } else if (arg[i].equalsIgnoreCase("-database")
201                       && (i + 1 < arg.length)) {
202                i++;
203
204                defDatabase = arg[i];
205            } else {
206                showUsage();
207
208                return;
209            }
210
211            i++;
212        }
213
214        ZaurusDatabaseManager m = new ZaurusDatabaseManager();
215
216        m.main();
217
218        // (ulrivo): make default connection if arguments set via the command line
219        Connection c = null;
220
221        if ((defDriver != null && defURL != null) || (defDatabase != null)) {
222            if (defDatabase != null) {
223                defDriver   = "org.hsqldb_voltpatches.jdbcDriver";
224                defURL      = "jdbc:hsqldb:" + defDatabase;
225                defUser     = "SA";
226                defPassword = "";
227            }
228
229            try {
230                Class.forName(defDriver).newInstance();
231
232                c = DriverManager.getConnection(defURL, defUser, defPassword);
233            } catch (Exception e) {
234                System.out.println("No connection for " + defDriver + " at "
235                                   + defURL);
236                e.printStackTrace();
237            }
238        } else {
239            c = ZaurusConnectionDialog.createConnection(m.fMain, "Connect",
240                    new Insets(defWidth, defHeight, defLocX, defLocY));
241        }
242
243        if (c == null) {
244            return;
245        }
246
247        m.connect(c);
248    }
249
250    private static void showUsage() {
251
252        System.out.println(
253            "Usage: java org.hsqldb_voltpatches.util.ZaurusDatabaseManager [options]");
254        System.out.println("where options could be:");
255        System.out.println(
256            "If the next two options are set, the specified connection will be used:");
257        System.out.println("   -driver dr");
258        System.out.println("   -url address");
259        System.out.println("-user name");
260        System.out.println("-password passw");
261        System.out.println("Alternative the database argument is used,");
262        System.out.println(
263            "and the hsqldb Driver Standalone is choosen for user 'SA'.");
264        System.out.println("-database db");
265        System.out.println(
266            "-query qu                   the query qu will be read during initialization");
267        System.out.println(
268            "-defaultDirectory defdir    default dir for the file open dialog");
269        System.out.println(
270            "If the next two options are set, the frame will be set to the specified values:");
271        System.out.println("   -width width");
272        System.out.println("   -height height");
273        System.out.println("-locX positon left ");
274        System.out.println("-locY positon top ");
275        System.out.println("");
276        System.out.println(
277            "1. Example: java org.hsqldb_voltpatches.util.ZaurusDatabaseManager +");
278        System.out.println("  -driver 'org.hsqldb_voltpatches.jdbcDriver' +");
279        System.out.println("  -url 'jdbc:hsqldb:test'");
280        System.out.println(
281            "2. Example: java org.hsqldb_voltpatches.util.ZaurusDatabaseManager +");
282        System.out.println("  -database 'test'");
283    }
284
285    /**
286     * Method declaration
287     *
288     */
289    public void main() {
290
291        fMain = new Frame("HSQLDB Database Manager for Zaurus");
292        imgEmpty = createImage(new MemoryImageSource(2, 2, new int[4 * 4], 2,
293                2));
294
295        fMain.setIconImage(imgEmpty);
296        fMain.addWindowListener(this);
297
298        MenuBar bar = new MenuBar();
299
300        // no shortcuts used
301        String[] fitems = {
302            "-Connect...", "--", "-Open Script...", "-Save Script...",
303            "-Save Result...", "--", "-Exit"
304        };
305
306        addMenu(bar, "File", fitems);
307
308        String[] vitems = {
309            "-Refresh Tree", "--", "-View Tree", "-View Command",
310            "-View Result", "-View Editor", "--", "-Results in Grid",
311            "-Results in Text"
312        };
313
314        addMenu(bar, "View", vitems);
315
316        String[] sitems = {
317            "-SELECT", "-INSERT", "-UPDATE", "-DELETE", "--", "-CREATE TABLE",
318            "-DROP TABLE", "-CREATE INDEX", "-DROP INDEX", "--", "-SCRIPT",
319            "-SHUTDOWN", "--", "-Test Script"
320        };
321
322        addMenu(bar, "SQL", sitems);
323
324        Menu recent = new Menu("Recent");
325
326        mRecent = new Menu("Recent");
327
328        bar.add(mRecent);
329
330        String[] soptions = {
331            "-AutoCommit on", "-AutoCommit off", "-Commit", "-Rollback", "--",
332            "-Disable MaxRows", "-Set MaxRows to 100", "--", "-Logging on",
333            "-Logging off", "--",
334            "-Insert test data"    // , "-Transfer"
335        };
336
337        addMenu(bar, "Options", soptions);
338
339        String[] shelp = { "-Show HTML-Help in browser" };
340
341        addMenu(bar, "?", shelp);
342        fMain.setMenuBar(bar);
343        fMain.setSize(defWidth, defHeight);
344        fMain.add("Center", this);
345        initGUI();
346
347        sRecent = new String[iMaxRecent];
348
349        Dimension d    = Toolkit.getDefaultToolkit().getScreenSize();
350        Dimension size = fMain.getSize();
351
352        // (ulrivo): arguments from command line or
353        // full size on screen with less than 640 width
354        if (d.width > 640) {
355            fMain.setLocation((d.width - size.width) / 2,
356                              (d.height - size.height) / 2);
357        } else if (defWidth > 0 && defHeight > 0) {
358            fMain.setLocation(defLocX, defLocY);
359            fMain.setSize(defWidth, defHeight);
360        } else {
361            fMain.setLocation(0, 0);
362            fMain.setSize(d);
363        }
364
365        fMain.show();
366
367        // (ulrivo): load query from command line
368        if (defQuery != null) {
369            txtCommand.setText(DatabaseManagerCommon.readFile(defQuery));
370        }
371
372        txtCommand.requestFocus();
373    }
374
375    /**
376     * Method declaration
377     *
378     *
379     * @param k
380     */
381    public void keyTyped(KeyEvent k) {
382
383        // Strg+Enter or Shift+Enter executes the actual SQL statement in command panel
384        if (k.getKeyChar() == '\n'
385                && (k.isControlDown() || k.isShiftDown())) {
386            k.consume();
387            execute();
388            layoutCard.show(pCard, "result");
389        }
390    }
391
392    public void keyPressed(KeyEvent k) {
393
394        //  System.out.println("Key pressed: " + k.getKeyCode());
395    }
396
397    /**
398     * Method declaration
399     *
400     *
401     * @param ev
402     */
403    public void actionPerformed(ActionEvent ev) {
404
405        String s = ev.getActionCommand();
406
407        if (s == null) {
408            if (ev.getSource() instanceof MenuItem) {
409                MenuItem i;
410
411                s = ((MenuItem) ev.getSource()).getLabel();
412            }
413        }
414
415        if (s.equals("Execute")) {
416            execute();
417            layoutCard.show(pCard, "result");
418        } else if (s.equals("Tree")) {
419            layoutCard.show(pCard, "tree");
420        } else if (s.equals("Command")) {
421            layoutCard.show(pCard, "command");
422        } else if (s.equals("Result")) {
423            layoutCard.show(pCard, "result");
424        } else if (s.equals("Editor")) {
425            layoutCard.show(pCard, "editor");
426        } else if (s.equals("Exit")) {
427            windowClosing(null);
428        } else if (s.equals("Logging on")) {
429            JavaSystem.setLogToSystem(true);
430        } else if (s.equals("Logging off")) {
431            JavaSystem.setLogToSystem(false);
432        } else if (s.equals("Refresh Tree")) {
433            refreshTree();
434            layoutCard.show(pCard, "tree");
435        } else if (s.startsWith("#")) {
436            int i = Integer.parseInt(s.substring(1));
437
438            txtCommand.setText(sRecent[i]);
439        } else if (s.equals("Connect...")) {
440            connect(ZaurusConnectionDialog.createConnection(fMain, "Connect",
441                    new Insets(defWidth, defHeight, defLocX, defLocY)));
442            refreshTree();
443            layoutCard.show(pCard, "tree");
444        } else if (s.equals("View Tree")) {
445            layoutCard.show(pCard, "tree");
446        } else if (s.equals("View Command")) {
447            layoutCard.show(pCard, "command");
448        } else if (s.equals("View Result")) {
449            layoutCard.show(pCard, "result");
450        } else if (s.equals("View Editor")) {
451            layoutCard.show(pCard, "editor");
452        } else if (s.equals("Results in Grid")) {
453            iResult = 0;
454
455            pResult.removeAll();
456            pResult.add("Center", gResult);
457            pResult.doLayout();
458            layoutCard.show(pCard, "result");
459        } else if (s.equals("Open Script...")) {
460            FileDialog f = new FileDialog(fMain, "Open Script",
461                                          FileDialog.LOAD);
462
463            // (ulrivo): set default directory if set from command line
464            if (defDirectory != null) {
465                f.setDirectory(defDirectory);
466            }
467
468            f.show();
469
470            String file = f.getFile();
471
472            if (file != null) {
473                txtCommand.setText(
474                    DatabaseManagerCommon.readFile(f.getDirectory() + file));
475            }
476
477            layoutCard.show(pCard, "command");
478        } else if (s.equals("Save Script...")) {
479            FileDialog f = new FileDialog(fMain, "Save Script",
480                                          FileDialog.SAVE);
481
482            // (ulrivo): set default directory if set from command line
483            if (defDirectory != null) {
484                f.setDirectory(defDirectory);
485            }
486
487            f.show();
488
489            String file = f.getFile();
490
491            if (file != null) {
492                DatabaseManagerCommon.writeFile(f.getDirectory() + file,
493                                                txtCommand.getText());
494            }
495        } else if (s.equals("Save Result...")) {
496            FileDialog f = new FileDialog(fMain, "Save Result",
497                                          FileDialog.SAVE);
498
499            // (ulrivo): set default directory if set from command line
500            if (defDirectory != null) {
501                f.setDirectory(defDirectory);
502            }
503
504            f.show();
505
506            String file = f.getFile();
507
508            if (file != null) {
509                showResultInText();
510                DatabaseManagerCommon.writeFile(f.getDirectory() + file,
511                                                txtResult.getText());
512            }
513        } else if (s.equals("Results in Text")) {
514            iResult = 1;
515
516            pResult.removeAll();
517            pResult.add("Center", txtResult);
518            pResult.doLayout();
519            showResultInText();
520            layoutCard.show(pCard, "result");
521        } else if (s.equals("AutoCommit on")) {
522            try {
523                cConn.setAutoCommit(true);
524            } catch (SQLException e) {}
525        } else if (s.equals("AutoCommit off")) {
526            try {
527                cConn.setAutoCommit(false);
528            } catch (SQLException e) {}
529        } else if (s.equals("Commit")) {
530            try {
531                cConn.commit();
532            } catch (SQLException e) {}
533        } else if (s.equals("Insert test data")) {
534            insertTestData();
535            layoutCard.show(pCard, "result");
536        } else if (s.equals("Rollback")) {
537            try {
538                cConn.rollback();
539            } catch (SQLException e) {}
540        } else if (s.equals("Disable MaxRows")) {
541            try {
542                sStatement.setMaxRows(0);
543            } catch (SQLException e) {}
544        } else if (s.equals("Set MaxRows to 100")) {
545            try {
546                sStatement.setMaxRows(100);
547            } catch (SQLException e) {}
548        } else if (s.equals("SELECT")) {
549            showHelp(DatabaseManagerCommon.selectHelp);
550        } else if (s.equals("INSERT")) {
551            showHelp(DatabaseManagerCommon.insertHelp);
552        } else if (s.equals("UPDATE")) {
553            showHelp(DatabaseManagerCommon.updateHelp);
554        } else if (s.equals("DELETE")) {
555            showHelp(DatabaseManagerCommon.deleteHelp);
556        } else if (s.equals("CREATE TABLE")) {
557            showHelp(DatabaseManagerCommon.createTableHelp);
558        } else if (s.equals("DROP TABLE")) {
559            showHelp(DatabaseManagerCommon.dropTableHelp);
560        } else if (s.equals("CREATE INDEX")) {
561            showHelp(DatabaseManagerCommon.createIndexHelp);
562        } else if (s.equals("DROP INDEX")) {
563            showHelp(DatabaseManagerCommon.dropIndexHelp);
564        } else if (s.equals("CHECKPOINT")) {
565            showHelp(DatabaseManagerCommon.checkpointHelp);
566        } else if (s.equals("SCRIPT")) {
567            showHelp(DatabaseManagerCommon.scriptHelp);
568        } else if (s.equals("SHUTDOWN")) {
569            showHelp(DatabaseManagerCommon.shutdownHelp);
570        } else if (s.equals("SET")) {
571            showHelp(DatabaseManagerCommon.setHelp);
572        } else if (s.equals("Test Script")) {
573            showHelp(DatabaseManagerCommon.testHelp);
574        } else if (s.equals("Show HTML-Help in browser")) {
575            try {
576                System.out.println("Starting Opera on index.html");
577                Runtime.getRuntime().exec(new String[] {
578                    "opera", "/home/QtPalmtop/help/html/hsqldb/index.html"
579                });
580            } catch (IOException e) {
581                System.out.println("A problem with Opera occured.");
582            }
583        }
584    }
585
586    /**
587     * Method declaration
588     *
589     */
590    private void initGUI() {
591
592        Panel pQuery   = new Panel();
593        Panel pCommand = new Panel();
594
595        // define a Panel pCard which takes four different cards/views:
596        // tree of tables, command SQL text area, result window and an editor/input form
597        pCard      = new Panel();
598        layoutCard = new CardLayout(2, 2);
599
600        pCard.setLayout(layoutCard);
601
602        // four buttons at the top to quickly switch between the four views
603        butTree    = new Button("Tree");
604        butCommand = new Button("Command");
605        butResult  = new Button("Result");
606        butEditor  = new Button("Editor");
607
608        butTree.addActionListener(this);
609        butCommand.addActionListener(this);
610        butResult.addActionListener(this);
611        butEditor.addActionListener(this);
612
613        Panel pButtons = new Panel();
614
615        pButtons.setLayout(new GridLayout(1, 4, 8, 8));
616        pButtons.add(butTree);
617        pButtons.add(butCommand);
618        pButtons.add(butResult);
619        pButtons.add(butEditor);
620
621        pResult = new Panel();
622
623        pQuery.setLayout(new BorderLayout());
624        pCommand.setLayout(new BorderLayout());
625        pResult.setLayout(new BorderLayout());
626
627        Font fFont = new Font("Dialog", Font.PLAIN, 12);
628
629        txtCommand = new TextArea(5, 40);
630
631        txtCommand.addKeyListener(this);
632
633        txtResult = new TextArea(20, 40);
634
635        txtCommand.setFont(fFont);
636        txtResult.setFont(new Font("Courier", Font.PLAIN, 12));
637
638        butExecute = new Button("Execute");
639
640        butExecute.addActionListener(this);
641        pCommand.add("South", butExecute);
642        pCommand.add("Center", txtCommand);
643
644        gResult = new Grid();
645
646        setLayout(new BorderLayout());
647        pResult.add("Center", gResult);
648
649        tTree = new Tree();
650
651        tTree.setMinimumSize(new Dimension(200, 100));
652        gResult.setMinimumSize(new Dimension(200, 300));
653
654        eEditor = new ZaurusEditor();
655
656        pCard.add("tree", tTree);
657        pCard.add("command", pCommand);
658        pCard.add("result", pResult);
659        pCard.add("editor", eEditor);
660        fMain.add("Center", pCard);
661        fMain.add("North", pButtons);
662        doLayout();
663        fMain.pack();
664    }
665
666    protected void refreshTree() {
667        super.refreshTree();
668        eEditor.refresh(cConn);
669    }
670}