KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > internal > corext > codemanipulation > StubUtility


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  * John Kaplan, johnkaplantech@gmail.com - 108071 [code templates] template for body of newly created class
11  *******************************************************************************/

12 package org.eclipse.jdt.internal.corext.codemanipulation;
13
14 import java.io.IOException JavaDoc;
15 import java.lang.reflect.Modifier JavaDoc;
16 import java.util.AbstractList JavaDoc;
17 import java.util.ArrayList JavaDoc;
18 import java.util.Arrays JavaDoc;
19 import java.util.Collection JavaDoc;
20 import java.util.Comparator JavaDoc;
21 import java.util.HashSet JavaDoc;
22 import java.util.LinkedHashSet JavaDoc;
23 import java.util.List JavaDoc;
24 import java.util.Set JavaDoc;
25 import java.util.StringTokenizer JavaDoc;
26
27 import org.eclipse.text.edits.DeleteEdit;
28 import org.eclipse.text.edits.MalformedTreeException;
29 import org.eclipse.text.edits.MultiTextEdit;
30
31 import org.eclipse.core.runtime.CoreException;
32 import org.eclipse.core.runtime.IStatus;
33 import org.eclipse.core.runtime.Platform;
34 import org.eclipse.core.runtime.Status;
35 import org.eclipse.core.runtime.preferences.IScopeContext;
36 import org.eclipse.core.runtime.preferences.InstanceScope;
37
38 import org.eclipse.core.resources.IProject;
39 import org.eclipse.core.resources.ProjectScope;
40
41 import org.eclipse.jface.text.BadLocationException;
42 import org.eclipse.jface.text.Document;
43 import org.eclipse.jface.text.IDocument;
44 import org.eclipse.jface.text.IRegion;
45 import org.eclipse.jface.text.templates.Template;
46 import org.eclipse.jface.text.templates.TemplateBuffer;
47 import org.eclipse.jface.text.templates.TemplateException;
48 import org.eclipse.jface.text.templates.TemplateVariable;
49 import org.eclipse.jface.text.templates.persistence.TemplatePersistenceData;
50 import org.eclipse.jface.text.templates.persistence.TemplateStore;
51
52 import org.eclipse.jdt.core.Flags;
53 import org.eclipse.jdt.core.IBuffer;
54 import org.eclipse.jdt.core.ICompilationUnit;
55 import org.eclipse.jdt.core.IJavaElement;
56 import org.eclipse.jdt.core.IJavaProject;
57 import org.eclipse.jdt.core.IMethod;
58 import org.eclipse.jdt.core.IOpenable;
59 import org.eclipse.jdt.core.IPackageFragment;
60 import org.eclipse.jdt.core.IParent;
61 import org.eclipse.jdt.core.ISourceReference;
62 import org.eclipse.jdt.core.IType;
63 import org.eclipse.jdt.core.ITypeParameter;
64 import org.eclipse.jdt.core.JavaConventions;
65 import org.eclipse.jdt.core.JavaCore;
66 import org.eclipse.jdt.core.JavaModelException;
67 import org.eclipse.jdt.core.NamingConventions;
68 import org.eclipse.jdt.core.Signature;
69 import org.eclipse.jdt.core.dom.AST;
70 import org.eclipse.jdt.core.dom.ASTNode;
71 import org.eclipse.jdt.core.dom.ASTParser;
72 import org.eclipse.jdt.core.dom.AbstractTypeDeclaration;
73 import org.eclipse.jdt.core.dom.ArrayType;
74 import org.eclipse.jdt.core.dom.CastExpression;
75 import org.eclipse.jdt.core.dom.ClassInstanceCreation;
76 import org.eclipse.jdt.core.dom.CompilationUnit;
77 import org.eclipse.jdt.core.dom.ConstructorInvocation;
78 import org.eclipse.jdt.core.dom.Expression;
79 import org.eclipse.jdt.core.dom.FieldAccess;
80 import org.eclipse.jdt.core.dom.IBinding;
81 import org.eclipse.jdt.core.dom.IMethodBinding;
82 import org.eclipse.jdt.core.dom.ITypeBinding;
83 import org.eclipse.jdt.core.dom.IVariableBinding;
84 import org.eclipse.jdt.core.dom.MethodDeclaration;
85 import org.eclipse.jdt.core.dom.MethodInvocation;
86 import org.eclipse.jdt.core.dom.Name;
87 import org.eclipse.jdt.core.dom.NumberLiteral;
88 import org.eclipse.jdt.core.dom.ParameterizedType;
89 import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
90 import org.eclipse.jdt.core.dom.StringLiteral;
91 import org.eclipse.jdt.core.dom.StructuralPropertyDescriptor;
92 import org.eclipse.jdt.core.dom.SuperConstructorInvocation;
93 import org.eclipse.jdt.core.dom.SuperMethodInvocation;
94 import org.eclipse.jdt.core.dom.Type;
95 import org.eclipse.jdt.core.dom.TypeParameter;
96 import org.eclipse.jdt.core.dom.rewrite.ImportRewrite;
97 import org.eclipse.jdt.core.formatter.IndentManipulation;
98
99 import org.eclipse.jdt.internal.corext.dom.ASTNodes;
100 import org.eclipse.jdt.internal.corext.dom.Bindings;
101 import org.eclipse.jdt.internal.corext.template.java.CodeTemplateContext;
102 import org.eclipse.jdt.internal.corext.template.java.CodeTemplateContextType;
103 import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
104 import org.eclipse.jdt.internal.corext.util.Strings;
105
106 import org.eclipse.jdt.ui.CodeStyleConfiguration;
107 import org.eclipse.jdt.ui.PreferenceConstants;
108
109 import org.eclipse.jdt.internal.ui.JavaPlugin;
110 import org.eclipse.jdt.internal.ui.JavaUIStatus;
111 import org.eclipse.jdt.internal.ui.text.correction.ASTResolving;
112 import org.eclipse.jdt.internal.ui.viewsupport.ProjectTemplateStore;
113
114 public class StubUtility {
115     
116     private static final String JavaDoc[] EMPTY= new String JavaDoc[0];
117     
118     private static final Set JavaDoc VALID_TYPE_BODY_TEMPLATES;
119     static {
120         VALID_TYPE_BODY_TEMPLATES= new HashSet JavaDoc();
121         VALID_TYPE_BODY_TEMPLATES.add(CodeTemplateContextType.CLASSBODY_ID);
122         VALID_TYPE_BODY_TEMPLATES.add(CodeTemplateContextType.INTERFACEBODY_ID);
123         VALID_TYPE_BODY_TEMPLATES.add(CodeTemplateContextType.ENUMBODY_ID);
124         VALID_TYPE_BODY_TEMPLATES.add(CodeTemplateContextType.ANNOTATIONBODY_ID);
125     }
126     
127     /*
128      * Don't use this method directly, use CodeGeneration.
129      */

130     public static String JavaDoc getMethodBodyContent(boolean isConstructor, IJavaProject project, String JavaDoc destTypeName, String JavaDoc methodName, String JavaDoc bodyStatement, String JavaDoc lineDelimiter) throws CoreException {
131         String JavaDoc templateName= isConstructor ? CodeTemplateContextType.CONSTRUCTORSTUB_ID : CodeTemplateContextType.METHODSTUB_ID;
132         Template template= getCodeTemplate(templateName, project);
133         if (template == null) {
134             return bodyStatement;
135         }
136         CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), project, lineDelimiter);
137         context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, methodName);
138         context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, destTypeName);
139         context.setVariable(CodeTemplateContextType.BODY_STATEMENT, bodyStatement);
140         String JavaDoc str= evaluateTemplate(context, template, new String JavaDoc[] { CodeTemplateContextType.BODY_STATEMENT });
141         if (str == null && !Strings.containsOnlyWhitespaces(bodyStatement)) {
142             return bodyStatement;
143         }
144         return str;
145     }
146     
147     /*
148      * Don't use this method directly, use CodeGeneration.
149      */

150     public static String JavaDoc getGetterMethodBodyContent(IJavaProject project, String JavaDoc destTypeName, String JavaDoc methodName, String JavaDoc fieldName, String JavaDoc lineDelimiter) throws CoreException {
151         String JavaDoc templateName= CodeTemplateContextType.GETTERSTUB_ID;
152         Template template= getCodeTemplate(templateName, project);
153         if (template == null) {
154             return null;
155         }
156         CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), project, lineDelimiter);
157         context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, methodName);
158         context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, destTypeName);
159         context.setVariable(CodeTemplateContextType.FIELD, fieldName);
160         
161         return evaluateTemplate(context, template);
162     }
163     
164     /*
165      * Don't use this method directly, use CodeGeneration.
166      */

