KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > j2ee > persistence > wizard > dao > EjbFacadeWizardIterator


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 package org.netbeans.modules.j2ee.persistence.wizard.dao;
20
21 import com.sun.source.tree.AnnotationTree;
22 import com.sun.source.tree.BlockTree;
23 import com.sun.source.tree.ClassTree;
24 import com.sun.source.tree.CompilationUnitTree;
25 import com.sun.source.tree.ExpressionTree;
26 import com.sun.source.tree.MethodTree;
27 import com.sun.source.tree.ModifiersTree;
28 import com.sun.source.tree.Tree;
29 import com.sun.source.tree.TypeParameterTree;
30 import com.sun.source.tree.VariableTree;
31 import java.awt.Component JavaDoc;
32 import java.io.IOException JavaDoc;
33 import java.util.Collections JavaDoc;
34 import java.util.HashSet JavaDoc;
35 import java.util.List JavaDoc;
36 import java.util.NoSuchElementException JavaDoc;
37 import java.util.Set JavaDoc;
38 import java.util.logging.Level JavaDoc;
39 import java.util.logging.Logger JavaDoc;
40 import javax.lang.model.element.Modifier;
41 import javax.swing.JComponent JavaDoc;
42 import javax.swing.event.ChangeListener JavaDoc;
43 import org.netbeans.api.java.source.JavaSource;
44 import org.netbeans.api.java.source.JavaSource.Phase;
45 import org.netbeans.api.java.source.ModificationResult;
46 import org.netbeans.api.java.source.TreeMaker;
47 import org.netbeans.api.java.source.WorkingCopy;
48 import org.netbeans.api.project.Project;
49 import org.netbeans.modules.j2ee.persistence.util.AbstractTask;
50 import org.netbeans.modules.j2ee.persistence.util.GenerationUtils;
51 import org.netbeans.modules.j2ee.persistence.action.EntityManagerGenerator;
52 import org.netbeans.modules.j2ee.persistence.action.GenerationOptions;
53 import org.netbeans.modules.j2ee.persistence.api.metadata.orm.Entity;
54 import org.netbeans.modules.j2ee.persistence.dd.persistence.model_1_0.PersistenceUnit;
55 import org.netbeans.modules.j2ee.persistence.provider.InvalidPersistenceXmlException;
56 import org.netbeans.modules.j2ee.persistence.provider.ProviderUtil;
57 import org.netbeans.modules.j2ee.persistence.wizard.PersistenceClientEntitySelection;
58 import org.netbeans.modules.j2ee.persistence.wizard.Util;
59 import org.netbeans.modules.j2ee.persistence.wizard.WizardProperties;
60 import org.netbeans.spi.project.ui.templates.support.Templates;
61 import org.openide.WizardDescriptor;
62 import org.openide.filesystems.FileObject;
63 import org.openide.util.HelpCtx;
64 import org.openide.util.NbBundle;
65
66 public final class EjbFacadeWizardIterator implements WizardDescriptor.InstantiatingIterator {
67     
68     private static final String JavaDoc WIZARD_PANEL_CONTENT_DATA = "WizardPanel_contentData"; // NOI18N
69

70     private int index;
71     private WizardDescriptor wizard;
72     private WizardDescriptor.Panel[] panels;
73     private String JavaDoc[] steps;
74     private int stepsStartPos;
75     
76     private WizardDescriptor.Panel[] getPanels() {
77         return panels;
78     }
79     
80     
81     public Set JavaDoc instantiate() throws IOException JavaDoc {
82         List JavaDoc<Entity> entities = (List JavaDoc<Entity>) wizard.getProperty(WizardProperties.ENTITY_CLASS);
83         final FileObject targetFolder = Templates.getTargetFolder(wizard);
84         final Set JavaDoc createdFiles = new HashSet JavaDoc();
85         final EjbFacadeWizardPanel2 panel = (EjbFacadeWizardPanel2) panels[1];
86         String JavaDoc pkg = panel.getPackage();
87         
88         PersistenceUnit persistenceUnit = (PersistenceUnit) wizard.getProperty(WizardProperties.PERSISTENCE_UNIT);
89         if (persistenceUnit != null){
90             try{
91                 ProviderUtil.addPersistenceUnit(persistenceUnit, Templates.getProject(wizard));
92             } catch (InvalidPersistenceXmlException ipx){
93                 // just log for debugging purposes, at this point the user has
94
// already been warned about an invalid persistence.xml
95
Logger.getLogger(EjbFacadeWizardIterator.class.getName()).log(Level.FINE, "Invalid persistence.xml: " + ipx.getPath(), ipx); //NO18N
96
}
97         }
98         
99         for (Entity entity : entities) {
100             final String JavaDoc entityClass = entity.getClass2();
101             final String JavaDoc simpleClassName = Util.simpleClassName(entityClass);
102             final String JavaDoc variableName = simpleClassName.toLowerCase().charAt(0) + simpleClassName.substring(1);
103             final String JavaDoc facadeNameBase = pkg + "." + simpleClassName;
104             // String classBean = JMIUtils.uniqueClassName(facadeNameBase + "Facade", targetFolder);
105
final String JavaDoc classBean = getUniqueClassName(facadeNameBase + "Facade", targetFolder);
106             // classBean = classBean.substring(classBean.lastIndexOf(".") + 1);
107

108             final FileObject sourceFile = GenerationUtils.createClass(targetFolder, classBean, null);// name must be made unique
109
createdFiles.add(sourceFile);
110             createdFiles.addAll(generate(sourceFile, targetFolder, classBean, pkg, panel.isRemote(), panel.isLocal()));
111             
112         }
113         return createdFiles;
114     }
115     
116     
117     Set JavaDoc<FileObject> generate(final FileObject sourcexFile, final FileObject targetFolder, final String JavaDoc classBean, String JavaDoc pkg, final boolean hasRemote, final boolean hasLocal) throws IOException JavaDoc{
118         
119         final Set JavaDoc<FileObject> createdFiles = new HashSet JavaDoc<FileObject>();
120         final String JavaDoc entityClass = classBean;
121         final String JavaDoc simpleClassName = Util.simpleClassName(entityClass);
122         final String JavaDoc variableName = simpleClassName.toLowerCase().charAt(0) + simpleClassName.substring(1);
123         final String JavaDoc facadeNameBase = pkg + "." + simpleClassName;
124         // String classBean = JMIUtils.uniqueClassName(facadeNameBase + "Facade", targetFolder);
125
// final String classBean = getUniqueClassName(facadeNameBase + "Facade", targetFolder);
126

127         final FileObject facade = GenerationUtils.createClass(targetFolder, classBean + "Facade", null);
128         createdFiles.add(facade);
129         JavaSource source = JavaSource.forFileObject(facade);
130         source.runModificationTask(new AbstractTask<WorkingCopy>() {
131             public void run(WorkingCopy workingCopy) throws Exception JavaDoc {
132                 workingCopy.toPhase(Phase.RESOLVED);
133                 CompilationUnitTree cut = workingCopy.getCompilationUnit();
134                 TreeMaker make = workingCopy.getTreeMaker();
135                 
136                 for (Tree typeDeclaration : cut.getTypeDecls()){
137                     if (Tree.Kind.CLASS == typeDeclaration.getKind()){
138                         ClassTree clazz = (ClassTree) typeDeclaration;
139                         AnnotationTree annotations = make.Annotation(make.Identifier("javax.ejb.Stateless"), Collections.<ExpressionTree>emptyList());
140                         ModifiersTree modifiers = make.Modifiers(clazz.getModifiers(), Collections.<AnnotationTree>singletonList(annotations));
141                         ClassTree modifiedClass =
142                                 make.Class(modifiers, clazz.getSimpleName(), clazz.getTypeParameters(), clazz.getExtendsClause(), (List JavaDoc<ExpressionTree>)clazz.getImplementsClause(), Collections.<Tree>emptyList());
143                         workingCopy.rewrite(clazz, modifiedClass);
144                         
145                         FileObject local = null;
146                         FileObject remote = null;
147                         if (hasLocal){
148                             String JavaDoc classLocal = getUniqueClassName(facadeNameBase + "FacadeLocal", targetFolder);
149                             classLocal = Util.simpleClassName(classLocal);
150                             local = createInterface(classLocal, "javax.ejb.Local", targetFolder);
151                             createdFiles.add(local);
152                         }
153                         if (hasRemote){
154                             String JavaDoc classRemote = getUniqueClassName(facadeNameBase + "FacadeRemote", targetFolder);
155                             classRemote = Util.simpleClassName(classRemote);
156                             remote = createInterface(classRemote, "javax.ejb.Remote", targetFolder);
157                             createdFiles.add(remote);
158                         }
159                         EntityManagerGenerator generator = new EntityManagerGenerator(facade, classBean);
160                         
161                         GenerationOptions createOptions = new GenerationOptions();
162                         createOptions.setMethodName("create");
163                         createOptions.setOperation(GenerationOptions.Operation.PERSIST);
164                         createOptions.setReturnType("void");
165                         createOptions.setParameterName(variableName);
166                         createOptions.setParameterType(entityClass);
167                         generator.generate(createOptions);
168                         addMethodToInterface("create", "void", variableName, entityClass, local);
169                         addMethodToInterface("create", "void", variableName, entityClass, remote);
170                         
171                         GenerationOptions editOptions = new GenerationOptions();
172                         editOptions.setMethodName("edit");
173                         editOptions.setOperation(GenerationOptions.Operation.PERSIST);
174                         editOptions.setReturnType("void");
175                         editOptions.setParameterName(variableName);
176                         editOptions.setParameterType(entityClass);
177                         generator.generate(editOptions);
178                         addMethodToInterface("edit", "void", variableName, entityClass, local);
179                         addMethodToInterface("edit", "void", variableName, entityClass, remote);
180                         
181                         GenerationOptions destroyOptions = new GenerationOptions();
182                         destroyOptions.setMethodName("remove");
183                         destroyOptions.setOperation(GenerationOptions.Operation.REMOVE);
184                         destroyOptions.setReturnType("void");
185                         destroyOptions.setParameterName(variableName);
186                         destroyOptions.setParameterType(entityClass);
187                         generator.generate(destroyOptions);
188                         addMethodToInterface("destroy", "void", variableName, entityClass, local);
189                         addMethodToInterface("destroy", "void", variableName, entityClass, remote);
190                         
191                         GenerationOptions findOptions = new GenerationOptions();
192                         findOptions.setMethodName("find");
193                         findOptions.setOperation(GenerationOptions.Operation.FIND);
194                         findOptions.setReturnType("void");
195                         findOptions.setParameterName(variableName);
196                         findOptions.setParameterType(entityClass);
197                         generator.generate(findOptions);
198                         addMethodToInterface("find", "void", variableName, entityClass, local);
199                         addMethodToInterface("find", "void", variableName, entityClass, remote);
200                         
201                         GenerationOptions findAllOptions = new GenerationOptions();
202                         findAllOptions.setMethodName("findAll");
203                         findAllOptions.setOperation(GenerationOptions.Operation.FIND_ALL);
204                         findAllOptions.setReturnType("void");
205                         findAllOptions.setParameterName(variableName);
206                         findAllOptions.setParameterType(entityClass);
207                         generator.generate(findAllOptions);
208                         addMethodToInterface("findAll", "void", variableName, entityClass, local);
209                         addMethodToInterface("findAll", "void", variableName, entityClass, remote);
210                         
211                     }
212                 }
213             }
214         });
215         return createdFiles;
216     }
217     
218     String JavaDoc getUniqueClassName(String JavaDoc candidateName, FileObject targetFolder){
219         return candidateName; // TODO: RETOUCHE
220
}
221     
222     
223     /**
224      * Creates an interface with the given <code>name</code>, annotated with an annotation
225      * of the given <code>annotationType</code>. <i>Package private visibility just because of tests</i>.
226      * @param
227      * @param
228      */

229     FileObject createInterface(String JavaDoc name, final String JavaDoc annotationType, FileObject targetFolder) throws IOException JavaDoc{
230         FileObject sourceFile = GenerationUtils.createInterface(targetFolder, name, null);
231         JavaSource source = JavaSource.forFileObject(sourceFile);
232         ModificationResult result = source.runModificationTask(new AbstractTask<WorkingCopy>() {
233             public void run(WorkingCopy workingCopy) throws Exception JavaDoc {
234                 
235                 workingCopy.toPhase(Phase.RESOLVED);
236                 TreeMaker make = workingCopy.getTreeMaker();
237                 CompilationUnitTree cut = workingCopy.getCompilationUnit();
238                 
239                 for (Tree typeDeclaration : cut.getTypeDecls()){
240                     if (Tree.Kind.CLASS == typeDeclaration.getKind()){
241                         ClassTree clazz = (ClassTree) typeDeclaration;
242                         AnnotationTree annotations = make.Annotation(make.Identifier(annotationType), Collections.<ExpressionTree>emptyList());
243                         ModifiersTree modifiers = make.Modifiers(clazz.getModifiers(), Collections.<AnnotationTree>singletonList(annotations));
244                         ClassTree modifiedClass =
245                                 make.Class(modifiers, clazz.getSimpleName(), clazz.getTypeParameters(), clazz.getExtendsClause(), Collections.<ExpressionTree>emptyList(), Collections.<Tree>emptyList());
246                         workingCopy.rewrite(clazz, modifiedClass);
247                     }
248                 }
249             }
250         });
251         result.commit();
252         return source.getFileObjects().iterator().next();
253         
254     }
255     
256     void addMethodToInterface(final String JavaDoc name, final String JavaDoc returnType, final String JavaDoc parameterName,
257             final String JavaDoc parameterType, final FileObject target) throws IOException JavaDoc {
258         
259         if (target == null){
260             return;
261         }
262         
263         JavaSource source = JavaSource.forFileObject(target);
264         ModificationResult result = source.runModificationTask(new AbstractTask<WorkingCopy>() {
265             public void run(WorkingCopy parameter) throws Exception JavaDoc {
266                 parameter.toPhase(Phase.RESOLVED);
267                 TreeMaker make = parameter.getTreeMaker();
268                 CompilationUnitTree cut = parameter.getCompilationUnit();
269                 for (Tree tree : cut.getTypeDecls()){
270                     if (tree.getKind() == Tree.Kind.CLASS){
271                         ClassTree iface = (ClassTree) tree;
272                         ModifiersTree mt = make.Modifiers(Collections.<Modifier>emptySet());
273                         VariableTree vt = make.Variable(mt, parameterName, make.Identifier(parameterType), null);
274                         MethodTree method = make.Method(mt,
275                                 name,
276                                 make.Identifier(returnType),
277                                 Collections.<TypeParameterTree>emptyList(),
278                                 Collections.<VariableTree>singletonList(vt),
279                                 Collections.<ExpressionTree>emptyList(),
280                                 (BlockTree) null,
281                                 null);
282                         ClassTree modifiedClass = make.addClassMember(iface, method);
283                         parameter.rewrite(iface, modifiedClass);
284                     }
285                 }
286             }
287         });
288         result.commit();
289         
290     }
291     
292     public void initialize(WizardDescriptor wizard) {
293         this.wizard = wizard;
294         wizard.putProperty("NewFileWizard_Title",
295                 NbBundle.getMessage(EjbFacadeWizardIterator.class, "Templates/Persistence/ejbFacade"));
296         Project project = Templates.getProject(wizard);
297         if (panels == null) {
298             panels = new WizardDescriptor.Panel[] {
299                 new PersistenceClientEntitySelection(
300                         NbBundle.getMessage(EjbFacadeWizardIterator.class, "LBL_EntityClasses"),
301                         new HelpCtx(EjbFacadeWizardIterator.class.getName() + "$PersistenceClientEntitySelection"), wizard), // NOI18N
302
new EjbFacadeWizardPanel2(project, wizard)
303             };
304             if (steps == null) {
305                 mergeSteps(new String JavaDoc[] {
306                     NbBundle.getMessage(EjbFacadeWizardIterator.class, "LBL_EntityClasses"),
307                     NbBundle.getMessage(EjbFacadeWizardIterator.class, "LBL_GeneratedSessionBeans"),
308                 });
309             }
310             for (int i = 0; i < panels.length; i++) {
311                 Component JavaDoc c = panels[i].getComponent();
312                 if (c instanceof JComponent JavaDoc) { // assume Swing components
313
JComponent JavaDoc jc = (JComponent JavaDoc) c;
314                     // Sets step number of a component
315
jc.putClientProperty("WizardPanel_contentSelectedIndex", new Integer JavaDoc(i));
316                     // Sets steps names for a panel
317
jc.putClientProperty("WizardPanel_contentData", steps);
318                     // Turn on subtitle creation on each step
319
jc.putClientProperty("WizardPanel_autoWizardStyle", Boolean.TRUE);
320                     // Show steps on the left side with the image on the background
321
jc.putClientProperty("WizardPanel_contentDisplayed", Boolean.TRUE);
322                     // Turn on numbering of all steps
323
jc.putClientProperty("WizardPanel_contentNumbered", Boolean.TRUE);
324                 }
325             }
326         }
327     }
328     
329     public void uninitialize(WizardDescriptor wizard) {
330         panels = null;
331     }
332     
333     public WizardDescriptor.Panel current() {
334         return getPanels()[index];
335     }
336     
337     public String JavaDoc name() {
338         return NbBundle.getMessage(EjbFacadeWizardIterator.class, "LBL_FacadeWizardTitle");
339     }
340     
341     public boolean hasNext() {
342         return index < getPanels().length - 1;
343     }
344     
345     public boolean hasPrevious() {
346         return index > 0;
347     }
348     
349     public void nextPanel() {
350         if (!hasNext()) {
351             throw new NoSuchElementException JavaDoc();
352         }
353         index++;
354     }
355     
356     public void previousPanel() {
357         if (!hasPrevious()) {
358             throw new NoSuchElementException JavaDoc();
359         }
360         index--;
361     }
362     
363     // If nothing unusual changes in the middle of the wizard, simply:
364
public void addChangeListener(ChangeListener JavaDoc l) {}
365     public void removeChangeListener(ChangeListener JavaDoc l) {}
366     
367     private void mergeSteps(String JavaDoc[] thisSteps) {
368         Object JavaDoc prop = wizard.getProperty(WIZARD_PANEL_CONTENT_DATA);
369         String JavaDoc[] beforeSteps;
370         
371         if (prop instanceof String JavaDoc[]) {
372             beforeSteps = (String JavaDoc[]) prop;
373             stepsStartPos = beforeSteps.length;
374             if (stepsStartPos > 0 && ("...".equals(beforeSteps[stepsStartPos - 1]))) { // NOI18N
375
stepsStartPos--;
376             }
377         } else {
378             beforeSteps = null;
379             stepsStartPos = 0;
380         }
381         
382         steps = new String JavaDoc[stepsStartPos + thisSteps.length];
383         System.arraycopy(beforeSteps, 0, steps, 0, stepsStartPos);
384         System.arraycopy(thisSteps, 0, steps, stepsStartPos, thisSteps.length);
385     }
386     
387 }
388
Popular Tags