KickJava   Java API By Example, From Geeks To Geeks.

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


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.Dialog JavaDoc;
23 import java.awt.Dimension JavaDoc;
24 import java.awt.event.ActionEvent JavaDoc;
25 import java.awt.event.ActionListener JavaDoc;
26 import java.beans.PropertyChangeEvent JavaDoc;
27 import java.beans.PropertyChangeListener JavaDoc;
28 import java.sql.ResultSet JavaDoc;
29 import java.sql.SQLException JavaDoc;
30 import java.sql.Connection JavaDoc;
31 import java.text.MessageFormat JavaDoc;
32 import java.util.Vector JavaDoc;
33 import javax.swing.JComponent JavaDoc;
34
35 import javax.swing.JTabbedPane JavaDoc;
36 import javax.swing.event.ChangeEvent JavaDoc;
37 import javax.swing.event.ChangeListener JavaDoc;
38 import org.netbeans.api.progress.ProgressHandle;
39 import org.netbeans.api.progress.ProgressHandleFactory;
40 import org.netbeans.modules.db.explorer.ConnectionList;
41
42 import org.openide.DialogDescriptor;
43 import org.openide.DialogDisplayer;
44 import org.openide.NotifyDescriptor;
45 import org.openide.ErrorManager;
46 import org.openide.nodes.Node;
47
48 import org.netbeans.api.db.explorer.DatabaseException;
49 import org.netbeans.lib.ddl.DDLException;
50 import org.netbeans.modules.db.ExceptionListener;
51 import org.netbeans.modules.db.explorer.DatabaseConnection;
52
53 //commented out for 3.6 release, need to solve for next Studio release
54
//import org.netbeans.modules.db.explorer.PointbasePlus;
55

