KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > j2ee > persistence > wizard > fromdb > RelatedCMPWizard


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.j2ee.persistence.wizard.fromdb;
21
22 import java.awt.Component JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.util.Collection JavaDoc;
25 import java.util.Collections JavaDoc;
26 import java.util.Set JavaDoc;
27 import java.util.logging.Level JavaDoc;
28 import java.util.logging.Logger JavaDoc;
29 import javax.swing.JComponent JavaDoc;
30 import javax.swing.SwingUtilities JavaDoc;
31 import org.netbeans.api.progress.ProgressHandle;
32 import org.netbeans.api.progress.ProgressHandleFactory;
33 import org.netbeans.api.project.Project;
34 import org.netbeans.api.project.ProjectUtils;
35 import org.netbeans.modules.j2ee.persistence.api.PersistenceLocation;
36 import org.netbeans.modules.j2ee.persistence.provider.InvalidPersistenceXmlException;
37 import org.netbeans.modules.j2ee.persistence.provider.ProviderUtil;
38 import org.netbeans.spi.project.ui.templates.support.Templates;
39 import org.openide.DialogDisplayer;
40 import org.openide.ErrorManager;
41 import org.openide.NotifyDescriptor;
42 import org.openide.WizardDescriptor;
43 import org.openide.filesystems.FileObject;
44 import org.openide.loaders.DataFolder;
45 import org.openide.loaders.DataObject;
46 import org.openide.loaders.TemplateWizard;
47 import org.openide.util.Lookup;
48 import org.openide.util.NbBundle;
49 import org.openide.util.RequestProcessor;
50 import org.openide.windows.WindowManager;
51
52 /**
53  *
54  * @author Chris Webster, Martin Adamek, Andrei Badea
55  */

