KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > terracotta > dso > JdtUtils


1 /*
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package org.terracotta.dso;
5
6 import org.eclipse.core.runtime.IProgressMonitor;
7 import org.eclipse.jdt.core.IClassFile;
8 import org.eclipse.jdt.core.ICodeAssist;
9 import org.eclipse.jdt.core.ICompilationUnit;
10 import org.eclipse.jdt.core.IJavaElement;
11 import org.eclipse.jdt.core.IJavaModelStatusConstants;
12 import org.eclipse.jdt.core.IJavaProject;
13 import org.eclipse.jdt.core.IPackageFragment;
14 import org.eclipse.jdt.core.IPackageFragmentRoot;
15 import org.eclipse.jdt.core.IType;
16 import org.eclipse.jdt.core.JavaModelException;
17 import org.eclipse.jdt.core.Signature;
18 import org.eclipse.jdt.ui.JavaUI;
19 import org.eclipse.jface.text.Assert;
20 import org.eclipse.jface.text.ITextSelection;
21 import org.eclipse.ui.IEditorInput;
22 import org.eclipse.ui.IEditorPart;
23 import org.eclipse.ui.texteditor.ITextEditor;
24
25 public class JdtUtils {
26   private static final IJavaElement[] EMPTY_RESULT= new IJavaElement[0];
27
28   /**
29    * Finds a type by its qualified type name (dot separated).
30    * @param jproject The java project to search in
31    * @param fullyQualifiedName The fully qualified name (type name with enclosing type names and package (all separated by dots))
32    * @return The type found, or null if not existing
33    */

34   public static IType findType(IJavaProject jproject, String JavaDoc fullyQualifiedName) throws JavaModelException {
35     //workaround for bug 22883
36
fullyQualifiedName = fullyQualifiedName.replace('$', '.');
37     IType type= jproject.findType(fullyQualifiedName, (IProgressMonitor)null);
38     if (type != null)
39       return type;
40     IPackageFragmentRoot[] roots= jproject.getPackageFragmentRoots();
41     for (int i= 0; i < roots.length; i++) {
42       IPackageFragmentRoot root= roots[i];
43       type= findType(root, fullyQualifiedName);
44       if (type != null && type.exists())
45         return type;
46     }
47     return null;
48   }
49
50   private static IType findType(IPackageFragmentRoot root, String JavaDoc fullyQualifiedName) throws JavaModelException{
51     IJavaElement[] children= root.getChildren();
52     for (int i= 0; i < children.length; i++) {
53       IJavaElement element= children[i];
54       if (element.getElementType() == IJavaElement.PACKAGE_FRAGMENT){
55         IPackageFragment pack= (IPackageFragment)element;
56         if (! fullyQualifiedName.startsWith(pack.getElementName()))
57           continue;
58         IType type= findType(pack, fullyQualifiedName);
59         if (type != null && type.exists())
60           return type;
61       }
62     }
63     return null;
64   }
65   
66   private static IType findType(IPackageFragment pack, String JavaDoc fullyQualifiedName) throws JavaModelException{
67     ICompilationUnit[] cus= pack.getCompilationUnits();
68     for (int i= 0; i < cus.length; i++) {
69       ICompilationUnit unit= cus[i];
70       IType type= findType(unit, fullyQualifiedName);
71       if (type != null && type.exists())
72         return type;
73     }
74     return null;
75   }
76   
77   private static IType findType(ICompilationUnit cu, String JavaDoc fullyQualifiedName) throws JavaModelException{
78     IType[] types= cu.getAllTypes();
79     for (int i= 0; i < types.length; i++) {
80       IType type= types[i];
81       if (getFullyQualifiedName(type).equals(fullyQualifiedName))
82         return type;
83     }
84     return null;
85   }
86
87   /**
88    * Returns the fully qualified name of the given type using '.' as separators.
89    * This is a replace for IType.getFullyQualifiedTypeName
90    * which uses '$' as separators. As '$' is also a valid character in an id
91    * this is ambiguous. JavaCore PR: 1GCFUNT
92    */

