KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > barracuda > testbed > workbench > jdbc > JDBCTester


1 package org.enhydra.barracuda.testbed.workbench.jdbc;
2
3 import java.awt.*;
4 import java.awt.event.*;
5 import java.io.*;
6 import java.sql.*;
7 import java.util.*;
8 import javax.swing.*;
9 import javax.swing.event.*;
10
11 import org.enhydra.barracuda.plankton.data.*;
12
13 import org.enhydra.barracuda.testbed.workbench.util.gui.Containers;
14 import org.enhydra.barracuda.testbed.workbench.util.gui.Cursors;
15 import org.enhydra.barracuda.testbed.workbench.util.gui.DefaultComponentListener;
16
17 /**
18  * JDBC Tester
19  */

20 public class JDBCTester extends JPanel {
21
22     //public vars (these are set up to connect to a Microsoft SQL server db; you can modify
23
//them accordingly. You will need to provide your own JDBC drivers in the classpath)
24
public static String JavaDoc DEFAULT_URL = "jdbc:JSQLConnect://localhost/database=Master/user=sa";
25     public static String JavaDoc DEFAULT_DRIVERS = "com.jnetdirect.jsql.JSQLDriver";
26     public static String JavaDoc DEFAULT_USER = "";
27     public static String JavaDoc DEFAULT_PWD = "";
28     public static String JavaDoc DEFAULT_SQL_STR = "SELECT * FROM sysdatabases";
29     
30     //debug vars
31
public static int showDebug = 0;
32
33     //working vars
34
private static String JavaDoc sep = System.getProperty("line.separator");
35     private boolean isConnected = false;
36     private Database db = null;
37     private String JavaDoc jdbcServerURL = null;
38     private String JavaDoc jdbcDriverName = null;
39     private String JavaDoc dbUserName = null;
40     private String JavaDoc dbPassword = null;
41
42     //objects
43
private boolean isInitialized = false;
44
45     //buttons & controls
46
//...Settings panel
47
private JTextField jtfURL = null;
48     private JTextField jtfDriver = null;
49     private JTextField jtfUser = null;
50     private JTextField jtfPwd = null;
51     private JButton jbConnect = null;
52     private JButton jbDisconnect = null;
53     //...Main panel
54
private JTabbedPane jtpTabs = null;
55     //...Query panel
56
private JPanel jpQuery = null;
57     private JTextArea jtaQuery = null;
58     //...Results panel
59
private JPanel jpResults = null;
60     private JTextArea jtaResults = null;
61     //...Footer panel
62
private JButton jbQuery = null;
63     private JButton jbClear = null;
64
65     
66     /**
67      * Public constructor
68      */

69     public JDBCTester() {
70         //set up a listener so when this guy is exposed we hear about it
71
this.addComponentListener(new LocalComponentListener());
72     }
73     
74     //============================================================
75
// Model / Controller info for the Master View
76
//============================================================
77
/**
78      * This method is responsible for laying out the
79      * UI components.
80      *
81      * @throws Exception
82      */

83     private void initViews() throws Exception JavaDoc {
84
85         //general
86
this.setLayout(new GridBagLayout());
87         LocalActionAdapter actionAdapter = new LocalActionAdapter();
88         LocalKeyListener keyListener = new LocalKeyListener();
89         Insets buttonInsets = new Insets(0, 5, 0, 5);
90
91
92         //settings panel
93
JPanel jpSettings = new JPanel();
94         jpSettings.setLayout(new GridBagLayout());
95         this.add(jpSettings, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0,
96             GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 0, 5), 0, 0));
97         //...JDBC URL
98
JLabel jlbURL = new JLabel("JDBC URL:");
99         jpSettings.add(jlbURL, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 0.0, 0.0,
100             GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 5, 2, 5), 0, 0));
101         jtfURL = new JTextField(DEFAULT_URL);
102         jpSettings.add(jtfURL, new GridBagConstraints(1, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0,
103             GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(2, 5, 2, 5), 0, 0));
104         //...JDBC Driver
105
JLabel jlbDriver = new JLabel("JDBC Driver:");
106         jpSettings.add(jlbDriver, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 0.0, 0.0,
107             GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 5, 2, 5), 0, 0));
108         jtfDriver = new JTextField(DEFAULT_DRIVERS);
109         jpSettings.add(jtfDriver, new GridBagConstraints(1, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0,
110             GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(2, 5, 2, 5), 0, 0));
111         //...User
112
JLabel jlbUser = new JLabel("Username:");
113         jpSettings.add(jlbUser, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 0.0, 0.0,
114             GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 5, 2, 5), 0, 0));
115         JPanel jpUserPwd = new JPanel();
116         jpUserPwd.setLayout(new GridBagLayout());
117         jpSettings.add(jpUserPwd, new GridBagConstraints(1, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0,
118             GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
119         jtfUser = new JTextField(DEFAULT_USER,10);
120         jpUserPwd.add(jtfUser, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 0.0, 0.0,
121             GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 5, 2, 5), 0, 0));
122         //...Pwd
123
JLabel jlbPwd = new JLabel("Password:");
124         jpUserPwd.add(jlbPwd, new GridBagConstraints(1, GridBagConstraints.RELATIVE, 1, 1, 0.0, 0.0,
125             GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 5, 2, 5), 0, 0));
126         jtfPwd = new JTextField(DEFAULT_PWD,10);
127         jpUserPwd.add(jtfPwd, new GridBagConstraints(2, GridBagConstraints.RELATIVE, 1, 1, 0.0, 0.0,
128             GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 5, 2, 5), 0, 0));
129         //...Filler (to push the fields over)
130
jpUserPwd.add(new JLabel(" "), new GridBagConstraints(3, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0,
131             GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
132         //...Connect
133
jbConnect = new JButton("Connect");
134         jbConnect.setToolTipText("Connect to the Database");
135         jbConnect.setMargin(buttonInsets);
136         jbConnect.addActionListener(actionAdapter);
137         jpSettings.add(jbConnect, new GridBagConstraints(99, GridBagConstraints.RELATIVE, 1, 1, 0.0, 0.0,
138             GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
139         //...Disconnect
140
jbDisconnect = new JButton("Disconnect");
141         jbDisconnect.setToolTipText("Disconnect from the Database");
142         jbDisconnect.setMargin(buttonInsets);
143         jbDisconnect.addActionListener(actionAdapter);
144         jpSettings.add(jbDisconnect, new GridBagConstraints(99, GridBagConstraints.RELATIVE, 1, 1, 0.0, 0.0,
145             GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
146
147
148
149         //main panel
150
jtpTabs = new JTabbedPane();
151         jtpTabs.setTabPlacement(SwingConstants.BOTTOM);
152         this.add(jtpTabs, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 1.0,
153             GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 0, 5), 0, 0));
154
155         //...query panel
156
jpQuery = new JPanel();
157         jpQuery.setLayout(new GridBagLayout());
158         jtpTabs.addTab("SQL", null, jpQuery, "Create a JDBC Query/Update");
159         jtaQuery = new JTextArea(DEFAULT_SQL_STR);
160         jtaQuery.addKeyListener(keyListener);
161         JScrollPane jspQuery = new JScrollPane(jtaQuery);
162         jpQuery.add(jspQuery, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 1.0,
163             GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, 0));
164
165         //...results panel
166
jpResults = new JPanel();
167         jpResults.setLayout(new GridBagLayout());
168         jtpTabs.addTab("Results", null, jpResults, "View the results of a JDBC Query/Update");
169         jtaResults = new JTextArea();
170         jtaResults.addKeyListener(keyListener);
171         JScrollPane jspResults = new JScrollPane(jtaResults);
172         jpResults.add(jspResults, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 1.0,
173             GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, 0));
174
175
176
177         //Footer Panel
178
JPanel jpFooter = new JPanel();
179         jpFooter.setLayout(new GridBagLayout());
180         this.add(jpFooter, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0,
181             GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 5, 5, 5), 0, 0));
182         //...filler
183
jpFooter.add(new JLabel(" "), new GridBagConstraints(GridBagConstraints.RELATIVE, 0, 1, 1, 1.0, 0.0,
184             GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
185         //...Query
186
jbQuery = new JButton("Execute SQL");
187         jbQuery.setToolTipText("Execute the Query/Update SQL");
188         jbQuery.setMargin(buttonInsets);
189         jbQuery.addActionListener(actionAdapter);
190         jpFooter.add(jbQuery, new GridBagConstraints(GridBagConstraints.RELATIVE, 0, 1, 1, 0.0, 0.0,
191             GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 5), 0, 0));
192         //...Clear
193
jbClear = new JButton("Clear");
194         jbClear.setToolTipText("Clear the visible window");
195         jbClear.setMargin(buttonInsets);
196         jbClear.addActionListener(actionAdapter);
197         jpFooter.add(jbClear, new GridBagConstraints(GridBagConstraints.RELATIVE, 0, 1, 1, 0.0, 0.0,
198             GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
199     
200         //setWorking = false
201
setWorking(false);
202     }
203
204     /**
205      * Connect to the database
206      */

207     public void doConnect() {
208         try {
209             //set working = true
210
setWorking(true);
211
212             //get the setting
213
jdbcServerURL = jtfURL.getText();
214             jdbcDriverName = jtfDriver.getText();
215             dbUserName = jtfUser.getText();
216             dbPassword = jtfPwd.getText();
217         
218             //switch to the output window
219
jtpTabs.setSelectedIndex(1);
220         
221             //connect to the database
222
try {
223                 db = new Database(jdbcDriverName, jdbcServerURL, dbUserName, dbPassword);
224                 db.connectServer();
225                 jtaResults.append ("Connection negotiated"+sep);
226                 isConnected = true;
227             } catch (Exception JavaDoc e) {
228                 db = null;
229                 jtaResults.append ("Connection failed:"+sep);
230                 ByteArrayOutputStream baos = new ByteArrayOutputStream();
231                 e.printStackTrace(new PrintStream(baos));
232                 jtaResults.append (baos.toString()+sep);
233                 java.awt.Toolkit.getDefaultToolkit().beep();
234                 JOptionPane.showMessageDialog(null, "Connection failed: "+e.toString(), "Error!", JOptionPane.ERROR_MESSAGE);
235             }
236
237         } finally {
238             //set working = false
239
setWorking(false);
240         }
241     }
242     
243     /**
244      * Disconnect from the database
245      */

246     public void doDisconnect() {
247         try {
248             //set working = true
249
setWorking(true);
250
251             //switch to the output window
252
jtpTabs.setSelectedIndex(1);
253         
254             //disconnect from the database
255
try {
256                 db.disconnectServer();
257                 db = null;
258                 jtaResults.append ("Disconnected"+sep);
259                 isConnected = false;
260             } catch (Exception JavaDoc e) {
261                 jtaResults.append ("Disconnection failed:"+sep);
262                 ByteArrayOutputStream baos = new ByteArrayOutputStream();
263                 e.printStackTrace(new PrintStream(baos));
264                 jtaResults.append (baos.toString()+sep);
265                 JOptionPane.showMessageDialog(null, "Disconnect failed: "+e.toString(), "Error!", JOptionPane.ERROR_MESSAGE);
266             }
267         } finally {
268             //set working = false
269
setWorking(false);
270         }
271     }
272     
273     /**
274      * Execute a query / update
275      */

276     public void doQuery() {
277         try {
278             //set working = true
279
setWorking(true);
280
281             //switch to the output window
282
jtpTabs.setSelectedIndex(1);
283         
284             //prepare the sql String
285
String JavaDoc sql = ""+jtaQuery.getText().trim();
286             // (TODO: need to strip out separators)
287
jtaResults.append("SQL: "+sql+sep);
288             jtaResults.append("==========================================================="+sep);
289             if (sql.length()<1) {
290                 JOptionPane.showMessageDialog(null, "Invalid Query/Update String...Nothing was entered!", "Error!", JOptionPane.ERROR_MESSAGE);
291                 jtpTabs.setSelectedIndex(0);
292                 return;
293             }
294             
295             //figure out whether we're querying or updating
296
boolean isUpdate = true;
297             if (sql.toLowerCase().startsWith("select")) isUpdate = false;
298
299             //execute the query
300
Statement stmt = null;
301             try {
302                 stmt = db.createStatement();
303                 if (isUpdate) {
304                     //do the update
305
int rows = stmt.executeUpdate(sql);
306                     db.commit();
307                     jtaResults.append(rows+" rows updated"+sep+sep);
308                     
309                 } else {
310                     //do the query
311
ResultSet rs = stmt.executeQuery(sql);
312
313                     // get the metadata
314
int columns = rs.getMetaData().getColumnCount();
315                     String JavaDoc columnName;
316                     String JavaDoc columnType;
317                     StringBuffer JavaDoc sb = new StringBuffer JavaDoc(500);
318                     String JavaDoc delim = "";
319                     for (int pos = 1; pos <= columns; pos++) {
320                         columnName = rs.getMetaData().getColumnName(pos);
321                         columnType = rs.getMetaData().getColumnTypeName(pos);
322                         sb.append(delim+columnName+"["+columnType+"]");
323                         if (pos==1) delim = ", ";
324                     }
325                     jtaResults.append("Cols: "+sb.toString()+sep);
326                     
327                     // get the individual result set data
328
Object JavaDoc rowData;
329                     int row = 0;
330                     while (rs.next()) {
331                         sb = new StringBuffer JavaDoc(500);
332                         delim = "";
333                         for (int pos = 1; pos <= columns; pos++) {
334                             rowData = rs.getObject(pos);
335                             sb.append(delim+rowData);
336                             if (pos==1) delim = ", ";
337                         }
338                         jtaResults.append("Row "+(++row)+": "+sb.toString()+sep);
339                         jtaResults.append(" "+sep);
340                     }
341                     if (row==0) jtaResults.append("Rows: (empty result set)"+sep+sep);
342                 }
343                 
344             }
345             catch (Exception JavaDoc e) {
346                 jtaResults.append ("Query failed:"+sep);
347                 ByteArrayOutputStream baos = new ByteArrayOutputStream();
348                 e.printStackTrace(new PrintStream(baos));
349                 jtaResults.append (baos.toString()+sep);
350                 JOptionPane.showMessageDialog(null, "Query failed: "+e.getMessage(), "Error!", JOptionPane.ERROR_MESSAGE);
351             } finally {
352                 try {stmt.close();}
353                 catch (SQLException se) {}
354             }
355         } finally {
356             //set working = false
357
setWorking(false);
358         }
359     }
360     
361     /**
362      * Clear the current screen
363      */

364     public void doClear() {
365         try {
366             //set working = true
367
setWorking(true);
368
369             //clear the currently exposed screen
370
int curscreen = jtpTabs.getSelectedIndex();
371             if (curscreen==0) jtaQuery.setText("");
372             else if (curscreen==1) jtaResults.setText("");
373
374         } finally {
375             //set working = false
376
setWorking(false);
377         }
378     }
379     
380     private void setWorking(boolean val) {
381         //set the cursors
382
Cursors.setWorking(Containers.getRootContainer(this), val);
383
384         //disable key fields
385
jbConnect.setEnabled(!isConnected && !val);
386         jbDisconnect.setEnabled(isConnected && !val);
387         jbQuery.setEnabled(isConnected && !val);
388         jbClear.setEnabled(!val);
389     }
390     
391
392     //-------------------- ComponentListener ---------------------
393
/**
394      * Handle component events
395      */

396     class LocalComponentListener extends DefaultComponentListener {
397     
398         /**
399          * Invoked when the component has been made visible.
400          */

401         public void componentShown(ComponentEvent e) {
402             if (showDebug>1) System.out.println ("Shown:"+e);
403             
404             //init the screen and catch any unexpected errors
405
if (!isInitialized) try {
406                 initViews();
407                 isInitialized = true;
408             } catch (Exception JavaDoc be) {
409                 System.out.println ("Error initializing "+this);
410                 be.printStackTrace();
411             }
412         }
413     }
414
415     //-------------------- ActionListener ------------------------
416
/**
417      * Handle the actions for buttons
418      */

419     class LocalActionAdapter implements java.awt.event.ActionListener JavaDoc {
420
421         /**
422          * actionPerformed method
423          */

424         public void actionPerformed(ActionEvent e) {
425             //handle the action
426
Object JavaDoc o = e.getSource();
427             if (o==jbConnect) doConnect();
428             else if (o==jbDisconnect) doDisconnect();
429             else if (o==jbQuery) doQuery();
430             else if (o==jbClear) doClear();
431             else {
432                 System.out.println ("Unhandled Action:"+o);
433             }
434         }
435     }
436     
437     //-------------------- KeyListener ---------------------------
438
/**
439      * Listener for keystrokes
440      */

441     class LocalKeyListener implements java.awt.event.KeyListener JavaDoc {
442
443         public void keyPressed(KeyEvent e) {
444             if (e.getKeyCode()==KeyEvent.VK_ENTER && e.isControlDown()) {
445                 jbQuery.doClick();
446             }
447         }
448
449         public void keyReleased(KeyEvent e) {
450             //ignore
451
}
452          
453         public void keyTyped(KeyEvent e) {
454             //ignore
455
}
456     }
457
458     
459 }
460
Popular Tags