KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > internal > junit > util > JUnitStubUtility


1 /*******************************************************************************
2  * Copyright (c) 2000, 2006 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11
12 package org.eclipse.jdt.internal.junit.util;
13
14 import org.eclipse.text.edits.MalformedTreeException;
15 import org.eclipse.text.edits.TextEdit;
16
17 import org.eclipse.core.runtime.CoreException;
18
19 import org.eclipse.jface.text.BadLocationException;
20 import org.eclipse.jface.text.Document;
21
22 import org.eclipse.jdt.core.Flags;
23 import org.eclipse.jdt.core.ICompilationUnit;
24 import org.eclipse.jdt.core.IJavaElement;
25 import org.eclipse.jdt.core.IJavaProject;
26 import org.eclipse.jdt.core.IMember;
27 import org.eclipse.jdt.core.IMethod;
28 import org.eclipse.jdt.core.IPackageFragment;
29 import org.eclipse.jdt.core.IType;
30 import org.eclipse.jdt.core.JavaCore;
31 import org.eclipse.jdt.core.JavaModelException;
32 import org.eclipse.jdt.core.Signature;
33 import org.eclipse.jdt.core.ToolFactory;
34 import org.eclipse.jdt.core.dom.AST;
35 import org.eclipse.jdt.core.dom.ASTParser;
36 import org.eclipse.jdt.core.dom.IBinding;
37 import org.eclipse.jdt.core.dom.IMethodBinding;
38 import org.eclipse.jdt.core.dom.ITypeBinding;
39 import org.eclipse.jdt.core.formatter.CodeFormatter;
40 import org.eclipse.jdt.core.formatter.IndentManipulation;
41
42 import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
43
44 import org.eclipse.jdt.ui.CodeGeneration;
45 import org.eclipse.jdt.ui.PreferenceConstants;
46 import org.eclipse.jdt.ui.wizards.NewTypeWizardPage.ImportsManager;
47
48 /**
49  * Utility methods for code generation.
50  * TODO: some methods are duplicated from org.eclipse.jdt.ui
51  */

