001: /*
002: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
003: *
004: * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
005: *
006: * The contents of this file are subject to the terms of either the GNU
007: * General Public License Version 2 only ("GPL") or the Common
008: * Development and Distribution License("CDDL") (collectively, the
009: * "License"). You may not use this file except in compliance with the
010: * License. You can obtain a copy of the License at
011: * http://www.netbeans.org/cddl-gplv2.html
012: * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
013: * specific language governing permissions and limitations under the
014: * License. When distributing the software, include this License Header
015: * Notice in each file and include the License file at
016: * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
017: * particular file as subject to the "Classpath" exception as provided
018: * by Sun in the GPL Version 2 section of the License file that
019: * accompanied this code. If applicable, add the following below the
020: * License Header, with the fields enclosed by brackets [] replaced by
021: * your own identifying information:
022: * "Portions Copyrighted [year] [name of copyright owner]"
023: *
024: * Contributor(s):
025: *
026: * The Original Software is NetBeans. The Initial Developer of the Original
027: * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
028: * Microsystems, Inc. All Rights Reserved.
029: *
030: * If you wish your version of this file to be governed by only the CDDL
031: * or only the GPL Version 2, indicate your decision by adding
032: * "[Contributor] elects to include this software in this distribution
033: * under the [CDDL or GPL Version 2] license." If you do not indicate a
034: * single choice of license, a recipient has the option to distribute
035: * your version of this file under either the CDDL, the GPL Version 2 or
036: * to extend the choice of license to its licensees as provided above.
037: * However, if you add GPL Version 2 code and therefore, elected the GPL
038: * Version 2 license, then the option applies only if the new code is
039: * made subject to such option by the copyright holder.
040: */
041:
042: package org.netbeans.modules.dbschema.jdbcimpl.wizard;
043:
044: import java.beans.*;
045: import java.sql.SQLException;
046: import java.text.MessageFormat;
047: import java.util.*;
048: import java.util.logging.Level;
049: import java.util.logging.Logger;
050: import org.netbeans.api.db.explorer.ConnectionManager;
051: import org.netbeans.api.db.explorer.DatabaseConnection;
052:
053: import org.openide.awt.StatusDisplayer;
054: import org.openide.filesystems.*;
055: import org.openide.nodes.Node;
056: import org.openide.util.NbBundle;
057: import org.openide.util.RequestProcessor;
058:
059: import org.netbeans.modules.dbschema.*;
060: import org.netbeans.modules.dbschema.jdbcimpl.*;
061: import org.openide.util.Exceptions;
062:
063: public class RecaptureSchema {
064:
065: private static final boolean debug = Boolean
066: .getBoolean("org.netbeans.modules.dbschema.recapture.debug");
067:
068: ResourceBundle bundle = NbBundle
069: .getBundle("org.netbeans.modules.dbschema.jdbcimpl.resources.Bundle"); //NOI18N
070:
071: private DBSchemaWizardData data;
072: private Node dbSchemaNode;
073:
074: public RecaptureSchema(Node dbSchemaNode) {
075: this .dbSchemaNode = dbSchemaNode;
076: data = new DBSchemaWizardData();
077: data.setExistingConn(true);
078: }
079:
080: public void start() throws ClassNotFoundException, SQLException {
081: final DBschemaDataObject dobj = (DBschemaDataObject) dbSchemaNode
082: .getCookie(DBschemaDataObject.class);
083: final SchemaElement elem = dobj.getSchema();
084: //elem.
085: //ConnectionProvider cp = new ConnectionProvider(elem.getDriver(), elem.getUrl(), elem.getUsername(), null);
086: if (debug) {
087: System.out
088: .println("[dbschema] url='" + elem.getUrl() + "'");
089: }
090: final FileObject fo1 = dobj.getPrimaryFile();
091: try {
092: SchemaElement.removeFromCache(elem.getName().getFullName()
093: + "#" + fo1.getURL().toString()); //NOI18N
094: } catch (FileStateInvalidException ex) {
095: Logger.getLogger("global").log(Level.INFO, null, ex);
096: }
097:
098: TableElement tableAndViewElements[] = elem.getTables();
099: // now break down to tables and views
100: final LinkedList tables = new LinkedList();
101: final LinkedList views = new LinkedList();
102: for (int i = 0; i < tableAndViewElements.length; i++) {
103: TableElement te = tableAndViewElements[i];
104: if (te.isTable()) {
105: if (debug) {
106: System.out.println("[dbschema] adding table='"
107: + te.getName() + "'");
108: }
109: tables.add(te.getName().getName());
110: } else {
111: if (debug) {
112: System.out.println("[dbschema] adding view='"
113: + te.getName() + "'");
114: }
115: views.add(te.getName().getName());
116: }
117: }
118:
119: final boolean conned = data.isConnected();
120: final boolean ec = data.isExistingConn();
121: final DatabaseConnection dbconn = data.getDatabaseConnection();
122: // final String target1 = target;
123: final String dbIdentName = elem.getUrl();
124: //dbconn.getName();
125: if (debug) {
126: System.out.println("[dbschema] conned='" + conned + "'");
127: System.out.println("[dbschema] ec='" + ec + "'");
128: System.out.println("[dbschema] NEW dbIdentName='"
129: + dbIdentName + "'");
130: }
131: final ConnectionProvider cp = createConnectionProvider(data,
132: elem.getUrl());
133: try {
134: final ConnectionProvider c = cp;
135: if (c == null) {
136: throw new SQLException(bundle
137: .getString("EXC_ConnectionNotEstablished"));
138: }
139: if (debug) {
140: System.out.println("[dbschema] c.getConnection()='"
141: + c.getConnection() + "'");
142: }
143:
144: RequestProcessor.getDefault().post(new Runnable() {
145: public void run() {
146: try {
147: StatusDisplayer
148: .getDefault()
149: .setStatusText(
150: bundle
151: .getString("CreatingDatabaseSchema")); //NOI18N
152:
153: final ProgressFrame pf = new ProgressFrame();
154: final SchemaElementImpl sei = new SchemaElementImpl(
155: c);
156:
157: PropertyChangeListener listener = new PropertyChangeListener() {
158: public void propertyChange(
159: PropertyChangeEvent event) {
160: String message;
161:
162: if (event.getPropertyName().equals(
163: "totalCount")) { //NOI18N
164: pf.setMaximum(((Integer) event
165: .getNewValue()).intValue());
166: return;
167: }
168:
169: if (event.getPropertyName().equals(
170: "progress")) { //NOI18N
171: pf.setValue(((Integer) event
172: .getNewValue()).intValue());
173: return;
174: }
175:
176: if (event.getPropertyName().equals(
177: "tableName")) { //NOI18N
178: message = MessageFormat
179: .format(
180: bundle
181: .getString("CapturingTable"),
182: new String[] { ((String) event
183: .getNewValue())
184: .toUpperCase() }); //NOI18N
185: pf.setMessage(message);
186: return;
187: }
188:
189: if (event.getPropertyName().equals(
190: "FKt")) { //NOI18N
191: message = MessageFormat
192: .format(
193: bundle
194: .getString("CaptureFK"),
195: new String[] {
196: ((String) event
197: .getNewValue())
198: .toUpperCase(),
199: bundle
200: .getString("CaptureFKtable") }); //NOI18N
201: pf.setMessage(message);
202: return;
203: }
204:
205: if (event.getPropertyName().equals(
206: "FKv")) { //NOI18N
207: message = MessageFormat
208: .format(
209: bundle
210: .getString("CaptureFK"),
211: new String[] {
212: ((String) event
213: .getNewValue())
214: .toUpperCase(),
215: bundle
216: .getString("CaptureFKview") }); //NOI18N
217: pf.setMessage(message);
218: return;
219: }
220:
221: if (event.getPropertyName().equals(
222: "viewName")) { //NOI18N
223: message = MessageFormat
224: .format(
225: bundle
226: .getString("CapturingView"),
227: new String[] { ((String) event
228: .getNewValue())
229: .toUpperCase() }); //NOI18N
230: pf.setMessage(message);
231: return;
232: }
233:
234: if (event.getPropertyName().equals(
235: "cancel")) { //NOI18N
236: sei.setStop(true);
237: StatusDisplayer.getDefault()
238: .setStatusText(""); //NOI18N
239: return;
240: }
241: }
242: };
243:
244: pf.propertySupport
245: .addPropertyChangeListener(listener);
246: pf.setVisible(true);
247:
248: sei.propertySupport
249: .addPropertyChangeListener(listener);
250: final SchemaElement se = new SchemaElement(sei);
251: //se.setName(DBIdentifier.create(dbIdentName));
252: se.setName(elem.getName());
253:
254: sei.initTables(c, tables, views, false);
255: pf.finishProgress();
256:
257: if (!sei.isStop()) {
258: fo1.getFileSystem().runAtomicAction(
259: new FileSystem.AtomicAction() {
260: public void run()
261: throws java.io.IOException {
262: //FileObject fo1 = fo.createData(target1, "dbschema"); //NOI18N
263: if (debug) {
264: System.out
265: .println("SchemaElement: "
266: + dumpSe(se));
267: }
268: FileLock fl = fo1.lock();
269: java.io.OutputStream out = fo1
270: .getOutputStream(fl);
271: if (out == null)
272: throw new java.io.IOException(
273: "Unable to open output stream");
274:
275: pf
276: .setMessage(bundle
277: .getString("SavingDatabaseSchema")); //NOI18N
278: StatusDisplayer
279: .getDefault()
280: .setStatusText(
281: bundle
282: .getString("SavingDatabaseSchema")); //NOI18N
283:
284: se.save(out);
285: fl.releaseLock();
286: }
287: });
288:
289: // refresh the node
290: SchemaElement.addToCache(se);
291: dobj.setSchemaElementImpl(sei);
292: dobj.setSchema(se);
293:
294: pf.setMessage(bundle
295: .getString("SchemaSaved")); //NOI18N
296: StatusDisplayer.getDefault().setStatusText(
297: bundle.getString("SchemaSaved")); //NOI18N
298:
299: pf.setVisible(false);
300: pf.dispose();
301: }
302:
303: //c.closeConnection();
304: if (conned)
305: if (ec)
306: ConnectionManager.getDefault()
307: .disconnect(dbconn);
308: else
309: c.closeConnection();
310: } catch (Exception exc) {
311: Exceptions.printStackTrace(exc);
312: }
313: }
314: }, 0);
315: } catch (Exception exc) {
316: String message = MessageFormat.format(bundle
317: .getString("UnableToCreateSchema"),
318: new String[] { exc.getMessage() }); //NOI18N
319: StatusDisplayer.getDefault().setStatusText(message);
320: if (debug) {
321: Logger.getLogger("global").log(Level.INFO, null, exc);
322: }
323:
324: try {
325: if (cp != null)
326: cp.closeConnection();
327: if (data.isConnected())
328: if (data.isExistingConn())
329: ConnectionManager.getDefault().disconnect(
330: data.getDatabaseConnection());
331: else
332: cp.closeConnection();
333: } catch (Exception exc1) {
334: //unable to disconnect
335: }
336: }
337: }
338:
339: private String dumpSe(SchemaElement se) {
340: StringBuffer s = new StringBuffer();
341: s.append("name " + se.getName());
342: s.append("\n");
343: s.append("driver " + se.getDriverName());
344: s.append("\n");
345: s.append("username " + se.getUsername());
346: s.append("\n");
347: TableElement tables[] = se.getTables();
348: s.append("tables count " + tables.length);
349: s.append("\n");
350: for (int i = 0; i < tables.length; i++) {
351: s.append(" table " + tables[i].getName());
352: s.append("\n");
353: ColumnElement columns[] = tables[i].getColumns();
354: for (int j = 0; j < columns.length; j++) {
355: s.append(" column " + columns[j].getName());
356: s.append("\n");
357: }
358: }
359: return s.toString();
360: }
361:
362: public ConnectionProvider createConnectionProvider(
363: DBSchemaWizardData data, String url) throws SQLException {
364:
365: DatabaseConnection dbconn = findDatabaseConnection(url);
366: if (dbconn == null) {
367: if (debug) {
368: System.out.println("[dbschema-ccp] not found dbconn='"
369: + dbconn + "'");
370: }
371: return null;
372: }
373: if (debug) {
374: System.out.println("[dbschema-ccp] found dbconn='"
375: + dbconn.getDatabaseURL() + "'");
376: }
377: data.setDatabaseConnection(dbconn);
378: ConnectionHandler ch = new ConnectionHandler(data);
379: if (ch.ensureConnection()) {
380: dbconn = data.getDatabaseConnection();
381: if (debug) {
382: System.out
383: .println("[dbschema-ccp] connection ensured ='"
384: + dbconn.getDatabaseURL() + "'");
385: }
386: ConnectionProvider connectionProvider = new ConnectionProvider(
387: dbconn.getJDBCConnection(), dbconn.getDriverClass());
388: connectionProvider.setSchema(dbconn.getSchema());
389: //String schemaName = cni.getName();
390: //schemaElementImpl.setName(DBIdentifier.create(schemaName));
391: return connectionProvider;
392: }
393: if (debug) {
394: System.out
395: .println("[dbschema-ccp] connection not ensured, returning null");
396: }
397: return null;
398: }
399:
400: private DatabaseConnection findDatabaseConnection(String url) {
401: DatabaseConnection dbconns[] = ConnectionManager.getDefault()
402: .getConnections();
403: for (int i = 0; i < dbconns.length; i++) {
404: if (url.equals(dbconns[i].getDatabaseURL())) {
405: return dbconns[i];
406: }
407: }
408: return null;
409: }
410:
411: private static class ConnectionHandler extends DBSchemaTablesPanel {
412: public ConnectionHandler(DBSchemaWizardData data) {
413: super (data, new ArrayList());
414: }
415:
416: public boolean ensureConnection() {
417: return init();
418: }
419: }
420:
421: }
|