KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > j2ee > ejbcore > _RetoucheUtil


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.ejbcore;
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.ModifiersTree;
26 import com.sun.source.tree.VariableTree;
27 import java.io.IOException JavaDoc;
28 import java.util.ArrayList JavaDoc;
29 import java.util.HashSet JavaDoc;
30 import java.util.List JavaDoc;
31 import java.util.Map JavaDoc;
32 import java.util.Set JavaDoc;
33 import javax.lang.model.element.Element;
34 import javax.lang.model.element.ElementKind;
35 import javax.lang.model.element.ExecutableElement;
36 import javax.lang.model.element.Modifier;
37 import javax.lang.model.element.TypeElement;
38 import javax.lang.model.type.ArrayType;
39 import javax.lang.model.type.TypeKind;
40 import javax.lang.model.type.TypeMirror;
41 import org.netbeans.api.java.source.CompilationController;
42 import org.netbeans.api.java.source.ElementHandle;
43 import org.netbeans.api.java.source.JavaSource;
44 import org.netbeans.api.java.source.TreeMaker;
45 import org.netbeans.api.java.source.WorkingCopy;
46 import org.netbeans.modules.j2ee.common.source.AbstractTask;
47 import org.netbeans.modules.j2ee.common.source.GenerationUtils;
48 import org.netbeans.modules.j2ee.common.source.SourceUtils;
49 import org.openide.filesystems.FileObject;
50 import org.openide.nodes.Node;
51 import org.openide.util.Parameters;
52
53 /**
54  *
55  * @author Martin Adamek
56  */

