KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > db > explorer > actions > ConnectUsingDriverAction


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.db.explorer.actions;
21
22 import java.awt.event.ActionEvent JavaDoc;
23 import java.awt.event.ActionListener JavaDoc;
24 import java.beans.PropertyChangeEvent JavaDoc;
25 import java.beans.PropertyChangeListener JavaDoc;
26 import java.sql.Connection JavaDoc;
27 import java.sql.ResultSet JavaDoc;
28 import java.sql.SQLException JavaDoc;
29 import java.text.MessageFormat JavaDoc;
30 import java.util.Vector JavaDoc;
31
32 import javax.swing.JTabbedPane JavaDoc;
33 import javax.swing.event.ChangeEvent JavaDoc;
34 import javax.swing.event.ChangeListener JavaDoc;
35 import org.netbeans.modules.db.explorer.ConnectionList;
36 import org.netbeans.modules.db.explorer.dlg.ConnectionDialogMediator;
37
38 import org.openide.DialogDescriptor;
39 import org.openide.DialogDisplayer;
40 import org.openide.NotifyDescriptor;
41 import org.openide.ErrorManager;
42 import org.openide.nodes.Node;
43
44 import org.netbeans.api.db.explorer.DatabaseException;
45 import org.netbeans.modules.db.ExceptionListener;
46 import org.netbeans.modules.db.explorer.DatabaseConnection;
47
48 //commented out for 3.6 release, need to solve for next Studio release
49
//import org.netbeans.modules.db.explorer.PointbasePlus;
50

