KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > internal > corext > refactoring > nls > NLSHintHelper


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

11 package org.eclipse.jdt.internal.corext.refactoring.nls;
12
13 import java.io.ByteArrayInputStream JavaDoc;
14 import java.io.IOException JavaDoc;
15 import java.io.InputStream JavaDoc;
16 import java.util.HashMap JavaDoc;
17 import java.util.Iterator JavaDoc;
18 import java.util.List JavaDoc;
19 import java.util.Map JavaDoc;
20 import java.util.Properties JavaDoc;
21
22 import org.eclipse.core.runtime.Assert;
23 import org.eclipse.core.runtime.CoreException;
24
25 import org.eclipse.core.filebuffers.FileBuffers;
26 import org.eclipse.core.filebuffers.ITextFileBuffer;
27 import org.eclipse.core.filebuffers.ITextFileBufferManager;
28 import org.eclipse.core.filebuffers.LocationKind;
29
30 import org.eclipse.core.resources.IFile;
31 import org.eclipse.core.resources.IStorage;
32
33 import org.eclipse.jface.text.IDocument;
34 import org.eclipse.jface.text.IRegion;
35 import org.eclipse.jface.text.Region;
36
37 import org.eclipse.jdt.core.IClassFile;
38 import org.eclipse.jdt.core.ICompilationUnit;
39 import org.eclipse.jdt.core.IJavaElement;
40 import org.eclipse.jdt.core.IJavaProject;
41 import org.eclipse.jdt.core.IOpenable;
42 import org.eclipse.jdt.core.IPackageFragment;
43 import org.eclipse.jdt.core.IPackageFragmentRoot;
44 import org.eclipse.jdt.core.JavaModelException;
45 import org.eclipse.jdt.core.Signature;
46 import org.eclipse.jdt.core.dom.ASTNode;
47 import org.eclipse.jdt.core.dom.ASTVisitor;
48 import org.eclipse.jdt.core.dom.Assignment;
49 import org.eclipse.jdt.core.dom.CompilationUnit;
50 import org.eclipse.jdt.core.dom.Expression;
51 import org.eclipse.jdt.core.dom.IBinding;
52 import org.eclipse.jdt.core.dom.IMethodBinding;
53 import org.eclipse.jdt.core.dom.ITypeBinding;
54 import org.eclipse.jdt.core.dom.IVariableBinding;
55 import org.eclipse.jdt.core.dom.MethodInvocation;
56 import org.eclipse.jdt.core.dom.Modifier;
57 import org.eclipse.jdt.core.dom.Name;
58 import org.eclipse.jdt.core.dom.QualifiedName;
59 import org.eclipse.jdt.core.dom.SimpleType;
60 import org.eclipse.jdt.core.dom.StringLiteral;
61 import org.eclipse.jdt.core.dom.TypeLiteral;
62 import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
63
64 import org.eclipse.jdt.internal.corext.dom.Bindings;
65 import org.eclipse.jdt.internal.corext.dom.NodeFinder;
66 import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
67
68 import org.eclipse.jdt.internal.ui.JavaPlugin;
69 import org.eclipse.jdt.internal.ui.javaeditor.ASTProvider;
70
71 public class NLSHintHelper {
72
73     private NLSHintHelper() {
74     }
75
76     /**
77      * Returns the accessor binding info or <code>null</code> if this element is not a nls'ed entry
78      */

79     public static AccessorClassReference getAccessorClassReference(CompilationUnit astRoot, NLSElement nlsElement) {
80         IRegion region= nlsElement.getPosition();
81         return getAccessorClassReference(astRoot, region);
82     }
83     
84     /**
85      * Returns the accessor binding info or <code>null</code> if this element is not a nls'ed entry
86      */

87     public static AccessorClassReference getAccessorClassReference(CompilationUnit astRoot, IRegion region) {
88         ASTNode nlsStringLiteral= NodeFinder.perform(astRoot, region.getOffset(), region.getLength());
89         if (nlsStringLiteral == null) {
90             return null; // not found
91
}
92         ASTNode parent= nlsStringLiteral.getParent();
93         
94         ITypeBinding accessorBinding= null;
95         if (parent instanceof MethodInvocation) {
96             MethodInvocation methodInvocation= (MethodInvocation) parent;
97             List JavaDoc args= methodInvocation.arguments();
98             if (args.indexOf(nlsStringLiteral) != 0) {
99                 return null; // must be first argument in lookup method
100
}
101             
102             Expression firstArgument= (Expression)args.get(0);
103             ITypeBinding argumentBinding= firstArgument.resolveTypeBinding();
104             if (argumentBinding == null || !argumentBinding.getQualifiedName().equals("java.lang.String")) { //$NON-NLS-1$
105
return null;
106             }
107             
108             ITypeBinding typeBinding= methodInvocation.resolveTypeBinding();
109             if (typeBinding == null || !typeBinding.getQualifiedName().equals("java.lang.String")) { //$NON-NLS-1$
110
return null;
111             }
112             
113             IMethodBinding methodBinding= methodInvocation.resolveMethodBinding();
114             if (methodBinding == null || !Modifier.isStatic(methodBinding.getModifiers())) {
115                 return null; // only static methods qualify
116
}
117     
118             accessorBinding= methodBinding.getDeclaringClass();
119         } else if (parent instanceof QualifiedName) {
120             QualifiedName name= (QualifiedName)parent;
121             IBinding binding= name.resolveBinding();
122             if (!(binding instanceof IVariableBinding))
123                 return null;
124             
125             IVariableBinding variableBinding= (IVariableBinding)binding;
126             if (!Modifier.isStatic(variableBinding.getModifiers()))
127                 return null;
128             
129             accessorBinding= variableBinding.getDeclaringClass();
130         } else if (parent instanceof VariableDeclarationFragment) {
131             VariableDeclarationFragment decl= (VariableDeclarationFragment)parent;
132             if (decl.getInitializer() != null)
133                 return null;
134             
135             IBinding binding= decl.resolveBinding();
136             if (!(binding instanceof IVariableBinding))
137                 return null;
138             
139             IVariableBinding variableBinding= (IVariableBinding)binding;
140             if (!Modifier.isStatic(variableBinding.getModifiers()))
141                 return null;
142             
143             if (!Modifier.isPublic(variableBinding.getModifiers()))
144                 return null;
145             
146             accessorBinding= variableBinding.getDeclaringClass();
147         }
148         if (accessorBinding == null)
149             return null;
150         
151         String JavaDoc resourceBundleName;
152         try {
153             resourceBundleName= getResourceBundleName(accessorBinding);
154         } catch (JavaModelException e) {
155             return null;
156         }
157         
158         if (resourceBundleName != null)
159             return new AccessorClassReference(accessorBinding, resourceBundleName, new Region(parent.getStartPosition(), parent.getLength()));
160
161         return null;
162     }
163     
164     public static IPackageFragment getPackageOfAccessorClass(IJavaProject javaProject, ITypeBinding accessorBinding) throws JavaModelException {
165         if (accessorBinding != null) {
166             ICompilationUnit unit= Bindings.findCompilationUnit(accessorBinding, javaProject);
167             if (unit != null) {
168                 return (IPackageFragment) unit.getParent();
169             }
170         }
171         return null;
172     }
173
174     public static String JavaDoc getResourceBundleName(ITypeBinding accessorClassBinding) throws JavaModelException {
175         IJavaElement je= accessorClassBinding.getJavaElement();
176         if (je == null)
177             return null;
178         
179         IOpenable openable= je.getOpenable();
180         IJavaElement container= null;
181         if (openable instanceof ICompilationUnit)
182             container= (ICompilationUnit)openable;
183         else if (openable instanceof IClassFile)
184             container= (IClassFile)openable;
185         else
186             Assert.isLegal(false);
187         CompilationUnit astRoot= JavaPlugin.getDefault().getASTProvider().getAST(container, ASTProvider.WAIT_YES, null);
188     
189         return getResourceBundleName(astRoot);
190     }
191     
192     public static String JavaDoc getResourceBundleName(ICompilationUnit unit) throws JavaModelException {
193         return getResourceBundleName(JavaPlugin.getDefault().getASTProvider().getAST(unit, ASTProvider.WAIT_YES, null));
194     }
195     
196     public static String JavaDoc getResourceBundleName(IClassFile classFile) throws JavaModelException {
197         return getResourceBundleName(JavaPlugin.getDefault().getASTProvider().getAST(classFile, ASTProvider.WAIT_YES, null));
198     }
199     
200     public static String JavaDoc getResourceBundleName(CompilationUnit astRoot) throws JavaModelException {
201
202         if (astRoot == null)
203             return null;
204         
205         final Map JavaDoc resultCollector= new HashMap JavaDoc(5);
206         final Object JavaDoc RESULT_KEY= new Object JavaDoc();
207         final Object JavaDoc FIELD_KEY= new Object JavaDoc();
208         
209         astRoot.accept(new ASTVisitor() {
210
211             public boolean visit(MethodInvocation node) {
212                 IMethodBinding method= node.resolveMethodBinding();
213                 if (method == null)
214                     return true;
215
216                 String JavaDoc name= method.getDeclaringClass().getQualifiedName();
217                 if (!("java.util.ResourceBundle".equals(name) && "getBundle".equals(method.getName()) && node.arguments().size() > 0) && //old school //$NON-NLS-1$ //$NON-NLS-2$
218
!("org.eclipse.osgi.util.NLS".equals(name) && "initializeMessages".equals(method.getName()) && node.arguments().size() == 2)) //Eclipse style //$NON-NLS-1$ //$NON-NLS-2$
219
return true;
220
221                 Expression argument= (Expression)node.arguments().get(0);
222                 String JavaDoc bundleName= getBundleName(argument);
223                 if (bundleName != null)
224                     resultCollector.put(RESULT_KEY, bundleName);
225
226                 if (argument instanceof Name) {
227                     Object JavaDoc fieldNameBinding= ((Name)argument).resolveBinding();
228                     if (fieldNameBinding != null)
229                         resultCollector.put(FIELD_KEY, fieldNameBinding);
230                 }
231
232                 return false;
233             }
234
235             public boolean visit(VariableDeclarationFragment node) {
236                 Expression initializer= node.getInitializer();
237                 String JavaDoc bundleName= getBundleName(initializer);
238                 if (bundleName != null) {
239                     Object JavaDoc fieldNameBinding= node.getName().resolveBinding();
240                     if (fieldNameBinding != null)
241                         resultCollector.put(fieldNameBinding, bundleName);
242                     return false;
243                 }
244                 return true;
245             }
246
247             public boolean visit(Assignment node) {
248                 if (node.getLeftHandSide() instanceof Name) {
249                     String JavaDoc bundleName= getBundleName(node.getRightHandSide());
250                     if (bundleName != null) {
251                         Object JavaDoc fieldNameBinding= ((Name)node.getLeftHandSide()).resolveBinding();
252                         if (fieldNameBinding != null) {
253                             resultCollector.put(fieldNameBinding, bundleName);
254                             return false;
255                         }
256                     }
257                 }
258                 return true;
259             }
260
261             private String JavaDoc getBundleName(Expression initializer) {
262                 if (initializer instanceof StringLiteral)
263                     return ((StringLiteral)initializer).getLiteralValue();
264
265                 if (initializer instanceof MethodInvocation) {
266                     MethodInvocation methInvocation= (MethodInvocation)initializer;
267                     Expression exp= methInvocation.getExpression();
268                     if ((exp != null) && (exp instanceof TypeLiteral)) {
269                         SimpleType simple= (SimpleType)((TypeLiteral) exp).getType();
270                         ITypeBinding typeBinding= simple.resolveBinding();
271                         if (typeBinding != null)
272                             return typeBinding.getQualifiedName();
273                     }
274                 }
275                 return null;
276             }
277
278         });
279
280         
281         Object JavaDoc fieldName;
282         String JavaDoc result;
283         
284         // First try hard-coded bundle name String field names from NLS tooling:
285
Iterator JavaDoc iter= resultCollector.keySet().iterator();
286         while (iter.hasNext()) {
287             Object JavaDoc o= iter.next();
288             if (!(o instanceof IBinding))
289                 continue;
290             IBinding binding= (IBinding)o;
291             fieldName= binding.getName();
292             if (fieldName.equals("BUNDLE_NAME") || fieldName.equals("RESOURCE_BUNDLE") || fieldName.equals("bundleName")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
293
result= (String JavaDoc)resultCollector.get(binding);
294                 if (result != null)
295                     return result;
296             }
297         }
298
299         result= (String JavaDoc)resultCollector.get(RESULT_KEY);
300         if (result != null)
301             return result;
302
303         fieldName= resultCollector.get(FIELD_KEY);
304         if (fieldName != null)
305             return (String JavaDoc)resultCollector.get(fieldName);
306
307         return null;
308     }
309
310     public static IPackageFragment getResourceBundlePackage(IJavaProject javaProject, String JavaDoc packageName, String JavaDoc resourceName) throws JavaModelException {
311         IPackageFragmentRoot[] allRoots= javaProject.getAllPackageFragmentRoots();
312         for (int i= 0; i < allRoots.length; i++) {
313             IPackageFragmentRoot root= allRoots[i];
314             if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
315                 IPackageFragment packageFragment= root.getPackageFragment(packageName);
316                 if (packageFragment.exists()) {
317                     Object JavaDoc[] resources= packageFragment.isDefaultPackage() ? root.getNonJavaResources() : packageFragment.getNonJavaResources();
318                     for (int j= 0; j < resources.length; j++) {
319                         Object JavaDoc object= resources[j];
320                         if (object instanceof IFile) {
321                             IFile file= (IFile) object;
322                             if (file.getName().equals(resourceName)) {
323                                 return packageFragment;
324                             }
325                         }
326                     }
327                 }
328             }
329         }
330         return null;
331     }
332     
333     public static IStorage getResourceBundle(ICompilationUnit compilationUnit) throws JavaModelException {
334         IJavaProject project= compilationUnit.getJavaProject();
335         if (project == null)
336             return null;
337         
338         String JavaDoc name= getResourceBundleName(compilationUnit);
339         if (name == null)
340             return null;
341         
342         String JavaDoc packName= Signature.getQualifier(name);
343         String JavaDoc resourceName= Signature.getSimpleName(name) + NLSRefactoring.PROPERTY_FILE_EXT;
344         
345         return getResourceBundle(project, packName, resourceName);
346     }
347     
348     public static IStorage getResourceBundle(IJavaProject javaProject, String JavaDoc packageName, String JavaDoc resourceName) throws JavaModelException {
349         IPackageFragmentRoot[] allRoots= javaProject.getAllPackageFragmentRoots();
350         for (int i= 0; i < allRoots.length; i++) {
351             IPackageFragmentRoot root= allRoots[i];
352             if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
353                 IStorage storage= getResourceBundle(root, packageName, resourceName);
354                 if (storage != null)
355                     return storage;
356             }
357         }
358         return null;
359     }
360     
361     public static IStorage getResourceBundle(IPackageFragmentRoot root, String JavaDoc packageName, String JavaDoc resourceName) throws JavaModelException {
362         IPackageFragment packageFragment= root.getPackageFragment(packageName);
363         if (packageFragment.exists()) {
364             Object JavaDoc[] resources= packageFragment.isDefaultPackage() ? root.getNonJavaResources() : packageFragment.getNonJavaResources();
365             for (int j= 0; j < resources.length; j++) {
366                 Object JavaDoc object= resources[j];
367                 if (JavaModelUtil.isOpenableStorage(object)) {
368                     IStorage storage= (IStorage)object;
369                     if (storage.getName().equals(resourceName)) {
370                         return storage;
371                     }
372                 }
373             }
374         }
375         return null;
376     }
377
378     public static IStorage getResourceBundle(IJavaProject javaProject, AccessorClassReference accessorClassReference) throws JavaModelException {
379         String JavaDoc resourceBundle= accessorClassReference.getResourceBundleName();
380         if (resourceBundle == null)
381             return null;
382         
383         String JavaDoc resourceName= Signature.getSimpleName(resourceBundle) + NLSRefactoring.PROPERTY_FILE_EXT;
384         String JavaDoc packName= Signature.getQualifier(resourceBundle);
385         ITypeBinding accessorClass= accessorClassReference.getBinding();
386         
387         if (accessorClass.isFromSource())
388             return getResourceBundle(javaProject, packName, resourceName);
389         else if (accessorClass.getJavaElement() != null)
390             return getResourceBundle((IPackageFragmentRoot)accessorClass.getJavaElement().getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT), packName, resourceName);
391         
392         return null;
393     }
394     
395     /**
396      * Reads the properties from the given storage and
397      * returns it.
398      *
399      * @param javaProject the Java project
400      * @param accessorClassReference the accessor class reference
401      * @return the properties or <code>null</code> if it was not successfully read
402      */