57 public final class _RetoucheUtil {
58     
59     private _RetoucheUtil() {}
60     
61     /** never call this from javac task */
62     public static String JavaDoc getMainClassName(final FileObject classFO) throws IOException JavaDoc {
63         JavaSource javaSource = JavaSource.forFileObject(classFO);
64         final String JavaDoc[] result = new String JavaDoc[1];
65         javaSource.runUserActionTask(new AbstractTask<CompilationController>() {
66             public void run(CompilationController controller) throws IOException JavaDoc {
67                 controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
68                 SourceUtils sourceUtils = SourceUtils.newInstance(controller);
69                 if (sourceUtils != null) {
70                     result[0] = sourceUtils.getTypeElement().getQualifiedName().toString();
71                 }
72             }
73         }, true);
74         return result[0];
75     }
76
77     /**
78      * @return true if the given <code>javaClass</code> contains a feature
79      * whose name is identical with the given <code>feature</code>'s name.
80      */

81     public static boolean containsFeature(TypeElement javaClass, Element searchedElement) {
82         for (Element element : javaClass.getEnclosedElements()) {
83             if (searchedElement.getSimpleName().equals(element.getSimpleName())) {
84                 return true;
85             }
86         }
87         return false;
88     }
89
90     @SuppressWarnings JavaDoc("unchecked")
91     private static ElementHandle<TypeElement> getElementHandle(ElementHandle elementHandle) {
92         if (elementHandle != null && ElementKind.CLASS == elementHandle.getKind()) {
93             return (ElementHandle<TypeElement>) elementHandle;
94         }
95         return null;
96     }
97     
98     public static ElementHandle<TypeElement> getJavaClassFromNode(Node node) throws IOException JavaDoc {
99         ElementHandle<TypeElement> elementHandle = getElementHandle(node.getLookup().lookup(ElementHandle.class));
100         if (elementHandle != null) {
101             return elementHandle;
102         }
103         //TODO: RETOUCHE TypeElement from Node, this one just takes main TypeElement if ElementHandle is not found
104
FileObject fileObject = node.getLookup().lookup(FileObject.class);
105         if (fileObject == null) {
106             return null;
107         }
108         JavaSource javaSource = JavaSource.forFileObject(fileObject);
109         if (javaSource == null) {
110             return null;
111         }
112         final List JavaDoc<ElementHandle<TypeElement>> result = new ArrayList JavaDoc<ElementHandle<TypeElement>>();
113         javaSource.runUserActionTask(new AbstractTask<CompilationController>() {
114             public void run(CompilationController controller) throws IOException JavaDoc {
115                 controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
116                 SourceUtils sourceUtils = SourceUtils.newInstance(controller);
117                 if (sourceUtils != null) {
118                     TypeElement typeElement = sourceUtils.getTypeElement();
119                     result.add(ElementHandle.create(typeElement));
120                 }
121             }
122         }, true);
123         if (result.size() > 0) {
124             return result.get(0);
125         }
126         return null;
127     }
128
129     public static ExecutableElement getMethodFromNode(Node node) {
130         //TODO: RETOUCHE ExecutableElement from Node
131
return null;
132     }
133     
134     public static void generateAnnotatedField(FileObject fileObject, final String JavaDoc className, final String JavaDoc annotationType,
135             final String JavaDoc name, final String JavaDoc fieldType, final Map JavaDoc<String JavaDoc, String JavaDoc> attributes, final boolean isStatic) throws IOException JavaDoc {
136         JavaSource javaSource = JavaSource.forFileObject(fileObject);
137         javaSource.runModificationTask(new AbstractTask<WorkingCopy>() {
138             public void run(WorkingCopy workingCopy) throws IOException JavaDoc {
139                 workingCopy.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
140                 TypeElement typeElement = workingCopy.getElements().getTypeElement(className);
141                 TreeMaker treeMaker = workingCopy.getTreeMaker();
142                 GenerationUtils generationUtils = GenerationUtils.newInstance(workingCopy, typeElement);
143                 TypeElement returnTypeElement = workingCopy.getElements().getTypeElement(fieldType);
144                 // modifiers
145
Set JavaDoc<Modifier> modifiers = new HashSet JavaDoc<Modifier>();
146                 modifiers.add(Modifier.PRIVATE);
147                 if (isStatic) {
148                     modifiers.add(Modifier.STATIC);
149                 }
150                 // annotation woth attributes
151
List JavaDoc<ExpressionTree> attributesList = new ArrayList JavaDoc<ExpressionTree>();
152                 for (Map.Entry JavaDoc<String JavaDoc, String JavaDoc> entry : attributes.entrySet()) {
153                     ExpressionTree attributeTree = generationUtils.createAnnotationArgument(entry.getKey(), entry.getValue());
154                     attributesList.add(attributeTree);
155                 }
156                 AnnotationTree annotationTree = generationUtils.createAnnotation(annotationType, attributesList);
157                 ModifiersTree modifiersTree = treeMaker.addModifiersAnnotation(treeMaker.Modifiers(modifiers), annotationTree);
158                 // field itself
159
VariableTree variableTree = treeMaker.Variable(
160                         modifiersTree,
161                         name,
162                         treeMaker.QualIdent(returnTypeElement),
163                         null
164                         );
165                 // adding field to class
166
ClassTree classTree = workingCopy.getTrees().getTree(typeElement);
167                 ClassTree newClassTree = treeMaker.addClassMember(classTree, variableTree);
168                 workingCopy.rewrite(classTree, newClassTree);
169             }
170         }).commit();
171     }
172
173     public static boolean isInterface(FileObject fileObject, final ElementHandle<TypeElement> elementHandle) throws IOException JavaDoc {
174         final boolean[] isInterface = new boolean[1];
175         JavaSource javaSource = JavaSource.forFileObject(fileObject);
176         if (javaSource == null || elementHandle == null) {
177             return false;
178         }
179         javaSource.runUserActionTask(new AbstractTask<CompilationController>() {
180             public void run(CompilationController controller) throws IOException JavaDoc {
181                 controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
182                 TypeElement typeElement = elementHandle.resolve(controller);
183                 isInterface[0] = ElementKind.INTERFACE == typeElement.getKind();
184             }
185         }, true);
186         return isInterface[0];
187     }
188
189     /**
190      * Generates unique member name in class-scope
191      * @param javaClass scope for uniqueness
192      * @param memberName suggested member name
193      * @param defaultValue default value applied if member name cannot be converted to legal Java identifier
194      * @return given member name if no such member exists or given member name without any illegal characters extended with unique number
195      */

196     public static String JavaDoc uniqueMemberName(FileObject fileObject, final String JavaDoc className, final String JavaDoc memberName, final String JavaDoc defaultValue) throws IOException JavaDoc{
197         JavaSource javaSource = JavaSource.forFileObject(fileObject);
198         final String JavaDoc[] result = new String JavaDoc[1];
199         javaSource.runUserActionTask(new AbstractTask<CompilationController>() {
200             public void run(CompilationController controller) throws IOException JavaDoc {
201                 controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
202                 String JavaDoc newName = convertToJavaIdentifier(memberName, defaultValue);
203                 List JavaDoc<String JavaDoc> existingMethodNames = new ArrayList JavaDoc<String JavaDoc>();
204                 TypeElement typeElement = controller.getElements().getTypeElement(className);
205                 for (Element element : typeElement.getEnclosedElements()) {
206                     existingMethodNames.add(element.getSimpleName().toString());
207                 }
208                 int uniquefier = 1;
209                 while (existingMethodNames.contains(newName)){
210                     newName = memberName + uniquefier++;
211                 }
212                 result[0] = newName;
213             }
214         }, true);
215         return result[0];
216     }
217     
218     private static String JavaDoc convertToJavaIdentifier(String JavaDoc name, String JavaDoc defaultValue) {
219         Parameters.notWhitespace("name", name);
220         Parameters.notWhitespace("defaultValue", defaultValue);
221         String JavaDoc str = name;
222         while (str.length() > 0 && !Character.isJavaIdentifierStart(str.charAt(0))) {
223             str = str.substring(1);
224         }
225         StringBuilder JavaDoc result = new StringBuilder JavaDoc();
226         if (str.length() > 0) {
227             char firstChar = str.charAt(0);
228             firstChar = Character.toLowerCase(firstChar);
229             result.append(firstChar);
230             for (int i = 1; i < str.length(); i++) {
231                 char character = str.charAt(i);
232                 if (Character.isJavaIdentifierPart(character)) {
233                     result.append(character);
234                 }
235             }
236         } else {
237             result.append(defaultValue);
238         }
239         return result.toString();
240     }
241
242     /**
243      * Tries to find {@link FileObject} which contains class with given className.<br>
244      * This method will enter javac context for referenceFileObject to find class by its className,
245      * therefore don't call this method within other javac context.
246      *
247      * @param referenceFileObject helper file for entering javac context
248      * @param className fully-qualified class name to resolve file for
249      * @return resolved file or null if not found
250      */

251     public static FileObject resolveFileObjectForClass(FileObject referenceFileObject, final String JavaDoc className) throws IOException JavaDoc {
252         final FileObject[] result = new FileObject[1];
253         JavaSource javaSource = JavaSource.forFileObject(referenceFileObject);
254         javaSource.runUserActionTask(new AbstractTask<CompilationController>() {
255             public void run(CompilationController controller) {
256                 TypeElement typeElement = controller.getElements().getTypeElement(className);
257                 result[0] = org.netbeans.api.java.source.SourceUtils.getFile(typeElement, controller.getClasspathInfo());
258             }
259         }, true);
260         return result[0];
261     }
262     
263     //TODO: RETOUCHE move/reuse in SourceUtil, or best - get from java/source!
264
// package private only for unit test
265
// see #90968
266
public static String JavaDoc getTypeName(CompilationController controller, TypeMirror typeMirror) {
267         TypeKind typeKind = typeMirror.getKind();
268         switch (typeKind) {
269             case BOOLEAN : return "boolean"; // NOI18N
270
case BYTE : return "byte"; // NOI18N
271
case CHAR : return "char"; // NOI18N
272
case DOUBLE : return "double"; // NOI18N
273
case FLOAT : return "float"; // NOI18N
274
case INT : return "int"; // NOI18N
275
case LONG : return "long"; // NOI18N
276
case SHORT : return "short"; // NOI18N
277
case VOID : return "void"; // NOI18N
278
case DECLARED :
279                 Element element = controller.getTypes().asElement(typeMirror);
280                 return ((TypeElement) element).getQualifiedName().toString();
281             case ARRAY :
282                 ArrayType arrayType = (ArrayType) typeMirror;
283                 Element componentTypeElement = controller.getTypes().asElement(arrayType.getComponentType());
284                 return ((TypeElement) componentTypeElement).getQualifiedName().toString() + "[]";
285             case ERROR :
286             case EXECUTABLE :
287             case NONE :
288             case NULL :
289             case OTHER :
290             case PACKAGE :
291             case TYPEVAR :
292             case WILDCARD :
293             default:break;
294         }
295         return null;
296     }
297
298 }
299
Popular Tags