KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > websvc > core > AddWsOperationHelper


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.websvc.core;
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.PrimitiveTypeTree;
28 import com.sun.source.tree.Tree;
29 import com.sun.source.tree.Tree.Kind;
30 import com.sun.source.tree.VariableTree;
31 import java.io.IOException JavaDoc;
32 import java.util.ArrayList JavaDoc;
33 import java.util.Collection JavaDoc;
34 import java.util.Collections JavaDoc;
35 import java.util.List JavaDoc;
36 import java.util.Set JavaDoc;
37 import javax.lang.model.element.Element;
38 import javax.lang.model.element.ExecutableElement;
39 import javax.lang.model.element.Modifier;
40 import javax.lang.model.element.TypeElement;
41 import javax.lang.model.type.TypeKind;
42 import javax.lang.model.util.ElementFilter;
43 import org.netbeans.api.java.source.CancellableTask;
44 import org.netbeans.api.java.source.Comment;
45 import org.netbeans.api.java.source.Comment.Style;
46 import org.netbeans.api.java.source.CompilationController;
47 import org.netbeans.api.java.source.JavaSource;
48 import org.netbeans.api.java.source.TreeMaker;
49 import org.netbeans.modules.j2ee.common.method.MethodModelSupport;
50 import org.netbeans.modules.j2ee.common.source.GenerationUtils;
51 import org.netbeans.modules.j2ee.common.source.SourceUtils;
52 import org.openide.util.NbBundle;
53 import static org.netbeans.api.java.source.JavaSource.Phase;
54 import org.netbeans.api.java.source.WorkingCopy;
55 import org.netbeans.api.progress.ProgressHandle;
56 import org.netbeans.api.progress.ProgressHandleFactory;
57 import org.netbeans.modules.j2ee.api.ejbjar.EjbJar;
58 import org.netbeans.modules.j2ee.common.method.MethodCustomizer;
59 import org.netbeans.modules.j2ee.common.method.MethodCustomizerFactory;
60 import org.netbeans.modules.j2ee.common.method.MethodModel;
61 import org.openide.ErrorManager;
62 import org.openide.filesystems.FileObject;
63
64 /**
65  * Helper for adding WS Operation to Web Service.
66  * @author Milan Kuchtiak
67  */