167     public static String JavaDoc getSetterMethodBodyContent(IJavaProject project, String JavaDoc destTypeName, String JavaDoc methodName, String JavaDoc fieldName, String JavaDoc paramName, String JavaDoc lineDelimiter) throws CoreException {
168         String JavaDoc templateName= CodeTemplateContextType.SETTERSTUB_ID;
169         Template template= getCodeTemplate(templateName, project);
170         if (template == null) {
171             return null;
172         }
173         CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), project, lineDelimiter);
174         context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, methodName);
175         context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, destTypeName);
176         context.setVariable(CodeTemplateContextType.FIELD, fieldName);
177         context.setVariable(CodeTemplateContextType.FIELD_TYPE, fieldName);
178         context.setVariable(CodeTemplateContextType.PARAM, paramName);
179         
180         return evaluateTemplate(context, template);
181     }
182     
183     public static String JavaDoc getCatchBodyContent(ICompilationUnit cu, String JavaDoc exceptionType, String JavaDoc variableName, ASTNode locationInAST, String JavaDoc lineDelimiter) throws CoreException {
184         String JavaDoc enclosingType= ""; //$NON-NLS-1$
185
String JavaDoc enclosingMethod= ""; //$NON-NLS-1$
186

187         if (locationInAST != null) {
188             MethodDeclaration parentMethod= ASTResolving.findParentMethodDeclaration(locationInAST);
189             if (parentMethod != null) {
190                 enclosingMethod= parentMethod.getName().getIdentifier();
191                 locationInAST= parentMethod;
192             }
193             ASTNode parentType= ASTResolving.findParentType(locationInAST);
194             if (parentType instanceof AbstractTypeDeclaration) {
195                 enclosingType= ((AbstractTypeDeclaration) parentType).getName().getIdentifier();
196             }
197         }
198         return getCatchBodyContent(cu, exceptionType, variableName, enclosingType, enclosingMethod, lineDelimiter);
199     }
200     
201     
202     public static String JavaDoc getCatchBodyContent(ICompilationUnit cu, String JavaDoc exceptionType, String JavaDoc variableName, String JavaDoc enclosingType, String JavaDoc enclosingMethod, String JavaDoc lineDelimiter) throws CoreException {
203         Template template= getCodeTemplate(CodeTemplateContextType.CATCHBLOCK_ID, cu.getJavaProject());
204         if (template == null) {
205             return null;
206         }
207
208         CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), cu.getJavaProject(), lineDelimiter);
209         context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, enclosingType);
210         context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, enclosingMethod);
211         context.setVariable(CodeTemplateContextType.EXCEPTION_TYPE, exceptionType);
212         context.setVariable(CodeTemplateContextType.EXCEPTION_VAR, variableName);
213         return evaluateTemplate(context, template);
214     }
215     
216     /*
217      * Don't use this method directly, use CodeGeneration.
218      * @see org.eclipse.jdt.ui.CodeGeneration#getCompilationUnitContent(ICompilationUnit, String, String, String, String)
219      */

220     public static String JavaDoc getCompilationUnitContent(ICompilationUnit cu, String JavaDoc fileComment, String JavaDoc typeComment, String JavaDoc typeContent, String JavaDoc lineDelimiter) throws CoreException {
221         IPackageFragment pack= (IPackageFragment) cu.getParent();
222         String JavaDoc packDecl= pack.isDefaultPackage() ? "" : "package " + pack.getElementName() + ';'; //$NON-NLS-1$ //$NON-NLS-2$
223
return getCompilationUnitContent(cu, packDecl, fileComment, typeComment, typeContent, lineDelimiter);
224     }
225     
226     public static String JavaDoc getCompilationUnitContent(ICompilationUnit cu, String JavaDoc packDecl, String JavaDoc fileComment, String JavaDoc typeComment, String JavaDoc typeContent, String JavaDoc lineDelimiter) throws CoreException {
227         Template template= getCodeTemplate(CodeTemplateContextType.NEWTYPE_ID, cu.getJavaProject());
228         if (template == null) {
229             return null;
230         }
231         
232         IJavaProject project= cu.getJavaProject();
233         CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), project, lineDelimiter);
234         context.setCompilationUnitVariables(cu);
235         context.setVariable(CodeTemplateContextType.PACKAGE_DECLARATION, packDecl);
236         context.setVariable(CodeTemplateContextType.TYPE_COMMENT, typeComment != null ? typeComment : ""); //$NON-NLS-1$
237
context.setVariable(CodeTemplateContextType.FILE_COMMENT, fileComment != null ? fileComment : ""); //$NON-NLS-1$
238
context.setVariable(CodeTemplateContextType.TYPE_DECLARATION, typeContent);
239         context.setVariable(CodeTemplateContextType.TYPENAME, JavaCore.removeJavaLikeExtension(cu.getElementName()));
240         
241         String JavaDoc[] fullLine= { CodeTemplateContextType.PACKAGE_DECLARATION, CodeTemplateContextType.FILE_COMMENT, CodeTemplateContextType.TYPE_COMMENT };
242         return evaluateTemplate(context, template, fullLine);
243     }
244     
245     
246     /*
247      * Don't use this method directly, use CodeGeneration.
248      * @see org.eclipse.jdt.ui.CodeGeneration#getFileComment(ICompilationUnit, String)
249      */

250     public static String JavaDoc getFileComment(ICompilationUnit cu, String JavaDoc lineDelimiter) throws CoreException {
251         Template template= getCodeTemplate(CodeTemplateContextType.FILECOMMENT_ID, cu.getJavaProject());
252         if (template == null) {
253             return null;
254         }
255         
256         IJavaProject project= cu.getJavaProject();
257         CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), project, lineDelimiter);
258         context.setCompilationUnitVariables(cu);
259         context.setVariable(CodeTemplateContextType.TYPENAME, JavaCore.removeJavaLikeExtension(cu.getElementName()));
260         return evaluateTemplate(context, template);
261     }
262
263     /*
264      * Don't use this method directly, use CodeGeneration.
265      * @see org.eclipse.jdt.ui.CodeGeneration#getTypeComment(ICompilationUnit, String, String[], String)
266      */

267     public static String JavaDoc getTypeComment(ICompilationUnit cu, String JavaDoc typeQualifiedName, String JavaDoc[] typeParameterNames, String JavaDoc lineDelim) throws CoreException {
268         Template template= getCodeTemplate(CodeTemplateContextType.TYPECOMMENT_ID, cu.getJavaProject());
269         if (template == null) {
270             return null;
271         }
272         CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), cu.getJavaProject(), lineDelim);
273         context.setCompilationUnitVariables(cu);
274         context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, Signature.getQualifier(typeQualifiedName));
275         context.setVariable(CodeTemplateContextType.TYPENAME, Signature.getSimpleName(typeQualifiedName));
276
277         TemplateBuffer buffer;
278         try {
279             buffer= context.evaluate(template);
280         } catch (BadLocationException e) {
281             throw new CoreException(Status.CANCEL_STATUS);
282         } catch (TemplateException e) {
283             throw new CoreException(Status.CANCEL_STATUS);
284         }
285         String JavaDoc str= buffer.getString();
286         if (Strings.containsOnlyWhitespaces(str)) {
287             return null;
288         }
289         
290         TemplateVariable position= findVariable(buffer, CodeTemplateContextType.TAGS); // look if Javadoc tags have to be added
291
if (position == null) {
292             return str;
293         }
294         
295         IDocument document= new Document(str);
296         int[] tagOffsets= position.getOffsets();
297         for (int i= tagOffsets.length - 1; i >= 0; i--) { // from last to first
298
try {
299                 insertTag(document, tagOffsets[i], position.getLength(), EMPTY, EMPTY, null, typeParameterNames, false, lineDelim);
300             } catch (BadLocationException e) {
301                 throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e));
302             }
303         }
304         return document.get();
305     }
306
307     /*
308      * Returns the parameters type names used in see tags. Currently, these are always fully qualified.
309      */

310     public static String JavaDoc[] getParameterTypeNamesForSeeTag(IMethodBinding binding) {
311         ITypeBinding[] typeBindings= binding.getParameterTypes();
312         String JavaDoc[] result= new String JavaDoc[typeBindings.length];
313         for (int i= 0; i < result.length; i++) {
314             ITypeBinding curr= typeBindings[i];
315             if (curr.isTypeVariable()) {
316                 curr= curr.getErasure(); // in Javadoc only use type variable erasure
317
}
318             curr= curr.getTypeDeclaration(); // no parameterized types
319
result[i]= curr.getQualifiedName();
320         }
321         return result;
322     }
323     
324     /*
325      * Returns the parameters type names used in see tags. Currently, these are always fully qualified.
326      */

327     private static String JavaDoc[] getParameterTypeNamesForSeeTag(IMethod overridden) {
328         try {
329             ASTParser parser= ASTParser.newParser(AST.JLS3);
330             parser.setProject(overridden.getJavaProject());
331             IBinding[] bindings= parser.createBindings(new IJavaElement[] { overridden }, null);
332             if (bindings.length == 1 && bindings[0] instanceof IMethodBinding) {
333                 return getParameterTypeNamesForSeeTag((IMethodBinding) bindings[0]);
334             }
335         } catch (IllegalStateException JavaDoc e) {
336             // method does not exist
337
}
338         // fall back code. Not good for generic methods!
339
String JavaDoc[] paramTypes= overridden.getParameterTypes();
340         String JavaDoc[] paramTypeNames= new String JavaDoc[paramTypes.length];
341         for (int i= 0; i < paramTypes.length; i++) {
342             paramTypeNames[i]= Signature.toString(Signature.getTypeErasure(paramTypes[i]));
343         }
344         return paramTypeNames;
345     }
346
347     private static String JavaDoc getSeeTag(String JavaDoc declaringClassQualifiedName, String JavaDoc methodName, String JavaDoc[] parameterTypesQualifiedNames) {
348         StringBuffer JavaDoc buf= new StringBuffer JavaDoc();
349         buf.append("@see "); //$NON-NLS-1$
350
buf.append(declaringClassQualifiedName);
351         buf.append('#');
352         buf.append(methodName);
353         buf.append('(');
354         for (int i= 0; i < parameterTypesQualifiedNames.length; i++) {
355             if (i > 0) {
356                 buf.append(", "); //$NON-NLS-1$
357
}
358             buf.append(parameterTypesQualifiedNames[i]);
359         }
360         buf.append(')');
361         return buf.toString();
362     }
363     
364     public static String JavaDoc[] getTypeParameterNames(ITypeParameter[] typeParameters) {
365         String JavaDoc[] typeParametersNames= new String JavaDoc[typeParameters.length];
366         for (int i= 0; i < typeParameters.length; i++) {
367             typeParametersNames[i]= typeParameters[i].getElementName();
368         }
369         return typeParametersNames;
370     }
371
372     /**
373      * Don't use this method directly, use CodeGeneration.
374      * @see org.eclipse.jdt.ui.CodeGeneration#getTypeBody(String, ICompilationUnit, String, String)
375      */