56 import org.netbeans.modules.db.explorer.dlg.ConnectionDialog;
57 import org.netbeans.modules.db.explorer.dlg.ConnectPanel;
58 import org.netbeans.modules.db.explorer.dlg.ConnectProgressDialog;
59 import org.netbeans.modules.db.explorer.dlg.ConnectionDialogMediator;
60 import org.netbeans.modules.db.explorer.dlg.SchemaPanel;
61 import org.netbeans.modules.db.explorer.infos.ConnectionNodeInfo;
62 import org.netbeans.modules.db.explorer.infos.DatabaseNodeInfo;
63 import org.netbeans.modules.db.explorer.nodes.DatabaseNode;
64
65 public class ConnectAction extends DatabaseAction {
66     static final long serialVersionUID =-6822218300035053411L;
67
68     ConnectionDialog dlg;
69     boolean advancedPanel = false;
70     boolean okPressed = false;
71
72     protected boolean enable(Node[] activatedNodes) {
73         Node node;
74         if (activatedNodes != null && activatedNodes.length == 1)
75             node = activatedNodes[0];
76         else
77             return false;
78
79         DatabaseNodeInfo info = (DatabaseNodeInfo) node.getCookie(DatabaseNodeInfo.class);
80         if (info != null) {
81             DatabaseNodeInfo nfo = info.getParent(DatabaseNode.CONNECTION);
82             if (nfo != null)
83                 return (nfo.getConnection() == null);
84         }
85
86         return false;
87     }
88
89     protected int mode() {
90         return MODE_ALL;
91     }
92
93     public void performAction(Node[] activatedNodes) {
94         Node node = activatedNodes[0];
95         DatabaseNodeInfo info = (DatabaseNodeInfo) node.getCookie(DatabaseNodeInfo.class);
96         ConnectionNodeInfo nfo = (ConnectionNodeInfo) info.getParent(DatabaseNode.CONNECTION);
97         
98 //commented out for 3.6 release, need to solve for next Studio release
99
// if (PointbasePlus.DATABASE_URL.equals(nfo.getDatabase()) && PointbasePlus.DRIVER.equals(nfo.getDriver()) && PointbasePlus.USER_NAME.equals(nfo.getUser()))
100
// try {
101
// // add the connection (if needed) and connect to Pointbase SAMPLE database
102
// PointbasePlus.addOrConnectAccordingToOption();
103
// user = nfo.getUser();
104
// pwd = nfo.getPassword();
105
// rpwd = (Boolean) nfo.get(DatabaseNodeInfo.REMEMBER_PWD);
106
// remember = ((rpwd != null) ? rpwd.booleanValue() : false);
107
// } catch(Exception ex) {
108
// //ignore the exception and open connect dialog
109
//// org.openide.ErrorManager.getDefault().notify(org.openide.ErrorManager.INFORMATIONAL, ex);
110
// }
111

112         new ConnectionDialogDisplayer().showDialog(nfo, false);
113     }
114     
115     public static final class ConnectionDialogDisplayer extends ConnectionDialogMediator {
116         
117         ConnectionDialog dlg;
118         boolean advancedPanel = false;
119         boolean okPressed = false;
120         
121         public void showDialog(final ConnectionNodeInfo nfo, boolean showDialog) {
122             String JavaDoc user = nfo.getUser();
123             String JavaDoc pwd = nfo.getPassword();
124             Boolean JavaDoc rpwd = (Boolean JavaDoc) nfo.get(DatabaseNodeInfo.REMEMBER_PWD);
125             boolean remember = ((rpwd != null) ? rpwd.booleanValue() : false);
126             
127             final DatabaseConnection dbcon = (DatabaseConnection) nfo.getDatabaseConnection();
128
129             final ExceptionListener excListener = new ExceptionListener() {
130                 public void exceptionOccurred(Exception JavaDoc exc) {
131                     if (exc instanceof DDLException) {
132                         ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, exc.getCause());
133                     } else {
134                         ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, exc);
135                     }
136                     
137                     String JavaDoc message = null;
138                     if (exc instanceof ClassNotFoundException JavaDoc) {
139                         message = MessageFormat.format(bundle().getString("EXC_ClassNotFound"), new String JavaDoc[] {exc.getMessage()}); //NOI18N
140
} else {
141                         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
142                         buffer.append(MessageFormat.format(bundle().getString("ERR_UnableToConnect"), new String JavaDoc[] {exc.getMessage()})); //NOI18N
143
if (exc instanceof DDLException && exc.getCause() instanceof SQLException JavaDoc) {
144                             SQLException JavaDoc sqlEx = ((SQLException JavaDoc)exc.getCause()).getNextException();
145                             while (sqlEx != null) {
146                                 buffer.append("\n\n" + sqlEx.getMessage()); // NOI18N
147
sqlEx = sqlEx.getNextException();
148                             }
149                         }
150                         message = buffer.toString();
151                     }
152                     DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(message, NotifyDescriptor.ERROR_MESSAGE));
153                 }
154             };
155
156             dbcon.addExceptionListener(excListener);
157
158             if (user == null || pwd == null || !remember) {
159                 final ConnectPanel basePanel = new ConnectPanel(this, dbcon);
160                 final SchemaPanel schemaPanel = new SchemaPanel(this, dbcon);
161
162                 PropertyChangeListener JavaDoc argumentListener = new PropertyChangeListener JavaDoc() {
163                     public void propertyChange(PropertyChangeEvent JavaDoc event) {
164                         if (event.getPropertyName().equals("argumentChanged")) { //NOI18N
165
schemaPanel.setSchemas(new Vector JavaDoc(), ""); //NOI18N
166
schemaPanel.resetProgress();
167                             try {
168                                 Connection JavaDoc conn = dbcon.getConnection();
169                                 if (conn != null && !conn.isClosed())
170                                     conn.close();
171                             } catch (SQLException JavaDoc exc) {
172                                 //unable to close the connection
173
}
174                         }
175                     }
176                 };
177                 basePanel.addPropertyChangeListener(argumentListener);
178
179                 final PropertyChangeListener JavaDoc connectionListener = new PropertyChangeListener JavaDoc() {
180                         public void propertyChange(PropertyChangeEvent JavaDoc event) {
181                         if (event.getPropertyName().equals("connecting")) { // NOI18N
182
fireConnectionStarted();
183                         }
184                         if (event.getPropertyName().equals("failed")) { // NOI18N
185
fireConnectionFailed();
186                         }
187                         if (event.getPropertyName().equals("connected")) { //NOI18N
188
//connected by "Get Schemas" button in the schema panel => don't initialize the connection node,
189
//it will be done in actionListener
190
if (advancedPanel && !okPressed) {
191                                 // #67241: should not retrieve the schema list after connecting
192
// an existing connection, takes a long time on databases with a lot of schemas
193
// thus only retrieve the schema list when connected by the "Get schemas" button
194
if (retrieveSchemas(schemaPanel, dbcon, nfo.getSchema())) {
195                                     dbcon.setSchema(nfo.getSchema());
196                                 }
197                                 dlg.setSelectedComponent(schemaPanel);
198                                 fireConnectionFinished();
199                                 return;
200                             } else {
201                                 fireConnectionFinished();
202                                 dbcon.setSchema(nfo.getSchema());
203                             }
204                             
205                             try {
206                                 nfo.finishConnect(null, dbcon, dbcon.getConnection());
207                             } catch (DatabaseException exc) {
208                                 ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, exc);
209                                 String JavaDoc message = MessageFormat.format(bundle().getString("ERR_UnableToInitializeConnection"), new String JavaDoc[] {exc.getMessage()}); //NOI18N
210
DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(message, NotifyDescriptor.ERROR_MESSAGE));
211                                 return;
212                             }
213                             
214                             DatabaseConnection realDbcon = ConnectionList.getDefault().getConnection(dbcon);
215                             if (realDbcon != null) {
216                                 realDbcon.setPassword(dbcon.getPassword());
217                             }
218                             if (basePanel.rememberPassword()) {
219                                 nfo.put(DatabaseNodeInfo.REMEMBER_PWD, Boolean.TRUE);
220                             }
221
222                             if(dlg != null) {
223                                 dlg.close();
224     // removeListeners(cinfo);
225
}
226                         } else
227                             okPressed = false;
228                     }
229                 };
230
231                 dbcon.addPropertyChangeListener(connectionListener);
232
233                 ActionListener JavaDoc actionListener = new ActionListener JavaDoc() {
234                     public void actionPerformed(ActionEvent JavaDoc event) {
235                         if (event.getSource() == DialogDescriptor.OK_OPTION) {
236                             okPressed = true;
237                             nfo.setUser(basePanel.getUser());
238                             nfo.setPassword(basePanel.getPassword());
239                             dbcon.setUser(basePanel.getUser());
240                             dbcon.setPassword(basePanel.getPassword());
241
242                             try {
243                                 if (dbcon.getConnection() == null || dbcon.getConnection().isClosed())
244                                     dbcon.connect();
245                                 else {
246                                     dbcon.setSchema(schemaPanel.getSchema());
247                                     nfo.setSchema(schemaPanel.getSchema());
248
249                                     try {
250                                         nfo.finishConnect(null, dbcon, dbcon.getConnection());
251                                     } catch (DatabaseException exc) {
252                                         ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, exc);
253                                         String JavaDoc message = MessageFormat.format(bundle().getString("ERR_UnableToInitializeConnection"), new String JavaDoc[] {exc.getMessage()}); //NOI18N
254
DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(message, NotifyDescriptor.ERROR_MESSAGE));
255                                         return;
256                                     }
257                                     
258                                     DatabaseConnection realDbcon = ConnectionList.getDefault().getConnection(dbcon);
259                                     if (realDbcon != null) {
260                                         realDbcon.setPassword(dbcon.getPassword());
261                                     }
262                                     if (basePanel.rememberPassword()) {
263                                         nfo.put(DatabaseNodeInfo.REMEMBER_PWD, Boolean.TRUE);
264                                     }
265
266                                     if(dlg != null)
267                                         dlg.close();
268                                 }
269                             } catch (SQLException JavaDoc exc) {
270                                 //isClosed() method failed, try to connect
271
dbcon.connect();
272                             }
273                             return;
274                         }
275                     }
276                 };
277
278                 ChangeListener JavaDoc changeTabListener = new ChangeListener JavaDoc() {
279                     public void stateChanged (ChangeEvent JavaDoc e) {
280                         if (((JTabbedPane JavaDoc) e.getSource()).getSelectedComponent().equals(schemaPanel)) {
281                             advancedPanel = true;
282                             nfo.setUser(basePanel.getUser());
283                             nfo.setPassword(basePanel.getPassword());
284                             dbcon.setPassword(basePanel.getPassword());
285                         } else
286                             advancedPanel = false;
287                     }
288                 };
289
290                 dlg = new ConnectionDialog(this, basePanel, schemaPanel, basePanel.getTitle(), actionListener, changeTabListener);
291                 dlg.setVisible(true);
292             } else // without dialog with connection data (username, password), just with progress dlg based on the showDialog parameter
293
try {
294                     DialogDescriptor descriptor = null;
295                     ProgressHandle progress = null;
296                     
297                     if (showDialog) {
298                         progress = ProgressHandleFactory.createHandle("handle");
299                         JComponent JavaDoc progressComponent = ProgressHandleFactory.createProgressComponent(progress);
300                         progressComponent.setPreferredSize(new Dimension JavaDoc(250, 20));
301                         ConnectProgressDialog panel = new ConnectProgressDialog();
302                         panel.add(progressComponent);
303                         descriptor = new DialogDescriptor(panel, bundle().getString("ConnectDialogTitle"), true, new Object JavaDoc[] { DialogDescriptor.CANCEL_OPTION },
304                                 DialogDescriptor.CANCEL_OPTION, DialogDescriptor.DEFAULT_ALIGN, null, null);
305                     }
306                     final Dialog JavaDoc dialog = showDialog ? DialogDisplayer.getDefault().createDialog(descriptor) : null;
307                     
308                     final PropertyChangeListener JavaDoc connectionListener = new PropertyChangeListener JavaDoc() {
309                         public void propertyChange(PropertyChangeEvent JavaDoc event) {
310                             if (event.getPropertyName().equals("connected")) { //NOI18N
311
try {
312                                     nfo.finishConnect(null, dbcon, dbcon.getConnection());
313                                     if (dialog != null) {
314                                         dialog.setVisible(false);
315                                     }
316                                 } catch (DatabaseException exc) {
317                                     ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, exc);
318                                     String JavaDoc message = MessageFormat.format(bundle().getString("ERR_UnableToInitializeConnection"), new String JavaDoc[] {exc.getMessage()}); //NOI18N
319
DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(message, NotifyDescriptor.ERROR_MESSAGE));
320                                     return;
321                                 }
322                             } else if (event.getPropertyName().equals("failed")) { // NOI18N
323
if (dialog != null) {
324                                     dialog.setVisible(false);
325                                 }
326                             }
327                         }
328                     };
329                     
330                     dbcon.addPropertyChangeListener(connectionListener);
331                     dbcon.connect();
332                     
333                     if (showDialog) {
334                         progress.start();
335                         progress.switchToIndeterminate();
336                         dialog.setVisible(true);
337                         progress.finish();
338                         dialog.dispose();
339                     }
340                 } catch (Exception JavaDoc exc) {
341                     String JavaDoc message = MessageFormat.format(bundle().getString("ERR_UnableToConnect"), new String JavaDoc[] {exc.getMessage()}); // NOI18N
342
DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(message, NotifyDescriptor.ERROR_MESSAGE));
343                 }
344         }
345
346         protected boolean retrieveSchemas(SchemaPanel schemaPanel, DatabaseConnection dbcon, String JavaDoc defaultSchema) {
347             fireConnectionStep(bundle().getString("ConnectionProgress_Schemas")); // NOI18N
348
Vector JavaDoc schemas = new Vector JavaDoc();
349             try {
350                 ResultSet JavaDoc rs = dbcon.getConnection().getMetaData().getSchemas();
351                 if (rs != null)
352                     while (rs.next())
353                         schemas.add(rs.getString(1).trim());
354             } catch (SQLException JavaDoc exc) {
355 //commented out for 3.6 release, need to solve for next Studio release
356
// hack for Pointbase Network Server
357
// if (dbcon.getDriver().equals(PointbasePlus.DRIVER))
358
// if (exc.getErrorCode() == PointbasePlus.ERR_SERVER_REJECTED) {
359
String JavaDoc message = MessageFormat.format(bundle().getString("ERR_UnableObtainSchemas"), new String JavaDoc[] {exc.getMessage()}); // NOI18N
360
// message = MessageFormat.format(bundle().getString("EXC_PointbaseServerRejected"), new String[] {message, dbcon.getDatabase()}); // NOI18N
361
DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(message, NotifyDescriptor.ERROR_MESSAGE));
362 // schema will be set to null
363
// return true;
364
// }
365
}
366
367             return schemaPanel.setSchemas(schemas, defaultSchema);
368         }
369     }
370 }
371
Popular Tags