56 public class RelatedCMPWizard extends WizardDescriptor.ArrayIterator<WizardDescriptor> implements TemplateWizard.Iterator {
57     
58     private static final String JavaDoc WIZARD_PANEL_CONTENT_DATA = "WizardPanel_contentData"; // NOI18N
59
private static final String JavaDoc WIZARD_PANEL_CONTENT_SELECTED_INDEX = "WizardPanel_contentSelectedIndex"; //NOI18N;
60

61     private static final String JavaDoc PROP_HELPER = "wizard-helper"; //NOI18N
62
private static final String JavaDoc PROP_CMP = "wizard-is-cmp"; //NOI18N
63

64     private static final String JavaDoc TYPE_CMP = "cmp"; // NOI18N
65
private static final String JavaDoc TYPE_JPA = "jpa"; // NOI18N
66

67     private static final Lookup.Result<PersistenceGeneratorProvider> PERSISTENCE_PROVIDERS =
68             Lookup.getDefault().lookupResult(PersistenceGeneratorProvider.class);
69     
70     private final String JavaDoc type;
71     
72     private WizardDescriptor.Panel<WizardDescriptor>[] panels;
73     private String JavaDoc[] steps;
74     private int stepsStartPos;
75     
76     private WizardDescriptor wizardDescriptor;
77     
78     private PersistenceGenerator generator;
79     private RelatedCMPHelper helper;
80     private ProgressPanel progressPanel;
81     
82     public static RelatedCMPWizard createForJPA() {
83         return new RelatedCMPWizard(TYPE_JPA);
84     }
85     
86     public static RelatedCMPWizard createForCMP() {
87         return new RelatedCMPWizard(TYPE_CMP);
88     }
89     
90     public RelatedCMPWizard(String JavaDoc type) {
91         this.type = type;
92     }
93     
94     private static PersistenceGenerator createPersistenceGenerator(String JavaDoc type) {
95         assert type != null;
96         
97         Collection JavaDoc<? extends PersistenceGeneratorProvider> providers = PERSISTENCE_PROVIDERS.allInstances();
98         for (PersistenceGeneratorProvider provider : providers) {
99             if (type.equals(provider.getGeneratorType())) {
100                 return provider.createGenerator();
101             }
102         }
103         throw new AssertionError JavaDoc("Could not find a persistence generator of type " + type); // NOI18N
104
}
105     
106     private boolean isCMP() {
107         return TYPE_CMP.equals(type);
108     }
109     
110     @SuppressWarnings JavaDoc("unchecked")
111     protected WizardDescriptor.Panel<WizardDescriptor>[] initializePanels() {
112         panels = (WizardDescriptor.Panel<WizardDescriptor>[])new WizardDescriptor.Panel<?>[] {
113             new DatabaseTablesPanel.WizardPanel(),
114             new EntityClassesPanel.WizardPanel()
115         };
116         return panels;
117     }
118     
119     /**
120      * Overriden to set the wizard content data and selected index for
121      * each panel when it is needed, not in advance (which would cause
122      * all the panels' components to be created prematurely).
123      */

124     public WizardDescriptor.Panel<WizardDescriptor> current() {
125         WizardDescriptor.Panel<WizardDescriptor> panel = super.current();
126         
127         if (steps == null) {
128             mergeSteps(new String JavaDoc[] {
129                 NbBundle.getMessage(RelatedCMPWizard.class, "LBL_DatabaseTables"),
130                 NbBundle.getMessage(RelatedCMPWizard.class, isCMP() ? "LBL_EntityBeansLocation" : "LBL_EntityClasses"),
131             });
132         }
133         
134         JComponent JavaDoc component = (JComponent JavaDoc)panel.getComponent();
135         if (component.getClientProperty(WIZARD_PANEL_CONTENT_DATA) == null) {
136             component.putClientProperty(WIZARD_PANEL_CONTENT_DATA, steps);
137         }
138         if (component.getClientProperty(WIZARD_PANEL_CONTENT_SELECTED_INDEX) == null) {
139             if (panel == panels[0]) {
140                 component.putClientProperty(WIZARD_PANEL_CONTENT_SELECTED_INDEX, new Integer JavaDoc(0));
141                 // don't use an absolute step value like 1,
142
// since we dont' know how may steps there are before us
143
component.setName(steps[steps.length - 2]);
144             } else {
145                 component.putClientProperty(WIZARD_PANEL_CONTENT_SELECTED_INDEX, new Integer JavaDoc(1));
146                 // don't use an absolute step value like 2,
147
// since we dont' know how may steps there are before us
148
component.setName(steps[steps.length - 1]);
149             }
150         }
151         
152         return panel;
153     }
154     
155     static RelatedCMPHelper getHelper(WizardDescriptor wizardDescriptor) {
156         return (RelatedCMPHelper)wizardDescriptor.getProperty(PROP_HELPER);
157     }
158     
159     static boolean isCMP(WizardDescriptor wizardDescriptor) {
160         return ((Boolean JavaDoc)wizardDescriptor.getProperty(PROP_CMP)).booleanValue();
161     }
162     
163     public final void initialize(TemplateWizard wiz) {
164         wizardDescriptor = wiz;
165         
166         Project project = Templates.getProject(wiz);
167         generator = createPersistenceGenerator(type);
168         
169         FileObject configFilesFolder = PersistenceLocation.getLocation(project);
170         
171         helper = new RelatedCMPHelper(project, configFilesFolder, generator);
172         
173         wiz.putProperty(PROP_HELPER, helper);
174         wiz.putProperty(PROP_CMP, new Boolean JavaDoc(isCMP()));
175         
176         String JavaDoc wizardBundleKey = isCMP() ? "Templates/J2EE/RelatedCMP" : "Templates/Persistence/RelatedCMP"; // NOI18N
177
wiz.putProperty("NewFileWizard_Title", NbBundle.getMessage(RelatedCMPWizard.class, wizardBundleKey)); // NOI18N
178

179         generator.init(wiz);
180     }
181     
182     public void mergeSteps(String JavaDoc[] thisSteps) {
183         Object JavaDoc prop = wizardDescriptor.getProperty(WIZARD_PANEL_CONTENT_DATA);
184         String JavaDoc[] beforeSteps;
185         
186         if (prop instanceof String JavaDoc[]) {
187             beforeSteps = (String JavaDoc[]) prop;
188             stepsStartPos = beforeSteps.length;
189             if (stepsStartPos > 0 && ("...".equals(beforeSteps[stepsStartPos - 1]))) { // NOI18N
190
stepsStartPos--;
191             }
192         } else {
193             beforeSteps = null;
194             stepsStartPos = 0;
195         }
196         
197         steps = new String JavaDoc[stepsStartPos + thisSteps.length];
198         System.arraycopy(beforeSteps, 0, steps, 0, stepsStartPos);
199         System.arraycopy(thisSteps, 0, steps, stepsStartPos, thisSteps.length);
200     }
201     
202     public final void uninitialize(TemplateWizard wiz) {
203         generator.uninit();
204     }
205     
206     public Set JavaDoc<DataObject> instantiate(final TemplateWizard wiz) throws IOException JavaDoc {
207         Component JavaDoc c = WindowManager.getDefault().getMainWindow();
208         
209         // create the pu first if needed
210
if (helper.getPersistenceUnit() != null){
211             try {
212                 ProviderUtil.addPersistenceUnit(helper.getPersistenceUnit(), Templates.getProject(wiz));
213             } catch (InvalidPersistenceXmlException ipx){
214                 // just log for debugging purposes, at this point the user has
215
// already been warned about an invalid persistence.xml
216
Logger.getLogger(RelatedCMPWizard.class.getName()).log(Level.FINE, "Invalid persistence.xml: " + ipx.getPath(), ipx); //NO18N
217
}
218         }
219         
220         final String JavaDoc title = NbBundle.getMessage(RelatedCMPWizard.class, isCMP() ? "TXT_EjbGeneration" : "TXT_EntityClassesGeneration");
221         final ProgressHandle handle = ProgressHandleFactory.createHandle(title);
222         
223         progressPanel = new ProgressPanel();
224         final JComponent JavaDoc progressComponent = ProgressHandleFactory.createProgressComponent(handle);
225         
226         final Runnable JavaDoc r = new Runnable JavaDoc() {
227             public void run() {
228                 try {
229                     createBeans(wiz, handle);
230                 } catch (IOException JavaDoc ioe) {
231                     ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ioe);
232                     NotifyDescriptor nd =
233                             new NotifyDescriptor.Message(ioe.getLocalizedMessage(),
234                             NotifyDescriptor.ERROR_MESSAGE);
235                     DialogDisplayer.getDefault().notify(nd);
236                 } finally {
237                     generator.uninit();
238                 }
239             }
240         };
241         
242         // Ugly hack ensuring the progress dialog opens after the wizard closes. Needed because:
243
// 1) the wizard is not closed in the AWT event in which instantiate() is called.
244
// Instead it is closed in an event scheduled by SwingUtilities.invokeLater().
245
// 2) when a modal dialog is created its owner is set to the foremost modal
246
// dialog already displayed (if any). Because of #1 the wizard will be
247
// closed when the progress dialog is already open, and since the wizard
248
// is the owner of the progress dialog, the progress dialog is closed too.
249
// The order of the events in the event queue:
250
// - this event
251
// - the first invocation event of our runnable
252
// - the invocation event which closes the wizard
253
// - the second invocation event of our runnable
254

255         SwingUtilities.invokeLater(new Runnable JavaDoc() {
256             private boolean first = true;
257             public void run() {
258                 if (!first) {
259                     RequestProcessor.getDefault().post(r);
260                     progressPanel.open(progressComponent, title);
261                 } else {
262                     first = false;
263                     SwingUtilities.invokeLater(this);
264                 }
265             }
266         });
267         
268         // The commented code below is the ideal state, but since there is not way to request
269
// TemplateWizard.Iterator.instantiate() be called asynchronously it
270
// would cause the wizard to stay visible until the bean generation process
271
// finishes. So for now just returning the package -- not a problem,
272
// JavaPersistenceGenerator.createdObjects() returns an empty set anyway.
273

274         // remember to wait for createBeans() to actually return!
275
// Set created = generator.createdObjects();
276
// if (created.size() == 0) {
277
// created = Collections.singleton(SourceGroupSupport.getFolderForPackage(helper.getLocation(), helper.getPackageName()));
278
// }
279

280         return Collections.<DataObject>singleton(DataFolder.findFolder(
281             SourceGroupSupport.getFolderForPackage(helper.getLocation(), helper.getPackageName())
282         ));
283     }
284     
285     private void createBeans(TemplateWizard wiz, ProgressHandle handle) throws IOException JavaDoc {
286         try {
287             handle.start();
288             Project project = Templates.getProject(wiz);
289             handle.progress(NbBundle.getMessage(RelatedCMPWizard.class, "TXT_SavingSchema"));
290             progressPanel.setText(NbBundle.getMessage(RelatedCMPWizard.class, "TXT_SavingSchema"));
291             
292             FileObject dbschemaFile = helper.getDBSchemaFile();
293             if (dbschemaFile == null) {
294                 FileObject configFilesFolder = getHelper(wiz).getConfigFilesFolder();
295                 if (configFilesFolder == null && !isCMP()) {
296                     // if we got here, this must be an entity class library project or just a
297
// project without persistence.xml
298
configFilesFolder = PersistenceLocation.createLocation(project);
299                 }
300                 assert configFilesFolder != null : "Should have set configFilesFolder, e.g. by retrieving it from a PersistenceLocationProvider or EjbJar or by asking the user"; // NOI18N
301

302                 String JavaDoc projectName = ProjectUtils.getInformation(project).getDisplayName();
303                 dbschemaFile = DBSchemaManager.updateDBSchemas(helper.getSchemaElement(), helper.getDBSchemaFileList(), configFilesFolder, projectName);
304             }
305             
306             String JavaDoc extracting = NbBundle.getMessage(RelatedCMPWizard.class, isCMP() ?
307                 "TXT_ExtractingBeansAndRelationships" : "TXT_ExtractingEntityClassesAndRelationships");
308             
309             handle.progress(extracting);
310             progressPanel.setText(extracting);
311             
312             helper.buildBeans();
313             
314             FileObject pkg = SourceGroupSupport.getFolderForPackage(helper.getLocation(), helper.getPackageName());
315             generator.generateBeans(progressPanel, helper, dbschemaFile, handle, false);
316             
317             // if (EjbJar.VERSION_3_0.equals(dd.getVersion().toString())) {
318
// JavaPersistenceGenerator jpg = new JavaPersistenceGenerator();
319
// jpg.generateBeans(
320
// } else {
321
// CmpGenerator gen = new CmpGenerator();
322
// gen.generateBeans(progressPanel,helper, pkg, dbschemaFile, genHelper, handle, module.getDeploymentDescriptor(), pwm, dd, false);
323
// }
324
} finally {
325             handle.finish();
326             SwingUtilities.invokeLater(new Runnable JavaDoc() {
327                 public void run() {
328                     progressPanel.close();
329                 }
330             });
331         }
332     }
333     
334 }
335
Popular Tags