376     public static String JavaDoc getTypeBody(String JavaDoc templateID, ICompilationUnit cu, String JavaDoc typeName, String JavaDoc lineDelim) throws CoreException {
377         if ( !VALID_TYPE_BODY_TEMPLATES.contains(templateID)) {
378             throw new IllegalArgumentException JavaDoc("Invalid code template ID: " + templateID); //$NON-NLS-1$
379
}
380         
381         Template template= getCodeTemplate(templateID, cu.getJavaProject());
382         if (template == null) {
383             return null;
384         }
385         CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), cu.getJavaProject(), lineDelim);
386         context.setCompilationUnitVariables(cu);
387         context.setVariable(CodeTemplateContextType.TYPENAME, typeName);
388
389         return evaluateTemplate(context, template);
390     }
391     
392     /*
393      * Don't use this method directly, use CodeGeneration.
394      * @see org.eclipse.jdt.ui.CodeGeneration#getMethodComment(ICompilationUnit, String, String, String[], String[], String, String[], IMethod, String)
395      */

396     public static String JavaDoc getMethodComment(ICompilationUnit cu, String JavaDoc typeName, String JavaDoc methodName, String JavaDoc[] paramNames, String JavaDoc[] excTypeSig, String JavaDoc retTypeSig, String JavaDoc[] typeParameterNames, IMethod target, boolean delegate, String JavaDoc lineDelimiter) throws CoreException {
397         String JavaDoc templateName= CodeTemplateContextType.METHODCOMMENT_ID;
398         if (retTypeSig == null) {
399             templateName= CodeTemplateContextType.CONSTRUCTORCOMMENT_ID;
400         } else if (target != null) {
401             if (delegate)
402                 templateName= CodeTemplateContextType.DELEGATECOMMENT_ID;
403             else
404                 templateName= CodeTemplateContextType.OVERRIDECOMMENT_ID;
405         }
406         Template template= getCodeTemplate(templateName, cu.getJavaProject());
407         if (template == null) {
408             return null;
409         }
410         CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), cu.getJavaProject(), lineDelimiter);
411         context.setCompilationUnitVariables(cu);
412         context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, typeName);
413         context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, methodName);
414                 
415         if (retTypeSig != null) {
416             context.setVariable(CodeTemplateContextType.RETURN_TYPE, Signature.toString(retTypeSig));
417         }
418         if (target != null) {
419             String JavaDoc targetTypeName= target.getDeclaringType().getFullyQualifiedName('.');
420             String JavaDoc[] targetParamTypeNames= getParameterTypeNamesForSeeTag(target);
421             if (delegate)
422                 context.setVariable(CodeTemplateContextType.SEE_TO_TARGET_TAG, getSeeTag(targetTypeName, methodName, targetParamTypeNames));
423             else
424                 context.setVariable(CodeTemplateContextType.SEE_TO_OVERRIDDEN_TAG, getSeeTag(targetTypeName, methodName, targetParamTypeNames));
425         }
426         TemplateBuffer buffer;
427         try {
428             buffer= context.evaluate(template);
429         } catch (BadLocationException e) {
430             throw new CoreException(Status.CANCEL_STATUS);
431         } catch (TemplateException e) {
432             throw new CoreException(Status.CANCEL_STATUS);
433         }
434         if (buffer == null) {
435             return null;
436         }
437         
438         String JavaDoc str= buffer.getString();
439         if (Strings.containsOnlyWhitespaces(str)) {
440             return null;
441         }
442         TemplateVariable position= findVariable(buffer, CodeTemplateContextType.TAGS); // look if Javadoc tags have to be added
443
if (position == null) {
444             return str;
445         }
446             
447         IDocument document= new Document(str);
448         String JavaDoc[] exceptionNames= new String JavaDoc[excTypeSig.length];
449         for (int i= 0; i < excTypeSig.length; i++) {
450             exceptionNames[i]= Signature.toString(excTypeSig[i]);
451         }
452         String JavaDoc returnType= retTypeSig != null ? Signature.toString(retTypeSig) : null;
453         int[] tagOffsets= position.getOffsets();
454         for (int i= tagOffsets.length - 1; i >= 0; i--) { // from last to first
455
try {
456                 insertTag(document, tagOffsets[i], position.getLength(), paramNames, exceptionNames, returnType, typeParameterNames, false, lineDelimiter);
457             } catch (BadLocationException e) {
458                 throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e));
459             }
460         }
461         return document.get();
462     }
463     
464     // remove lines for empty variables
465
private static String JavaDoc fixEmptyVariables(TemplateBuffer buffer, String JavaDoc[] variables) throws MalformedTreeException, BadLocationException {
466         IDocument doc= new Document(buffer.getString());
467         int nLines= doc.getNumberOfLines();
468         MultiTextEdit edit= new MultiTextEdit();
469         HashSet JavaDoc removedLines= new HashSet JavaDoc();
470         for (int i= 0; i < variables.length; i++) {
471             TemplateVariable position= findVariable(buffer, variables[i]); // look if Javadoc tags have to be added
472
if (position == null || position.getLength() > 0) {
473                 continue;
474             }
475             int[] offsets= position.getOffsets();
476             for (int k= 0; k < offsets.length; k++) {
477                 int line= doc.getLineOfOffset(offsets[k]);
478                 IRegion lineInfo= doc.getLineInformation(line);
479                 int offset= lineInfo.getOffset();
480                 String JavaDoc str= doc.get(offset, lineInfo.getLength());
481                 if (Strings.containsOnlyWhitespaces(str) && nLines > line + 1 && removedLines.add(new Integer JavaDoc(line))) {
482                     int nextStart= doc.getLineOffset(line + 1);
483                     edit.addChild(new DeleteEdit(offset, nextStart - offset));
484                 }
485             }
486         }
487         edit.apply(doc, 0);
488         return doc.get();
489     }
490     
491     /*
492      * Don't use this method directly, use CodeGeneration.
493      */

494     public static String JavaDoc getFieldComment(ICompilationUnit cu, String JavaDoc typeName, String JavaDoc fieldName, String JavaDoc lineDelimiter) throws CoreException {
495         Template template= getCodeTemplate(CodeTemplateContextType.FIELDCOMMENT_ID, cu.getJavaProject());
496         if (template == null) {
497             return null;
498         }
499         CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), cu.getJavaProject(), lineDelimiter);
500         context.setCompilationUnitVariables(cu);
501         context.setVariable(CodeTemplateContextType.FIELD_TYPE, typeName);
502         context.setVariable(CodeTemplateContextType.FIELD, fieldName);
503         
504         return evaluateTemplate(context, template);
505     }
506     
507     
508     /*
509      * Don't use this method directly, use CodeGeneration.
510      * @see org.eclipse.jdt.ui.CodeGeneration#getSetterComment(ICompilationUnit, String, String, String, String, String, String, String)
511      */

512     public static String JavaDoc getSetterComment(ICompilationUnit cu, String JavaDoc typeName, String JavaDoc methodName, String JavaDoc fieldName, String JavaDoc fieldType, String JavaDoc paramName, String JavaDoc bareFieldName, String JavaDoc lineDelimiter) throws CoreException {
513         String JavaDoc templateName= CodeTemplateContextType.SETTERCOMMENT_ID;
514         Template template= getCodeTemplate(templateName, cu.getJavaProject());
515         if (template == null) {
516             return null;
517         }
518         
519         CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), cu.getJavaProject(), lineDelimiter);
520         context.setCompilationUnitVariables(cu);
521         context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, typeName);
522         context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, methodName);
523         context.setVariable(CodeTemplateContextType.FIELD, fieldName);
524         context.setVariable(CodeTemplateContextType.FIELD_TYPE, fieldType);
525         context.setVariable(CodeTemplateContextType.BARE_FIELD_NAME, bareFieldName);
526         context.setVariable(CodeTemplateContextType.PARAM, paramName);
527
528         return evaluateTemplate(context, template);
529     }
530     
531     /*
532      * Don't use this method directly, use CodeGeneration.
533      * @see org.eclipse.jdt.ui.CodeGeneration#getGetterComment(ICompilationUnit, String, String, String, String, String, String)
534      */

