View Javadoc

1   package com.explosion.datastream.exql.gui;
2   
3   /*
4    * =============================================================================
5    * 
6    * Copyright 2004 Stephen Cowx
7    * 
8    * Licensed under the Apache License, Version 2.0 (the "License"); you may not
9    * use this file except in compliance with the License. You may obtain a copy of
10   * the License at
11   * 
12   * http://www.apache.org/licenses/LICENSE-2.0
13   * 
14   * Unless required by applicable law or agreed to in writing, software
15   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
17   * License for the specific language governing permissions and limitations under
18   * the License.
19   * 
20   * =============================================================================
21   */
22  
23  import java.awt.BorderLayout;
24  import java.awt.Component;
25  import java.awt.Dimension;
26  import java.awt.event.ActionEvent;
27  import java.awt.event.ActionListener;
28  import java.io.File;
29  import java.io.FileWriter;
30  import java.util.ArrayList;
31  import java.util.HashMap;
32  import java.util.List;
33  import java.util.Map;
34  import java.util.Vector;
35  
36  import javax.swing.JButton;
37  import javax.swing.JOptionPane;
38  import javax.swing.JPanel;
39  import javax.swing.JSplitPane;
40  import javax.swing.JTabbedPane;
41  import javax.swing.table.TableModel;
42  
43  import org.apache.log4j.LogManager;
44  import org.apache.log4j.Logger;
45  
46  import com.explosion.datastream.exql.EXQLConstants;
47  import com.explosion.datastream.exql.gui.dbbrowser.DBDataViewer;
48  import com.explosion.datastream.exql.gui.dbbrowser.DBEntityBrowser;
49  import com.explosion.datastream.exql.gui.querywriter.SQlQueryWriterBase;
50  import com.explosion.datastream.exql.gui.scriptrunner.ScriptRunnerBase;
51  import com.explosion.datastream.exql.impexp.DelimitedExportFormatter;
52  import com.explosion.expf.Application;
53  import com.explosion.expf.Closeable;
54  import com.explosion.expf.ExpActionListener;
55  import com.explosion.expf.ExpComponent;
56  import com.explosion.expf.ExpConstants;
57  import com.explosion.expf.ExpFrame;
58  import com.explosion.expf.menusandtools.tool.ExpToolBar;
59  import com.explosion.expf.menusandtools.tool.ExpToolBarSegment;
60  import com.explosion.expfmodules.rdbmsconn.connect.ConnectionManager;
61  import com.explosion.expfmodules.rdbmsconn.dbom.DBEntity;
62  import com.explosion.expfmodules.rdbmsconn.dbom.EntityMetaData;
63  import com.explosion.utilities.FileSystemUtils;
64  import com.explosion.utilities.exception.ExceptionManagerFactory;
65  import com.explosion.utilities.process.ProcessMonitoringStatusBar;
66  
67  /***
68   * Base for the sql tool.
69   */
70  
71  public class EXQLBaseTool extends JPanel implements ExpComponent, Closeable
72  {
73  
74      private int connectionKey = -1;
75      private ConnectionManager connectionManager;
76      private JTabbedPane infoPane = new JTabbedPane();
77      private ProcessMonitoringStatusBar processMonitoringStatusBar;
78      private DBEntityBrowser browser;
79      private DBDataViewer viewer;
80      private SQlQueryWriterBase simpleQueryTool;
81      private EXQLBaseTool instance;
82  
83      private JSplitPane basePane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
84      private static Logger log = LogManager.getLogger(EXQLBaseTool.class);
85      private ExpToolBar toolbar;
86      private EntityMetaData currentEntityMetaData;
87      private String connectionName;
88      
89      private List scriptRunners = new ArrayList();
90      
91      /***
92       * This constructor is used solely for the purposes of testing
93       */
94      protected EXQLBaseTool() throws IllegalAccessError
95      {  
96      }
97  
98      /***
99       * This is the right constructor to use under all circumstances (The other constructor is for testing)
100      * @param connectionKey
101      * @param connectionManager
102      * @throws Exception
103      */
104     public EXQLBaseTool(int connectionKey, ConnectionManager connectionManager) throws Exception
105     {
106         try
107         {
108             this.connectionKey = connectionKey;
109             this.connectionManager = connectionManager;
110             
111             processMonitoringStatusBar = new ProcessMonitoringStatusBar(Application.getApplicationFrame());
112             instance = this;
113 
114             EXQLBaseToolLocalListener localListener = new EXQLBaseToolLocalListener(this);
115             EXQLBaseToolGlobalListener globalListener = new EXQLBaseToolGlobalListener(this);
116 
117             browser = new DBEntityBrowser(this, connectionKey, processMonitoringStatusBar);
118             viewer = new DBDataViewer(this, connectionManager.getConnection(connectionKey), processMonitoringStatusBar);
119             connectionName = connectionManager.getConnectionDescriptor(connectionKey).getIdentifier();
120             simpleQueryTool = new SQlQueryWriterBase(this, connectionManager.getConnection(connectionKey), connectionName, processMonitoringStatusBar);
121 
122             init();
123         } catch (Exception ex)
124         {
125             ExceptionManagerFactory.getExceptionManager().manageException(ex, "Exception caught while initialising exqlBaseTool.");
126         }
127     }
128 
129     public void init() throws Exception
130     {
131         Application.addToGlobalCookie(EXQLConstants.MENU_CLOSEALL_CONNECTIONS, 1);
132         Application.addToLocalCookie(EXQLConstants.MENU_CLOSE_CONNECTION, 1, this);
133         Application.addToLocalCookie(EXQLConstants.MENU_REFRESH, 1, this);
134         Application.addToLocalCookie(EXQLConstants.MENU_RUNSCRIPT, 1, this);
135         
136         JSplitPane browserPane = new JSplitPane();
137         browserPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
138         browserPane.setLeftComponent(browser);
139         browserPane.setRightComponent(viewer);
140         browserPane.setResizeWeight(0.5);
141         
142         infoPane.addTab("Browse", browserPane);
143         infoPane.addTab("Queries", simpleQueryTool);
144         //infoPane.addTab("Log", logPane);
145         
146         this.setLayout(new BorderLayout());
147         this.add(infoPane, BorderLayout.CENTER);
148         this.add(processMonitoringStatusBar, BorderLayout.SOUTH);
149         
150         applyPreferences();
151     }
152     
153     /***
154      * This method adds a script runner on to the 
155      * set of tabs for this tool
156      * @param file
157      */
158     public void addScriptRunner(File file)
159     {
160         ScriptRunnerBase runner = new ScriptRunnerBase(this, connectionManager.getConnection(connectionKey), connectionName, processMonitoringStatusBar, file);
161         this.infoPane.add(file.getName(),runner );
162         scriptRunners.add(runner);
163         infoPane.setSelectedIndex(infoPane.getComponentCount()-1);
164     }
165     
166     /***
167      * This method adds a script runner on to the 
168      * set of tabs for this tool
169      * @param file
170      */
171     public void removeScriptRunner(ScriptRunnerBase runner)
172     {
173         Component[] components = infoPane.getComponents();
174         for (int i = 0; i < components.length; i++) {
175             if (components[i] == runner)
176             {
177                 infoPane.remove(i);
178                 break;
179             }
180         }
181         scriptRunners.remove(runner);
182     }
183     
184     /***
185      * This method adds a script runner on to the 
186      * set of tabs for this tool
187      * @param file
188      */
189     public void renameScriptRunner(ScriptRunnerBase runner, String newName)
190     {
191         Component[] components = infoPane.getComponents();
192         for (int i = 0; i < components.length; i++) {
193             if (components[i] == runner)
194             {
195                 infoPane.setTitleAt(i,newName);
196                 break;
197             }
198         }
199     }
200 
201     public ExpToolBar getToolBar() throws Exception
202     {
203         if (toolbar == null)
204         {
205             /* Create and initialise a toolbar */
206             toolbar = new ExpToolBar(((ExpFrame) Application.getApplicationFrame()).getListener());
207 
208             ExpToolBarSegment exqlSegment = toolbar.createNewSegment(ExpToolBarSegment.ANY_POSITION);
209             JButton refreshButton = toolbar.createExpToolBarItem(EXQLConstants.REFRESH_ICON_IMAGE, "Refresh", EXQLConstants.MENU_REFRESH, 1);
210             exqlSegment.addElement(refreshButton);
211             JButton runscriptButton = toolbar.createExpToolBarItem(EXQLConstants.RUNSCRIPT_ICON_IMAGE, "Run script", EXQLConstants.MENU_RUNSCRIPT, 1);
212             exqlSegment.addElement(runscriptButton);
213             JButton editSQLButton = toolbar.createExpToolBarItem(EXQLConstants.EDIT_SQL_ICON_IMAGE, "View SQL", EXQLConstants.MENU_EDIT_SQL, 1);
214             exqlSegment.addElement(editSQLButton);
215             JButton formatSQLButton = toolbar.createExpToolBarItem(EXQLConstants.FORMAT_SQL_ICON_IMAGE, "Format SQL", EXQLConstants.MENU_FORMAT_SQL, 1);
216             exqlSegment.addElement(formatSQLButton);
217             
218 
219             ExpToolBarSegment editSegment = toolbar.createNewSegment(ExpToolBarSegment.ALWAYS_LAST_SEGMENT);
220             editSegment.addElement(null);
221             JButton insertButton = toolbar.createExpToolBarItem(EXQLConstants.ADD_ICON_IMAGE, "Insert row", EXQLConstants.MENU_INSERT_ROW, 1);
222             editSegment.addElement(insertButton);
223             JButton deleteButton = toolbar.createExpToolBarItem(EXQLConstants.DELETE_ICON_IMAGE, "Delete row", EXQLConstants.MENU_DELETE_ROW, 1);
224             editSegment.addElement(deleteButton);
225             JButton executeButton = toolbar.createExpToolBarItem(EXQLConstants.EXECUTE_ICON_IMAGE, "Execute update", EXQLConstants.MENU_EXECUTE_CHANGES, 1);
226             editSegment.addElement(executeButton);
227 
228             toolbar.constructToolBar();
229         }
230         return this.toolbar;
231     }
232 
233     /***
234      * Appends a message to the history windows
235      */
236     public void log(String message)
237     {
238         log.info(message);
239     }
240 
241     public void refreshTool()
242     {
243         try
244         {
245             disableComponent();
246             browser.refresh();
247             viewer.update();
248             enableComponent();
249 
250         } catch (Exception e)
251         {
252             ExceptionManagerFactory.getExceptionManager().manageException(e, "Exception caught while refreshing.");
253         }
254     }
255 
256     public void changePane(String paneName)
257     {
258         if (paneName.equals("Browse"))
259             infoPane.setSelectedIndex(0);
260         else
261             infoPane.setSelectedIndex(1);
262     }
263 
264     public void disableComponent()
265     {
266         Application.ensureLocalCookie(EXQLConstants.MENU_REFRESH, 0, this);
267         Application.ensureLocalCookie(EXQLConstants.MENU_RUNSCRIPT, 0, this);
268         
269         Application.ensureLocalCookie(EXQLConstants.MENU_COMMIT_CHANGES, 0, this);
270         Application.ensureLocalCookie(EXQLConstants.MENU_DELETE_ROW, 0, this);
271         Application.ensureLocalCookie(EXQLConstants.MENU_DUPLICATE_ROW, 0, this);
272         Application.ensureLocalCookie(EXQLConstants.MENU_EDIT_SQL, 0, this);
273         Application.ensureLocalCookie(EXQLConstants.MENU_EXECUTE_CHANGES, 0, this);
274         Application.ensureLocalCookie(EXQLConstants.MENU_EXPORT, 0, this);
275         Application.ensureLocalCookie(EXQLConstants.MENU_EXPORT_SELECTED, 0, this);
276         Application.ensureLocalCookie(EXQLConstants.MENU_INSERT_ROW, 0, this);
277 
278         
279         infoPane.setEnabled(false);
280         browser.disableComponent();
281         viewer.disableComponent();
282         simpleQueryTool.disableComponent();
283         
284         for (int i=0;i<scriptRunners.size();i++)
285         {
286             ((ScriptRunnerBase) scriptRunners.get(i)).disableComponent();
287         }
288     }
289 
290     public void enableComponent()
291     {
292         Application.ensureLocalCookie(EXQLConstants.MENU_REFRESH, 1, this);
293         Application.ensureLocalCookie(EXQLConstants.MENU_RUNSCRIPT, 1, this);
294 
295         infoPane.setEnabled(true);
296         browser.enableComponent();
297         viewer.enableComponent();
298         simpleQueryTool.enableComponent();
299         
300         for (int i=0;i<scriptRunners.size();i++)
301         {
302             ((ScriptRunnerBase) scriptRunners.get(i)).enableComponent();
303         }
304     }
305 
306     public void applyPreferences()
307     {
308         browser.applyPreferences();
309         viewer.applyPreferences();
310         simpleQueryTool.applyPreferences();
311     }
312 
313     public String getCloseCommand()
314     {
315         return EXQLConstants.MENU_CLOSE_CONNECTION;
316     }
317 
318     public ActionListener getGlobalListener()
319     {
320         return null;
321     }
322 
323     public boolean close()
324     {
325         connectionManager.disconnect(this.connectionKey);
326         simpleQueryTool.close();
327         Application.removeFromGlobalCookie(EXQLConstants.MENU_CLOSEALL_CONNECTIONS, 1);
328         return true;
329     }
330 
331     public ProcessMonitoringStatusBar getProgressStatusBar()
332     {
333         return this.processMonitoringStatusBar;
334     }
335 
336     public SQlQueryWriterBase getQueryTool()
337     {
338         return this.simpleQueryTool;
339     }
340 
341     /***
342      * @return
343      */
344     public DBEntityBrowser getBrowser()
345     {
346         return browser;
347     }
348 
349     /***
350      * @param browser
351      */
352     public void setBrowser(DBEntityBrowser browser)
353     {
354         this.browser = browser;
355     }
356 
357     /***
358      * @return Returns the viewer.
359      */
360     public DBDataViewer getViewer()
361     {
362         return viewer;
363     }
364     /***
365      * @return Returns the currentEntityMetaData.
366      */
367     public EntityMetaData getCurrentEntityMetaData()
368     {
369         return currentEntityMetaData;
370     }
371     
372     /***
373      * @param currentEntityMetaData The currentEntityMetaData to set.
374      */
375     public void setCurrentEntityMetaData(EntityMetaData currentEntityMetaData)
376     {
377         this.currentEntityMetaData = currentEntityMetaData;
378     }
379     
380     /***
381      * Exports the results from the current table
382      * @throws Exception 
383      *
384      */
385     public void export() throws Exception
386     {
387         File[] files = FileSystemUtils.chooseFiles(Application.getApplicationFrame(),FileSystemUtils.FILES_ONLY,false,new File("."),FileSystemUtils.OPENTYPE,"Export to");
388         File file = files[0];
389         
390         FileWriter writer = new FileWriter(file,false);
391         DelimitedExportFormatter formatter = new DelimitedExportFormatter();
392         TableModel model = null;
393         if (this.viewer.isVisible())
394         {
395             model = this.viewer.getView().getDataTable().getModel();
396         }
397         else if (this.simpleQueryTool.getView().isVisible())
398         {
399             model = this.simpleQueryTool.getView().getDataTable().getModel();
400         }
401         else
402         {
403             JOptionPane.showMessageDialog(this,"No results to export","Export", JOptionPane.INFORMATION_MESSAGE);
404             return;
405         }
406         
407         for (int i=0;i<model.getRowCount();i++)
408         {
409             Vector row = new Vector();
410             Vector columns = new Vector();
411             
412             for (int t=0;t<model.getColumnCount();t++)
413             {
414                 row.add(model.getValueAt(i,t));
415                 columns.add(model.getColumnName(t));
416             }
417             formatter.write(writer, columns, row);
418         }
419         writer.close();
420     }
421 }
422 
423 class EXQLBaseToolLocalListener implements ExpActionListener
424 {
425 
426     private HashMap map;
427     private EXQLBaseTool tool;
428 
429     /***
430      * Constructor for TextEditorLocalListener.
431      */
432     public EXQLBaseToolLocalListener(EXQLBaseTool tool)
433     {
434         this.tool = tool;
435         map = new HashMap();
436         map.put(EXQLConstants.MENU_CLOSE_CONNECTION, EXQLConstants.MENU_CLOSE_CONNECTION);
437         map.put(EXQLConstants.MENU_REFRESH, EXQLConstants.MENU_REFRESH);
438         map.put(EXQLConstants.MENU_RUNSCRIPT, EXQLConstants.MENU_RUNSCRIPT);
439         map.put(EXQLConstants.MENU_EDIT_SQL, EXQLConstants.MENU_EDIT_SQL);
440         map.put(EXQLConstants.MENU_DELETE_ROW, EXQLConstants.MENU_DELETE_ROW);
441         map.put(EXQLConstants.MENU_INSERT_ROW, EXQLConstants.MENU_INSERT_ROW);
442         map.put(EXQLConstants.MENU_EXECUTE_CHANGES, EXQLConstants.MENU_EXECUTE_CHANGES);
443         map.put(EXQLConstants.MENU_EXPORT, EXQLConstants.MENU_EXPORT);
444         map.put(EXQLConstants.MENU_EXPORT_SELECTED, EXQLConstants.MENU_EXPORT_SELECTED);
445         
446         /*
447          * Register this listener with the CompoundListener so that it listens
448          * for local events
449          */
450         ((ExpFrame) Application.getApplicationFrame()).getListener().addLocalActionListener(this, tool);
451     }
452    
453     /***
454      * @see package
455      *      com.explosion.expf.Interfaces.ExpActionListener#getListensFor()
456      */
457     public Map getListensFor()
458     {
459         return map;
460     }
461 
462     /***
463      * @see java.awt.event.ActionListener#actionPerformed(ActionEvent)
464      */
465     public void actionPerformed(ActionEvent e)
466     {
467         try
468         {
469             if (e.getActionCommand().equals(EXQLConstants.MENU_CLOSE_CONNECTION))
470             {
471                 if (tool.close())
472                     ((ExpFrame) Application.getApplicationFrame()).closeFrameWithComponent(tool, ExpFrame.DOC_FRAME_LAYER);
473             } 
474             else if (e.getActionCommand().equals(EXQLConstants.MENU_REFRESH))
475             {
476                 tool.refreshTool();
477             } 
478             else if (e.getActionCommand().equals(EXQLConstants.MENU_EDIT_SQL))
479             {
480                 DBEntity dbed = tool.getBrowser().getSelectedTableEntityDescriptor();
481                 if (dbed != null)
482                 {
483                     SQLPopup popup = new SQLPopup(dbed);
484                     ((ExpFrame) Application.getApplicationFrame()).createModalDialog(popup, new Dimension(400, 400), "Edit SQL", true);
485                 }
486             } else if (e.getActionCommand().equals(EXQLConstants.MENU_RUNSCRIPT))
487             {
488                 File[] files = FileSystemUtils.chooseFiles(tool, FileSystemUtils.OPENTYPE, false, null, FileSystemUtils.FILES_ONLY, "Run script");
489                 if (files != null && files[0] != null)
490                 {
491                     tool.addScriptRunner(files[0]);
492                 }
493             } 
494             else if (e.getActionCommand().equals(EXQLConstants.MENU_INSERT_ROW))
495             {
496                 tool.getViewer().getView().getDataTable().insertNewRow();
497             }
498             else if (e.getActionCommand().equals(EXQLConstants.MENU_DELETE_ROW))
499             {
500                 tool.getViewer().getView().getDataTable().deleteSelectedRows();
501             }
502             else if (e.getActionCommand().equals(EXQLConstants.MENU_EXECUTE_CHANGES))
503             {
504                 tool.getViewer().executeChanges();
505             }
506             else if (e.getActionCommand().equals(EXQLConstants.MENU_EXPORT))
507             {
508                 tool.export();
509             }
510         } catch (Exception ex)
511         {
512             com.explosion.utilities.exception.ExceptionManagerFactory.getExceptionManager().manageException(ex, "Exception caught while responding to SimpleProcess Event.");
513         }
514 
515     }
516 
517 }
518 
519 class EXQLBaseToolGlobalListener implements ExpActionListener
520 {
521 
522     private HashMap map;
523     private EXQLBaseTool tool;
524 
525     /***
526      * Constructor for EXQLBaseToolGlobalListener.
527      */
528     public EXQLBaseToolGlobalListener(EXQLBaseTool tool)
529     {
530         this.tool = tool;
531         map = new HashMap();
532         map.put(EXQLConstants.MENU_CLOSEALL_CONNECTIONS, EXQLConstants.MENU_CLOSEALL_CONNECTIONS);
533         map.put(ExpConstants.MENU_CLOSE,ExpConstants.MENU_CLOSE);
534 
535         /*
536          * Register this listener with the CompoundListener so that it listens
537          * for local events
538          */
539         ((ExpFrame) Application.getApplicationFrame()).getListener().addGlobalActionListener(this, tool);
540     }
541 
542     /***
543      * @see package
544      *      com.explosion.expf.Interfaces.ExpActionListener#getListensFor()
545      */
546     public Map getListensFor()
547     {
548         return map;
549     }
550 
551     /***
552      * @see java.awt.event.ActionListener#actionPerformed(ActionEvent)
553      */
554     public void actionPerformed(ActionEvent e)
555     {
556         try
557         {
558             if (e.getActionCommand().equals(EXQLConstants.MENU_CLOSEALL_CONNECTIONS))
559             {
560                 if (tool.close())
561                     ((ExpFrame) Application.getApplicationFrame()).closeFrameWithComponent(tool, ExpFrame.DOC_FRAME_LAYER);
562             }
563             if (e.getActionCommand().equals(ExpConstants.MENU_CLOSE))
564             {
565                 if (tool.close())
566                     ((ExpFrame) Application.getApplicationFrame()).closeFrameWithComponent(tool, ExpFrame.DOC_FRAME_LAYER);
567             }
568         } catch (Exception ex)
569         {
570             com.explosion.utilities.exception.ExceptionManagerFactory.getExceptionManager().manageException(ex, "Exception caught while responding to SimpleProcess Event.");
571         }
572 
573     }
574 
575 }
576