KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > j2ee > persistence > wizard > entity > EntityWizard


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.entity;
21
22 import com.sun.source.tree.AnnotationTree;
23 import com.sun.source.tree.ClassTree;
24 import com.sun.source.tree.ExpressionTree;
25 import com.sun.source.tree.MethodTree;
26 import com.sun.source.tree.ModifiersTree;
27 import com.sun.source.tree.Tree;
28 import com.sun.source.tree.VariableTree;
29 import java.io.IOException JavaDoc;
30 import java.util.ArrayList JavaDoc;
31 import org.netbeans.modules.j2ee.persistence.provider.ProviderUtil;
32 import org.openide.*;
33 import org.openide.util.*;
34 import java.util.Collections JavaDoc;
35 import java.util.HashSet JavaDoc;
36 import java.util.List JavaDoc;
37 import java.util.NoSuchElementException JavaDoc;
38 import java.util.Set JavaDoc;
39 import java.util.logging.Level JavaDoc;
40 import java.util.logging.Logger JavaDoc;
41 import javax.lang.model.element.Modifier;
42 import javax.lang.model.type.TypeMirror;
43 import org.netbeans.api.java.classpath.ClassPath;
44 import org.netbeans.api.java.source.JavaSource;
45 import org.netbeans.api.java.source.TreeMaker;
46 import org.netbeans.api.java.source.WorkingCopy;
47 import org.netbeans.api.project.Project;
48 import org.netbeans.api.project.SourceGroup;
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.dd.persistence.model_1_0.PersistenceUnit;
52 import org.netbeans.modules.j2ee.persistence.provider.InvalidPersistenceXmlException;
53 import org.netbeans.modules.j2ee.persistence.unit.PUDataObject;
54 import org.netbeans.modules.j2ee.persistence.util.JPAClassPathHelper;
55 import org.netbeans.modules.j2ee.persistence.wizard.DelegatingWizardDescriptorPanel;
56 import org.netbeans.modules.j2ee.persistence.wizard.Util;
57 import org.netbeans.spi.java.classpath.ClassPathProvider;
58 import org.netbeans.spi.java.project.support.ui.templates.JavaTemplates;
59 import org.netbeans.spi.project.ui.templates.support.Templates;
60 import org.openide.filesystems.FileObject;
61
62 /**
63  * A wizard for creating entity classes.
64  *
65  * @author Martin Adamek
66  * @author Erno Mononen
67  */