535     public static String JavaDoc getGetterComment(ICompilationUnit cu, String JavaDoc typeName, String JavaDoc methodName, String JavaDoc fieldName, String JavaDoc fieldType, String JavaDoc bareFieldName, String JavaDoc lineDelimiter) throws CoreException {
536         String JavaDoc templateName= CodeTemplateContextType.GETTERCOMMENT_ID;
537         Template template= getCodeTemplate(templateName, cu.getJavaProject());
538         if (template == null) {
539             return null;
540         }
541         CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), cu.getJavaProject(), lineDelimiter);
542         context.setCompilationUnitVariables(cu);
543         context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, typeName);
544         context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, methodName);
545         context.setVariable(CodeTemplateContextType.FIELD, fieldName);
546         context.setVariable(CodeTemplateContextType.FIELD_TYPE, fieldType);
547         context.setVariable(CodeTemplateContextType.BARE_FIELD_NAME, bareFieldName);
548
549         return evaluateTemplate(context, template);
550     }
551     
552     private static String JavaDoc evaluateTemplate(CodeTemplateContext context, Template template) throws CoreException {
553         TemplateBuffer buffer;
554         try {
555             buffer= context.evaluate(template);
556         } catch (BadLocationException e) {
557             throw new CoreException(Status.CANCEL_STATUS);
558         } catch (TemplateException e) {
559             throw new CoreException(Status.CANCEL_STATUS);
560         }
561         if (buffer == null)
562             return null;
563         String JavaDoc str= buffer.getString();
564         if (Strings.containsOnlyWhitespaces(str)) {
565             return null;
566         }
567         return str;
568     }
569     
570     private static String JavaDoc evaluateTemplate(CodeTemplateContext context, Template template, String JavaDoc[] fullLineVariables) throws CoreException {
571         TemplateBuffer buffer;
572         try {
573             buffer= context.evaluate(template);
574             if (buffer == null)
575                 return null;
576             String JavaDoc str= fixEmptyVariables(buffer, fullLineVariables);
577             if (Strings.containsOnlyWhitespaces(str)) {
578                 return null;
579             }
580             return str;
581         } catch (BadLocationException e) {
582             throw new CoreException(Status.CANCEL_STATUS);
583         } catch (TemplateException e) {
584             throw new CoreException(Status.CANCEL_STATUS);
585         }
586     }
587
588     
589     /*
590      * Don't use this method directly, use CodeGeneration.
591      * @see org.eclipse.jdt.ui.CodeGeneration#getMethodComment(ICompilationUnit, String, MethodDeclaration, boolean, String, String[], String)
592      */

593     public static String JavaDoc getMethodComment(ICompilationUnit cu, String JavaDoc typeName, MethodDeclaration decl, boolean isDeprecated, String JavaDoc targetName, String JavaDoc targetMethodDeclaringTypeName, String JavaDoc[] targetMethodParameterTypeNames, boolean delegate, String JavaDoc lineDelimiter) throws CoreException {
594         boolean needsTarget= targetMethodDeclaringTypeName != null && targetMethodParameterTypeNames != null;
595         String JavaDoc templateName= CodeTemplateContextType.METHODCOMMENT_ID;
596         if (decl.isConstructor()) {
597             templateName= CodeTemplateContextType.CONSTRUCTORCOMMENT_ID;
598         } else if (needsTarget) {
599             if (delegate)
600                 templateName= CodeTemplateContextType.DELEGATECOMMENT_ID;
601             else
602                 templateName= CodeTemplateContextType.OVERRIDECOMMENT_ID;
603         }
604         Template template= getCodeTemplate(templateName, cu.getJavaProject());
605         if (template == null) {
606             return null;
607         }
608         CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), cu.getJavaProject(), lineDelimiter);
609         context.setCompilationUnitVariables(cu);
610         context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, typeName);
611         context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, decl.getName().getIdentifier());
612         if (!decl.isConstructor()) {
613             context.setVariable(CodeTemplateContextType.RETURN_TYPE, ASTNodes.asString(getReturnType(decl)));
614         }
615         if (needsTarget) {
616             if (delegate)
617                 context.setVariable(CodeTemplateContextType.SEE_TO_TARGET_TAG, getSeeTag(targetMethodDeclaringTypeName, targetName, targetMethodParameterTypeNames));
618             else
619                 context.setVariable(CodeTemplateContextType.SEE_TO_OVERRIDDEN_TAG, getSeeTag(targetMethodDeclaringTypeName, targetName, targetMethodParameterTypeNames));
620         }
621         
622         TemplateBuffer buffer;
623         try {
624             buffer= context.evaluate(template);
625         } catch (BadLocationException e) {
626             throw new CoreException(Status.CANCEL_STATUS);
627         } catch (TemplateException e) {
628             throw new CoreException(Status.CANCEL_STATUS);
629         }
630         if (buffer == null)
631             return null;
632         String JavaDoc str= buffer.getString();
633         if (Strings.containsOnlyWhitespaces(str)) {
634             return null;
635         }
636         TemplateVariable position= findVariable(buffer, CodeTemplateContextType.TAGS); // look if Javadoc tags have to be added
637
if (position == null) {
638             return str;
639         }
640             
641         IDocument textBuffer= new Document(str);
642         List JavaDoc typeParams= decl.typeParameters();
643         String JavaDoc[] typeParamNames= new String JavaDoc[typeParams.size()];
644         for (int i= 0; i < typeParamNames.length; i++) {
645             TypeParameter elem= (TypeParameter) typeParams.get(i);
646             typeParamNames[i]= elem.getName().getIdentifier();
647         }
648         List JavaDoc params= decl.parameters();
649         String JavaDoc[] paramNames= new String JavaDoc[params.size()];
650         for (int i= 0; i < paramNames.length; i++) {
651             SingleVariableDeclaration elem= (SingleVariableDeclaration) params.get(i);
652             paramNames[i]= elem.getName().getIdentifier();
653         }
654         List JavaDoc exceptions= decl.thrownExceptions();
655         String JavaDoc[] exceptionNames= new String JavaDoc[exceptions.size()];
656         for (int i= 0; i < exceptionNames.length; i++) {
657             exceptionNames[i]= ASTNodes.getSimpleNameIdentifier((Name) exceptions.get(i));
658         }
659         
660         String JavaDoc returnType= null;
661         if (!decl.isConstructor()) {
662             returnType= ASTNodes.asString(getReturnType(decl));
663         }
664         int[] tagOffsets= position.getOffsets();
665         for (int i= tagOffsets.length - 1; i >= 0; i--) { // from last to first
666
try {
667                 insertTag(textBuffer, tagOffsets[i], position.getLength(), paramNames, exceptionNames, returnType, typeParamNames, isDeprecated, lineDelimiter);
668             } catch (BadLocationException e) {
669                 throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e));
670             }
671         }
672         return textBuffer.get();
673     }
674     
675     /**
676      * @deprecated Deprecated to avoid deprecated warnings
677      */

678     private static ASTNode getReturnType(MethodDeclaration decl) {
679         // used from API, can't eliminate
680
return (decl.getAST().apiLevel() == AST.JLS2) ? decl.getReturnType() : decl.getReturnType2();
681     }
682     
683     
684     private static TemplateVariable findVariable(TemplateBuffer buffer, String JavaDoc variable) {
685         TemplateVariable[] positions= buffer.getVariables();
686         for (int i= 0; i < positions.length; i++) {
687             TemplateVariable curr= positions[i];
688             if (variable.equals(curr.getType())) {
689                 return curr;
690             }
691         }
692         return null;
693     }
694     
695     private static void insertTag(IDocument textBuffer, int offset, int length, String JavaDoc[] paramNames, String JavaDoc[] exceptionNames, String JavaDoc returnType, String JavaDoc[] typeParameterNames, boolean isDeprecated, String JavaDoc lineDelimiter) throws BadLocationException {
696         IRegion region= textBuffer.getLineInformationOfOffset(offset);
697         if (region == null) {
698             return;
699         }
700         String JavaDoc lineStart= textBuffer.get(region.getOffset(), offset - region.getOffset());
701         
702         StringBuffer JavaDoc buf= new StringBuffer JavaDoc();
703         for (int i= 0; i < typeParameterNames.length; i++) {
704             if (buf.length() > 0) {
705                 buf.append(lineDelimiter).append(lineStart);
706             }
707             buf.append("@param <").append(typeParameterNames[i]).append('>'); //$NON-NLS-1$
708
}
709         for (int i= 0; i < paramNames.length; i++) {
710             if (buf.length() > 0) {
711                 buf.append(lineDelimiter).append(lineStart);
712             }
713             buf.append("@param ").append(paramNames[i]); //$NON-NLS-1$
714
}
715         if (returnType != null && !returnType.equals("void")) { //$NON-NLS-1$
716
if (buf.length() > 0) {
717                 buf.append(lineDelimiter).append(lineStart);
718             }
719             buf.append("@return"); //$NON-NLS-1$
720
}
721         if (exceptionNames != null) {
722             for (int i= 0; i < exceptionNames.length; i++) {
723                 if (buf.length() > 0) {
724                     buf.append(lineDelimiter).append(lineStart);
725                 }
726                 buf.append("@throws ").append(exceptionNames[i]); //$NON-NLS-1$
727
}
728         }
729         if (isDeprecated) {
730             if (buf.length() > 0) {
731                 buf.append(lineDelimiter).append(lineStart);
732             }
733             buf.append("@deprecated"); //$NON-NLS-1$
734
}
735         if (buf.length() == 0 && isAllCommentWhitespace(lineStart)) {
736             int prevLine= textBuffer.getLineOfOffset(offset) -1;
737             if (prevLine > 0) {
738                 IRegion prevRegion= textBuffer.getLineInformation(prevLine);
739                 int prevLineEnd= prevRegion.getOffset() + prevRegion.getLength();
740                 // clear full line
741
textBuffer.replace(prevLineEnd, offset + length - prevLineEnd, ""); //$NON-NLS-1$
742
return;
743             }
744         }
745         textBuffer.replace(offset, length, buf.toString());
746     }
747     
748     private static boolean isAllCommentWhitespace(String JavaDoc lineStart) {
749         for (int i= 0; i < lineStart.length(); i++) {
750             char ch= lineStart.charAt(i);
751             if (!Character.isWhitespace(ch) && ch != '*') {
752                 return false;
753             }
754         }
755         return true;
756     }
757         
758     /**
759      * Returns the line delimiter which is used in the specified project.
760      *
761      * @param project the java project, or <code>null</code>
762      * @return the used line delimiter
763      */