51 import org.netbeans.modules.db.explorer.dlg.ConnectionDialog;
52 import org.netbeans.modules.db.explorer.dlg.NewConnectionPanel;
53 import org.netbeans.modules.db.explorer.dlg.SchemaPanel;
54 import org.netbeans.api.db.explorer.JDBCDriver;
55 import org.netbeans.api.db.explorer.JDBCDriverManager;
56 import org.netbeans.lib.ddl.DDLException;
57 import org.netbeans.modules.db.explorer.driver.JDBCDriverSupport;
58 import org.netbeans.modules.db.explorer.infos.ConnectionNodeInfo;
59 import org.netbeans.modules.db.explorer.infos.DatabaseNodeInfo;
60 import org.netbeans.modules.db.explorer.infos.DriverNodeInfo;
61 import org.netbeans.modules.db.explorer.infos.RootNodeInfo;
62 import org.netbeans.modules.db.explorer.nodes.RootNode;
63
64 public class ConnectUsingDriverAction extends DatabaseAction {
65     static final long serialVersionUID =8245005834483564671L;
66
67     protected boolean enable(Node[] activatedNodes) {
68         return (activatedNodes != null && activatedNodes.length == 1);
69     }
70
71     public void performAction(Node[] activatedNodes) {
72         Node node = activatedNodes[0];
73         DriverNodeInfo info = (DriverNodeInfo) node.getCookie(DatabaseNodeInfo.class);
74         JDBCDriver driver = info.getJDBCDriver();
75         
76         String JavaDoc driverName, driverClass;
77         if (driver != null) {
78             driverName = driver.getName();
79             driverClass = driver.getClassName();
80         } else {
81             // no JDBCDriver, have to resort to the info
82
driverName = info.getName();
83             // info.getURL() suprisingly returns the driver class
84
driverClass = info.getURL();
85         }
86         new NewConnectionDialogDisplayer().showDialog(driverName, driverClass);
87     }
88     
89     public static final class NewConnectionDialogDisplayer extends ConnectionDialogMediator {
90         
91         ConnectionDialog dlg;
92         ConnectionNodeInfo cni;
93         boolean advancedPanel = false;
94         boolean okPressed = false;
95
96         public void showDialog(String JavaDoc driverName, String JavaDoc driverClass) {
97             showDialog(driverName, driverClass, null, null, null);
98         }
99         
100         public DatabaseConnection showDialog(JDBCDriver driver, String JavaDoc databaseUrl, String JavaDoc user, String JavaDoc password) {
101             String JavaDoc driverName = (driver != null) ? driver.getName() : null;
102             String JavaDoc driverClass = (driver != null) ? driver.getClassName() : null;
103             return showDialog(driverName, driverClass, databaseUrl, user, password);
104         }
105         
106         public DatabaseConnection showDialog(String JavaDoc driverName, String JavaDoc driverClass, String JavaDoc databaseUrl, String JavaDoc user, String JavaDoc password) {
107             String JavaDoc finalDriverClass = null;
108             
109             JDBCDriver[] drivers;
110             if ((null != databaseUrl) && (null != driverClass)) {
111                 drivers = JDBCDriverManager.getDefault().getDrivers(driverClass);
112                 finalDriverClass = driverClass;
113             } else {
114                 drivers = JDBCDriverManager.getDefault().getDrivers();
115             }
116             
117             // issue 74723: select the Derby network driver by default
118
// otherwise just select the first driver
119
String JavaDoc selectedDriverName = null;
120             String JavaDoc selectedDriverClass = null;
121             if (driverName == null || driverClass == null) {
122                 for (int i = 0; i < drivers.length; i++) {
123                     if (JDBCDriverSupport.isAvailable(drivers[i])) {
124                         if (selectedDriverName == null) {
125                             selectedDriverName = drivers[i].getName();
126                             selectedDriverClass = drivers[i].getClassName();
127                         }
128                         if ("org.apache.derby.jdbc.ClientDriver".equals(drivers[i].getClassName())) { // NOI18N
129
selectedDriverName = drivers[i].getName();
130                             selectedDriverClass = drivers[i].getClassName();
131                             break;
132                         }
133                     }
134                 }
135             } else {
136                 selectedDriverName = driverName;
137                 selectedDriverClass = driverClass;
138             }
139             
140             final DatabaseConnection cinfo = new DatabaseConnection();
141             cinfo.setDriverName(selectedDriverName);
142             cinfo.setDriver(selectedDriverClass);
143             if (user != null) {
144                 cinfo.setUser(user);
145             }
146             if (password != null) {
147                 cinfo.setPassword(password);
148             }
149
150             if (null != databaseUrl) {
151                 cinfo.setDatabase(databaseUrl);
152             }
153             
154             final NewConnectionPanel basePanel = new NewConnectionPanel(this, finalDriverClass, cinfo);
155             final SchemaPanel schemaPanel = new SchemaPanel(this, cinfo);
156
157             PropertyChangeListener JavaDoc argumentListener = new PropertyChangeListener JavaDoc() {
158                 public void propertyChange(PropertyChangeEvent JavaDoc event) {
159                     if (event.getPropertyName().equals("argumentChanged")) { //NOI18N
160
schemaPanel.setSchemas(new Vector JavaDoc(), ""); //NOI18N
161
schemaPanel.resetProgress();
162                         try {
163                             Connection JavaDoc conn = cinfo.getConnection();
164                             if (conn != null && !conn.isClosed())
165                                 conn.close();
166                         } catch (SQLException JavaDoc exc) {
167                             //unable to close the connection
168
}
169
170                     }
171                 }
172             };
173             basePanel.addPropertyChangeListener(argumentListener);
174
175             final PropertyChangeListener JavaDoc connectionListener = new PropertyChangeListener JavaDoc() {
176                 public void propertyChange(PropertyChangeEvent JavaDoc event) {
177                     if (event.getPropertyName().equals("connecting")) { // NOI18N
178
fireConnectionStarted();
179                     }
180                     if (event.getPropertyName().equals("failed")) { // NOI18N
181
fireConnectionFailed();
182                     }
183                     if (event.getPropertyName().equals("connected")) { //NOI18N
184
if (retrieveSchemas(schemaPanel, cinfo, cinfo.getUser()))
185                             cinfo.setSchema(schemaPanel.getSchema());
186                         else {
187                             //switch to schema panel
188
fireConnectionFinished();
189                             dlg.setSelectedComponent(schemaPanel);
190                             return;
191                         }
192                         
193                         fireConnectionFinished();
194
195                         //connected by "Get Schemas" button in the schema panel => don't create connection node
196
//and don't close the connect dialog
197
if (advancedPanel && !okPressed)
198                             return;
199
200                         try {
201                             ((RootNodeInfo)RootNode.getInstance().getInfo()).addConnection(cinfo);
202                         } catch (DatabaseException exc) {
203                             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, exc);
204                             String JavaDoc message = MessageFormat.format(bundle().getString("ERR_UnableToAddConnection"), new String JavaDoc[] {exc.getMessage()}); //NOI18N
205
DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(message, NotifyDescriptor.ERROR_MESSAGE));
206                             try {
207                                 cinfo.getConnection().close();
208                             } catch (SQLException JavaDoc e) {
209                                 //unable to close db connection
210
}
211                             return;
212                         }
213
214                         if(dlg != null) {
215                             dlg.close();
216 // removeListeners(cinfo);
217
}
218                     } else
219                         okPressed = false;
220                 }
221             };
222
223             final ExceptionListener excListener = new ExceptionListener() {
224                 public void exceptionOccurred(Exception JavaDoc exc) {
225                     if (exc instanceof DDLException) {
226                         ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, exc.getCause());
227                     } else {
228                         ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, exc);
229                     }
230                     
231                     String JavaDoc message = null;
232                     if (exc instanceof ClassNotFoundException JavaDoc) {
233                         message = MessageFormat.format(bundle().getString("EXC_ClassNotFound"), new String JavaDoc[] {exc.getMessage()}); //NOI18N
234
} else {
235                         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
236                         buffer.append(MessageFormat.format(bundle().getString("ERR_UnableToAddConnection"), new String JavaDoc[] {exc.getMessage()})); //NOI18N
237
if (exc instanceof DDLException && exc.getCause() instanceof SQLException JavaDoc) {
238                             SQLException JavaDoc sqlEx = ((SQLException JavaDoc)exc.getCause()).getNextException();
239                             while (sqlEx != null) {
240                                 buffer.append("\n\n" + sqlEx.getMessage()); // NOI18N
241
sqlEx = sqlEx.getNextException();
242                             }
243                         }
244                         message = buffer.toString();
245                     }
246                     DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(message, NotifyDescriptor.ERROR_MESSAGE));
247                 }
248             };
249
250             cinfo.addPropertyChangeListener(connectionListener);
251             cinfo.addExceptionListener(excListener);
252
253             ActionListener JavaDoc actionListener = new ActionListener JavaDoc() {
254                 public void actionPerformed(ActionEvent JavaDoc event) {
255                     if (event.getSource() == DialogDescriptor.OK_OPTION) {
256                         okPressed = true;
257                         basePanel.setConnectionInfo();
258                         try {
259                             if (cinfo.getConnection() == null || cinfo.getConnection().isClosed())
260                                 cinfo.connect();
261                             else {
262                                 cinfo.setSchema(schemaPanel.getSchema());
263                                 ((RootNodeInfo)RootNode.getInstance().getInfo()).addConnection(cinfo);
264                                 if(dlg != null)
265                                     dlg.close();
266                             }
267                         } catch (SQLException JavaDoc exc) {
268                             //isClosed() method failed, try to connect
269
cinfo.connect();
270                         } catch (DatabaseException exc) {
271                             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, exc);
272                             String JavaDoc message = MessageFormat.format(bundle().getString("ERR_UnableToAddConnection"), new String JavaDoc[] {exc.getMessage()}); //NOI18N
273
DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(message, NotifyDescriptor.ERROR_MESSAGE));
274                             try {
275                                 cinfo.getConnection().close();
276                                 cinfo.setConnection(null);
277                             } catch (SQLException JavaDoc e) {
278                                 //unable to close db connection
279
cinfo.setConnection(null);
280                             } finally {
281                             }
282                         }
283                         return;
284                     }
285                 }
286             };
287
288             ChangeListener JavaDoc changeTabListener = new ChangeListener JavaDoc() {
289                 public void stateChanged (ChangeEvent JavaDoc e) {
290                     if (((JTabbedPane JavaDoc) e.getSource()).getSelectedComponent().equals(schemaPanel)) {
291                         advancedPanel = true;
292                         basePanel.setConnectionInfo();
293                     } else
294                         advancedPanel = false;
295                 }
296             };
297
298             dlg = new ConnectionDialog(this, basePanel, schemaPanel, basePanel.getTitle(), actionListener, changeTabListener);
299             dlg.setVisible(true);
300             
301             return ConnectionList.getDefault().getConnection(cinfo);
302         }
303
304 // private void removeListeners() {
305
// cinfo.removePropertyChangeListener(connectionListener);
306
// cinfo.removeExceptionListener(excListener);
307
// }
308