68
69 public final class EntityWizard implements WizardDescriptor.InstantiatingIterator {
70     private WizardDescriptor.Panel[] panels;
71     private int index = 0;
72     private EntityWizardDescriptor ejbPanel;
73     private WizardDescriptor wiz;
74     private SourceGroup[] sourceGroups;
75     
76     public static EntityWizard create() {
77         return new EntityWizard();
78     }
79     
80     public String JavaDoc name() {
81         return NbBundle.getMessage(EntityWizard.class, "LBL_EntityEJBWizardTitle");
82     }
83     
84     public void uninitialize(WizardDescriptor wiz) {
85     }
86     
87     public void initialize(WizardDescriptor wizardDescriptor) {
88         wiz = wizardDescriptor;
89         Project project = Templates.getProject(wiz);
90         sourceGroups = Util.getJavaSourceGroups(project);
91         ejbPanel = new EntityWizardDescriptor();
92         WizardDescriptor.Panel p = new ValidatingPanel(JavaTemplates.createPackageChooser(project,sourceGroups, ejbPanel, true));
93         panels = new WizardDescriptor.Panel[] {p};
94         Util.mergeSteps(wiz, panels, null);
95         
96     }
97     
98     public Set JavaDoc instantiate() throws IOException JavaDoc {
99         
100         FileObject result = generateEntity(
101                 Templates.getTargetFolder(wiz),
102                 Templates.getTargetName(wiz),
103                 ejbPanel.getPrimaryKeyClassName(),
104                 false // setting PROPERTY access type by default
105
);
106         
107         try{
108             PersistenceUnit punit = ejbPanel.getPersistenceUnit();
109             if (punit != null){
110                 ProviderUtil.addPersistenceUnit(punit, Templates.getProject(wiz));
111             }
112             addEntityToPersistenceUnit(result);
113         } catch (InvalidPersistenceXmlException ipx){
114             // just log for debugging purposes, at this point the user has
115
// already been warned about an invalid persistence.xml
116
Logger.getLogger(EntityWizard.class.getName()).log(Level.FINE, "Invalid persistence.xml: " + ipx.getPath(), ipx); //NO18N
117
}
118         
119         return Collections.singleton(result);
120     }
121     
122     /**
123      * Adds the given entity to the persistence unit defined in the project in which this wizard
124      * was invoked.
125      * @param entity the entity to be added.
126      */

127     private void addEntityToPersistenceUnit(FileObject entity) throws InvalidPersistenceXmlException{
128         
129         Project project = Templates.getProject(wiz);
130         String JavaDoc entityFQN = "";
131         ClassPathProvider classPathProvider = project.getLookup().lookup(ClassPathProvider.class);
132         if (classPathProvider != null) {
133             entityFQN = classPathProvider.findClassPath(entity, ClassPath.SOURCE).getResourceName(entity, '.', false);
134         }
135         
136         if (project != null && !Util.isSupportedJavaEEVersion(project) && ProviderUtil.getDDFile(project) != null) {
137             PUDataObject pudo = ProviderUtil.getPUDataObject(project);
138             PersistenceUnit pu[] = pudo.getPersistence().getPersistenceUnit();
139             //only add if a PU exists, if there are more we do not know where to add - UI needed to ask
140
if (pu.length == 1) {
141                 pudo.addClass(pu[0], entityFQN);
142             }
143         }
144     }
145     
146     
147     public void addChangeListener(javax.swing.event.ChangeListener JavaDoc l) {
148     }
149     
150     public void removeChangeListener(javax.swing.event.ChangeListener JavaDoc l) {
151     }
152     
153     public boolean hasPrevious() {
154         return index > 0;
155     }
156     
157     public boolean hasNext() {
158         return index < panels.length - 1;
159     }
160     
161     public void nextPanel() {
162         if (! hasNext()) {
163             throw new NoSuchElementException JavaDoc();
164         }
165         index++;
166     }
167     
168     public void previousPanel() {
169         if (! hasPrevious()) {
170             throw new NoSuchElementException JavaDoc();
171         }
172         index--;
173     }
174     
175     public WizardDescriptor.Panel current() {
176         return panels[index];
177     }
178     
179     /**
180      * Generates an entity class.
181      *
182      * @param targetFolder the target folder for the entity.
183      * @param targetName the target name of the entity.
184      * @param primaryKeyClassName the name of the primary key class, needs to be
185      * resolvable in the generated entity's scope.
186      * @param isAccessProperty defines the access strategy for the id field.
187      * @return a FileObject representing the generated entity.
188      */

189     public static FileObject generateEntity(FileObject targetFolder, String JavaDoc targetName,
190             final String JavaDoc primaryKeyClassName, final boolean isAccessProperty) throws IOException JavaDoc {
191         
192         FileObject entityFo = GenerationUtils.createClass(targetFolder, targetName, null);
193         
194         ClassPath compile = ClassPath.getClassPath(targetFolder, ClassPath.COMPILE);
195         Set JavaDoc<ClassPath> compileClassPaths = new HashSet JavaDoc<ClassPath>();
196         compileClassPaths.add(compile);
197         
198         JPAClassPathHelper cpHelper = new JPAClassPathHelper(
199                 Collections.<ClassPath>singleton(ClassPath.getClassPath(targetFolder, ClassPath.BOOT)),
200                 Collections.<ClassPath>singleton(ClassPath.getClassPath(targetFolder, ClassPath.COMPILE)),
201                 Collections.<ClassPath>singleton(ClassPath.getClassPath(targetFolder, ClassPath.SOURCE))
202                 );
203         
204
205         JavaSource targetSource = JavaSource.create(cpHelper.createClasspathInfo(), entityFo);
206         AbstractTask task = new AbstractTask<WorkingCopy>() {
207             
208             public void run(WorkingCopy workingCopy) throws Exception JavaDoc {
209                 GenerationUtils genUtils = GenerationUtils.newInstance(workingCopy);
210                 ClassTree clazz = genUtils.getClassTree();
211                 ClassTree modifiedClazz = genUtils.ensureNoArgConstructor(clazz);
212                 TreeMaker make = workingCopy.getTreeMaker();
213                 
214                 String JavaDoc idFieldName = "id"; // NO18N
215
TypeMirror type = workingCopy.getTreeUtilities().parseType(primaryKeyClassName, genUtils.getTypeElement());
216                 Tree typeTree = make.Type(type);
217                 
218                 Set JavaDoc<Modifier> serialVersionUIDModifiers = new HashSet JavaDoc<Modifier>();
219                 serialVersionUIDModifiers.add(Modifier.PRIVATE);
220                 serialVersionUIDModifiers.add(Modifier.STATIC);
221                 serialVersionUIDModifiers.add(Modifier.FINAL);
222                 
223                 VariableTree serialVersionUID = make.Variable(make.Modifiers(serialVersionUIDModifiers), "serialVersionUID", genUtils.createType("long"), make.Literal(Long.valueOf("1"))); //NO18N
224
VariableTree idField = make.Variable(genUtils.createModifiers(Modifier.PRIVATE), idFieldName, typeTree, null);
225                 ModifiersTree idMethodModifiers = genUtils.createModifiers(Modifier.PUBLIC);
226                 MethodTree idGetter = genUtils.createPropertyGetterMethod(idMethodModifiers, idFieldName, typeTree);
227                 MethodTree idSetter = genUtils.createPropertySetterMethod(idMethodModifiers, idFieldName, typeTree);
228                 AnnotationTree idAnnotation = genUtils.createAnnotation("javax.persistence.Id"); //NO18N
229
ExpressionTree generationStrategy = genUtils.createAnnotationArgument("strategy", "javax.persistence.GenerationType", "AUTO"); //NO18N
230
AnnotationTree generatedValueAnnotation = genUtils.createAnnotation("javax.persistence.GeneratedValue", Collections.singletonList(generationStrategy)); //NO18N
231

232                 if (isAccessProperty){
233                     idField = genUtils.addAnnotation(idField, idAnnotation);
234                     idField = genUtils.addAnnotation(idField, generatedValueAnnotation);
235                 } else {
236                     idGetter = genUtils.addAnnotation(idGetter, idAnnotation);
237                     idGetter = genUtils.addAnnotation(idGetter, generatedValueAnnotation);
238                 }
239                 
240                 List JavaDoc<VariableTree> classFields = new ArrayList JavaDoc<VariableTree>();
241                 classFields.add(serialVersionUID);
242                 classFields.add(idField);
243                 modifiedClazz = genUtils.addClassFields(clazz, classFields);
244                 modifiedClazz = make.addClassMember(modifiedClazz, idSetter);
245                 modifiedClazz = make.addClassMember(modifiedClazz, idGetter);
246                 modifiedClazz = genUtils.addImplementsClause(modifiedClazz, "java.io.Serializable");
247                 modifiedClazz = genUtils.addAnnotation(modifiedClazz, genUtils.createAnnotation("javax.persistence.Entity"));
248                 workingCopy.rewrite(clazz, modifiedClazz);
249             }
250         };
251         
252         targetSource.runModificationTask(task).commit();
253         
254         return entityFo;
255     }
256     
257     /**
258      * A panel which checks whether the target project has a valid server set,
259      * otherwise it delegates to the real panel.
260      */

261     private static final class ValidatingPanel extends DelegatingWizardDescriptorPanel {
262         
263         public ValidatingPanel(WizardDescriptor.Panel delegate) {
264             super(delegate);
265         }
266         
267         public boolean isValid() {
268             if (!ProviderUtil.isValidServerInstanceOrNone(getProject())) {
269                 getWizardDescriptor().putProperty("WizardPanel_errorMessage",
270                         NbBundle.getMessage(EntityWizardDescriptor.class, "ERR_MissingServer")); // NOI18N
271
return false;
272             }
273             return super.isValid();
274         }
275     }
276 }
277
Popular Tags