source: src/main/java/weka/gui/sql/QueryPanel.java @ 20

Last change on this file since 20 was 4, checked in by gnappo, 14 years ago

Import di weka.

File size: 11.3 KB
Line 
1/*
2 *    This program is free software; you can redistribute it and/or modify
3 *    it under the terms of the GNU General Public License as published by
4 *    the Free Software Foundation; either version 2 of the License, or
5 *    (at your option) any later version.
6 *
7 *    This program is distributed in the hope that it will be useful,
8 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
9 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10 *    GNU General Public License for more details.
11 *
12 *    You should have received a copy of the GNU General Public License
13 *    along with this program; if not, write to the Free Software
14 *    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
15 */
16
17/*
18 * QueryPanel.java
19 * Copyright (C) 2005 University of Waikato, Hamilton, New Zealand
20 *
21 */
22
23package weka.gui.sql;
24
25import weka.gui.ListSelectorDialog;
26import weka.gui.sql.event.ConnectionEvent;
27import weka.gui.sql.event.ConnectionListener;
28import weka.gui.sql.event.HistoryChangedEvent;
29import weka.gui.sql.event.HistoryChangedListener;
30import weka.gui.sql.event.QueryExecuteEvent;
31import weka.gui.sql.event.QueryExecuteListener;
32
33import java.awt.BorderLayout;
34import java.awt.Dimension;
35import java.awt.FlowLayout;
36import java.awt.Font;
37import java.awt.event.ActionEvent;
38import java.awt.event.ActionListener;
39import java.sql.ResultSet;
40import java.util.HashSet;
41import java.util.Iterator;
42
43import javax.swing.DefaultListModel;
44import javax.swing.JButton;
45import javax.swing.JFrame;
46import javax.swing.JLabel;
47import javax.swing.JList;
48import javax.swing.JPanel;
49import javax.swing.JScrollPane;
50import javax.swing.JSpinner;
51import javax.swing.JTextArea;
52import javax.swing.SpinnerNumberModel;
53import javax.swing.event.CaretEvent;
54import javax.swing.event.CaretListener;
55
56/**
57 * Represents a panel for entering an SQL query.
58 *
59 * @author      FracPete (fracpete at waikato dot ac dot nz)
60 * @version     $Revision: 1.4 $
61 */
62public class QueryPanel 
63  extends JPanel
64  implements ConnectionListener, CaretListener {
65
66  /** for serialization. */
67  private static final long serialVersionUID = 4348967824619706636L;
68
69  /** the name of the history. */
70  public final static String HISTORY_NAME = "query";
71
72  /** the name for the max rows in the history. */
73  public final static String MAX_ROWS = "max_rows";
74 
75  /** the parent of this panel. */
76  protected JFrame m_Parent;
77
78  /** the textarea for the query. */
79  protected JTextArea m_TextQuery;
80
81  /** the execute button. */
82  protected JButton m_ButtonExecute = new JButton("Execute");
83
84  /** the clear button. */
85  protected JButton m_ButtonClear = new JButton("Clear");
86
87  /** the history button. */
88  protected JButton m_ButtonHistory = new JButton("History...");
89
90  /** the spinner for the maximum number of rows. */
91  protected JSpinner m_SpinnerMaxRows = new JSpinner();
92
93  /** the connection listeners. */
94  protected HashSet m_QueryExecuteListeners;
95
96  /** the history listeners. */
97  protected HashSet m_HistoryChangedListeners;
98
99  /** for working on the database. */
100  protected DbUtils m_DbUtils;
101
102  /** whether we have a connection to a database or not. */
103  protected boolean m_Connected;
104
105  /** the query history. */
106  protected DefaultListModel m_History = new DefaultListModel();
107 
108  /**
109   * initializes the panel.
110   *
111   * @param parent        the parent of this panel
112   */
113  public QueryPanel(JFrame parent) {
114    super();
115   
116    m_Parent                  = parent;
117    m_QueryExecuteListeners   = new HashSet();
118    m_HistoryChangedListeners = new HashSet();
119    m_DbUtils                 = null;
120    m_Connected               = false;
121
122    createPanel();
123  }
124
125  /**
126   * creates the panel with all its components.
127   */
128  protected void createPanel() {
129    JPanel              panel;
130    JPanel              panel2;
131    JPanel              panel3;
132    SpinnerNumberModel  model;
133   
134    setLayout(new BorderLayout());
135   
136    // textarea
137    m_TextQuery = new JTextArea();
138    m_TextQuery.addCaretListener(this);
139    m_TextQuery.setFont(
140        new Font("Monospaced", Font.PLAIN, m_TextQuery.getFont().getSize()));
141    add(new JScrollPane(m_TextQuery), BorderLayout.CENTER);
142
143    // buttons
144    panel = new JPanel(new BorderLayout());
145    add(panel, BorderLayout.EAST);
146    m_ButtonExecute.setMnemonic('E');
147    m_ButtonExecute.addActionListener(new ActionListener() {
148        public void actionPerformed(ActionEvent e) {
149          execute();
150        }
151      });
152    panel.add(m_ButtonExecute, BorderLayout.NORTH);
153    panel2 = new JPanel(new BorderLayout());
154    panel.add(panel2, BorderLayout.CENTER);
155    m_ButtonClear.setMnemonic('r');
156    m_ButtonClear.addActionListener(new ActionListener() {
157        public void actionPerformed(ActionEvent e) {
158          clear();
159        }
160      });
161    panel2.add(m_ButtonClear, BorderLayout.NORTH);
162    panel3 = new JPanel(new BorderLayout());
163    panel2.add(panel3, BorderLayout.CENTER);
164    m_ButtonHistory.addActionListener(new ActionListener() {
165        public void actionPerformed(ActionEvent e) {
166          showHistory();
167        }
168      });
169    panel3.add(m_ButtonHistory, BorderLayout.NORTH);
170
171    // limit
172    panel3 = new JPanel(new FlowLayout());
173    panel3.add(new JLabel("max. rows"));
174    panel3.add(m_SpinnerMaxRows);
175    panel2.add(panel3, BorderLayout.SOUTH);
176    model = (SpinnerNumberModel) m_SpinnerMaxRows.getModel();
177    model.setMaximum(new Integer(Integer.MAX_VALUE));
178    model.setMinimum(new Integer(0));
179    model.setValue(new Integer(100));
180    model.setStepSize(new Integer(100));
181    m_SpinnerMaxRows.setMinimumSize(
182        new Dimension(50, m_SpinnerMaxRows.getHeight()));
183    m_SpinnerMaxRows.setToolTipText("with 0 all rows are retrieved");
184     
185    // set initial state
186    setButtons();
187  }
188
189  /**
190   * sets the focus in a designated control.
191   */
192  public void setFocus() {
193    m_TextQuery.requestFocus();
194  }
195
196  /**
197   * sets the buttons according to the connected-state.
198   */
199  protected void setButtons() {
200    boolean isEmpty;
201   
202    isEmpty = m_TextQuery.getText().trim().equals("");
203   
204    m_ButtonExecute.setEnabled((m_Connected) && (!isEmpty));
205    m_ButtonClear.setEnabled(!isEmpty);
206    m_ButtonHistory.setEnabled(m_History.size() > 0);
207  }
208 
209  /**
210   * This method gets called when the connection is either established
211   * or disconnected.
212   *
213   * @param evt         the event
214   */
215  public void connectionChange(ConnectionEvent evt) {
216    m_Connected = evt.isConnected();
217    m_DbUtils   = evt.getDbUtils();
218    setButtons();
219  }
220
221  /**
222   * executes the current query.
223   */
224  public void execute() {
225    Exception     ex;
226    ResultSet     rs;
227   
228    // not connected?
229    if (!m_ButtonExecute.isEnabled())
230      return;
231
232    // no query?
233    if (m_TextQuery.getText().trim().equals(""))
234      return;
235
236    // close old resultset
237    try {
238      if (m_DbUtils.getResultSet() != null)
239        m_DbUtils.close();
240    }
241    catch (Exception e) {
242      // ignore (if no resultset present we get an unncessary NullPointerEx.)
243    }
244
245    ex = null;
246    rs = null;
247   
248    try {
249      if (m_DbUtils.execute(getQuery())) {
250        rs = m_DbUtils.getResultSet();
251        // add to history
252        addHistory(getQuery());
253      }
254    }
255    catch (Exception e) {
256      ex = new Exception(e.getMessage());
257    }
258
259    notifyQueryExecuteListeners(rs, ex);
260
261    setButtons();
262  }
263
264  /**
265   * clears the textarea.
266   */
267  public void clear() {
268    m_TextQuery.setText("");
269    m_SpinnerMaxRows.setValue(new Integer(100));
270  }
271
272  /**
273   * adds the given string to the history (removes duplicates).
274   *
275   * @param s           the string to add
276   */
277  protected void addHistory(String s) {
278    if (s.equals(""))
279      return;
280   
281    // no duplicates!
282    if (m_History.contains(s))
283      m_History.removeElement(s);
284
285    m_History.add(0, s);
286   
287    // send notification
288    notifyHistoryChangedListeners();
289  }
290
291  /**
292   * sets the local history to the given one.
293   *
294   * @param history     the history to use
295   */
296  public void setHistory(DefaultListModel history) {
297    int           i;
298   
299    m_History.clear();
300    for (i = 0; i < history.size(); i++)
301      m_History.addElement(history.get(i));
302
303    setButtons();
304  }
305
306  /**
307   * returns the history.
308   *
309   * @return        the current history
310   */
311  public DefaultListModel getHistory() {
312    return m_History;
313  }
314
315  /**
316   * displays the query history.
317   */
318  public void showHistory() {
319    JList                 list;
320    ListSelectorDialog    dialog;
321
322    list   = new JList(m_History);
323    dialog = new ListSelectorDialog(m_Parent, list);
324   
325    if (dialog.showDialog() == ListSelectorDialog.APPROVE_OPTION) {
326      if (list.getSelectedValue() != null)
327        setQuery(list.getSelectedValue().toString());
328    }
329
330    setButtons();
331  }
332
333  /**
334   * sets the query in the textarea.
335   *
336   * @param query         the query to display
337   */
338  public void setQuery(String query) {
339    m_TextQuery.setText(query);
340  }
341
342  /**
343   * returns the currently displayed query.
344   *
345   * @return            the query
346   */
347  public String getQuery() {
348    return m_TextQuery.getText();
349  }
350
351  /**
352   * sets the maximum number of rows to display. 0 means unlimited.
353   *
354   * @param rows        the maximum number of rows
355   */
356  public void setMaxRows(int rows) {
357    if (rows >= 0)
358      m_SpinnerMaxRows.setValue(new Integer(rows));
359  }
360
361  /**
362   * returns the current value for the maximum number of rows. 0 means
363   * unlimited.
364   *
365   * @return            the maximum number of rows
366   */
367  public int getMaxRows() {
368    return ((Integer) m_SpinnerMaxRows.getValue()).intValue();
369  }
370
371  /**
372   * adds the given listener to the list of listeners.
373   *
374   * @param l       the listener to add to the list
375   */
376  public void addQueryExecuteListener(QueryExecuteListener l) {
377    m_QueryExecuteListeners.add(l);
378  }
379
380  /**
381   * removes the given listener from the list of listeners.
382   *
383   * @param l       the listener to remove
384   */
385  public void removeQueryExecuteListener(QueryExecuteListener l) {
386    m_QueryExecuteListeners.remove(l);
387  }
388
389  /**
390   * notifies the listeners of the event.
391   *
392   * @param rs          the resultset
393   * @param ex          the exception
394   */
395  protected void notifyQueryExecuteListeners(ResultSet rs, Exception ex) {
396    Iterator              iter;
397    QueryExecuteListener  l;
398
399    iter = m_QueryExecuteListeners.iterator();
400    while (iter.hasNext()) {
401      l = (QueryExecuteListener) iter.next();
402      l.queryExecuted(
403          new QueryExecuteEvent(
404            this, m_DbUtils, getQuery(), getMaxRows(), rs, ex));
405    }
406  }
407
408  /**
409   * adds the given listener to the list of listeners.
410   *
411   * @param l       the listener to add to the list
412   */
413  public void addHistoryChangedListener(HistoryChangedListener l) {
414    m_HistoryChangedListeners.add(l);
415  }
416
417  /**
418   * removes the given listener from the list of listeners.
419   *
420   * @param l       the listener to remove
421   */
422  public void removeHistoryChangedListener(HistoryChangedListener l) {
423    m_HistoryChangedListeners.remove(l);
424  }
425
426  /**
427   * notifies the history listeners of the event.
428   */
429  protected void notifyHistoryChangedListeners() {
430    Iterator                iter;
431    HistoryChangedListener  l;
432
433    iter = m_HistoryChangedListeners.iterator();
434    while (iter.hasNext()) {
435      l = (HistoryChangedListener) iter.next();
436      l.historyChanged(
437          new HistoryChangedEvent(this, HISTORY_NAME, getHistory()));
438    }
439  }
440
441  /**
442   * Called when the caret position is updated.
443   *
444   * @param event       the event
445   */
446  public void caretUpdate(CaretEvent event) {
447    setButtons();
448  }
449}
450
Note: See TracBrowser for help on using the repository browser.