309         protected boolean retrieveSchemas(SchemaPanel schemaPanel, DatabaseConnection dbcon, String JavaDoc defaultSchema) {
310             fireConnectionStep(bundle().getString("ConnectionProgress_Schemas")); // NOI18N
311
Vector JavaDoc schemas = new Vector JavaDoc();
312             try {
313                 ResultSet JavaDoc rs = dbcon.getConnection().getMetaData().getSchemas();
314                 if (rs != null)
315                     while (rs.next()) {
316                         schemas.add(rs.getString(1).trim());
317                     }
318             } catch (SQLException JavaDoc exc) {
319 //commented out for 3.6 release, need to solve for next Studio release
320
// hack for Pointbase Network Server
321
// if (dbcon.getDriver().equals(PointbasePlus.DRIVER))
322
// if (exc.getErrorCode() == PointbasePlus.ERR_SERVER_REJECTED) {
323
String JavaDoc message = MessageFormat.format(bundle().getString("ERR_UnableObtainSchemas"), new String JavaDoc[] {exc.getMessage()}); // NOI18N
324
// message = MessageFormat.format(bundle().getString("EXC_PointbaseServerRejected"), new String[] {message, dbcon.getDatabase()}); // NOI18N
325
DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(message, NotifyDescriptor.ERROR_MESSAGE));
326 // schema will be set to null
327
// return true;
328
// }
329
}
330
331             return schemaPanel.setSchemas(schemas, defaultSchema);
332         }
333     }
334 }
335
Popular Tags