KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > apisupport > refactoring > AbstractRefactoringPlugin


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.apisupport.refactoring;
21
22 import java.io.BufferedReader JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.io.InputStreamReader JavaDoc;
25 import java.lang.reflect.Modifier JavaDoc;
26 import java.util.Enumeration JavaDoc;
27 import java.util.Iterator JavaDoc;
28 import java.util.List JavaDoc;
29 import java.util.Map JavaDoc;
30 import java.util.jar.Attributes JavaDoc;
31 import java.util.jar.Manifest JavaDoc;
32 import java.util.regex.Matcher JavaDoc;
33 import java.util.regex.Pattern JavaDoc;
34 import org.netbeans.api.project.FileOwnerQuery;
35 import org.netbeans.api.project.Project;
36 import org.netbeans.jmi.javamodel.Constructor;
37 import org.netbeans.jmi.javamodel.JavaClass;
38 import org.netbeans.jmi.javamodel.Method;
39 import org.netbeans.jmi.javamodel.Parameter;
40 import org.netbeans.jmi.javamodel.Resource;
41 import org.netbeans.modules.apisupport.project.NbModuleProject;
42 import org.netbeans.modules.apisupport.project.layers.LayerUtils;
43 import org.netbeans.modules.javacore.api.JavaModel;
44 import org.netbeans.modules.refactoring.api.AbstractRefactoring;
45 import org.netbeans.modules.refactoring.api.Problem;
46 import org.netbeans.modules.refactoring.spi.RefactoringElementImplementation;
47 import org.netbeans.modules.refactoring.spi.RefactoringElementsBag;
48 import org.netbeans.modules.refactoring.spi.RefactoringPlugin;
49 import org.openide.ErrorManager;
50 import org.openide.filesystems.FileObject;
51 import org.openide.filesystems.FileSystem;
52
53 /**
54  *
55  * @author mkleint
56  */

