KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectstyle > cayenne > modeler > dialog > db > DBGeneratorOptions


1 /* ====================================================================
2  *
3  * The ObjectStyle Group Software License, version 1.1
4  * ObjectStyle Group - http://objectstyle.org/
5  *
6  * Copyright (c) 2002-2005, Andrei (Andrus) Adamchik and individual authors
7  * of the software. All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  * notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  * notice, this list of conditions and the following disclaimer in
18  * the documentation and/or other materials provided with the
19  * distribution.
20  *
21  * 3. The end-user documentation included with the redistribution, if any,
22  * must include the following acknowlegement:
23  * "This product includes software developed by independent contributors
24  * and hosted on ObjectStyle Group web site (http://objectstyle.org/)."
25  * Alternately, this acknowlegement may appear in the software itself,
26  * if and wherever such third-party acknowlegements normally appear.
27  *
28  * 4. The names "ObjectStyle Group" and "Cayenne" must not be used to endorse
29  * or promote products derived from this software without prior written
30  * permission. For written permission, email
31  * "andrus at objectstyle dot org".
32  *
33  * 5. Products derived from this software may not be called "ObjectStyle"
34  * or "Cayenne", nor may "ObjectStyle" or "Cayenne" appear in their
35  * names without prior written permission.
36  *
37  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
38  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
39  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
40  * DISCLAIMED. IN NO EVENT SHALL THE OBJECTSTYLE GROUP OR
41  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
42  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
43  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
44  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
45  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
46  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
47  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
48  * SUCH DAMAGE.
49  * ====================================================================
50  *
51  * This software consists of voluntary contributions made by many
52  * individuals and hosted on ObjectStyle Group web site. For more
53  * information on the ObjectStyle Group, please see
54  * <http://objectstyle.org/>.
55  */

56 package org.objectstyle.cayenne.modeler.dialog.db;
57
58 import java.awt.Component JavaDoc;
59 import java.io.File JavaDoc;
60 import java.io.FileWriter JavaDoc;
61 import java.io.IOException JavaDoc;
62 import java.io.PrintWriter JavaDoc;
63 import java.util.Iterator JavaDoc;
64
65 import javax.sql.DataSource JavaDoc;
66 import javax.swing.JDialog JavaDoc;
67 import javax.swing.JFileChooser JavaDoc;
68 import javax.swing.JOptionPane JavaDoc;
69 import javax.swing.event.ChangeEvent JavaDoc;
70 import javax.swing.event.ChangeListener JavaDoc;
71
72 import org.objectstyle.cayenne.access.DbGenerator;
73 import org.objectstyle.cayenne.dba.DbAdapter;
74 import org.objectstyle.cayenne.map.DataMap;
75 import org.objectstyle.cayenne.modeler.Application;
76 import org.objectstyle.cayenne.modeler.ProjectController;
77 import org.objectstyle.cayenne.modeler.dialog.ValidationResultBrowser;
78 import org.objectstyle.cayenne.modeler.pref.DBConnectionInfo;
79 import org.objectstyle.cayenne.modeler.pref.DBGeneratorDefaults;
80 import org.objectstyle.cayenne.modeler.util.CayenneController;
81 import org.objectstyle.cayenne.swing.BindingBuilder;
82 import org.objectstyle.cayenne.swing.ObjectBinding;
83 import org.objectstyle.cayenne.validation.ValidationResult;
84
85 /**
86  * @author Andrei Adamchik
87  */