93   public static String JavaDoc getFullyQualifiedName(IType type) {
94     try {
95       if (type.isBinary() && !type.isAnonymous()) {
96         IType declaringType= type.getDeclaringType();
97         if (declaringType != null) {
98           return getFullyQualifiedName(declaringType) + '.' + type.getElementName();
99         }
100       }
101     } catch (JavaModelException e) {
102       // ignore
103
}
104     return type.getFullyQualifiedName('.');
105   }
106
107   /**
108    * Force a reconcile of a compilation unit.
109    * @param unit
110    */

111   public static void reconcile(ICompilationUnit unit) throws JavaModelException {
112     unit.reconcile(
113         ICompilationUnit.NO_AST,
114         false /* don't force problem detection */,
115         null /* use primary owner */,
116         null /* no progress monitor */);
117   }
118
119   /**
120    * Returns the package fragment root of <code>IJavaElement</code>. If the given
121    * element is already a package fragment root, the element itself is returned.
122    */

123   public static IPackageFragmentRoot getPackageFragmentRoot(IJavaElement element) {
124     return (IPackageFragmentRoot) element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
125   }
126
127   /**
128    * Resolves a type name in the context of the declaring type.
129    *
130    * @param refTypeSig the type name in signature notation (for example 'QVector') this can also be an array type, but dimensions will be ignored.
131    * @param declaringType the context for resolving (type where the reference was made in)
132    * @return returns the fully qualified type name or build-in-type name. if a unresolved type couldn't be resolved null is returned
133    */

134   public static String JavaDoc getResolvedTypeName(String JavaDoc refTypeSig, IType declaringType) throws JavaModelException {
135     int arrayCount= Signature.getArrayCount(refTypeSig);
136     char type= refTypeSig.charAt(arrayCount);
137     if (type == Signature.C_UNRESOLVED) {
138       String JavaDoc name= ""; //$NON-NLS-1$
139
int bracket= refTypeSig.indexOf(Signature.C_GENERIC_START, arrayCount + 1);
140       if (bracket > 0)
141         name= refTypeSig.substring(arrayCount + 1, bracket);
142       else {
143         int semi= refTypeSig.indexOf(Signature.C_SEMICOLON, arrayCount + 1);
144         if (semi == -1) {
145           throw new IllegalArgumentException JavaDoc();
146         }
147         name= refTypeSig.substring(arrayCount + 1, semi);
148       }
149       String JavaDoc[][] resolvedNames= declaringType.resolveType(name);
150       if (resolvedNames != null && resolvedNames.length > 0) {
151         return concatenateName(resolvedNames[0][0], resolvedNames[0][1]);
152       }
153       return null;
154     } else {
155       return Signature.toString(refTypeSig.substring(arrayCount));
156     }
157   }
158
159   public static String JavaDoc getResolvedTypeFileName(String JavaDoc refTypeSig, IType declaringType) throws JavaModelException {
160     int arrayCount= Signature.getArrayCount(refTypeSig);
161     char type= refTypeSig.charAt(arrayCount);
162     if (type == Signature.C_UNRESOLVED) {
163       String JavaDoc name= ""; //$NON-NLS-1$
164
int bracket= refTypeSig.indexOf(Signature.C_GENERIC_START, arrayCount + 1);
165       if (bracket > 0)
166         name= refTypeSig.substring(arrayCount + 1, bracket);
167       else {
168         int semi= refTypeSig.indexOf(Signature.C_SEMICOLON, arrayCount + 1);
169         if (semi == -1) {
170           throw new IllegalArgumentException JavaDoc();
171         }
172         name= refTypeSig.substring(arrayCount + 1, semi);
173       }
174       String JavaDoc[][] resolvedNames= declaringType.resolveType(name);
175       if (resolvedNames != null && resolvedNames.length > 0) {
176         return concatenateName(resolvedNames[0][0], resolvedNames[0][1].replace('.', '$'));
177       }
178       return "*";
179     } else {
180       return Signature.toString(refTypeSig.substring(arrayCount));
181     }
182   }
183
184   /**
185    * Determine if refTypeSig is unresolved.
186    */