57 public abstract class AbstractRefactoringPlugin implements RefactoringPlugin {
58     protected static ErrorManager err = ErrorManager.getDefault().getInstance("org.netbeans.modules.apisupport.refactoring"); // NOI18N
59

60     protected AbstractRefactoring refactoring;
61     // a regexp pattern for ordering attributes
62
protected Pattern JavaDoc orderingLayerAttrPattern = Pattern.compile("([\\S]+)/([\\S]+)"); //NOI18N
63
/** Creates a new instance of AbstractRefactoringPlugin */
64     public AbstractRefactoringPlugin(AbstractRefactoring refactoring) {
65         this.refactoring = refactoring;
66     }
67     
68     /** Checks pre-conditions of the refactoring and returns problems.
69      * @return Problems found or null (if no problems were identified)
70      */

71     public Problem preCheck() {
72         return null;
73     }
74     
75     /** Checks parameters of the refactoring.
76      * @return Problems found or null (if no problems were identified)
77      */

78     public Problem checkParameters() {
79         return null;
80     }
81     
82     /**
83      * returns the line number in the file if found, otherwise -1
84      */

85     protected final int checkContentOfFile(FileObject fo, String JavaDoc classToLookFor) {
86         BufferedReader JavaDoc reader = null;
87         try {
88             reader = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(fo.getInputStream(), "UTF-8")); // NOI18N
89
String JavaDoc line = reader.readLine();
90             int counter = 0;
91             while (line != null) {
92                 if (line.indexOf(classToLookFor) != -1) {
93                     return counter;
94                 }
95                 counter = counter + 1;
96                 line = reader.readLine();
97             }
98         } catch (IOException JavaDoc exc) {
99             //TODO
100
} finally {
101             if (reader != null) {
102                 try {
103                     reader.close();
104                 } catch (IOException JavaDoc x) {
105                     // ignore
106
}
107             }
108         }
109         return -1;
110     }
111     
112     protected final void checkManifest(NbModuleProject project, JavaClass clzz, RefactoringElementsBag refactoringElements) {
113         String JavaDoc name = clzz.getName();
114         String JavaDoc pathName = name.replace('.', '/') + ".class"; //NOI18N
115
Manifest JavaDoc mf = project.getManifest();
116         if (mf == null) {
117             return;
118         }
119         Attributes JavaDoc attrs = mf.getMainAttributes();
120         Iterator JavaDoc it = attrs.entrySet().iterator();
121         while (it.hasNext()) {
122             Map.Entry JavaDoc entry = (Map.Entry JavaDoc)it.next();
123             String JavaDoc val = (String JavaDoc)entry.getValue();
124             if (val.indexOf(name) != -1 || val.indexOf(pathName) != -1) {
125                 RefactoringElementImplementation elem =
126                         createManifestRefactoring(clzz, project.getManifestFile(), ((Attributes.Name JavaDoc)entry.getKey()).toString(), val, null);
127                 if (elem != null) {
128                     refactoringElements.add(refactoring, elem);
129                 }
130             }
131         }
132         Map JavaDoc entries = mf.getEntries();
133         if (entries != null) {
134             it = entries.entrySet().iterator();
135             while (it.hasNext()) {
136                 Map.Entry JavaDoc secEnt = (Map.Entry JavaDoc)it.next();
137                 attrs = (Attributes JavaDoc)secEnt.getValue();
138                 String JavaDoc val = (String JavaDoc)secEnt.getKey();
139                 if (val.indexOf(name) != -1 || val.indexOf(pathName) != -1) {
140                     String JavaDoc section = attrs.getValue("OpenIDE-Module-Class"); //NOI18N
141
RefactoringElementImplementation elem =
142                             createManifestRefactoring(clzz, project.getManifestFile(), null, val, section);
143                     if (elem != null) {
144                         refactoringElements.add(refactoring, elem);
145                     }
146                 }
147             }
148         }
149     }
150     
151     protected final void checkMetaInfServices(Project project, JavaClass clzz, RefactoringElementsBag refactoringElements) {
152         FileObject services = Utility.findMetaInfServices(project);
153         if (services == null) {
154             return;
155         }
156         String JavaDoc name = clzz.getName();
157         // Easiest to check them all; otherwise would need to find all interfaces and superclasses:
158
FileObject[] files = services.getChildren();
159         for (int i = 0; i < files.length; i++) {
160             int line = checkContentOfFile(files[i], name);
161             if (line != -1) {
162                 RefactoringElementImplementation elem =
163                         createMetaInfServicesRefactoring(clzz, files[i], line);
164                 if (elem != null) {
165                     refactoringElements.add(refactoring, elem);
166                 }
167             }
168         }
169     }
170     
171     protected final void checkLayer(NbModuleProject project, JavaClass clzz, RefactoringElementsBag refactoringElements) {
172         LayerUtils.LayerHandle handle = LayerUtils.layerForProject(project);
173         FileSystem fs = handle.layer(false);
174         if (fs != null) {
175             checkFileObject(fs.getRoot(), clzz, refactoringElements, handle);
176         }
177     }
178     
179     
180     private void checkFileObject(FileObject fo, JavaClass clzz, RefactoringElementsBag refactoringElements, LayerUtils.LayerHandle handle) {
181         if (fo.isFolder()) {
182             FileObject[] childs = fo.getChildren();
183             for (int i =0; i < childs.length; i++) {
184                 checkFileObject(childs[i], clzz, refactoringElements, handle);
185             }
186             Enumeration JavaDoc en = fo.getAttributes();
187             // check ordering attributes?
188
while (en.hasMoreElements()) {
189                 String JavaDoc attrKey = (String JavaDoc)en.nextElement();
190                 Matcher JavaDoc match = orderingLayerAttrPattern.matcher(attrKey);
191                 if (match.matches()) {
192                     String JavaDoc first = match.group(1);
193                     if (first.endsWith(".instance")) { //NOI18N
194
String JavaDoc name = first.substring(0, first.length() - ".instance".length()).replace('-', '.'); //NOI18N
195
if (name.equals(clzz.getName())) {
196                             RefactoringElementImplementation elem = createLayerRefactoring(clzz, handle, fo, attrKey);
197                             if (elem != null) {
198                                 refactoringElements.add(refactoring, elem);
199                             }
200                         }
201                     }
202                     String JavaDoc second = match.group(2);
203                     if (second.endsWith(".instance")) { //NOI18N
204
String JavaDoc name = second.substring(0, second.length() - ".instance".length()).replace('-', '.'); //NOI18N
205
if (name.equals(clzz.getName())) {
206                             RefactoringElementImplementation elem = createLayerRefactoring(clzz, handle, fo, attrKey);
207                             if (elem != null) {
208                                 refactoringElements.add(refactoring, elem);
209                             }
210                         }
211                     }
212                 }
213             }
214         } else if (fo.isData()) {
215             
216             Enumeration JavaDoc en = fo.getAttributes();
217             // check just a few specific attributes or iterate all?
218
while (en.hasMoreElements()) {
219                 String JavaDoc attrKey = (String JavaDoc)en.nextElement();
220                 Object JavaDoc val = fo.getAttribute("literal:" + attrKey); //NOI18N
221
if (val instanceof String JavaDoc) {
222                     String JavaDoc attrValue = (String JavaDoc)val;
223                     String JavaDoc value = attrValue;
224                     if (attrValue.startsWith("new:")) { //NOI18N
225
value = attrValue.substring("new:".length()); //NOI18N
226
}
227                     if (attrValue.startsWith("method:")) { //NOI18N
228
value = attrValue.substring("method:".length()); //NOI18N
229
int index = value.lastIndexOf('.');
230                         if (index > 0) {
231                             value = value.substring(0, index);
232                         }
233                     }
234                     String JavaDoc pattern1 = clzz.getName().replaceAll("\\.", "\\."); //NOI18N
235
String JavaDoc pattern2 = "[a-zA-Z0-9/-]*" + clzz.getName().replaceAll("\\.", "-") + "\\.instance"; //NOI18N
236

237                     if (value.matches(pattern1) || value.matches(pattern2)) {
238                         RefactoringElementImplementation elem = createLayerRefactoring(clzz, handle, fo, attrKey);
239                         if (elem != null) {
240                             refactoringElements.add(refactoring, elem);
241                         }
242                     }
243                 }
244             }
245             // the actual fileobject is checked after the attributes, so that both can be performed.
246
if ("instance".equals(fo.getExt())) { // NOI18N
247
String JavaDoc name = fo.getName().replace('-', '.');
248                 if (name.equals(clzz.getName())) {
249                     RefactoringElementImplementation elem = createLayerRefactoring(clzz, handle, fo, null);
250                     if (elem != null) {
251                         refactoringElements.add(refactoring, elem);
252                     }
253                 }
254             }
255             if ("settings".equals(fo.getExt())) { // NOI18N
256
//TODO check also content of settings files for matches?
257
}
258             
259         }
260         
261     }
262     
263     protected final Problem checkLayer(Method method, RefactoringElementsBag refactoringElements) {
264         Problem problem = null;
265         // do our check just on public static methods..
266
if (! Modifier.isPublic(method.getModifiers()) || !Modifier.isStatic(method.getModifiers())) {
267             return problem;
268         }
269         // with no parameters or with parameter of type FileObject
270
List JavaDoc params = method.getParameters();
271         if (params.size() > 1) {
272             return problem;
273         }
274         Iterator JavaDoc it = params.iterator();
275         while (it.hasNext()) {
276             Parameter param =(Parameter)it.next();
277             if (! "org.openide.filesystems.FileObject".equals(param.getType().getName())) { // NOI18N
278
return problem;
279             }
280         }
281         Resource res = method.getResource();
282         FileObject fo = JavaModel.getFileObject(res);
283         Project project = FileOwnerQuery.getOwner(fo);
284         if (project != null && project instanceof NbModuleProject) {
285             LayerUtils.LayerHandle handle = LayerUtils.layerForProject((NbModuleProject)project);
286             FileSystem fs = handle.layer(false);
287             if (fs != null) {
288                 checkFileObject(fs.getRoot(), method, null, refactoringElements, handle);
289             }
290         }
291         return problem;
292     }
293     
294     protected final Problem checkLayer(Constructor constructor, RefactoringElementsBag refactoringElements) {
295         Problem problem = null;
296         // just consider public constructors with no params..
297
if (!Modifier.isPublic(constructor.getModifiers())) {
298             return problem;
299         }
300         List JavaDoc params = constructor.getParameters();
301         if (params.size() > 0) {
302             return problem;
303         }
304         Resource res = constructor.getResource();
305         FileObject fo = JavaModel.getFileObject(res);
306         Project project = FileOwnerQuery.getOwner(fo);
307         if (project != null && project instanceof NbModuleProject) {
308             LayerUtils.LayerHandle handle = LayerUtils.layerForProject((NbModuleProject)project);
309             FileSystem fs = handle.layer(false);
310             if (fs != null) {
311                 checkFileObject(fs.getRoot(), null, constructor, refactoringElements, handle);
312             }
313         }
314         return problem;
315     }
316     
317     private void checkFileObject(FileObject fo, Method method, Constructor constructor,
318             RefactoringElementsBag refactoringElements, LayerUtils.LayerHandle handle) {
319         if (fo.isFolder()) {
320             FileObject[] childs = fo.getChildren();
321             for (int i =0; i < childs.length; i++) {
322                 checkFileObject(childs[i], method, constructor, refactoringElements, handle);
323             }
324         } else if (fo.isData()) {
325             if ("settings".equals(fo.getExt())) { // NOI18N
326
//TODO check also content of settings files for matches?
327
}
328             Enumeration JavaDoc en = fo.getAttributes();
329             // check just a few specific attributes or iterate all?
330
while (en.hasMoreElements()) {
331                 String JavaDoc attrKey = (String JavaDoc)en.nextElement();
332                 Object JavaDoc val = fo.getAttribute("literal:" + attrKey); //NOI18N
333
if (val instanceof String JavaDoc) {
334                     String JavaDoc attrValue = (String JavaDoc)val;
335                     if (method != null && attrValue.startsWith("method:") && attrValue.endsWith(method.getName())) { //NOI18N
336
String JavaDoc clazz = attrValue.substring("method:".length()); //NOI18N
337
String JavaDoc methodString = null;
338                         int index = clazz.lastIndexOf('.');
339                         if (index > 0) {
340                             methodString = clazz.substring(index + 1);
341                             clazz = clazz.substring(0, index);
342                         }
343                         if (methodString != null && methodString.equals(method.getName()) &&
344                                 clazz.equals(method.getDeclaringClass().getName())) {
345                             RefactoringElementImplementation elem = createLayerRefactoring(method, handle, fo, attrKey);
346                             if (elem != null) {
347                                 refactoringElements.add(refactoring, elem);
348                             }
349                         }
350                     }
351                     if (constructor != null && attrValue.startsWith("new:")) { //NOI18N
352
String JavaDoc clazz = attrValue.substring("new:".length()); //NOI18N
353
if (clazz.equals(constructor.getDeclaringClass().getName())) {
354                             RefactoringElementImplementation elem = createLayerRefactoring(constructor, handle, fo, attrKey);
355                             if (elem != null) {
356                                 refactoringElements.add(refactoring, elem);
357                             }
358                         }
359                     }
360                 }
361             }
362         }
363         
364     }
365     
366     protected abstract RefactoringElementImplementation createMetaInfServicesRefactoring(JavaClass clazz,
367             FileObject serviceFile, int line);
368     
369     protected abstract RefactoringElementImplementation createManifestRefactoring(JavaClass clazz,
370             FileObject manifestFile,
371             String JavaDoc attributeKey,
372             String JavaDoc attributeValue,
373             String JavaDoc section);
374     
375     protected RefactoringElementImplementation createLayerRefactoring(JavaClass clazz,
376             LayerUtils.LayerHandle handle,
377             FileObject layerFileObject,
378             String JavaDoc layerAttribute) {
379         throw new AssertionError JavaDoc("if you call checkLayer(), you need to implement this method");
380     }
381     
382     protected RefactoringElementImplementation createLayerRefactoring(Method method,
383             LayerUtils.LayerHandle handle,
384             FileObject layerFileObject,
385             String JavaDoc layerAttribute) {
386         throw new AssertionError JavaDoc("if you call checkLayer(), you need to implement this method");
387     }
388     
389     protected RefactoringElementImplementation createLayerRefactoring(Constructor constructor,
390             LayerUtils.LayerHandle handle,
391             FileObject layerFileObject,
392             String JavaDoc layerAttribute) {
393         throw new AssertionError JavaDoc("if you call checkLayer(), you need to implement this method");
394     }
395     
396 }
397
Popular Tags