88 public class DBGeneratorOptions extends CayenneController {
89
90     protected DBGeneratorOptionsView view;
91     protected ObjectBinding[] optionBindings;
92     protected ObjectBinding sqlBinding;
93
94     protected DBConnectionInfo connectionInfo;
95     protected DataMap dataMap;
96     protected DBGeneratorDefaults generatorDefaults;
97     protected DbGenerator generator;
98     protected String JavaDoc textForSQL;
99
100     protected TableSelector tables;
101
102     public DBGeneratorOptions(ProjectController parent, String JavaDoc title,
103             DBConnectionInfo connectionInfo, DataMap dataMap) {
104         super(parent);
105
106         this.dataMap = dataMap;
107         this.tables = new TableSelector(parent);
108         this.view = new DBGeneratorOptionsView(tables.getView());
109         this.connectionInfo = connectionInfo;
110         this.generatorDefaults = (DBGeneratorDefaults) parent
111                 .getPreferenceDomainForProject()
112                 .getDetail("DbGenerator", DBGeneratorDefaults.class, true);
113
114         this.view.setTitle(title);
115         initController();
116
117         tables.updateTables(dataMap);
118         prepareGenerator();
119         generatorDefaults.configureGenerator(generator);
120         createSQL();
121         refreshView();
122     }
123
124     public Component JavaDoc getView() {
125         return view;
126     }
127
128     public DBGeneratorDefaults getGeneratorDefaults() {
129         return generatorDefaults;
130     }
131
132     public String JavaDoc getTextForSQL() {
133         return textForSQL;
134     }
135
136     protected void initController() {
137
138         BindingBuilder builder = new BindingBuilder(
139                 getApplication().getBindingFactory(),
140                 this);
141
142         sqlBinding = builder.bindToTextArea(view.getSql(), "textForSQL");
143
144         optionBindings = new ObjectBinding[5];
145         optionBindings[0] = builder.bindToStateChangeAndAction(view.getCreateFK(),
146                 "generatorDefaults.createFK",
147                 "refreshSQLAction()");
148         optionBindings[1] = builder.bindToStateChangeAndAction(view.getCreatePK(),
149                 "generatorDefaults.createPK",
150                 "refreshSQLAction()");
151         optionBindings[2] = builder.bindToStateChangeAndAction(view.getCreateTables(),
152                 "generatorDefaults.createTables",
153                 "refreshSQLAction()");
154         optionBindings[3] = builder.bindToStateChangeAndAction(view.getDropPK(),
155                 "generatorDefaults.dropPK",
156                 "refreshSQLAction()");
157         optionBindings[4] = builder.bindToStateChangeAndAction(view.getDropTables(),
158                 "generatorDefaults.dropTables",
159                 "refreshSQLAction()");
160
161         builder.bindToAction(view.getGenerateButton(), "generateSchemaAction()");
162         builder.bindToAction(view.getSaveSqlButton(), "storeSQLAction()");
163         builder.bindToAction(view.getCancelButton(), "closeAction()");
164
165         // refresh SQL if different tables were selected
166
view.getTabs().addChangeListener(new ChangeListener JavaDoc() {
167
168             public void stateChanged(ChangeEvent JavaDoc e) {
169                 if (view.getTabs().getSelectedIndex() == 0) {
170                     // this assumes that some tables where checked/unchecked... not very
171
// efficient
172
refreshGeneratorAction();
173                 }
174             }
175         });
176     }
177
178     /**
179      * Creates new internal DbGenerator instance.
180      */

181     protected void prepareGenerator() {
182         try {
183             DbAdapter adapter = connectionInfo.makeAdapter(getApplication()
184                     .getClassLoadingService());
185             this.generator = new DbGenerator(adapter, dataMap, tables.getExcludedTables());
186             this.generatorDefaults.adjustForAdapter(adapter);
187         }
188         catch (Exception JavaDoc ex) {
189             reportError("Error loading adapter", ex);
190         }
191     }
192
193     /**
194      * Returns SQL statements generated for selected schema generation options.
195      */

196     protected void createSQL() {
197         // convert them to string representation for display
198
StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
199         Iterator JavaDoc it = generator.configuredStatements().iterator();
200         String JavaDoc batchTerminator = generator.getAdapter().getBatchTerminator();
201
202         String JavaDoc lineEnd = (batchTerminator != null)
203                 ? "\n" + batchTerminator + "\n\n"
204                 : "\n\n";
205
206         while (it.hasNext()) {
207             buf.append(it.next()).append(lineEnd);
208         }
209
210         textForSQL = buf.toString();
211     }
212
213     protected void refreshView() {
214
215         for (int i = 0; i < optionBindings.length; i++) {
216             optionBindings[i].updateView();
217         }
218
219         sqlBinding.updateView();
220     }
221
222     // ===============
223
// Actions
224
// ===============
225

226     /**
227      * Starts options dialog.
228      */

229     public void startupAction() {
230         view.pack();
231         view.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
232         view.setModal(true);
233         makeCloseableOnEscape();
234         centerView();
235         view.setVisible(true);
236     }
237
238     public void refreshGeneratorAction() {
239         prepareGenerator();
240         refreshSQLAction();
241     }
242
243     /**
244      * Updates a text area showing generated SQL.
245      */

246     public void refreshSQLAction() {
247         // sync generator with defaults, make SQL, then sync the view...
248
generatorDefaults.configureGenerator(generator);
249         createSQL();
250         sqlBinding.updateView();
251     }
252
253     /**
254      * Performs configured schema operations via DbGenerator.
255      */

256     public void generateSchemaAction() {
257         refreshGeneratorAction();
258
259         // sanity check...
260
if (generator.isEmpty(true)) {
261             JOptionPane.showMessageDialog(getView(), "Nothing to generate.");
262             return;
263         }
264
265         try {
266             DataSource JavaDoc dataSource = connectionInfo.makeDataSource(getApplication()
267                     .getClassLoadingService());
268             generator.runGenerator(dataSource);
269
270             ValidationResult failures = generator.getFailures();
271
272             if (failures == null || !failures.hasFailures()) {
273                 JOptionPane.showMessageDialog(getView(), "Schema Generation Complete.");
274             }
275             else {
276                 new ValidationResultBrowser(this)
277                         .startupAction("Schema Generation Complete",
278                                 "Schema generation finished. The following problem(s) were ignored.",
279                                 failures);
280             }
281         }
282         catch (Throwable JavaDoc th) {
283             reportError("Schema Generation Error", th);
284         }
285     }
286
287     /**
288      * Allows user to save generated SQL in a file.
289      */

290     public void storeSQLAction() {
291         JFileChooser JavaDoc fc = new JFileChooser JavaDoc();
292         fc.setDialogType(JFileChooser.SAVE_DIALOG);
293         fc.setDialogTitle("Save SQL Script");
294
295         File JavaDoc projectDir = Application.getProject().getProjectDirectory();
296
297         if (projectDir != null) {
298             fc.setCurrentDirectory(projectDir);
299         }
300
301         if (fc.showSaveDialog(getView()) == JFileChooser.APPROVE_OPTION) {
302             refreshGeneratorAction();
303
304             try {
305                 File JavaDoc file = fc.getSelectedFile();
306                 FileWriter JavaDoc fw = new FileWriter JavaDoc(file);
307                 PrintWriter JavaDoc pw = new PrintWriter JavaDoc(fw);
308                 pw.print(textForSQL);
309                 pw.flush();
310                 pw.close();
311             }
312             catch (IOException JavaDoc ex) {
313                 reportError("Error Saving SQL", ex);
314             }
315         }
316     }
317
318     public void closeAction() {
319         view.dispose();
320     }
321 }
Popular Tags