187   public static boolean isTypeNameUnresolved(String JavaDoc refTypeSig) {
188     return refTypeSig.charAt(Signature.getArrayCount(refTypeSig)) == Signature.C_UNRESOLVED;
189   }
190     
191   /**
192    * Resolve refTypeSig in context of declaringType.
193    */

194   public static String JavaDoc resolveTypeName(String JavaDoc refTypeSig, IType declaringType) throws JavaModelException {
195     int arrayCount= Signature.getArrayCount(refTypeSig);
196     char type= refTypeSig.charAt(arrayCount);
197     if (type == Signature.C_UNRESOLVED) {
198       String JavaDoc name= ""; //$NON-NLS-1$
199
int bracket= refTypeSig.indexOf(Signature.C_GENERIC_START, arrayCount + 1);
200       if (bracket > 0)
201         name= refTypeSig.substring(arrayCount + 1, bracket);
202       else {
203         int semi= refTypeSig.indexOf(Signature.C_SEMICOLON, arrayCount + 1);
204         if (semi == -1) {
205           throw new IllegalArgumentException JavaDoc();
206         }
207         name= refTypeSig.substring(arrayCount + 1, semi);
208       }
209       String JavaDoc[][] resolvedNames= declaringType.resolveType(name);
210       if (resolvedNames != null && resolvedNames.length > 0) {
211         return JdtUtils.concatenateName(resolvedNames[0][0], resolvedNames[0][1]);
212       }
213       else {
214         throw new JavaModelException(new Exception JavaDoc(name + " not resolvable"),
215                                      IJavaModelStatusConstants.EVALUATION_ERROR);
216       }
217     }
218
219     return refTypeSig;
220   }
221   
222   /**
223    * Resolve refTypeSig in context of declaringType into sb.
224    */

225   public static void resolveTypeName(String JavaDoc refTypeSig, IType declaringType, StringBuffer JavaDoc sb)
226     throws JavaModelException
227   {
228     if(isTypeNameUnresolved(refTypeSig)) {
229       sb.append(refTypeSig.substring(0, refTypeSig.indexOf(Signature.C_UNRESOLVED)));
230       sb.append('L');
231       sb.append(resolveTypeName(refTypeSig, declaringType));
232       sb.append(';');
233     }
234     else {
235       sb.append(refTypeSig);
236     }
237   }
238   
239   /**
240    * Concatenates two names. Uses a dot for separation.
241    * Both strings can be empty or <code>null</code>.
242    */

243   public static String JavaDoc concatenateName(String JavaDoc name1, String JavaDoc name2) {
244     StringBuffer JavaDoc buf= new StringBuffer JavaDoc();
245     if (name1 != null && name1.length() > 0) {
246       buf.append(name1);
247     }
248     if (name2 != null && name2.length() > 0) {
249       if (buf.length() > 0) {
250         buf.append('.');
251       }
252       buf.append(name2);
253     }
254     return buf.toString();
255   }
256   
257   public static IJavaElement[] codeResolve(ITextEditor editor) throws JavaModelException {
258     return codeResolve(editor, true);
259   }
260     
261   /**
262    * @param primaryOnly if <code>true</code> only primary working copies will be returned
263    * @since 3.2
264    */

265   public static IJavaElement[] codeResolve(ITextEditor editor, boolean primaryOnly) throws JavaModelException {
266     return codeResolve(getInput(editor, primaryOnly), (ITextSelection)editor.getSelectionProvider().getSelection());
267   }
268
269   public static IJavaElement getInput(IEditorPart editor) {
270     return getInput(editor, true);
271   }
272   
273   /**
274    * @param primaryOnly if <code>true</code> only primary working copies will be returned
275    * @since 3.2
276    */

