KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > genimen > djeneric > tools > console > ConsolePanel


1 /*
2  * Copyright (c) 2001-2005 by Genimen BV (www.genimen.com) All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, is permitted provided that the following conditions are met: -
6  * Redistributions of source code must retain the above copyright notice, this
7  * list of conditions and the following disclaimer. - Redistributions in binary
8  * form must reproduce the above copyright notice, this list of conditions and
9  * the following disclaimer in the documentation and/or other materials
10  * provided with the distribution. - All advertising materials mentioning
11  * features or use of this software must display the following acknowledgment:
12  * "This product includes Djeneric." - Products derived from this software may
13  * not be called "Djeneric" nor may "Djeneric" appear in their names without
14  * prior written permission of Genimen BV. - Redistributions of any form
15  * whatsoever must retain the following acknowledgment: "This product includes
16  * Djeneric."
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 GENIMEN BV, DJENERIC.ORG, OR CONTRIBUTORS
22  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28  * POSSIBILITY OF SUCH DAMAGE.
29  */

30 package com.genimen.djeneric.tools.console;
31
32 import java.awt.BorderLayout JavaDoc;
33 import java.awt.Color JavaDoc;
34 import java.awt.Dimension JavaDoc;
35 import java.awt.FlowLayout JavaDoc;
36 import java.awt.Image JavaDoc;
37 import java.awt.Toolkit JavaDoc;
38 import java.awt.event.ActionEvent JavaDoc;
39 import java.awt.event.InputEvent JavaDoc;
40 import java.awt.event.KeyEvent JavaDoc;
41 import java.io.BufferedReader JavaDoc;
42 import java.io.File JavaDoc;
43 import java.io.FileReader JavaDoc;
44 import java.io.FileWriter JavaDoc;
45 import java.io.PrintWriter JavaDoc;
46 import java.net.URL JavaDoc;
47 import java.sql.ResultSet JavaDoc;
48 import java.sql.ResultSetMetaData JavaDoc;
49 import java.util.ArrayList JavaDoc;
50 import java.util.Vector JavaDoc;
51
52 import javax.swing.AbstractAction JavaDoc;
53 import javax.swing.DefaultComboBoxModel JavaDoc;
54 import javax.swing.ImageIcon JavaDoc;
55 import javax.swing.JButton JavaDoc;
56 import javax.swing.JCheckBox JavaDoc;
57 import javax.swing.JComboBox JavaDoc;
58 import javax.swing.JLabel JavaDoc;
59 import javax.swing.JPanel JavaDoc;
60 import javax.swing.JScrollPane JavaDoc;
61 import javax.swing.JSplitPane JavaDoc;
62 import javax.swing.JTabbedPane JavaDoc;
63 import javax.swing.JTextArea JavaDoc;
64 import javax.swing.KeyStroke JavaDoc;
65 import javax.swing.RepaintManager JavaDoc;
66 import javax.swing.text.BadLocationException JavaDoc;
67
68 import com.genimen.djeneric.language.Messages;
69 import com.genimen.djeneric.repository.DjExtent;
70 import com.genimen.djeneric.repository.DjOql;
71 import com.genimen.djeneric.repository.DjPersistenceManager;
72 import com.genimen.djeneric.repository.DjSession;
73 import com.genimen.djeneric.repository.oql.core.ParseException;
74 import com.genimen.djeneric.repository.rdbms.RdbmsSession;
75 import com.genimen.djeneric.repository.rdbms.SqlStatement;
76 import com.genimen.djeneric.ui.DjPropertyPathCompleter;
77 import com.genimen.djeneric.ui.DjStatusListener;
78 import com.genimen.djeneric.ui.DjSwingWorker;
79 import com.genimen.djeneric.ui.Util;
80 import com.genimen.djeneric.util.DjLogger;
81 import com.genimen.djeneric.util.DjString;
82 import com.genimen.djeneric.util.DjStringReplacer;
83 import com.genimen.djeneric.util.DjVersion;
84
85 public class ConsolePanel extends JPanel JavaDoc implements DjStatusListener
86 {
87   private static final long serialVersionUID = 1L;
88   int _maxRows = 100000;
89   int _maxColSize = 100;
90
91   public final static String JavaDoc HEADER_CMD = "header";
92   public final static String JavaDoc ECHO_CMD = "echo";
93   public final static String JavaDoc CLEAR_CMD = "clear";
94   public final static String JavaDoc SPOOL_CMD = "spool";
95   public final static String JavaDoc START_CMD = "start";
96   public final static String JavaDoc EXIT_CMD = "exit";
97   public final static String JavaDoc HELP_CMD = "help";
98
99   public final static int MAX_LINES_IN_OUTPUT = 3000;
100   public final static int MAX_LINES_DELTA = 1000;
101   public final static int PRINT_BUFFER_SIZE = 10000;
102
103   ArrayList JavaDoc _allExitListeners = new ArrayList JavaDoc();
104
105   Vector JavaDoc _allStatements = new Vector JavaDoc();
106   int _currentStatementIdx = 0;
107
108   String JavaDoc LINE_SEPARATOR = System.getProperty("line.separator", "\n");
109   PrintWriter JavaDoc _spoolFile = null;
110
111   JLabel JavaDoc statusBar = new JLabel JavaDoc();
112   DjPersistenceManager _mgr;
113   boolean _printHeader = true;
114   boolean _echo = true;
115   boolean _canceled = false;
116
117   RdbmsSession _session;
118   BorderLayout JavaDoc _layoutMain = new BorderLayout JavaDoc();
119   public JSplitPane JavaDoc _splitpane = new JSplitPane JavaDoc();
120   JScrollPane JavaDoc _scrResult = new JScrollPane JavaDoc();
121   JTextArea JavaDoc _edtResults = new JTextArea JavaDoc();
122   JButton JavaDoc _butExecuteStmt = new JButton JavaDoc();
123   JPanel JavaDoc _checkPanel = new JPanel JavaDoc();
124   JButton JavaDoc _butPrevStmt = new JButton JavaDoc();
125   JPanel JavaDoc _sqlPanel = new JPanel JavaDoc();
126   JTextArea JavaDoc _edtCommand = new JTextArea JavaDoc();
127   JButton JavaDoc _butNextStmt = new JButton JavaDoc();
128   JCheckBox JavaDoc _chkShowInternal = new JCheckBox JavaDoc();
129   JPanel JavaDoc _southPanel = new JPanel JavaDoc();
130   FlowLayout JavaDoc _layoutCheckpanel = new FlowLayout JavaDoc();
131   JPanel JavaDoc _buttonPanel = new JPanel JavaDoc();
132   BorderLayout JavaDoc _layoutSouth = new BorderLayout JavaDoc();
133   JScrollPane JavaDoc _scrCommand = new JScrollPane JavaDoc();
134   JTabbedPane JavaDoc _tabs = new JTabbedPane JavaDoc();
135   JCheckBox JavaDoc _chkVirtualMode = new JCheckBox JavaDoc();
136   BorderLayout JavaDoc borderLayout1 = new BorderLayout JavaDoc();
137   JPanel JavaDoc _pnlOql = new JPanel JavaDoc();
138   JPanel JavaDoc jPanel1 = new JPanel JavaDoc();
139   BorderLayout JavaDoc borderLayout2 = new BorderLayout JavaDoc();
140   JComboBox JavaDoc _cbbExtent = new JComboBox JavaDoc();
141   FlowLayout JavaDoc flowLayout1 = new FlowLayout JavaDoc();
142   JLabel JavaDoc jLabel1 = new JLabel JavaDoc();
143   JScrollPane JavaDoc jScrollPane1 = new JScrollPane JavaDoc();
144   JTextArea JavaDoc _edtOql = new JTextArea JavaDoc();
145   JPanel JavaDoc jPanel2 = new JPanel JavaDoc();
146   BorderLayout JavaDoc borderLayout3 = new BorderLayout JavaDoc();
147   JPanel JavaDoc jPanel3 = new JPanel JavaDoc();
148   JButton JavaDoc _butExecOql = new JButton JavaDoc();
149   JPanel JavaDoc jPanel4 = new JPanel JavaDoc();
150   FlowLayout JavaDoc flowLayout2 = new FlowLayout JavaDoc();
151   JComboBox JavaDoc _cbbHelpProperty = new JComboBox JavaDoc();
152   JComboBox JavaDoc _cbbHelpExtent = new JComboBox JavaDoc();
153   JButton JavaDoc _butAddProp = new JButton JavaDoc();
154   JButton JavaDoc _butCancel = new JButton JavaDoc();
155   DjPropertyPathCompleter _propertyPathCompleter;
156
157   public ConsolePanel() throws Exception JavaDoc
158   {
159     jbInit();
160
161     AbstractAction JavaDoc ctrlAction = new AbstractAction JavaDoc()
162     {
163       private static final long serialVersionUID = 1L;
164
165       public void actionPerformed(ActionEvent JavaDoc e)
166       {
167         if (_tabs.getSelectedComponent() == _pnlOql) _butExecOql_actionPerformed(null);
168
169         if (_tabs.getSelectedComponent() == _sqlPanel) _butExecuteStmt_actionPerformed(null);
170       }
171     };
172
173     _edtCommand.getKeymap().addActionForKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.CTRL_MASK),
174                                                   ctrlAction);
175
176     _edtOql.getKeymap().addActionForKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.CTRL_MASK),
177                                               ctrlAction);
178
179     _edtCommand.getKeymap().addActionForKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_UP, InputEvent.CTRL_MASK),
180                                                   new AbstractAction JavaDoc()
181                                                   {
182                                                     private static final long serialVersionUID = 1L;
183
184                                                     public void actionPerformed(ActionEvent JavaDoc e)
185                                                     {
186                                                       if (_tabs.getSelectedComponent() == _sqlPanel) _butPrevStmt_actionPerformed(null);
187                                                     }
188                                                   });
189
190     _edtCommand.getKeymap().addActionForKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, InputEvent.CTRL_MASK),
191                                                   new AbstractAction JavaDoc()
192                                                   {
193                                                     private static final long serialVersionUID = 1L;
194
195                                                     public void actionPerformed(ActionEvent JavaDoc e)
196                                                     {
197                                                       if (_tabs.getSelectedComponent() == _sqlPanel) _butNextStmt_actionPerformed(null);
198                                                     }
199                                                   });
200
201     _butNextStmt.setIcon(getImageIcon("down.gif"));
202     _butPrevStmt.setIcon(getImageIcon("up.gif"));
203   }
204
205   public DjSession getSession()
206   {
207     return _session;
208   }
209
210   public void setManager(DjPersistenceManager mgr) throws Exception JavaDoc
211   {
212     _mgr = mgr;
213     _session = (RdbmsSession) mgr.createSession();
214     _cbbExtent.setModel(new DefaultComboBoxModel JavaDoc(mgr.getExtentsSorted()));
215     _cbbHelpExtent.setModel(new DefaultComboBoxModel JavaDoc(mgr.getExtentsSorted()));
216     cbbHelpExtent_actionPerformed(null);
217     _cbbExtent_actionPerformed(null);
218   }
219
220   public DjPersistenceManager getManager()
221   {
222     return _mgr;
223   }
224
225   public void addExitListener(ConsoleExitListener lsnr)
226   {
227     _allExitListeners.add(lsnr);
228   }
229
230   /**
231    * Component initialization
232    *
233    * @exception Exception
234    * Description of the Exception
235    */

