KickJava   Java API By Example, From Geeks To Geeks.

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


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

11 package org.eclipse.jdt.internal.corext.refactoring.nls;
12
13 import com.ibm.icu.text.Collator;
14
15 import java.util.ArrayList JavaDoc;
16 import java.util.Collections JavaDoc;
17 import java.util.Comparator JavaDoc;
18 import java.util.HashSet JavaDoc;
19 import java.util.Iterator JavaDoc;
20 import java.util.List JavaDoc;
21
22 import org.eclipse.text.edits.TextEdit;
23
24 import org.eclipse.core.runtime.CoreException;
25 import org.eclipse.core.runtime.IPath;
26 import org.eclipse.core.runtime.IProgressMonitor;
27 import org.eclipse.core.runtime.IStatus;
28
29 import org.eclipse.core.resources.IFile;
30 import org.eclipse.core.resources.IProject;
31 import org.eclipse.core.resources.IResource;
32 import org.eclipse.core.resources.ResourcesPlugin;
33
34 import org.eclipse.ltk.core.refactoring.Change;
35
36 import org.eclipse.jdt.core.ICompilationUnit;
37 import org.eclipse.jdt.core.IJavaElement;
38 import org.eclipse.jdt.core.IJavaProject;
39 import org.eclipse.jdt.core.IPackageFragment;
40 import org.eclipse.jdt.core.IPackageFragmentRoot;
41 import org.eclipse.jdt.core.JavaCore;
42 import org.eclipse.jdt.core.dom.rewrite.ImportRewrite;
43 import org.eclipse.jdt.core.formatter.CodeFormatter;
44
45 import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
46 import org.eclipse.jdt.internal.corext.refactoring.nls.changes.CreateTextFileChange;
47 import org.eclipse.jdt.internal.corext.util.CodeFormatterUtil;
48 import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
49
50 import org.eclipse.jdt.ui.CodeGeneration;
51
52 import org.eclipse.jdt.internal.ui.JavaPlugin;
53 import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
54 import org.eclipse.jdt.internal.ui.preferences.MembersOrderPreferenceCache;
55
56 public class AccessorClassCreator {
57
58     private final ICompilationUnit fCu;
59     private final String JavaDoc fAccessorClassName;
60     private final IPath fAccessorPath;
61     private final IPath fResourceBundlePath;
62     private final IPackageFragment fAccessorPackage;
63     private final boolean fIsEclipseNLS;
64     private final NLSSubstitution[] fNLSSubstitutions;
65     private final String JavaDoc fSubstitutionPattern;
66
67     private AccessorClassCreator(ICompilationUnit cu, String JavaDoc accessorClassname, IPath accessorPath, IPackageFragment accessorPackage, IPath resourceBundlePath, boolean isEclipseNLS, NLSSubstitution[] nlsSubstitutions, String JavaDoc substitutionPattern) {
68         fCu= cu;
69         fAccessorClassName= accessorClassname;
70         fAccessorPath= accessorPath;
71         fAccessorPackage= accessorPackage;
72         fResourceBundlePath= resourceBundlePath;
73         fIsEclipseNLS= isEclipseNLS;
74         fNLSSubstitutions= nlsSubstitutions;
75         fSubstitutionPattern= substitutionPattern;
76     }
77
78     public static Change create(ICompilationUnit cu, String JavaDoc accessorClassname, IPath accessorPath, IPackageFragment accessorPackage, IPath resourceBundlePath, boolean isEclipseNLS, NLSSubstitution[] nlsSubstitutions, String JavaDoc substitutionPattern, IProgressMonitor pm) throws CoreException {
79         AccessorClassCreator accessorClass= new AccessorClassCreator(cu, accessorClassname, accessorPath, accessorPackage, resourceBundlePath, isEclipseNLS, nlsSubstitutions, substitutionPattern);
80
81         return new CreateTextFileChange(accessorPath, accessorClass.createAccessorCUSource(pm), null, "java"); //$NON-NLS-1$
82
}
83
84     private String JavaDoc createAccessorCUSource(IProgressMonitor pm) throws CoreException {
85         IProject project= getFileHandle(fAccessorPath).getProject();
86         String JavaDoc lineDelimiter= StubUtility.getLineDelimiterPreference(project);
87         return CodeFormatterUtil.format(CodeFormatter.K_COMPILATION_UNIT, getUnformattedSource(pm), 0, null, lineDelimiter, fCu.getJavaProject());
88     }
89     
90     private static IFile getFileHandle(IPath filePath) {
91         if (filePath == null)
92             return null;
93         return ResourcesPlugin.getWorkspace().getRoot().getFile(filePath);
94     }
95
96     private String JavaDoc getUnformattedSource(IProgressMonitor pm) throws CoreException {
97         ICompilationUnit newCu= null;
98         try {
99             newCu= fAccessorPackage.getCompilationUnit(fAccessorPath.lastSegment()).getWorkingCopy(null);
100
101             String JavaDoc typeComment= null, fileComment= null;
102             final IJavaProject project= newCu.getJavaProject();
103             final String JavaDoc lineDelim= StubUtility.getLineDelimiterUsed(project);
104             if (StubUtility.doAddComments(project)) {
105                 typeComment= CodeGeneration.getTypeComment(newCu, fAccessorClassName, lineDelim);
106                 fileComment= CodeGeneration.getFileComment(newCu, lineDelim);
107             }
108             String JavaDoc classContent= createClass(lineDelim);
109             String JavaDoc cuContent= CodeGeneration.getCompilationUnitContent(newCu, fileComment, typeComment, classContent, lineDelim);
110             if (cuContent == null) {
111                 StringBuffer JavaDoc buf= new StringBuffer JavaDoc();
112                 if (fileComment != null) {
113                     buf.append(fileComment).append(lineDelim);
114                 }
115                 if (!fAccessorPackage.isDefaultPackage()) {
116                     buf.append("package ").append(fAccessorPackage.getElementName()).append(';'); //$NON-NLS-1$
117
}
118                 buf.append(lineDelim).append(lineDelim);
119                 if (typeComment != null) {
120                     buf.append(typeComment).append(lineDelim);
121                 }
122                 buf.append(classContent);
123                 cuContent= buf.toString();
124             }
125             
126             newCu.getBuffer().setContents(cuContent);
127             addImportsToAccessorCu(newCu, pm);
128             return newCu.getSource();
129         } finally {
130             if (newCu != null) {
131                 newCu.discardWorkingCopy();
132             }
133         }
134     }
135
136     private void addImportsToAccessorCu(ICompilationUnit newCu, IProgressMonitor pm) throws CoreException {
137         ImportRewrite is= StubUtility.createImportRewrite(newCu, true);
138         if (fIsEclipseNLS) {
139             is.addImport("org.eclipse.osgi.util.NLS"); //$NON-NLS-1$
140
} else {
141             is.addImport("java.util.MissingResourceException"); //$NON-NLS-1$
142
is.addImport("java.util.ResourceBundle"); //$NON-NLS-1$
143
}
144         TextEdit edit= is.rewriteImports(pm);
145         JavaModelUtil.applyEdit(newCu, edit, false, null);
146     }
147
148     private String JavaDoc createClass(String JavaDoc lineDelim) throws CoreException {
149         if (fIsEclipseNLS) {
150             MembersOrderPreferenceCache sortOrder= JavaPlugin.getDefault().getMemberOrderPreferenceCache();
151             int constructorIdx= sortOrder.getCategoryIndex(MembersOrderPreferenceCache.CONSTRUCTORS_INDEX);
152             int fieldIdx= sortOrder.getCategoryIndex(MembersOrderPreferenceCache.STATIC_FIELDS_INDEX);
153             int initIdx= sortOrder.getCategoryIndex(MembersOrderPreferenceCache.STATIC_INIT_INDEX);
154             
155             String JavaDoc constructor= createConstructor(lineDelim) + lineDelim;
156             String JavaDoc initializer= createStaticInitializer(lineDelim) + lineDelim;
157             String JavaDoc fields= createStaticFields(lineDelim) + lineDelim;
158             
159             StringBuffer JavaDoc result= new StringBuffer JavaDoc();
160             result.append("public class ").append(fAccessorClassName).append(" extends NLS {"); //$NON-NLS-1$ //$NON-NLS-2$
161
result.append("private static final String ").append(NLSRefactoring.BUNDLE_NAME).append(" = \"").append(getResourceBundleName()).append("\"; "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
162
result.append(NLSElement.createTagText(1)).append(lineDelim);
163             
164             if (constructorIdx < fieldIdx) {
165                 if (fieldIdx < initIdx) {
166                     result.append(constructor);
167                     result.append(fields);
168                     result.append(initializer);
169                 } else {
170                     result.append(constructor);
171                     result.append(initializer);
172                     result.append(fields);
173                 }
174             } else {
175                 if (constructorIdx < initIdx) {
176                     result.append(fields);
177                     result.append(constructor);
178                     result.append(initializer);
179                 } else {
180                     result.append(fields);
181                     result.append(initializer);
182                     result.append(constructor);
183                 }
184             }
185             
186             result.append('}').append(lineDelim);
187             
188             return result.toString();
189         } else {
190             MembersOrderPreferenceCache sortOrder= JavaPlugin.getDefault().getMemberOrderPreferenceCache();
191             int constructorIdx= sortOrder.getCategoryIndex(MembersOrderPreferenceCache.CONSTRUCTORS_INDEX);
192             int methodIdx= sortOrder.getCategoryIndex(MembersOrderPreferenceCache.METHOD_INDEX);
193             
194             String JavaDoc constructor= lineDelim + createConstructor(lineDelim);
195             String JavaDoc method= lineDelim + createGetStringMethod(lineDelim);
196             
197             StringBuffer JavaDoc result= new StringBuffer JavaDoc();
198             result.append("public class ").append(fAccessorClassName).append(" {"); //$NON-NLS-1$ //$NON-NLS-2$
199
result.append("private static final String ").append(NLSRefactoring.BUNDLE_NAME); //$NON-NLS-1$
200
result.append(" = \"").append(getResourceBundleName()).append("\"; ").append(NLSElement.createTagText(1)).append(lineDelim); //$NON-NLS-1$ //$NON-NLS-2$
201

202             result.append(lineDelim).append("private static final ResourceBundle ").append(getResourceBundleConstantName()); //$NON-NLS-1$
203
result.append("= ResourceBundle.getBundle(").append(NLSRefactoring.BUNDLE_NAME).append(");").append(lineDelim); //$NON-NLS-1$ //$NON-NLS-2$
204

205             if (constructorIdx < methodIdx) {
206                 result.append(constructor);
207                 result.append(method);
208             } else {
209                 result.append(constructor);
210                 result.append(method);
211             }
212             
213             result.append(lineDelim).append('}').append(lineDelim);
214             
215             return result.toString();
216         }
217     }
218
219     private String JavaDoc getResourceBundleConstantName() {
220         return "RESOURCE_BUNDLE";//$NON-NLS-1$
221
}
222     
223     private String JavaDoc createStaticFields(String JavaDoc lineDelim) {
224         HashSet JavaDoc added= new HashSet JavaDoc();
225         List JavaDoc subs= new ArrayList JavaDoc();
226         for (int i= 0; i < fNLSSubstitutions.length; i++) {
227             NLSSubstitution substitution= fNLSSubstitutions[i];
228             int newState= substitution.getState();
229             if ((substitution.hasStateChanged() || substitution.isAccessorRename())&& newState == NLSSubstitution.EXTERNALIZED) {
230                 if (added.add(substitution.getKey()))
231                     subs.add(substitution);
232             }
233         }
234         Collections.sort(subs, new Comparator JavaDoc() {
235             private Collator fCollator= Collator.getInstance();
236             public int compare(Object JavaDoc o1, Object JavaDoc o2) {
237                 NLSSubstitution s0= (NLSSubstitution)o1;
238                 NLSSubstitution s1= (NLSSubstitution)o2;
239                 return fCollator.compare(s0.getKey(), s1.getKey());
240             }
241         });
242         StringBuffer JavaDoc buf= new StringBuffer JavaDoc();
243         for (Iterator JavaDoc iter= subs.iterator(); iter.hasNext();) {
244             NLSSubstitution element= (NLSSubstitution)iter.next();
245             appendStaticField(buf, element);
246         }
247         return buf.toString();
248     }
249
250     private void appendStaticField(StringBuffer JavaDoc buf, NLSSubstitution substitution) {
251         buf.append("public static String "); //$NON-NLS-1$
252
buf.append(substitution.getKey());
253         buf.append(';');
254     }
255     
256     private String JavaDoc createGetStringMethod(String JavaDoc lineDelim) throws CoreException {
257         StringBuffer JavaDoc result= new StringBuffer JavaDoc();
258         
259         result.append("public static String "); //$NON-NLS-1$
260
int i= fSubstitutionPattern.indexOf(NLSRefactoring.KEY);
261         if (i != -1) {
262             result.append(fSubstitutionPattern.substring(0, i));
263             result.append("String key"); //$NON-NLS-1$
264
result.append(fSubstitutionPattern.substring(i + NLSRefactoring.KEY.length()));
265         } else {
266             //fallback
267
result.append("getString(String key)"); //$NON-NLS-1$
268
}
269         result.append('{').append(lineDelim);
270         
271         result.append("try {").append(lineDelim) //$NON-NLS-1$
272
.append("return ") //$NON-NLS-1$
273
.append(getResourceBundleConstantName()).append(".getString(key);").append(lineDelim) //$NON-NLS-1$
274
.append("} catch (MissingResourceException e) {").append(lineDelim) //$NON-NLS-1$
275
.append("return '!' + key + '!';").append(lineDelim) //$NON-NLS-1$
276
.append("}"); //$NON-NLS-1$
277

278         result.append(lineDelim).append('}');
279         return result.toString();
280     }
281     
282     private String JavaDoc createStaticInitializer(String JavaDoc lineDelim) throws CoreException {
283         return "static {" //$NON-NLS-1$
284
+ lineDelim
285         + "// initialize resource bundle" //$NON-NLS-1$
286
+ lineDelim
287         + "NLS.initializeMessages(BUNDLE_NAME, " + fAccessorClassName + ".class);" //$NON-NLS-1$ //$NON-NLS-2$
288
+ lineDelim
289         + "}"; //$NON-NLS-1$
290
}
291
292     private String JavaDoc createConstructor(String JavaDoc lineDelim) {
293         return "private " + fAccessorClassName + "(){" + //$NON-NLS-2$//$NON-NLS-1$
294
lineDelim + '}';
295     }
296
297     /* Currently not used.
298      private String createGetStringMethodComment() throws CoreException {
299      if (fCodeGenerationSettings.createComments) {
300      String comment= CodeGeneration.getMethodComment(fCu, fAccessorClassName, "getString", //$NON-NLS-1$
301      new String[]{"key"}, //$NON-NLS-1$
302      new String[0], "QString;", //$NON-NLS-1$
303      null, lineDelim);
304      if (comment == null) {
305      return "";//$NON-NLS-1$
306      }
307
308      return comment + lineDelim;
309      } else {
310      return "";//$NON-NLS-1$
311      }
312      }
313      */

314
315     private String JavaDoc getPropertyFileName() {
316         return fResourceBundlePath.lastSegment();
317     }
318
319     private String JavaDoc getPropertyFileNameWithoutExtension() {
320         String JavaDoc fileName= getPropertyFileName();
321         return fileName.substring(0, fileName.indexOf(NLSRefactoring.PROPERTY_FILE_EXT));
322     }
323
324     private String JavaDoc getResourceBundleName() throws CoreException {
325         IResource res= ResourcesPlugin.getWorkspace().getRoot().findMember(fResourceBundlePath.removeLastSegments(1));
326         if (res != null && res.exists()) {
327             IJavaElement el= JavaCore.create(res);
328             if (el instanceof IPackageFragment) {
329                 IPackageFragment p= (IPackageFragment) el;
330                 return p.getElementName() + '.' + getPropertyFileNameWithoutExtension();
331             } else
332                 if ((el instanceof IPackageFragmentRoot) || (el instanceof IJavaProject)) {
333                     return getPropertyFileNameWithoutExtension();
334                 }
335         }
336         throw new CoreException(new StatusInfo(IStatus.ERROR, "Resourcebundle not specified")); //$NON-NLS-1$
337
}
338 }
339
Popular Tags