403     public static Properties JavaDoc getProperties(IJavaProject javaProject, AccessorClassReference accessorClassReference) {
404         try {
405             IStorage storage= NLSHintHelper.getResourceBundle(javaProject, accessorClassReference);
406             return getProperties(storage);
407         } catch (JavaModelException ex) {
408             // sorry no properties
409
return null;
410         }
411     }
412     
413     /**
414      * Reads the properties from the given storage and
415      * returns it.
416      *
417      * @param storage the storage
418      * @return the properties or <code>null</code> if it was not successfully read
419      */

420     public static Properties JavaDoc getProperties(IStorage storage) {
421         if (storage == null)
422             return null;
423
424         Properties JavaDoc props= new Properties JavaDoc();
425         InputStream JavaDoc is= null;
426         
427         ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager();
428         try {
429             if (manager != null) {
430                 ITextFileBuffer buffer= manager.getTextFileBuffer(storage.getFullPath(), LocationKind.NORMALIZE);
431                 if (buffer != null) {
432                     IDocument document= buffer.getDocument();
433                     is= new ByteArrayInputStream JavaDoc(document.get().getBytes());
434                 }
435             }
436             
437             // Fallback: read from storage
438
if (is == null)
439                 is= storage.getContents();
440             
441             props.load(is);
442             
443         } catch (IOException JavaDoc e) {
444             // sorry no properties
445
return null;
446         } catch (CoreException e) {
447             // sorry no properties
448
return null;
449         } finally {
450             if (is != null) try {
451                 is.close();
452             } catch (IOException JavaDoc e) {
453                 // return properties anyway but log
454
JavaPlugin.log(e);
455             }
456         }
457         return props;
458     }
459
460 }
461
Popular Tags