KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > dbschema > jdbcimpl > wizard > RecaptureSchema


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.dbschema.jdbcimpl.wizard;
21
22 import java.beans.*;
23 import java.sql.SQLException JavaDoc;
24 import java.text.MessageFormat JavaDoc;
25 import java.util.*;
26 import org.netbeans.api.db.explorer.ConnectionManager;
27 import org.netbeans.api.db.explorer.DatabaseConnection;
28
29 import org.openide.ErrorManager;
30 import org.openide.awt.StatusDisplayer;
31 import org.openide.filesystems.*;
32 import org.openide.nodes.Node;
33 import org.openide.util.NbBundle;
34 import org.openide.util.RequestProcessor;
35
36 import org.netbeans.modules.dbschema.*;
37 import org.netbeans.modules.dbschema.jdbcimpl.*;
38
39 public class RecaptureSchema {
40     
41     private static final boolean debug = Boolean.getBoolean("org.netbeans.modules.dbschema.recapture.debug");
42
43     ResourceBundle bundle = NbBundle.getBundle("org.netbeans.modules.dbschema.jdbcimpl.resources.Bundle"); //NOI18N
44

45     private DBSchemaWizardData data;
46     private Node dbSchemaNode;
47     
48
49     public RecaptureSchema(Node dbSchemaNode) {
50         this.dbSchemaNode = dbSchemaNode;
51         data = new DBSchemaWizardData();
52         data.setExistingConn(true);
53     }
54
55     public void start() throws ClassNotFoundException JavaDoc, SQLException JavaDoc {
56         final DBschemaDataObject dobj = (DBschemaDataObject)dbSchemaNode.getCookie(DBschemaDataObject.class);
57         final SchemaElement elem = dobj.getSchema();
58         //elem.
59
//ConnectionProvider cp = new ConnectionProvider(elem.getDriver(), elem.getUrl(), elem.getUsername(), null);
60
if (debug) {
61             System.out.println("[dbschema] url='" + elem.getUrl() + "'");
62         }
63         final FileObject fo1 = dobj.getPrimaryFile();
64         try {
65             SchemaElement.removeFromCache(elem.getName().getFullName() + "#" + fo1.getURL().toString()); //NOI18N
66
} catch (FileStateInvalidException ex) {
67             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
68         }
69         
70         TableElement tableAndViewElements[] = elem.getTables();
71         // now break down to tables and views
72
final LinkedList tables = new LinkedList();
73         final LinkedList views = new LinkedList();
74         for (int i = 0; i < tableAndViewElements.length; i++) {
75             TableElement te = tableAndViewElements[i];
76             if (te.isTable()) {
77                 if (debug) {
78                     System.out.println("[dbschema] adding table='" + te.getName() + "'");
79                 }
80                 tables.add(te.getName().getName());
81             }
82             else {
83                 if (debug) {
84                     System.out.println("[dbschema] adding view='" + te.getName() + "'");
85                 }
86                 views.add(te.getName().getName());
87             }
88         }
89         
90         final boolean conned = data.isConnected();
91         final boolean ec = data.isExistingConn();
92         final DatabaseConnection dbconn = data.getDatabaseConnection();
93 // final String target1 = target;
94
final String JavaDoc dbIdentName = elem.getUrl();
95             //dbconn.getName();
96
if (debug) {
97             System.out.println("[dbschema] conned='" + conned+ "'");
98             System.out.println("[dbschema] ec='" + ec + "'");
99             System.out.println("[dbschema] NEW dbIdentName='" + dbIdentName + "'");
100         }
101         final ConnectionProvider cp = createConnectionProvider(data, elem.getUrl());
102         try {
103             final ConnectionProvider c = cp;
104             if (c == null) {
105                 throw new SQLException JavaDoc(bundle.getString("EXC_ConnectionNotEstablished"));
106             }
107             if (debug) {
108                 System.out.println("[dbschema] c.getConnection()='" + c.getConnection() + "'");
109             }
110             
111             RequestProcessor.getDefault().post(new Runnable JavaDoc() {
112                 public void run () {
113                     try {
114                         StatusDisplayer.getDefault().setStatusText(bundle.getString("CreatingDatabaseSchema")); //NOI18N
115

116                         final ProgressFrame pf = new ProgressFrame();
117                         final SchemaElementImpl sei = new SchemaElementImpl(c);
118                         
119                         PropertyChangeListener listener = new PropertyChangeListener() {
120                             public void propertyChange(PropertyChangeEvent event) {
121                                 String JavaDoc message;
122                                 
123                                 if (event.getPropertyName().equals("totalCount")) { //NOI18N
124
pf.setMaximum(((Integer JavaDoc)event.getNewValue()).intValue());
125                                     return;
126                                 }
127
128                                 if (event.getPropertyName().equals("progress")) { //NOI18N
129
pf.setValue(((Integer JavaDoc)event.getNewValue()).intValue());
130                                     return;
131                                 }
132                                 
133                                 if (event.getPropertyName().equals("tableName")) { //NOI18N
134
message = MessageFormat.format(bundle.getString("CapturingTable"), new String JavaDoc[] {((String JavaDoc) event.getNewValue()).toUpperCase()}); //NOI18N
135
pf.setMessage(message);
136                                     return;
137                                 }
138                                 
139                                 if (event.getPropertyName().equals("FKt")) { //NOI18N
140
message = MessageFormat.format(bundle.getString("CaptureFK"), new String JavaDoc[] {((String JavaDoc) event.getNewValue()).toUpperCase(), bundle.getString("CaptureFKtable")}); //NOI18N
141
pf.setMessage(message);
142                                     return;
143                                 }
144                                 
145                                 if (event.getPropertyName().equals("FKv")) { //NOI18N
146
message = MessageFormat.format(bundle.getString("CaptureFK"), new String JavaDoc[] {((String JavaDoc) event.getNewValue()).toUpperCase(), bundle.getString("CaptureFKview")}); //NOI18N
147
pf.setMessage(message);
148                                     return;
149                                 }
150                                 
151                                 if (event.getPropertyName().equals("viewName")) { //NOI18N
152
message = MessageFormat.format(bundle.getString("CapturingView"), new String JavaDoc[] {((String JavaDoc) event.getNewValue()).toUpperCase()}); //NOI18N
153
pf.setMessage(message);
154                                     return;
155                                 }
156                                 
157                                 if (event.getPropertyName().equals("cancel")) { //NOI18N
158
sei.setStop(true);
159                                     StatusDisplayer.getDefault().setStatusText(""); //NOI18N
160
return;
161                                 }
162                             }
163                         };
164                         
165                         pf.propertySupport.addPropertyChangeListener(listener);
166                         pf.setVisible(true);
167                         
168                         sei.propertySupport.addPropertyChangeListener(listener);
169                         final SchemaElement se = new SchemaElement(sei);
170                         //se.setName(DBIdentifier.create(dbIdentName));
171
se.setName(elem.getName());
172                         
173                         sei.initTables(c, tables, views, false);
174                         pf.finishProgress();
175
176                         if (! sei.isStop()) {
177                             fo1.getFileSystem().runAtomicAction(new FileSystem.AtomicAction() {
178                                 public void run() throws java.io.IOException JavaDoc {
179                                     //FileObject fo1 = fo.createData(target1, "dbschema"); //NOI18N
180
if (debug) {
181                                         System.out.println("SchemaElement: " + dumpSe(se));
182                                     }
183                                     FileLock fl = fo1.lock();
184                                     java.io.OutputStream JavaDoc out = fo1.getOutputStream(fl);
185                                     if (out == null)
186                                         throw new java.io.IOException JavaDoc("Unable to open output stream");
187
188                                     pf.setMessage(bundle.getString("SavingDatabaseSchema")); //NOI18N
189
StatusDisplayer.getDefault().setStatusText(bundle.getString("SavingDatabaseSchema")); //NOI18N
190

191                                     se.save(out);
192                                     fl.releaseLock();
193                                 }
194                             });
195                             
196                             // refresh the node
197
SchemaElement.addToCache(se);
198                             dobj.setSchemaElementImpl(sei);
199                             dobj.setSchema(se);
200
201                             pf.setMessage(bundle.getString("SchemaSaved")); //NOI18N
202
StatusDisplayer.getDefault().setStatusText(bundle.getString("SchemaSaved")); //NOI18N
203

204                             pf.setVisible(false);
205                             pf.dispose();
206                         }
207                         
208                         //c.closeConnection();
209
if (conned)
210                             if (ec)
211                                 ConnectionManager.getDefault().disconnect(dbconn);
212                             else
213                                 c.closeConnection();
214                     } catch (Exception JavaDoc exc) {
215                         ErrorManager.getDefault().notify(exc);
216                     }
217                 }
218             }, 0);
219         } catch (Exception JavaDoc exc) {
220             String JavaDoc message = MessageFormat.format(bundle.getString("UnableToCreateSchema"), new String JavaDoc[] {exc.getMessage()}); //NOI18N
221
StatusDisplayer.getDefault().setStatusText(message);
222             if (debug) {
223                 ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, exc);
224             }
225             
226             try {
227                 if (cp != null)
228                     cp.closeConnection();
229                     if (data.isConnected())
230                         if (data.isExistingConn())
231                             ConnectionManager.getDefault().disconnect(data.getDatabaseConnection());
232                         else
233                             cp.closeConnection();
234             } catch (Exception JavaDoc exc1) {
235                 //unable to disconnect
236
}
237         }
238     }
239     
240     private String JavaDoc dumpSe(SchemaElement se) {
241         StringBuffer JavaDoc s = new StringBuffer JavaDoc();
242         s.append("name " + se.getName());
243         s.append("\n");
244         s.append("driver " + se.getDriverName());
245         s.append("\n");
246         s.append("username " + se.getUsername());
247         s.append("\n");
248         TableElement tables[] = se.getTables();
249         s.append("tables count " + tables.length);
250         s.append("\n");
251         for (int i = 0; i < tables.length; i++) {
252             s.append(" table " + tables[i].getName());
253             s.append("\n");
254             ColumnElement columns[] = tables[i].getColumns();
255             for (int j = 0; j < columns.length; j++) {
256                 s.append(" column " + columns[j].getName());
257                 s.append("\n");
258             }
259         }
260         return s.toString();
261     }
262     
263     public ConnectionProvider createConnectionProvider(DBSchemaWizardData data, String JavaDoc url) throws SQLException JavaDoc {
264         
265         DatabaseConnection dbconn = findDatabaseConnection(url);
266         if (dbconn == null) {
267             if (debug) {
268                 System.out.println("[dbschema-ccp] not found dbconn='" + dbconn + "'");
269             }
270             return null;
271         }
272         if (debug) {
273             System.out.println("[dbschema-ccp] found dbconn='" + dbconn.getDatabaseURL() + "'");
274         }
275         data.setDatabaseConnection(dbconn);
276         ConnectionHandler ch = new ConnectionHandler(data);
277         if (ch.ensureConnection()) {
278             dbconn = data.getDatabaseConnection();
279             if (debug) {
280                 System.out.println("[dbschema-ccp] connection ensured ='" + dbconn.getDatabaseURL() + "'");
281             }
282             ConnectionProvider connectionProvider =
283                 new ConnectionProvider(dbconn.getJDBCConnection(), dbconn.getDriverClass());
284             connectionProvider.setSchema(dbconn.getSchema());
285             //String schemaName = cni.getName();
286
//schemaElementImpl.setName(DBIdentifier.create(schemaName));
287
return connectionProvider;
288         }
289         if (debug) {
290             System.out.println("[dbschema-ccp] connection not ensured, returning null");
291         }
292         return null;
293     }
294     
295     private DatabaseConnection findDatabaseConnection(String JavaDoc url) {
296         DatabaseConnection dbconns[] = ConnectionManager.getDefault().getConnections();
297         for (int i = 0; i < dbconns.length; i++) {
298             if (url.equals(dbconns[i].getDatabaseURL())) {
299                 return dbconns[i];
300             }
301         }
302         return null;
303     }
304     
305     private static class ConnectionHandler extends DBSchemaTablesPanel {
306         public ConnectionHandler(DBSchemaWizardData data) {
307             super(data, new ArrayList());
308         }
309         
310         public boolean ensureConnection() {
311             return init();
312         }
313     }
314     
315 }
316
Popular Tags