764     public static String JavaDoc getLineDelimiterUsed(IJavaProject project) {
765         return getProjectLineDelimiter(project);
766     }
767
768     private static String JavaDoc getProjectLineDelimiter(IJavaProject javaProject) {
769         IProject project= null;
770         if (javaProject != null)
771             project= javaProject.getProject();
772         
773         String JavaDoc lineDelimiter= getLineDelimiterPreference(project);
774         if (lineDelimiter != null)
775             return lineDelimiter;
776         
777         return System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
778
}
779     
780     public static String JavaDoc getLineDelimiterPreference(IProject project) {
781         IScopeContext[] scopeContext;
782         if (project != null) {
783             // project preference
784
scopeContext= new IScopeContext[] { new ProjectScope(project) };
785             String JavaDoc lineDelimiter= Platform.getPreferencesService().getString(Platform.PI_RUNTIME, Platform.PREF_LINE_SEPARATOR, null, scopeContext);
786             if (lineDelimiter != null)
787                 return lineDelimiter;
788         }
789         // workspace preference
790
scopeContext= new IScopeContext[] { new InstanceScope() };
791         String JavaDoc platformDefault= System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
792
return Platform.getPreferencesService().getString(Platform.PI_RUNTIME, Platform.PREF_LINE_SEPARATOR, platformDefault, scopeContext);
793     }
794     
795     /**
796      * Examines a string and returns the first line delimiter found.
797      */

798     public static String JavaDoc getLineDelimiterUsed(IJavaElement elem) {
799         while (elem != null && !(elem instanceof IOpenable)) {
800             elem= elem.getParent();
801         }
802         if (elem != null) {
803             try {
804                 return ((IOpenable) elem).findRecommendedLineSeparator();
805             } catch (JavaModelException exception) {
806                 // Use project setting
807
}
808         }
809         return getProjectLineDelimiter(null);
810     }
811
812     /**
813      * Evaluates the indentation used by a Java element. (in tabulators)
814      */

815     public static int getIndentUsed(IJavaElement elem) throws JavaModelException {
816         if (elem instanceof ISourceReference) {
817             ICompilationUnit cu= (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT);
818             if (cu != null) {
819                 IBuffer buf= cu.getBuffer();
820                 int offset= ((ISourceReference)elem).getSourceRange().getOffset();
821                 int i= offset;
822                 // find beginning of line
823
while (i > 0 && !IndentManipulation.isLineDelimiterChar(buf.getChar(i - 1)) ){
824                     i--;
825                 }
826                 return Strings.computeIndentUnits(buf.getText(i, offset - i), elem.getJavaProject());
827             }
828         }
829         return 0;
830     }
831         
832     /**
833      * Returns the element after the give element.
834      */

835     public static IJavaElement findNextSibling(IJavaElement member) throws JavaModelException {
836         IJavaElement parent= member.getParent();
837         if (parent instanceof IParent) {
838             IJavaElement[] elements= ((IParent)parent).getChildren();
839             for (int i= elements.length - 2; i >= 0 ; i--) {
840                 if (member.equals(elements[i])) {
841                     return elements[i+1];
842                 }
843             }
844         }
845         return null;
846     }
847     
848     public static String JavaDoc getTodoTaskTag(IJavaProject project) {
849         String JavaDoc markers= null;
850         if (project == null) {
851             markers= JavaCore.getOption(JavaCore.COMPILER_TASK_TAGS);
852         } else {
853             markers= project.getOption(JavaCore.COMPILER_TASK_TAGS, true);
854         }
855         
856         if (markers != null && markers.length() > 0) {
857             int idx= markers.indexOf(',');
858             if (idx == -1) {
859                 return markers;
860             } else {
861                 return markers.substring(0, idx);
862             }
863         }
864         return null;
865     }
866     
867     private static String JavaDoc removeTypeArguments(String JavaDoc baseName) {
868         int idx= baseName.indexOf('<');
869         if (idx != -1) {
870             return baseName.substring(0, idx);
871         }
872         return baseName;
873     }
874     
875     
876     // --------------------------- name suggestions --------------------------
877

878     public static final int STATIC_FIELD= 1;
879     public static final int INSTANCE_FIELD= 2;
880     public static final int CONSTANT_FIELD= 3;
881     public static final int PARAMETER= 4;
882     public static final int LOCAL= 5;
883     
884     public static String JavaDoc[] getVariableNameSuggestions(int variableKind, IJavaProject project, ITypeBinding expectedType, Expression assignedExpression, Collection JavaDoc excluded) {
885         LinkedHashSet JavaDoc res= new LinkedHashSet JavaDoc(); // avoid duplicates but keep order
886

887         if (assignedExpression != null) {
888             String JavaDoc nameFromExpression= getBaseNameFromExpression(project, assignedExpression, variableKind);
889             if (nameFromExpression != null) {
890                 add(getVariableNameSuggestions(variableKind, project, nameFromExpression, 0, excluded, false), res); // pass 0 as dimension, base name already contains plural.
891
}
892         }
893         if (expectedType != null) {
894             expectedType= Bindings.normalizeTypeBinding(expectedType);
895             if (expectedType != null) {
896                 int dim= 0;
897                 if (expectedType.isArray()) {
898                     dim= expectedType.getDimensions();
899                     expectedType= expectedType.getElementType();
900                 }
901                 if (expectedType.isParameterizedType()) {
902                     expectedType= expectedType.getTypeDeclaration();
903                 }
904                 String JavaDoc typeName= expectedType.getQualifiedName();
905                 if (typeName.length() > 0) {
906                     String JavaDoc[] names= getVariableNameSuggestions(variableKind, project, typeName, dim, excluded, false);
907                     for (int i= 0; i < names.length; i++) {
908                         res.add(names[i]);
909                     }
910                 }
911             }
912         }
913         if (assignedExpression != null) {
914             // add at end, less important
915
String JavaDoc nameFromParent= getBaseNameFromLocationInParent(project, assignedExpression);
916             if (nameFromParent != null) {
917                 add(getVariableNameSuggestions(variableKind, project, nameFromParent, 0, excluded, false), res); // pass 0 as dimension, base name already contains plural.
918
}
919         }
920         if (res.isEmpty()) {
921             return getDefaultVariableNameSuggestions(variableKind, excluded);
922         }
923         return (String JavaDoc[]) res.toArray(new String JavaDoc[res.size()]);
924     }
925     
926     public static String JavaDoc[] getVariableNameSuggestions(int variableKind, IJavaProject project, Type expectedType, Expression assignedExpression, Collection JavaDoc excluded) {
927         LinkedHashSet JavaDoc res= new LinkedHashSet JavaDoc(); // avoid duplicates but keep order
928

929         if (assignedExpression != null) {
930             String JavaDoc nameFromExpression= getBaseNameFromExpression(project, assignedExpression, variableKind);
931             if (nameFromExpression != null) {
932                 add(getVariableNameSuggestions(variableKind, project, nameFromExpression, 0, excluded, false), res); // pass 0 as dimension, base name already contains plural.
933
}
934         }
935         if (expectedType != null) {
936             int dim= 0;
937             if (expectedType.isArrayType()) {
938                 ArrayType arrayType= (ArrayType) expectedType;
939                 dim= arrayType.getDimensions();
940                 expectedType= arrayType.getElementType();
941             }
942             if (expectedType.isParameterizedType()) {
943                 expectedType= ((ParameterizedType) expectedType).getType();
944             }
945             String JavaDoc typeName= ASTNodes.asString(expectedType);
946             
947             if (typeName.length() > 0) {
948                 String JavaDoc[] names= getVariableNameSuggestions(variableKind, project, typeName, dim, excluded, false);
949                 for (int i= 0; i < names.length; i++) {
950                     res.add(names[i]);
951                 }
952             }
953         }
954         if (assignedExpression != null) {
955             // add at end, less important
956
String JavaDoc nameFromParent= getBaseNameFromLocationInParent(project, assignedExpression);
957             if (nameFromParent != null) {
958                 add(getVariableNameSuggestions(variableKind, project, nameFromParent, 0, excluded, false), res); // pass 0 as dimension, base name already contains plural.
959
}
960         }
961         if (res.isEmpty()) {
962             return getDefaultVariableNameSuggestions(variableKind, excluded);
963         }
964         return (String JavaDoc[]) res.toArray(new String JavaDoc[res.size()]);
965     }
966     
967     private static String JavaDoc[] getDefaultVariableNameSuggestions(int variableKind, Collection JavaDoc excluded) {
968         String JavaDoc prop= variableKind == CONSTANT_FIELD ? "X" : "x"; //$NON-NLS-1$//$NON-NLS-2$
969
String JavaDoc name= prop;
970         int i= 1;
971         while (excluded.contains(name)) {
972             name= prop + i++;
973         }
974         return new String JavaDoc[] { name };
975     }
976     
977     /**
978      * Returns variable name suggestions for the given base name. This is a layer over the JDT.Core NamingConventions API to fix its shortcomings. JDT UI code should only use this
979      * API.
980      * @param variableKind Specifies what type the variable is: {@link #LOCAL}, {@link #PARAMETER}, {@link #STATIC_FIELD}, {@link #INSTANCE_FIELD} or {@link #CONSTANT_FIELD}.
981      * @param project the current project
982      * @param baseName the base name to make a suggestion on. the base name is expected to be a name without any pre- or suffixes in singular form. Type name are accepted as well.
983      * @param dimensions if greater than 0, the resulting name will be in plural form
984      * @param excluded a collection containing all excluded names or <code>null</code> if no names are excluded
985      * @param evaluateDefault if set, the result is guaranteed to contain at least one result. If not, the result can be an empty array.
986      *
987      * @return returns the name suggestions sorted by relevance (best proposal first). If <code>evaluateDefault</code> is set to true, the returned array is never empty.
988      * If <code>evaluateDefault</code> is set to false, an empty array is returned if there is no good suggestion for the given base name.
989      */