236   private void jbInit() throws Exception JavaDoc
237   {
238     this.setSize(new Dimension JavaDoc(747, 436));
239     statusBar.setText(" ");
240     setLayout(_layoutMain);
241     _splitpane.setOrientation(JSplitPane.VERTICAL_SPLIT);
242     _edtResults.setBackground(new Color JavaDoc(239, 240, 240));
243     _edtResults.setFont(new java.awt.Font JavaDoc("Monospaced", 0, 11));
244     _edtResults.setEditable(false);
245     _edtResults.setText(Messages.getString("ConsolePanel.VirtualDatabaseConsole", DjVersion.getVersion()) + "\n\n"
246                         + Messages.getString("ConsolePanel.TypeHelp"));
247     _butExecuteStmt.setToolTipText(Messages.getString("ConsolePanel.CtrlEnter"));
248     _butExecuteStmt.setMnemonic('X');
249     _butExecuteStmt.setText(Messages.getString("ConsolePanel.Execute"));
250     _butExecuteStmt.addActionListener(new java.awt.event.ActionListener JavaDoc()
251     {
252       public void actionPerformed(ActionEvent JavaDoc e)
253       {
254         _butExecuteStmt_actionPerformed(e);
255       }
256     });
257     _checkPanel.setLayout(_layoutCheckpanel);
258     _butPrevStmt.setPreferredSize(new Dimension JavaDoc(24, 24));
259     _butPrevStmt.setToolTipText(Messages.getString("ConsolePanel.PreviousStmt"));
260     _butPrevStmt.addActionListener(new java.awt.event.ActionListener JavaDoc()
261     {
262       public void actionPerformed(ActionEvent JavaDoc e)
263       {
264         _butPrevStmt_actionPerformed(e);
265       }
266     });
267     _sqlPanel.setLayout(borderLayout1);
268     _edtOql.setFont(new java.awt.Font JavaDoc("Monospaced", 0, 11));
269     _edtCommand.setFont(new java.awt.Font JavaDoc("Monospaced", 0, 11));
270     _edtCommand.setToolTipText(Messages.getString("ConsolePanel.PressCtrlEnter"));
271     _butNextStmt.setPreferredSize(new Dimension JavaDoc(24, 24));
272     _butNextStmt.setToolTipText(Messages.getString("ConsolePanel.NextStmt"));
273     _butNextStmt.addActionListener(new java.awt.event.ActionListener JavaDoc()
274     {
275       public void actionPerformed(ActionEvent JavaDoc e)
276       {
277         _butNextStmt_actionPerformed(e);
278       }
279     });
280     _chkShowInternal.setText(Messages.getString("ConsolePanel.ShowInternal"));
281     _southPanel.setLayout(_layoutSouth);
282     _layoutCheckpanel.setAlignment(FlowLayout.LEFT);
283     _chkVirtualMode.setSelected(true);
284     _chkVirtualMode.setText(Messages.getString("ConsolePanel.VirtualMode"));
285     _pnlOql.setLayout(borderLayout2);
286     _cbbExtent.addActionListener(new java.awt.event.ActionListener JavaDoc()
287     {
288       public void actionPerformed(ActionEvent JavaDoc e)
289       {
290         _cbbExtent_actionPerformed(e);
291       }
292     });
293     jPanel1.setLayout(flowLayout1);
294     flowLayout1.setAlignment(FlowLayout.LEFT);
295     jLabel1.setText(Messages.getString("ConsolePanel.FromExtent"));
296     jPanel2.setLayout(borderLayout3);
297     _butExecOql.setText(Messages.getString("ConsolePanel.Execute"));
298     _butExecOql.addActionListener(new java.awt.event.ActionListener JavaDoc()
299     {
300       public void actionPerformed(ActionEvent JavaDoc e)
301       {
302         _butExecOql_actionPerformed(e);
303       }
304     });
305     jPanel4.setLayout(flowLayout2);
306     flowLayout2.setAlignment(FlowLayout.LEFT);
307     _cbbHelpExtent.addActionListener(new java.awt.event.ActionListener JavaDoc()
308     {
309       public void actionPerformed(ActionEvent JavaDoc e)
310       {
311         cbbHelpExtent_actionPerformed(e);
312       }
313     });
314     _butAddProp.setText(Messages.getString("ConsolePanel.Paste"));
315     _butAddProp.addActionListener(new java.awt.event.ActionListener JavaDoc()
316     {
317       public void actionPerformed(ActionEvent JavaDoc e)
318       {
319         _butAddProp_actionPerformed(e);
320       }
321     });
322     _butCancel.setEnabled(false);
323     _butCancel.setText(Messages.getString("global.Cancel"));
324     _butCancel.addActionListener(new java.awt.event.ActionListener JavaDoc()
325     {
326       public void actionPerformed(ActionEvent JavaDoc e)
327       {
328         _butCancel_actionPerformed(e);
329       }
330     });
331     _cbbHelpExtent.setPreferredSize(new Dimension JavaDoc(200, 24));
332     _cbbHelpProperty.setPreferredSize(new Dimension JavaDoc(200, 24));
333     _cbbExtent.setPreferredSize(new Dimension JavaDoc(200, 24));
334     this.add(statusBar, BorderLayout.SOUTH);
335     _splitpane.add(_scrResult, JSplitPane.TOP);
336     _splitpane.add(_tabs, JSplitPane.BOTTOM);
337     _tabs.add(_sqlPanel, Messages.getString("ConsolePanel.SQL"));
338     _sqlPanel.add(_scrCommand, BorderLayout.CENTER);
339     _sqlPanel.add(_southPanel, BorderLayout.SOUTH);
340     _scrCommand.getViewport().add(_edtCommand, null);
341     _buttonPanel.add(_butCancel, null);
342     _buttonPanel.add(_butPrevStmt, null);
343     _buttonPanel.add(_butNextStmt, null);
344     _buttonPanel.add(_butExecuteStmt, null);
345     _tabs.add(_pnlOql, Messages.getString("ConsolePanel.OQL"));
346     _pnlOql.add(jPanel1, BorderLayout.NORTH);
347     jPanel1.add(jLabel1, null);
348     jPanel1.add(_cbbExtent, null);
349     _pnlOql.add(jScrollPane1, BorderLayout.CENTER);
350     _pnlOql.add(jPanel2, BorderLayout.SOUTH);
351     jPanel2.add(jPanel3, BorderLayout.EAST);
352     jPanel3.add(_butExecOql, null);
353     jPanel2.add(jPanel4, BorderLayout.WEST);
354     jPanel4.add(_cbbHelpExtent, null);
355     jPanel4.add(_cbbHelpProperty, null);
356     jPanel4.add(_butAddProp, null);
357     jScrollPane1.getViewport().add(_edtOql, null);
358     _southPanel.add(_checkPanel, BorderLayout.CENTER);
359     _southPanel.add(_buttonPanel, BorderLayout.EAST);
360     _checkPanel.add(_chkVirtualMode, null);
361     _checkPanel.add(_chkShowInternal, null);
362     _scrResult.getViewport().add(_edtResults, null);
363     add(_splitpane, BorderLayout.CENTER);
364
365     _splitpane.setDividerLocation(150);
366     Util.sizeButtons(this);
367
368   }
369
370   public void setShowInternal(boolean b)
371   {
372     _chkShowInternal.setSelected(b);
373   }
374
375   public void setVirtualMode(boolean b)
376   {
377     _chkVirtualMode.setSelected(b);
378   }
379
380   public boolean isShowInternal()
381   {
382     return _chkShowInternal.isSelected();
383   }
384
385   public boolean isVirtualMode()
386   {
387     return _chkVirtualMode.isSelected();
388   }
389
390   public void requestFocus()
391   {
392     _edtCommand.requestFocus();
393   }
394
395   public void setDividerLocation(int loc)
396   {
397     _splitpane.setDividerLocation(loc);
398   }
399
400   public int getDividerLocation()
401   {
402     return _splitpane.getDividerLocation();
403   }
404
405   public int getMaxRowsToFetch()
406   {
407     return _maxRows;
408   }
409
410   public int getMaxColumnSize()
411   {
412     return _maxColSize;
413   }
414
415   public void setMaxRowsToFetch(int n)
416   {
417     _maxRows = n;
418   }
419
420   public void setMaxColumnSize(int n)
421   {
422     _maxColSize = n;
423   }
424
425   boolean rememberStatement(String JavaDoc stmt)
426   {
427     boolean doAdd = true;
428     if (_allStatements.size() > 0)
429     {
430       String JavaDoc last = (String JavaDoc) _allStatements.lastElement();
431       doAdd = (!last.equals(stmt));
432     }
433     if (doAdd) _allStatements.add(stmt);
434     _currentStatementIdx = _allStatements.size() - 1;
435
436     return doAdd;
437   }
438
439   void _butExecuteStmt_actionPerformed(ActionEvent JavaDoc e)
440   {
441     String JavaDoc stmt = _edtCommand.getText().trim();
442     rememberStatement(stmt);
443     executeStatement(stmt);
444   }
445
446   public void executeStatement(final String JavaDoc theStmt)
447   {
448     _canceled = false;
449     _butCancel.setEnabled(true);
450     _butExecuteStmt.setEnabled(false);
451     _butExecOql.setEnabled(false);
452     _edtCommand.setEnabled(false);
453     _edtOql.setEnabled(false);
454
455     DjSwingWorker worker = new DjSwingWorker()
456     {
457       public Object JavaDoc construct()
458       {
459         String JavaDoc stmtWithoutConstantText = DjString.wipeConstantText(theStmt, '\'', '\\', ' ');
460
461         try
462         {
463           String JavaDoc stmt = theStmt;
464           while (stmt.length() > 0)
465           {
466             if (_canceled) break;
467
468             int idx = stmtWithoutConstantText.indexOf(';');
469             if (idx == -1) idx = stmt.length();
470             else idx++;
471
472             String JavaDoc curStmt = stmt.substring(0, idx);
473             stmt = stmt.substring(idx);
474             stmtWithoutConstantText = stmtWithoutConstantText.substring(idx);
475
476             executeSingleStatement(curStmt.trim());
477           }
478
479         }
480         catch (Exception JavaDoc x)
481         {
482           print("\n" + x.getMessage() + "\n");
483           DjLogger.log(x);
484         }
485         return null;
486       }
487
488       public void finished()
489       {
490         if (_canceled) print(Messages.getString("ConsolePanel.Cancelled"));
491
492         _butExecuteStmt.setEnabled(true);
493         _butExecOql.setEnabled(true);
494         _butCancel.setEnabled(false);
495         _edtCommand.setEnabled(true);
496         _edtOql.setEnabled(true);
497
498         updateScrollBar();
499         if (_tabs.getSelectedComponent() == _sqlPanel)
500         {
501           _edtCommand.requestFocus();
502           _edtCommand.selectAll();
503         }
504         if (_tabs.getSelectedComponent() == _pnlOql)
505         {
506           _edtOql.requestFocus();
507           _edtOql.selectAll();
508         }
509         updateScrollBar();
510
511       }
512     };
513     worker.start();
514   }
515
516   protected void updateScrollBar()
517   {
518     _edtResults.setCaretPosition(_edtResults.getText().length());
519   }
520
521   public void print(String JavaDoc str)
522   {
523     _edtResults.append(str);
524
525     try
526     {
527       if (_edtResults.getLineCount() > MAX_LINES_IN_OUTPUT)
528       {
529         int idx = _edtResults.getLineStartOffset(MAX_LINES_DELTA);
530         _edtResults.setText(_edtResults.getText().substring(idx));
531       }
532       updateScrollBar();
533     }
534     catch (BadLocationException JavaDoc blx)
535     {
536       DjLogger.log(blx);
537     }
538
539     if (_spoolFile != null)
540     {
541       if (!"\n".equals(LINE_SEPARATOR))
542       {
543         DjStringReplacer sr = new DjStringReplacer(str);
544         str = sr.replace("\n", LINE_SEPARATOR);
545       }
546       _spoolFile.print(str);
547     }
548   }
549
550   public void println(String JavaDoc str)
551   {
552     print(str + "\n");
553   }
554
555   public void executeSingleStatement(String JavaDoc stmt) throws Exception JavaDoc
556   {
557     if (!stmt.endsWith(";")) stmt += ";";
558
559     if (stmt.toLowerCase().startsWith(START_CMD + " ") || stmt.toLowerCase().startsWith(START_CMD + "\t"))
560     {
561       runScript(stmt);
562       return;
563     }
564
565     if (stmt.toLowerCase().startsWith(SPOOL_CMD + " ") || stmt.toLowerCase().startsWith(SPOOL_CMD + "\t"))
566     {
567       spool(stmt);
568       return;
569     }
570
571     if (stmt.toLowerCase().startsWith(HEADER_CMD + " ") || stmt.toLowerCase().startsWith(HEADER_CMD + "\t"))
572     {
573       header(stmt);
574       return;
575     }
576
577     if (stmt.toLowerCase().startsWith(ECHO_CMD + " ") || stmt.toLowerCase().startsWith(ECHO_CMD + "\t"))
578     {
579       echo(stmt);
580       return;
581     }
582
583     if (stmt.toLowerCase().startsWith(CLEAR_CMD))
584     {
585       _edtResults.setText("");
586       return;
587     }
588
589     if (stmt.toLowerCase().startsWith(HELP_CMD + ";"))
590     {
591       showHelp();
592       return;
593     }
594
595     if (stmt.toLowerCase().startsWith(EXIT_CMD + ";"))
596     {
597       for (int i = 0; i < _allExitListeners.size(); i++)
598       {
599         ConsoleExitListener l = (ConsoleExitListener) _allExitListeners.get(i);
600         l.consoleExit();
601       }
602       return;
603     }
604
605     SqlStatement sql;
606     if (_chkVirtualMode.isSelected()) sql = _session.getSqlStatement(stmt);
607     else sql = _session.getInternalSqlStatement(stmt);
608
609     String JavaDoc lower = stmt.toLowerCase();
610
611     if (_chkShowInternal.isSelected())
612     {
613       if (_echo) print("\n" + sql.getInternalSql() + "\n");
614     }
615     else
616     {
617       if (_echo) print("\n" + stmt + "\n");
618     }
619     if (lower.startsWith("select"))
620     {
621       try
622       {
623         ResultSet JavaDoc rs = sql.executeQuery();
624         ResultSetMetaData JavaDoc md = rs.getMetaData();
625
626         int colCount = md.getColumnCount();
627
628         String JavaDoc[] colNames = new String JavaDoc[colCount];
629         int[] colSizes = new int[colCount];
630         ArrayList JavaDoc rows = new ArrayList JavaDoc();
631
632         for (int i = 0; i < colCount; i++)
633         {
634           colNames[i] = md.getColumnLabel(i + 1);
635           colSizes[i] = colNames[i].length();
636         }
637
638         int rowCount = _maxRows;
639         while (rs.next() && (rowCount-- > 0))
640         {
641           if (_canceled) break;
642
643           String JavaDoc[] values = new String JavaDoc[colCount];
644           for (int i = 0; i < colCount; i++)
645           {
646             values[i] = rs.getString(i + 1);
647             if (values[i] == null) values[i] = "";
648
649             values[i] = values[i].replace('\n', '|');
650             if (values[i].length() > colSizes[i])
651             {
652               colSizes[i] = values[i].length();
653             }
654           }
655           rows.add(values);
656         }
657         rs.close();
658
659         // trim columns to their max length's
660
for (int i = 0; i < colCount; i++)
661         {
662           if (colSizes[i] > _maxColSize)
663           {
664             colSizes[i] = _maxColSize;
665           }
666         }
667
668         StringBuffer JavaDoc sb = new StringBuffer JavaDoc(2000);
669         sb.append("\n");
670
671         if (_printHeader)
672         {
673           for (int c = 0; c < colCount; c++)
674           {
675             sb.append(DjString.appendToLength(colNames[c], " ", colSizes[c]));
676             sb.append(" ");
677           }
678           sb.append("\n");
679           print(sb.toString());
680
681           sb = new StringBuffer JavaDoc(2000);
682           for (int c = 0; c < colCount; c++)
683           {
684             sb.append(DjString.appendToLength("", "-", colSizes[c]));
685             sb.append(" ");
686           }
687           sb.append("\n");
688           print(sb.toString());
689         }
690
691         sb = new StringBuffer JavaDoc(PRINT_BUFFER_SIZE);
692         for (int i = 0; i < rows.size(); i++)
693         {
694           if (_canceled) break;
695
696           if (i % 100 == 0 && i != 0)
697           {
698             print(sb.toString());
699             sb = new StringBuffer JavaDoc(PRINT_BUFFER_SIZE);
700           }
701           String JavaDoc[] cols = (String JavaDoc[]) rows.get(i);
702           for (int c = 0; c < colCount; c++)
703           {
704             sb.append(DjString.appendToLength(cols[c], " ", colSizes[c]));
705             sb.append(" ");
706           }
707           sb.append("\n");
708         }
709         print(sb.toString());
710
711         if (_echo && !_canceled) print("\n"
712                                        + Messages.getString("ConsolePanel.RowsFetched", String.valueOf(rows.size())));
713         if (rowCount == -1)
714         {
715           print(Messages.getString("ConsolePanel.MaximumRowsReached"));
716         }
717       }
718       finally
719       {
720         sql.close();
721       }
722     }
723     else
724     {
725       _butCancel.setEnabled(false);
726
727       int rows = sql.executeUpdate();
728       if (lower.startsWith("update") || lower.startsWith("delete"))
729       {
730         if (_echo) print("\n" + Messages.getString("ConsolePanel.RowsAffected", String.valueOf(rows)));
731       }
732       else
733       {
734         if (_echo) print(Messages.getString("ConsolePanel.ExecutedOk"));
735       }
736       // reset the cancel flag because update/delete was not canceled (no can
737
// do)
738
_canceled = false;
739     }
740     updateScrollBar();
741   }
742
743   public void showHelp()
744   {
745     print(Messages.getString("ConsolePanel.SQLTab") + Messages.getString("ConsolePanel.SeparateSQLWith")
746           + Messages.getString("ConsolePanel.Press") + Messages.getString("ConsolePanel.ExecCurrent")
747           + Messages.getString("ConsolePanel.HistoryBackward") + Messages.getString("ConsolePanel.HistoryForward")
748           + Messages.getString("ConsolePanel.Enter") + Messages.getString("ConsolePanel.CommitTrans")
749           + Messages.getString("ConsolePanel.RollbackTrans") + " " + CLEAR_CMD
750           + Messages.getString("ConsolePanel.ClearResults") + " " + HEADER_CMD
751           + Messages.getString("ConsolePanel.headers") + " " + ECHO_CMD + Messages.getString("ConsolePanel.echo")
752           + " " + SPOOL_CMD + Messages.getString("ConsolePanel.spool") + " " + SPOOL_CMD
753           + Messages.getString("ConsolePanel.StopSpool") + " " + START_CMD
754           + Messages.getString("ConsolePanel.runscript") + " " + EXIT_CMD
755           + Messages.getString("ConsolePanel.ExitConsole"));
756
757     print(Messages.getString("ConsolePanel.OqlTab") + Messages.getString("ConsolePanel.EnterJavaLike")
758           + Messages.getString("ConsolePanel.NotePropCase") + Messages.getString("ConsolePanel.StringsBetweenQuotes")
759           + Messages.getString("ConsolePanel.joinsWithDot") + Messages.getString("ConsolePanel.Example"));
760   }
761
762   public void header(String JavaDoc stmt) throws Exception JavaDoc
763   {
764     String JavaDoc cmd = stmt.substring(HEADER_CMD.length() + 1).trim();
765     if (cmd.endsWith(";")) cmd = cmd.substring(0, cmd.length() - 1);
766
767     if (!cmd.toLowerCase().startsWith("on") && !cmd.toLowerCase().startsWith("of"))
768     {
769       println(Messages.getString("ConsolePanel.Use") + " " + HEADER_CMD + " <ON | OFF> ");
770       return;
771     }
772     _printHeader = cmd.toLowerCase().startsWith("on");
773     if (_printHeader) println(Messages.getString("ConsolePanel.HeadersON"));
774     else println(Messages.getString("ConsolePanel.HeaderOFF"));
775   }
776
777   public void echo(String JavaDoc stmt) throws Exception JavaDoc
778   {
779     String JavaDoc cmd = stmt.substring(ECHO_CMD.length() + 1).trim();
780     if (cmd.endsWith(";")) cmd = cmd.substring(0, cmd.length() - 1);
781
782     if (!cmd.toLowerCase().startsWith("on") && !cmd.toLowerCase().startsWith("of"))
783     {
784       println(Messages.getString("ConsolePanel.Use") + ECHO_CMD + " <ON | OFF> ");
785       return;
786     }
787     _echo = cmd.toLowerCase().startsWith("on");
788     if (_echo) println(Messages.getString("ConsolePanel.EchoON"));
789     else println(Messages.getString("ConsolePanel.EchoOFF"));
790   }
791
792   public void spool(String JavaDoc stmt) throws Exception JavaDoc
793   {
794     String JavaDoc fileName = stmt.substring(SPOOL_CMD.length() + 1).trim();
795     if (fileName.endsWith(";")) fileName = fileName.substring(0, fileName.length() - 1);
796
797     if (_spoolFile != null)
798     {
799       _spoolFile.close();
800       _spoolFile = null;
801     }
802
803     if (fileName.equalsIgnoreCase("off"))
804     {
805       print(Messages.getString("ConsolePanel.SpoolingOff"));
806       return;
807     }
808
809     PrintWriter JavaDoc pw = new PrintWriter JavaDoc(new FileWriter JavaDoc(fileName));
810     print(Messages.getString("ConsolePanel.SpoolingTo") + fileName + "\n");
811     _spoolFile = pw;
812   }
813
814   public void runScript(String JavaDoc stmt) throws Exception JavaDoc
815   {
816     String JavaDoc fileName = stmt.substring(START_CMD.length() + 1).trim();
817     if (fileName.endsWith(";")) fileName = fileName.substring(0, fileName.length() - 1);
818
819     File JavaDoc inFile = new File JavaDoc(new File JavaDoc(fileName).getAbsolutePath());
820
821     BufferedReader JavaDoc br = new BufferedReader JavaDoc(new FileReader JavaDoc(inFile));
822     String JavaDoc cmd = "";
823     String JavaDoc ln;
824     while ((ln = br.readLine()) != null)
825     {
826       cmd += ln.trim();
827       if (cmd.endsWith(";"))
828       {
829         executeStatement(cmd);
830         RepaintManager JavaDoc rm = RepaintManager.currentManager(this);
831         if (rm != null)
832         {
833           rm.validateInvalidComponents();
834           rm.paintDirtyRegions();
835         }
836         cmd = "";
837       }
838     }
839     br.close();
840   }
841
842   public static ImageIcon JavaDoc getImageIcon(String JavaDoc fileName)
843   {
844     URL JavaDoc url = Console.class.getResource("nodes/images/" + fileName);
845     if (url != null) return new ImageIcon JavaDoc(url);
846     else return new ImageIcon JavaDoc("");
847     // Default to empty image
848
}
849
850   public static Image JavaDoc getImage(String JavaDoc fileName)
851   {
852     URL JavaDoc url = Console.class.getResource("nodes/images/" + fileName);
853     if (url != null) return Toolkit.getDefaultToolkit().getImage(url);
854
855     else return Toolkit.getDefaultToolkit().getImage("");
856   }
857
858   void _butPrevStmt_actionPerformed(ActionEvent JavaDoc e)
859   {
860     if (_currentStatementIdx > 0) _currentStatementIdx--;
861     if (_allStatements.size() > 0)
862     {
863       _edtCommand.setText(_allStatements.get(_currentStatementIdx).toString());
864       _edtCommand.selectAll();
865     }
866   }
867
868   void _butNextStmt_actionPerformed(ActionEvent JavaDoc e)
869   {
870     if (_currentStatementIdx < _allStatements.size() - 1) _currentStatementIdx++;
871     if (_currentStatementIdx <= _allStatements.size() - 1)
872     {
873       _edtCommand.setText(_allStatements.get(_currentStatementIdx).toString());
874       _edtCommand.selectAll();
875     }
876   }
877
878   public void closeSession() throws Exception JavaDoc
879   {
880     _session.close();
881   }
882
883   void _butExecOql_actionPerformed(ActionEvent JavaDoc e)
884   {
885     String JavaDoc oqlWhere = _edtOql.getText();
886
887     try
888     {
889       if (oqlWhere.toLowerCase().startsWith("where "))
890       {
891         oqlWhere = oqlWhere.substring(6).trim();
892         _edtOql.setText(oqlWhere);
893       }
894       DjOql oql = getSession().createOql((DjExtent) _cbbExtent.getSelectedItem(), oqlWhere);
895       String JavaDoc fromWhere = oql.getFromWhereClause();
896       String JavaDoc sql = "select ";
897       if (!oql.isResultUnique()) sql += "distinct ";
898       sql += oql.getAlias() + ".*\n" + fromWhere;
899       _chkVirtualMode.setSelected(true);
900       _edtCommand.setText(sql);
901       _tabs.setSelectedComponent(_sqlPanel);
902       executeStatement(sql);
903       if (!_canceled) _tabs.setSelectedComponent(_pnlOql);
904     }
905     catch (ParseException px)
906     {
907       print("\n" + px.getMessage() + "\n");
908       try
909       {
910         if (px.getLine() > 0 && px.getColumn() > 0)
911         {
912           int offset = _edtOql.getLineStartOffset(px.getLine() - 1) + px.getColumn() - 1;
913           _edtOql.setCaretPosition(offset);
914         }
915       }
916       catch (Exception JavaDoc e1)
917       {
918         DjLogger.log(e1);
919       }
920       _edtOql.requestFocus();
921     }
922
923   }
924
925   void cbbHelpExtent_actionPerformed(ActionEvent JavaDoc e)
926   {
927     DjExtent extent = (DjExtent) _cbbHelpExtent.getSelectedItem();
928     _cbbHelpProperty.setModel(new DefaultComboBoxModel JavaDoc(extent.getPropertiesSorted()));
929   }
930
931   void _butAddProp_actionPerformed(ActionEvent JavaDoc e)
932   {
933     _edtOql.replaceSelection(_cbbHelpProperty.getSelectedItem().toString());
934   }
935
936   void _cbbExtent_actionPerformed(ActionEvent JavaDoc e)
937   {
938     _cbbHelpExtent.setSelectedItem(_cbbExtent.getSelectedItem());
939
940     if (_propertyPathCompleter != null) _propertyPathCompleter.removeStatusListener(this);
941
942     _propertyPathCompleter = new DjPropertyPathCompleter((DjExtent) _cbbExtent.getSelectedItem(), _edtOql);
943     _propertyPathCompleter.setIncludeOne2Many(true);
944     _propertyPathCompleter.addStatusListener(this);
945   }
946
947   void _butCancel_actionPerformed(ActionEvent JavaDoc e)
948   {
949     _canceled = true;
950   }
951
952   /* (non-Javadoc)
953    * @see com.genimen.djeneric.ui.DjStatusListener#setStatusMessage(java.lang.String, boolean)
954    */

955   public void setStatusMessage(String JavaDoc msg, boolean isInformative)
956   {
957     _edtResults.append(msg + "\n");
958   }
959
960   public void setStatusMessage(Throwable JavaDoc t)
961   {
962     setStatusMessage(t.getMessage(), false);
963   }
964
965   /* (non-Javadoc)
966    * @see com.genimen.djeneric.ui.DjStatusListener#notifyModified()
967    */

968   public void notifyModified()
969   {
970   }
971
972 }
Popular Tags