277   private static IJavaElement getInput(IEditorPart editor, boolean primaryOnly) {
278     if (editor == null)
279       return null;
280     return getEditorInputJavaElement(editor, primaryOnly);
281   }
282   
283   public static ICompilationUnit getInputAsCompilationUnit(ITextEditor editor) {
284     Object JavaDoc editorInput= getInput(editor);
285     if (editorInput instanceof ICompilationUnit)
286       return (ICompilationUnit)editorInput;
287     return null;
288   }
289   
290   /**
291    * Returns the given editor's input as Java element.
292    *
293    * @param editor the editor
294    * @param primaryOnly if <code>true</code> only primary working copies will be returned
295    * @return the given editor's input as Java element or <code>null</code> if none
296    * @since 3.2
297    */

298   public static IJavaElement getEditorInputJavaElement(IEditorPart editor, boolean primaryOnly) {
299     Assert.isNotNull(editor);
300     IEditorInput editorInput= editor.getEditorInput();
301     if (editorInput == null)
302       return null;
303     
304     IJavaElement je= getEditorInputJavaElement(editorInput);
305     if (je != null || primaryOnly)
306       return je;
307
308     return JavaUI.getWorkingCopyManager().getWorkingCopy(editorInput);
309   }
310
311   /**
312    * Returns the Java element wrapped by the given editor input.
313    *
314    * @param editorInput the editor input
315    * @return the Java element wrapped by <code>editorInput</code> or <code>null</code> if none
316    * @since 3.2
317    */

318   public static IJavaElement getEditorInputJavaElement(IEditorInput editorInput) {
319     // Performance: check working copy manager first: this is faster
320
IJavaElement je= JavaUI.getWorkingCopyManager().getWorkingCopy(editorInput);
321     if (je != null)
322       return je;
323     
324     return (IJavaElement)editorInput.getAdapter(IJavaElement.class);
325   }
326   
327   public static IJavaElement[] codeResolve(IJavaElement input, ITextSelection selection) throws JavaModelException {
328     if (input instanceof ICodeAssist) {
329       if (input instanceof ICompilationUnit) {
330         reconcile((ICompilationUnit) input);
331       }
332       IJavaElement[] elements= ((ICodeAssist)input).codeSelect(selection.getOffset(), selection.getLength());
333       if (elements != null && elements.length > 0)
334         return elements;
335     }
336     return EMPTY_RESULT;
337   }
338   
339   public static IJavaElement getElementAtOffset(ITextEditor editor) throws JavaModelException {
340     return getElementAtOffset(editor, true);
341   }
342   
343   /**
344    * @param primaryOnly if <code>true</code> only primary working copies will be returned
345    * @since 3.2
346    */

347   private static IJavaElement getElementAtOffset(ITextEditor editor, boolean primaryOnly) throws JavaModelException {
348     return getElementAtOffset(getInput(editor, primaryOnly), (ITextSelection)editor.getSelectionProvider().getSelection());
349   }
350   
351   public static IJavaElement getElementAtOffset(IJavaElement input, ITextSelection selection) throws JavaModelException {
352     if (input instanceof ICompilationUnit) {
353       ICompilationUnit cunit= (ICompilationUnit) input;
354       reconcile(cunit);
355       IJavaElement ref= cunit.getElementAt(selection.getOffset());
356       if (ref == null)
357         return input;
358       else
359         return ref;
360     } else if (input instanceof IClassFile) {
361       IJavaElement ref= ((IClassFile)input).getElementAt(selection.getOffset());
362       if (ref == null)
363         return input;
364       else
365         return ref;
366     }
367     return null;
368   }
369 }
370
Popular Tags