990     public static String JavaDoc[] getVariableNameSuggestions(int variableKind, IJavaProject project, String JavaDoc baseName, int dimensions, Collection JavaDoc excluded, boolean evaluateDefault) {
991         String JavaDoc name= workaround38111(baseName);
992         name= removeTypeArguments(name);
993         String JavaDoc packageName= new String JavaDoc(); // not used, so don't compute for now
994
String JavaDoc[] result= null;
995         
996         switch (variableKind) {
997             case CONSTANT_FIELD:
998                 result= getConstantSuggestions(project, packageName, name, dimensions, excluded);
999                 break;
1000            case STATIC_FIELD:
1001                result= sortByLength(NamingConventions.suggestFieldNames(project, packageName, name, dimensions, Flags.AccStatic, getExcludedArray(excluded)));
1002                break;
1003            case INSTANCE_FIELD:
1004                result= sortByLength(NamingConventions.suggestFieldNames(project, packageName, name, dimensions, 0, getExcludedArray(excluded)));
1005                break;
1006            case PARAMETER:
1007                result= sortByLength(NamingConventions.suggestArgumentNames(project, packageName, name, dimensions, getExcludedArray(excluded)));
1008                break;
1009            case LOCAL:
1010                result= sortByLength(NamingConventions.suggestLocalVariableNames(project, packageName, name, dimensions, getExcludedArray(excluded)));
1011                break;
1012        }
1013        if (evaluateDefault) {
1014            if (result.length == 0) {
1015                result= getDefaultVariableNameSuggestions(variableKind, excluded);
1016            }
1017        } else if (variableKind != CONSTANT_FIELD) {
1018             // see 166464 API DCR: specify if naming convention should return default value or not
1019
String JavaDoc defaultValue= "NAME"; // default as chosen by jdt.core //$NON-NLS-1$
1020
if (!name.toUpperCase().endsWith(defaultValue) && result[0].toUpperCase().endsWith(defaultValue)) {
1021                return new String JavaDoc[0];
1022            }
1023        }
1024        return result;
1025    }
1026    
1027    private static String JavaDoc[] getExcludedArray(Collection JavaDoc excluded) {
1028        if (excluded == null) {
1029            return null;
1030        } else if (excluded instanceof ExcludedCollection) {
1031            return ((ExcludedCollection) excluded).getExcludedArray();
1032        }
1033        return (String JavaDoc[]) excluded.toArray(new String JavaDoc[excluded.size()]);
1034    }
1035    
1036    
1037    private static final String JavaDoc[] KNOWN_METHOD_NAME_PREFIXES= { "get", "is", "to"}; //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-1$
1038