68 public class AddWsOperationHelper {
69     
70     private final String JavaDoc name;
71     
72     public AddWsOperationHelper(String JavaDoc name) {
73         this.name = name;
74     }
75     
76     protected MethodModel getPrototypeMethod() {
77         return MethodModel.create(
78                 "operation", //NOI18N
79
"java.lang.String", //NOI18N
80
"",
81                 Collections.<MethodModel.Variable>emptyList(),
82                 Collections.<String JavaDoc>emptyList(),
83                 Collections.<Modifier>emptySet()
84                 );
85     }
86     
87     public String JavaDoc getTitle() {
88         return name;
89     }
90     
91     protected MethodCustomizer createDialog(FileObject fileObject, MethodModel methodModel) throws IOException JavaDoc {
92         
93         return MethodCustomizerFactory.operationMethod (
94                 getTitle(),
95                 methodModel,
96                 getExistingMethods(fileObject));
97     }
98
99     public void addMethod(FileObject fileObject, String JavaDoc className) throws IOException JavaDoc {
100         if (className == null) {
101             return;
102         }
103         MethodModel methodModel = getPrototypeMethod();
104         MethodCustomizer methodCustomizer = createDialog(fileObject, methodModel);
105         if (methodCustomizer.customizeMethod()) {
106             try {
107                 
108                 MethodModel method = methodCustomizer.getMethodModel();
109                 okButtonPressed(method, fileObject, className);
110             } catch (IOException JavaDoc ioe) {
111                 ErrorManager.getDefault().notify(ioe);
112             }
113         }
114     }
115     
116     protected void okButtonPressed(MethodModel method, FileObject implClassFo, String JavaDoc className) throws IOException JavaDoc {
117         ProgressHandle handle = ProgressHandleFactory.createHandle("Adding operation");
118         try {
119             handle.start(100);
120                 addOperation(method, implClassFo, handle);
121         } finally {
122             handle.finish();
123         }
124     }
125
126     protected FileObject getDDFile(FileObject fileObject) {
127         return EjbJar.getEjbJar(fileObject).getDeploymentDescriptor();
128     }
129     
130     /*
131      * Adds a method definition to the the implementation class
132      */

133     private void addOperation(final MethodModel methodModel, FileObject implClassFo, final ProgressHandle handle ) {
134         JavaSource targetSource = JavaSource.forFileObject(implClassFo);
135         handle.progress(10);
136         CancellableTask<WorkingCopy> modificationTask = new CancellableTask<WorkingCopy>() {
137             public void run(WorkingCopy workingCopy) throws IOException JavaDoc {
138                 workingCopy.toPhase(Phase.RESOLVED);
139                 MethodTree method = MethodModelSupport.createMethodTree(workingCopy, methodModel);
140                 if (method!=null) {
141                     TreeMaker make = workingCopy.getTreeMaker();
142                     GenerationUtils genUtils = GenerationUtils.newInstance(workingCopy);
143                     if (genUtils!=null) {
144                         handle.progress(20);
145                         ClassTree javaClass = genUtils.getClassTree();
146                         TypeElement webMethodAn = workingCopy.getElements().getTypeElement("javax.jws.WebMethod"); //NOI18N
147
TypeElement webParamAn = workingCopy.getElements().getTypeElement("javax.jws.WebParam"); //NOI18N
148

149                         AnnotationTree webMethodAnnotation = make.Annotation(
150                             make.QualIdent(webMethodAn),
151                             Collections.<ExpressionTree>emptyList()
152                         );
153                         // Public modifier
154
ModifiersTree publicModifier = make.Modifiers(
155                             Collections.<Modifier>singleton(Modifier.PUBLIC),
156                             Collections.<AnnotationTree>emptyList()
157                         );
158                         // add @WebMethod annotation
159
ModifiersTree modifiersTree = make.addModifiersAnnotation(publicModifier, webMethodAnnotation);
160                         
161                         handle.progress(40);
162                         // add @Oneway annotation
163
if (Kind.PRIMITIVE_TYPE == method.getReturnType().getKind()) {
164                             PrimitiveTypeTree primitiveType = (PrimitiveTypeTree)method.getReturnType();
165                             if (TypeKind.VOID == primitiveType.getPrimitiveTypeKind()) {
166                                 TypeElement oneWayAn = workingCopy.getElements().getTypeElement("javax.jws.Oneway"); //NOI18N
167
AnnotationTree oneWayAnnotation = make.Annotation(
168                                     make.QualIdent(oneWayAn),
169                                     Collections.<ExpressionTree>emptyList()
170                                 );
171                                 modifiersTree = make.addModifiersAnnotation(modifiersTree, oneWayAnnotation);
172                             }
173                         }
174
175                         // add @WebParam annotations
176
List JavaDoc<? extends VariableTree> parameters = method.getParameters();
177                         List JavaDoc<VariableTree> newParameters = new ArrayList JavaDoc<VariableTree>();
178                         for (VariableTree param:parameters) {
179                             AnnotationTree paramAnnotation = make.Annotation(
180                                 make.QualIdent(webParamAn),
181                                 Collections.<ExpressionTree>singletonList(
182                                     make.Assignment(make.Identifier("name"), make.Literal(param.getName().toString()))) //NOI18N
183
);
184                             newParameters.add(genUtils.addAnnotation(param, paramAnnotation));
185                         }
186                         
187                         handle.progress(70);
188                         // create new (annotated) method
189
MethodTree annotatedMethod = make.Method(
190                                     modifiersTree,
191                                     method.getName(),
192                                     method.getReturnType(),
193                                     method.getTypeParameters(),
194                                     newParameters,
195                                     method.getThrows(),
196                                     getMethodBody(method.getReturnType()), //NOI18N
197
(ExpressionTree)method.getDefaultValue());
198                         Comment comment = Comment.create(Style.JAVADOC, 0,0,0,NbBundle.getMessage(AddWsOperationHelper.class, "TXT_WSOperation"));
199                         make.addComment(annotatedMethod, comment, true);
200                         
201                         handle.progress(90);
202                         ClassTree modifiedClass = make.addClassMember(javaClass,annotatedMethod);
203                         workingCopy.rewrite(javaClass, modifiedClass);
204                     }
205                 }
206             }
207             public void cancel() {}
208         };
209         try {
210             targetSource.runModificationTask(modificationTask).commit();
211         } catch (IOException JavaDoc ex) {
212             ErrorManager.getDefault().notify(ex);
213         }
214     }
215     
216     private String JavaDoc getMethodBody(Tree returnType) {
217         String JavaDoc body = null;
218         if (Kind.PRIMITIVE_TYPE == returnType.getKind()) {
219             TypeKind type = ((PrimitiveTypeTree)returnType).getPrimitiveTypeKind();
220             if (TypeKind.VOID == type) body = ""; //NOI18N
221
else if (TypeKind.BOOLEAN == type) body = "return false;"; // NOI18N
222
else if (TypeKind.INT == type) body = "return 0;"; // NOI18N
223
else if (TypeKind.LONG == type) body = "return 0;"; // NOI18N
224
else if (TypeKind.FLOAT == type) body = "return 0.0;"; // NOI18N
225
else if (TypeKind.DOUBLE == type) body = "return 0.0;"; // NOI18N
226
else if (TypeKind.BYTE == type) body = "return 0;"; // NOI18N
227
else if (TypeKind.SHORT == type) body = "return 0;"; // NOI18N
228
else if (TypeKind.CHAR == type) body = "return ' ';"; // NOI18N
229
else body = "return null"; //NOI18N
230
} else
231             body = "return null"; //NOI18N
232
return "{\n"+NbBundle.getMessage(AddWsOperationHelper.class, "TXT_TodoComment")+"\n"+body+"\n}";
233     }
234     /*
235     protected static MethodsNode getMethodsNode() {
236         Node[] nodes = Utilities.actionsGlobalContext().lookup(new Lookup.Template<Node>(Node.class)).allInstances().toArray(new Node[0]);
237         if (nodes.length != 1) {
238             return null;
239         }
240         return nodes[0].getLookup().lookup(MethodsNode.class);
241     }
242     */

243     
244     private Collection JavaDoc<MethodModel> getExistingMethods(FileObject implClass) {
245         JavaSource javaSource = JavaSource.forFileObject(implClass);
246         final ResultHolder<MethodModel> result = new ResultHolder<MethodModel>();
247         if (javaSource!=null) {
248             CancellableTask<CompilationController> task = new CancellableTask<CompilationController>() {
249                 public void run(CompilationController controller) throws IOException JavaDoc {
250                     controller.toPhase(Phase.ELEMENTS_RESOLVED);
251                     SourceUtils srcUtils = SourceUtils.newInstance(controller);
252                     if (srcUtils!=null) {
253                         // find methods
254
List JavaDoc<ExecutableElement> allMethods = getMethods(controller, srcUtils.getTypeElement());
255                         Collection JavaDoc<MethodModel> wsOperations = new ArrayList JavaDoc<MethodModel>();
256                         boolean foundWebMethodAnnotation=false;
257                         for(ExecutableElement method:allMethods) {
258                             MethodModel methodModel = MethodModelSupport.createMethodModel(controller, method);
259                             wsOperations.add(methodModel);
260                         } // for
261
result.setResult(wsOperations);
262                     }
263                 }
264                 public void cancel() {}
265             };
266             try {
267                 javaSource.runUserActionTask(task, true);
268             } catch (IOException JavaDoc ex) {
269                 ErrorManager.getDefault().notify(ex);
270             }
271         }
272         return result.getResult();
273     }
274     
275     private List JavaDoc<ExecutableElement> getMethods(CompilationController controller, TypeElement classElement) throws IOException JavaDoc {
276         List JavaDoc<? extends Element> members = classElement.getEnclosedElements();
277         List JavaDoc<ExecutableElement> methods = ElementFilter.methodsIn(members);
278         List JavaDoc<ExecutableElement> publicMethods = new ArrayList JavaDoc<ExecutableElement>();
279         for (ExecutableElement method:methods) {
280             //Set<Modifier> modifiers = method.getModifiers();
281
//if (modifiers.contains(Modifier.PUBLIC)) {
282
publicMethods.add(method);
283             //}
284
}
285         return publicMethods;
286     }
287     
288     /** Holder class for result
289      */

290     private class ResultHolder<E> {
291         private Collection JavaDoc<E> result;
292         
293         public Collection JavaDoc<E> getResult() {
294             return result;
295         }
296         
297         public void setResult(Collection JavaDoc<E> result) {
298             this.result=result;
299         }
300     }
301 }
302
Popular Tags