52 public class JUnitStubUtility {
53     
54     public static GenStubSettings getCodeGenerationSettings(IJavaProject project) {
55         return new GenStubSettings(project);
56     }
57
58     public static class GenStubSettings {
59         public boolean callSuper;
60         public boolean methodOverwrites;
61         public boolean noBody;
62         
63         public boolean createComments;
64         public boolean useKeywordThis;
65                     
66         public final int tabWidth;
67         
68         public GenStubSettings(IJavaProject project) {
69             this.createComments= Boolean.valueOf(PreferenceConstants.getPreference(PreferenceConstants.CODEGEN_ADD_COMMENTS, project)).booleanValue();
70             this.useKeywordThis= Boolean.valueOf(PreferenceConstants.getPreference(PreferenceConstants.CODEGEN_KEYWORD_THIS, project)).booleanValue();
71             this.tabWidth= IndentManipulation.getTabWidth(project.getOptions(true));
72         }
73     }
74
75     public static String JavaDoc formatCompilationUnit(IJavaProject project, String JavaDoc sourceString, String JavaDoc lineDelim) {
76         return codeFormat(project, sourceString, CodeFormatter.K_COMPILATION_UNIT, 0, lineDelim);
77     }
78     
79     
80     public static String JavaDoc codeFormat(IJavaProject project, String JavaDoc sourceString, int kind, int initialIndentationLevel, String JavaDoc lineDelim) {
81         CodeFormatter formatter= ToolFactory.createCodeFormatter(project.getOptions(true));
82         TextEdit edit= formatter.format(kind, sourceString, 0, sourceString.length(), initialIndentationLevel, lineDelim);
83         if (edit != null) {
84             Document doc= new Document(sourceString);
85             try {
86                 edit.apply(doc);
87                 return doc.get();
88             } catch (MalformedTreeException e) {
89             } catch (BadLocationException e) {
90             }
91         }
92         return sourceString;
93     }
94
95     /**
96      * Generates a stub. Given a template method, a stub with the same signature
97      * will be constructed so it can be added to a type.
98      * @param destTypeName The name of the type to which the method will be added to (Used for the constructor)
99      * @param method A method template (method belongs to different type than the parent)
100      * @param settings Options as defined above (GENSTUB_*)
101      * @param imports Imports required by the sub are added to the imports structure
102      * @return The ynformatted stub
103      * @throws JavaModelException
104      */

105     public static String JavaDoc genStub(ICompilationUnit compilationUnit, String JavaDoc destTypeName, IMethod method, GenStubSettings settings, String JavaDoc extraAnnotations, ImportsManager imports) throws CoreException {
106         IType declaringtype= method.getDeclaringType();
107         StringBuffer JavaDoc buf= new StringBuffer JavaDoc();
108         String JavaDoc[] paramTypes= method.getParameterTypes();
109         String JavaDoc[] paramNames= method.getParameterNames();
110         String JavaDoc[] excTypes= method.getExceptionTypes();
111         String JavaDoc retTypeSig= method.getReturnType();
112         
113         int lastParam= paramTypes.length -1;
114         
115         String JavaDoc comment= null;
116         if (settings.createComments) {
117             if (method.isConstructor()) {
118                 comment= CodeGeneration.getMethodComment(compilationUnit, destTypeName, method.getElementName(), paramNames, excTypes, null, null, "\n"); //$NON-NLS-1$
119
} else {
120                 if (settings.methodOverwrites) {
121                     comment= CodeGeneration.getMethodComment(compilationUnit, destTypeName, method.getElementName(), paramNames, excTypes, retTypeSig, method, "\n"); //$NON-NLS-1$
122
} else {
123                     comment= CodeGeneration.getMethodComment(compilationUnit, destTypeName, method.getElementName(), paramNames, excTypes, retTypeSig, null, "\n"); //$NON-NLS-1$
124
}
125             }
126         }
127         if (comment != null) {
128             buf.append(comment).append('\n');
129         }
130         if (extraAnnotations != null) {
131             buf.append(extraAnnotations).append('\n');
132         }
133         
134         int flags= method.getFlags();
135         if (Flags.isPublic(flags) || (declaringtype.isInterface() && !settings.noBody)) {
136             buf.append("public "); //$NON-NLS-1$
137
} else if (Flags.isProtected(flags)) {
138             buf.append("protected "); //$NON-NLS-1$
139
} else if (Flags.isPrivate(flags)) {
140             buf.append("private "); //$NON-NLS-1$
141
}
142         if (Flags.isSynchronized(flags)) {
143             buf.append("synchronized "); //$NON-NLS-1$
144
}
145         if (Flags.isVolatile(flags)) {
146             buf.append("volatile "); //$NON-NLS-1$
147
}
148         if (Flags.isStrictfp(flags)) {
149             buf.append("strictfp "); //$NON-NLS-1$
150
}
151         if (Flags.isStatic(flags)) {
152             buf.append("static "); //$NON-NLS-1$
153
}
154             
155         if (method.isConstructor()) {
156             buf.append(destTypeName);
157         } else {
158             String JavaDoc retTypeFrm= Signature.toString(retTypeSig);
159             if (!isBuiltInType(retTypeSig)) {
160                 resolveAndAdd(retTypeSig, declaringtype, imports);
161             }
162             buf.append(Signature.getSimpleName(retTypeFrm));
163             buf.append(' ');
164             buf.append(method.getElementName());
165         }
166         buf.append('(');
167         for (int i= 0; i <= lastParam; i++) {
168             String JavaDoc paramTypeSig= paramTypes[i];
169             String JavaDoc paramTypeFrm= Signature.toString(paramTypeSig);
170             if (!isBuiltInType(paramTypeSig)) {
171                 resolveAndAdd(paramTypeSig, declaringtype, imports);
172             }
173             buf.append(Signature.getSimpleName(paramTypeFrm));
174             buf.append(' ');
175             buf.append(paramNames[i]);
176             if (i < lastParam) {
177                 buf.append(", "); //$NON-NLS-1$
178
}
179         }
180         buf.append(')');
181         
182         int lastExc= excTypes.length - 1;
183         if (lastExc >= 0) {
184             buf.append(" throws "); //$NON-NLS-1$
185
for (int i= 0; i <= lastExc; i++) {
186                 String JavaDoc excTypeSig= excTypes[i];
187                 String JavaDoc excTypeFrm= Signature.toString(excTypeSig);
188                 resolveAndAdd(excTypeSig, declaringtype, imports);
189                 buf.append(Signature.getSimpleName(excTypeFrm));
190                 if (i < lastExc) {
191                     buf.append(", "); //$NON-NLS-1$
192
}
193             }
194         }
195         if (settings.noBody) {
196             buf.append(";\n\n"); //$NON-NLS-1$
197
} else {
198             buf.append(" {\n\t"); //$NON-NLS-1$
199
if (!settings.callSuper) {
200                 if (retTypeSig != null && !retTypeSig.equals(Signature.SIG_VOID)) {
201                     buf.append('\t');
202                     if (!isBuiltInType(retTypeSig) || Signature.getArrayCount(retTypeSig) > 0) {
203                         buf.append("return null;\n\t"); //$NON-NLS-1$
204
} else if (retTypeSig.equals(Signature.SIG_BOOLEAN)) {
205                         buf.append("return false;\n\t"); //$NON-NLS-1$
206
} else {
207                         buf.append("return 0;\n\t"); //$NON-NLS-1$
208
}
209                 }
210             } else {
211                 buf.append('\t');
212                 if (!method.isConstructor()) {
213                     if (!Signature.SIG_VOID.equals(retTypeSig)) {
214                         buf.append("return "); //$NON-NLS-1$
215
}
216                     buf.append("super."); //$NON-NLS-1$
217
buf.append(method.getElementName());
218                 } else {
219                     buf.append("super"); //$NON-NLS-1$
220
}
221                 buf.append('(');
222                 for (int i= 0; i <= lastParam; i++) {
223                     buf.append(paramNames[i]);
224                     if (i < lastParam) {
225                         buf.append(", "); //$NON-NLS-1$
226
}
227                 }
228                 buf.append(");\n\t"); //$NON-NLS-1$
229
}
230             buf.append("}\n\n"); //$NON-NLS-1$
231
}
232         return buf.toString();
233     }
234     
235     private static boolean isBuiltInType(String JavaDoc typeName) {
236         char first= Signature.getElementType(typeName).charAt(0);
237         return (first != Signature.C_RESOLVED && first != Signature.C_UNRESOLVED);
238     }
239
240     private static void resolveAndAdd(String JavaDoc refTypeSig, IType declaringType, ImportsManager imports) throws JavaModelException {
241         String JavaDoc resolvedTypeName= JavaModelUtil.getResolvedTypeName(refTypeSig, declaringType);
242         if (resolvedTypeName != null) {
243             imports.addImport(resolvedTypeName);
244         }
245     }
246     
247     public static String JavaDoc getTodoTaskTag(IJavaProject project) {
248         String JavaDoc markers= null;
249         if (project == null) {
250             markers= JavaCore.getOption(JavaCore.COMPILER_TASK_TAGS);
251         } else {
252             markers= project.getOption(JavaCore.COMPILER_TASK_TAGS, true);
253         }
254         
255         if (markers != null && markers.length() > 0) {
256             int idx= markers.indexOf(',');
257             if (idx == -1) {
258                 return markers;
259             }
260             return markers.substring(0, idx);
261         }
262         return null;
263     }
264
265     /*
266      * Evaluates if a member (possible from another package) is visible from
267      * elements in a package.
268      */

269     public static boolean isVisible(IMember member, IPackageFragment pack) throws JavaModelException {
270         
271         int type= member.getElementType();
272         if (type == IJavaElement.INITIALIZER || (type == IJavaElement.METHOD && member.getElementName().startsWith("<"))) { //$NON-NLS-1$
273
return false;
274         }
275         
276         int otherflags= member.getFlags();
277         IType declaringType= member.getDeclaringType();
278         if (Flags.isPublic(otherflags) || (declaringType != null && declaringType.isInterface())) {
279             return true;
280         } else if (Flags.isPrivate(otherflags)) {
281             return false;
282         }
283         
284         IPackageFragment otherpack= (IPackageFragment) member.getAncestor(IJavaElement.PACKAGE_FRAGMENT);
285         return (pack != null && otherpack != null && pack.getElementName().equals(otherpack.getElementName()));
286     }
287     
288     private static boolean isVersionLessThan(String JavaDoc version1, String JavaDoc version2) {
289         return version1.compareTo(version2) < 0;
290     }
291     
292     public static boolean is50OrHigher(IJavaProject project) {
293         return !isVersionLessThan(project.getOption(JavaCore.COMPILER_COMPLIANCE, true), JavaCore.VERSION_1_5);
294     }
295     
296     public static String JavaDoc[] getParameterTypeNamesForSeeTag(IMethod overridden) {
297         try {
298             ASTParser parser= ASTParser.newParser(AST.JLS3);
299             parser.setProject(overridden.getJavaProject());
300             IBinding[] bindings= parser.createBindings(new IJavaElement[] { overridden }, null);
301             if (bindings.length == 1 && bindings[0] instanceof IMethodBinding) {
302                 return getParameterTypeNamesForSeeTag((IMethodBinding) bindings[0]);
303             }
304         } catch (IllegalStateException JavaDoc e) {
305             // method does not exist
306
}
307         // fall back code. Not good for generic methods!
308
String JavaDoc[] paramTypes= overridden.getParameterTypes();
309         String JavaDoc[] paramTypeNames= new String JavaDoc[paramTypes.length];
310         for (int i= 0; i < paramTypes.length; i++) {
311             paramTypeNames[i]= Signature.toString(Signature.getTypeErasure(paramTypes[i]));
312         }
313         return paramTypeNames;
314     }
315     
316     private static String JavaDoc[] getParameterTypeNamesForSeeTag(IMethodBinding binding) {
317         ITypeBinding[] typeBindings= binding.getParameterTypes();
318         String JavaDoc[] result= new String JavaDoc[typeBindings.length];
319         for (int i= 0; i < result.length; i++) {
320             ITypeBinding curr= typeBindings[i];
321             if (curr.isTypeVariable()) {
322                 curr= curr.getErasure(); // in Javadoc only use type variable erasure
323
}
324             curr= curr.getTypeDeclaration(); // no parameterized types
325
result[i]= curr.getQualifiedName();
326         }
327         return result;
328     }
329
330     
331 }
332
Popular Tags