1039    
1040    private static void add(String JavaDoc[] names, Set JavaDoc result) {
1041        for (int i= 0; i < names.length; i++) {
1042            result.add(names[i]);
1043        }
1044    }
1045    
1046    private static String JavaDoc getBaseNameFromExpression(IJavaProject project, Expression assignedExpression, int variableKind) {
1047        String JavaDoc name= null;
1048        if (assignedExpression instanceof CastExpression) {
1049            assignedExpression= ((CastExpression) assignedExpression).getExpression();
1050        }
1051        if (assignedExpression instanceof Name) {
1052            Name simpleNode= (Name) assignedExpression;
1053            IBinding binding= simpleNode.resolveBinding();
1054            if (binding instanceof IVariableBinding)
1055                return removePrefixAndSuffixForVariable(project, (IVariableBinding) binding);
1056            
1057            return ASTNodes.getSimpleNameIdentifier(simpleNode);
1058        } else if (assignedExpression instanceof MethodInvocation) {
1059            name= ((MethodInvocation) assignedExpression).getName().getIdentifier();
1060        } else if (assignedExpression instanceof SuperMethodInvocation) {
1061            name= ((SuperMethodInvocation) assignedExpression).getName().getIdentifier();
1062        } else if (assignedExpression instanceof FieldAccess) {
1063            return ((FieldAccess) assignedExpression).getName().getIdentifier();
1064        } else if (variableKind == CONSTANT_FIELD && (assignedExpression instanceof StringLiteral || assignedExpression instanceof NumberLiteral)) {
1065            String JavaDoc string= assignedExpression instanceof StringLiteral ? ((StringLiteral) assignedExpression).getLiteralValue() : ((NumberLiteral) assignedExpression).getToken();
1066            StringBuffer JavaDoc res= new StringBuffer JavaDoc();
1067            boolean needsUnderscore= false;
1068            for (int i= 0; i < string.length(); i++) {
1069                char ch= string.charAt(i);
1070                if (Character.isJavaIdentifierPart(ch)) {
1071                    if (res.length() == 0 && !Character.isJavaIdentifierStart(ch) || needsUnderscore) {
1072                        res.append('_');
1073                    }
1074                    res.append(ch);
1075                    needsUnderscore= false;
1076                } else {
1077                    needsUnderscore= res.length() > 0;
1078                }
1079            }
1080            if (res.length() > 0) {
1081                return res.toString();
1082            }
1083        }
1084        if (name != null) {
1085            for (int i= 0; i < KNOWN_METHOD_NAME_PREFIXES.length; i++) {
1086                String JavaDoc curr= KNOWN_METHOD_NAME_PREFIXES[i];
1087                if (name.startsWith(curr)) {
1088                    if (name.equals(curr)) {
1089                        return null; // don't suggest 'get' as variable name
1090
} else if (Character.isUpperCase(name.charAt(curr.length()))) {
1091                        return name.substring(curr.length());
1092                    }
1093                }
1094            }
1095        }
1096        return name;
1097    }
1098    
1099    private static String JavaDoc getBaseNameFromLocationInParent(IJavaProject project, Expression assignedExpression) {
1100        StructuralPropertyDescriptor location= assignedExpression.getLocationInParent();
1101        if (location == MethodInvocation.ARGUMENTS_PROPERTY) {
1102            MethodInvocation parent= (MethodInvocation) assignedExpression.getParent();
1103            IMethodBinding binding= parent.resolveMethodBinding();
1104            int index= parent.arguments().indexOf(assignedExpression);
1105            if (binding != null && index != -1) {
1106                return getParameterName(binding, index);
1107            }
1108        } else if (location == ClassInstanceCreation.ARGUMENTS_PROPERTY) {
1109            ClassInstanceCreation parent= (ClassInstanceCreation) assignedExpression.getParent();
1110            IMethodBinding binding= parent.resolveConstructorBinding();
1111            int index= parent.arguments().indexOf(assignedExpression);
1112            if (binding != null && index != -1) {
1113                return getParameterName(binding, index);
1114            }
1115        } else if (location == SuperMethodInvocation.ARGUMENTS_PROPERTY) {
1116            SuperMethodInvocation parent= (SuperMethodInvocation) assignedExpression.getParent();
1117            IMethodBinding binding= parent.resolveMethodBinding();
1118            int index= parent.arguments().indexOf(assignedExpression);
1119            if (binding != null && index != -1) {
1120                return getParameterName(binding, index);
1121            }
1122        } else if (location == ConstructorInvocation.ARGUMENTS_PROPERTY) {
1123            ConstructorInvocation parent= (ConstructorInvocation) assignedExpression.getParent();
1124            IMethodBinding binding= parent.resolveConstructorBinding();
1125            int index= parent.arguments().indexOf(assignedExpression);
1126            if (binding != null && index != -1) {
1127                return getParameterName(binding, index);
1128            }
1129        } else if (location == SuperConstructorInvocation.ARGUMENTS_PROPERTY) {
1130            SuperConstructorInvocation parent= (SuperConstructorInvocation) assignedExpression.getParent();
1131            IMethodBinding binding= parent.resolveConstructorBinding();
1132            int index= parent.arguments().indexOf(assignedExpression);
1133            if (binding != null && index != -1) {
1134                return getParameterName(binding, index);
1135            }
1136        }
1137        return null;
1138    }
1139    
1140    private static String JavaDoc getParameterName(IMethodBinding binding, int index) {
1141        try {
1142            IJavaElement javaElement= binding.getJavaElement();
1143            if (javaElement instanceof IMethod) {
1144                IMethod method= (IMethod) javaElement;
1145                if (method.getOpenable().getBuffer() != null) { // avoid dummy names and lookup from Javadoc
1146
String JavaDoc[] parameterNames= method.getParameterNames();
1147                    if (index < parameterNames.length) {
1148                        return NamingConventions.removePrefixAndSuffixForArgumentName(method.getJavaProject(), parameterNames[index]);
1149                    }
1150                }
1151            }
1152        } catch (JavaModelException e) {
1153            // ignore
1154
}
1155        return null;
1156    }
1157    
1158    public static String JavaDoc[] getArgumentNameSuggestions(IType type, String JavaDoc[] excluded) {
1159        return getVariableNameSuggestions(PARAMETER, type.getJavaProject(), JavaModelUtil.getFullyQualifiedName(type), 0, new ExcludedCollection(excluded), true);
1160    }
1161    
1162    public static String JavaDoc[] getArgumentNameSuggestions(IJavaProject project, Type type, String JavaDoc[] excluded) {
1163        int dim= 0;
1164        if (type.isArrayType()) {
1165            ArrayType arrayType= (ArrayType) type;
1166            dim= arrayType.getDimensions();
1167            type= arrayType.getElementType();
1168        }
1169        if (type.isParameterizedType()) {
1170            type= ((ParameterizedType) type).getType();
1171        }
1172        return getVariableNameSuggestions(PARAMETER, project, ASTNodes.asString(type), dim, new ExcludedCollection(excluded), true);
1173    }
1174    
1175    public static String JavaDoc[] getArgumentNameSuggestions(IJavaProject project, ITypeBinding binding, String JavaDoc[] excluded) {
1176        return getVariableNameSuggestions(PARAMETER, project, binding, null, new ExcludedCollection(excluded));
1177    }
1178        
1179    public static String JavaDoc[] getArgumentNameSuggestions(IJavaProject project, String JavaDoc baseName, int dimensions, String JavaDoc[] excluded) {
1180        return getVariableNameSuggestions(PARAMETER, project, baseName, dimensions, new ExcludedCollection(excluded), true);
1181    }
1182    
1183    public static String JavaDoc[] getFieldNameSuggestions(IType type, int fieldModifiers, String JavaDoc[] excluded) {
1184        return getFieldNameSuggestions(type.getJavaProject(), JavaModelUtil.getFullyQualifiedName(type), 0, fieldModifiers, excluded);
1185    }
1186         
1187    public static String JavaDoc[] getFieldNameSuggestions(IJavaProject project, String JavaDoc baseName, int dimensions, int modifiers, String JavaDoc[] excluded) {
1188        if (Flags.isFinal(modifiers) && Flags.isStatic(modifiers)) {
1189            return getVariableNameSuggestions(CONSTANT_FIELD, project, baseName, dimensions, new ExcludedCollection(excluded), true);
1190        } else if (Flags.isStatic(modifiers)) {
1191            return getVariableNameSuggestions(STATIC_FIELD, project, baseName, dimensions, new ExcludedCollection(excluded), true);
1192        }
1193        return getVariableNameSuggestions(INSTANCE_FIELD, project, baseName, dimensions, new ExcludedCollection(excluded), true);
1194    }
1195
1196    private static String JavaDoc[] getConstantSuggestions(IJavaProject project, String JavaDoc packageName, String JavaDoc typeName, int dimensions, Collection JavaDoc excluded) {
1197        //TODO: workaround JDT/Core bug 85946
1198

1199        String JavaDoc string= Signature.getSimpleName(typeName);
1200
1201        StringBuffer JavaDoc buf= new StringBuffer JavaDoc();
1202        boolean wasUpperCase= true;
1203        for (int i= 0; i < string.length() ; i++) {
1204            char ch= string.charAt(i);
1205            if (Character.isUpperCase(ch)) {
1206                if (!wasUpperCase) {
1207                    buf.append('_');
1208                }
1209                buf.append(ch);
1210            } else {
1211                buf.append(Character.toUpperCase(ch));
1212                wasUpperCase= ch == '_'; // avoid duplicate underscores
1213
}
1214        }
1215        ArrayList JavaDoc res= new ArrayList JavaDoc();
1216        String JavaDoc sourceLevel= project.getOption(JavaCore.COMPILER_SOURCE, true);
1217        String JavaDoc complianceLevel= project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
1218        
1219        boolean nameStarts= true;
1220        for (int i= 0; i < buf.length(); i++) {
1221            if (nameStarts) {
1222                String JavaDoc prop= buf.substring(i);
1223                if (!excluded.contains(prop) && JavaConventions.validateFieldName(prop, sourceLevel, complianceLevel).isOK()) {
1224                    res.add(prop);
1225                }
1226            }
1227            char ch= buf.charAt(i);
1228            nameStarts= ch == '_';
1229        }
1230        return (String JavaDoc[]) res.toArray(new String JavaDoc[res.size()]);
1231    }
1232    
1233    private static String JavaDoc getCamelCaseFromUpper(String JavaDoc string) {
1234        StringBuffer JavaDoc result= new StringBuffer JavaDoc();
1235        boolean lastWasUnderscore= false;
1236        for (int i= 0; i < string.length(); i++) {
1237            char ch= string.charAt(i);
1238            if (Character.isUpperCase(ch)) {
1239                if (!lastWasUnderscore) {
1240                    ch= Character.toLowerCase(ch);
1241                }
1242                result.append(ch);
1243                lastWasUnderscore= false;
1244            } else if (ch == '_') {
1245                lastWasUnderscore= true;
1246            } else {
1247                return string; // abort
1248
}
1249        }
1250        return result.toString();
1251    }
1252    
1253    public static String JavaDoc[] getLocalNameSuggestions(IJavaProject project, String JavaDoc baseName, int dimensions, String JavaDoc[] excluded) {
1254        return getVariableNameSuggestions(LOCAL, project, baseName, dimensions, new ExcludedCollection(excluded), true);
1255    }
1256    
1257    private static String JavaDoc[] sortByLength(String JavaDoc[] proposals) {
1258        Arrays.sort(proposals, new Comparator JavaDoc() {
1259            public int compare(Object JavaDoc o1, Object JavaDoc o2) {
1260                return ((String JavaDoc) o2).length() - ((String JavaDoc) o1).length();
1261            }
1262        });
1263        return proposals;
1264    }
1265    
1266    private static String JavaDoc workaround38111(String JavaDoc baseName) {
1267        if (BASE_TYPES.contains(baseName))
1268            return baseName;
1269        return Character.toUpperCase(baseName.charAt(0)) + baseName.substring(1);
1270    }
1271    
1272    private static final List JavaDoc BASE_TYPES= Arrays.asList(
1273            new String JavaDoc[] {"boolean", "byte", "char", "double", "float", "int", "long", "short"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
1274

1275    public static String JavaDoc suggestArgumentName(IJavaProject project, String JavaDoc baseName, String JavaDoc[] excluded) {
1276        return suggestVariableName(PARAMETER, project, baseName, 0, excluded);
1277    }
1278    
1279    private static String JavaDoc suggestVariableName(int varKind, IJavaProject project, String JavaDoc baseName, int dimension, String JavaDoc[] excluded) {
1280        return getVariableNameSuggestions(varKind, project, baseName, dimension, new ExcludedCollection(excluded), true)[0];
1281    }
1282    
1283    
1284    public static String JavaDoc[][] suggestArgumentNamesWithProposals(IJavaProject project, String JavaDoc[] paramNames) {
1285        String JavaDoc[][] newNames= new String JavaDoc[paramNames.length][];
1286        ArrayList JavaDoc takenNames= new ArrayList JavaDoc();
1287        
1288        // Ensure that the code generation preferences are respected
1289
for (int i= 0; i < paramNames.length; i++) {
1290            String JavaDoc curr= paramNames[i];
1291            String JavaDoc baseName= NamingConventions.removePrefixAndSuffixForArgumentName(project, curr);
1292
1293            String JavaDoc[] proposedNames= getVariableNameSuggestions(PARAMETER, project, curr, 0, takenNames, true);
1294            if (!curr.equals(baseName)) {
1295                // make the existing name to favourite
1296
LinkedHashSet JavaDoc updatedNames= new LinkedHashSet JavaDoc();
1297                updatedNames.add(curr);
1298                for (int k= 0; k < proposedNames.length; k++) {
1299                    updatedNames.add(proposedNames[k]);
1300                }
1301                proposedNames= (String JavaDoc[]) updatedNames.toArray(new String JavaDoc[updatedNames.size()]);
1302            }
1303            newNames[i]= proposedNames;
1304            takenNames.add(proposedNames[0]);
1305        }
1306        return newNames;
1307    }
1308    
1309    public static String JavaDoc[][] suggestArgumentNamesWithProposals(IJavaProject project, IMethodBinding binding) {
1310        int nParams= binding.getParameterTypes().length;
1311        if (nParams > 0) {
1312            try {
1313                IMethod method= (IMethod) binding.getMethodDeclaration().getJavaElement();
1314                if (method != null) {
1315                    return suggestArgumentNamesWithProposals(project, method.getParameterNames());
1316                }
1317            } catch (JavaModelException e) {
1318                // ignore
1319
}
1320        }
1321        String JavaDoc[][] names= new String JavaDoc[nParams][];
1322        for (int i= 0; i < names.length; i++) {
1323            names[i]= new String JavaDoc[] { "arg" + i }; //$NON-NLS-1$
1324
}
1325        return names;
1326    }
1327    
1328    
1329    public static String JavaDoc[] suggestArgumentNames(IJavaProject project, IMethodBinding binding) {
1330        int nParams= binding.getParameterTypes().length;
1331
1332        if (nParams > 0) {
1333            try {
1334                IMethod method= (IMethod) binding.getMethodDeclaration().getJavaElement();
1335                if (method != null) {
1336                    String JavaDoc[] paramNames= method.getParameterNames();
1337                    String JavaDoc[] namesArray= new String JavaDoc[0];
1338                    ArrayList JavaDoc newNames= new ArrayList JavaDoc(paramNames.length);
1339                    // Ensure that the code generation preferences are respected
1340
for (int i= 0; i < paramNames.length; i++) {
1341                        String JavaDoc curr= paramNames[i];
1342                        String JavaDoc baseName= NamingConventions.removePrefixAndSuffixForArgumentName(project, curr);
1343                        if (!curr.equals(baseName)) {
1344                            // make the existing name the favourite
1345
newNames.add(curr);
1346                        } else {
1347                            newNames.add(suggestArgumentName(project, curr, namesArray));
1348                        }
1349                        namesArray= (String JavaDoc[]) newNames.toArray(new String JavaDoc[newNames.size()]);
1350                    }
1351                    return namesArray;
1352                }
1353            } catch (JavaModelException e) {
1354                // ignore
1355
}
1356        }
1357        String JavaDoc[] names= new String JavaDoc[nParams];
1358        for (int i= 0; i < names.length; i++) {
1359            names[i]= "arg" + i; //$NON-NLS-1$
1360
}
1361        return names;
1362    }
1363    
1364    public static String JavaDoc removePrefixAndSuffixForVariable(IJavaProject project, IVariableBinding binding) {
1365        if (binding.isEnumConstant()) {
1366            return binding.getName();
1367        } else if (binding.isField()) {
1368            if (Modifier.isStatic(binding.getModifiers()) && Modifier.isFinal(binding.getModifiers())) {
1369                return getCamelCaseFromUpper(binding.getName());
1370            } else {
1371                return NamingConventions.removePrefixAndSuffixForFieldName(project, binding.getName(), binding.getModifiers());
1372            }
1373        } else if (binding.isParameter()) {
1374            return NamingConventions.removePrefixAndSuffixForArgumentName(project, binding.getName());
1375        } else {
1376            return NamingConventions.removePrefixAndSuffixForLocalVariableName(project, binding.getName());
1377        }
1378    }
1379    
1380    private static class ExcludedCollection extends AbstractList JavaDoc {
1381        private String JavaDoc[] fExcluded;
1382        public ExcludedCollection(String JavaDoc[] excluded) {
1383            fExcluded = excluded;
1384        }
1385        public String JavaDoc[] getExcludedArray() {
1386            return fExcluded;
1387        }
1388        public int size() {
1389            return fExcluded.length;
1390        }
1391        public Object JavaDoc get(int index) {
1392            return fExcluded[index];
1393        }
1394        public int indexOf(Object JavaDoc o) {
1395            if (o instanceof String JavaDoc) {
1396                for (int i= 0; i < fExcluded.length; i++) {
1397                     if (o.equals(fExcluded[i]))
1398                         return i;
1399                }
1400            }
1401            return -1;
1402        }
1403        public boolean contains(Object JavaDoc o) {
1404            return indexOf(o) != -1;
1405        }
1406    }
1407    
1408    
1409    public static boolean hasFieldName(IJavaProject project, String JavaDoc name) {
1410        String JavaDoc prefixes= project.getOption(JavaCore.CODEASSIST_FIELD_PREFIXES, true);
1411        String JavaDoc suffixes= project.getOption(JavaCore.CODEASSIST_FIELD_SUFFIXES, true);
1412        String JavaDoc staticPrefixes= project.getOption(JavaCore.CODEASSIST_STATIC_FIELD_PREFIXES, true);
1413        String JavaDoc staticSuffixes= project.getOption(JavaCore.CODEASSIST_STATIC_FIELD_SUFFIXES, true);
1414        
1415        
1416        return hasPrefixOrSuffix(prefixes, suffixes, name)
1417            || hasPrefixOrSuffix(staticPrefixes, staticSuffixes, name);
1418    }
1419    
1420    public static boolean hasParameterName(IJavaProject project, String JavaDoc name) {
1421        String JavaDoc prefixes= project.getOption(JavaCore.CODEASSIST_ARGUMENT_PREFIXES, true);
1422        String JavaDoc suffixes= project.getOption(JavaCore.CODEASSIST_ARGUMENT_SUFFIXES, true);
1423        return hasPrefixOrSuffix(prefixes, suffixes, name);
1424    }
1425    
1426    public static boolean hasLocalVariableName(IJavaProject project, String JavaDoc name) {
1427        String JavaDoc prefixes= project.getOption(JavaCore.CODEASSIST_LOCAL_PREFIXES, true);
1428        String JavaDoc suffixes= project.getOption(JavaCore.CODEASSIST_LOCAL_SUFFIXES, true);
1429        return hasPrefixOrSuffix(prefixes, suffixes, name);
1430    }
1431    
1432    public static boolean hasConstantName(String JavaDoc name) {
1433        return Character.isUpperCase(name.charAt(0));
1434    }
1435    
1436    
1437    private static boolean hasPrefixOrSuffix(String JavaDoc prefixes, String JavaDoc suffixes, String JavaDoc name) {
1438        final String JavaDoc listSeparartor= ","; //$NON-NLS-1$
1439

1440        StringTokenizer JavaDoc tok= new StringTokenizer JavaDoc(prefixes, listSeparartor);
1441        while (tok.hasMoreTokens()) {
1442            String JavaDoc curr= tok.nextToken();
1443            if (name.startsWith(curr)) {
1444                return true;
1445            }
1446        }
1447
1448        tok= new StringTokenizer JavaDoc(suffixes, listSeparartor);
1449        while (tok.hasMoreTokens()) {
1450            String JavaDoc curr= tok.nextToken();
1451            if (name.endsWith(curr)) {
1452                return true;
1453            }
1454        }
1455        return false;
1456    }
1457    
1458    // -------------------- preference access -----------------------
1459

1460    public static boolean useThisForFieldAccess(IJavaProject project) {
1461        return Boolean.valueOf(PreferenceConstants.getPreference(PreferenceConstants.CODEGEN_KEYWORD_THIS, project)).booleanValue();
1462    }
1463    
1464    public static boolean useIsForBooleanGetters(IJavaProject project) {
1465        return Boolean.valueOf(PreferenceConstants.getPreference(PreferenceConstants.CODEGEN_IS_FOR_GETTERS, project)).booleanValue();
1466    }
1467    
1468    public static String JavaDoc getExceptionVariableName(IJavaProject project) {
1469        return PreferenceConstants.getPreference(PreferenceConstants.CODEGEN_EXCEPTION_VAR_NAME, project);
1470    }
1471    
1472    public static boolean doAddComments(IJavaProject project) {
1473        return Boolean.valueOf(PreferenceConstants.getPreference(PreferenceConstants.CODEGEN_ADD_COMMENTS, project)).booleanValue();
1474    }
1475    
1476    public static void setCodeTemplate(String JavaDoc templateId, String JavaDoc pattern, IJavaProject project) {
1477        TemplateStore codeTemplateStore= JavaPlugin.getDefault().getCodeTemplateStore();
1478        TemplatePersistenceData data= codeTemplateStore.getTemplateData(templateId);
1479        Template orig= data.getTemplate();
1480        Template copy= new Template(orig.getName(), orig.getDescription(), orig.getContextTypeId(), pattern, true);
1481        data.setTemplate(copy);
1482    }
1483    
1484    private static Template getCodeTemplate(String JavaDoc id, IJavaProject project) {
1485        if (project == null)
1486            return JavaPlugin.getDefault().getCodeTemplateStore().findTemplateById(id);
1487        ProjectTemplateStore projectStore= new ProjectTemplateStore(project.getProject());
1488        try {
1489            projectStore.load();
1490        } catch (IOException JavaDoc e) {
1491            JavaPlugin.log(e);
1492        }
1493        return projectStore.findTemplateById(id);
1494    }
1495    
1496
1497    public static ImportRewrite createImportRewrite(ICompilationUnit cu, boolean restoreExistingImports) throws JavaModelException {
1498        return CodeStyleConfiguration.createImportRewrite(cu, restoreExistingImports);
1499    }
1500    
1501    public static ImportRewrite createImportRewrite(CompilationUnit astRoot, boolean restoreExistingImports) {
1502        return CodeStyleConfiguration.createImportRewrite(astRoot, restoreExistingImports);
1503    }
1504    
1505}
1506
Popular Tags