KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > test > j2ee > refactoring > RefactoringTestCase


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.test.j2ee.refactoring;
21
22 import java.io.File JavaDoc;
23 import java.io.FileInputStream JavaDoc;
24 import java.io.FileOutputStream JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.io.PrintStream JavaDoc;
27 import java.lang.reflect.Modifier JavaDoc;
28 import java.nio.channels.FileChannel JavaDoc;
29 import java.util.ArrayList JavaDoc;
30 import java.util.Arrays JavaDoc;
31 import java.util.Collection JavaDoc;
32 import java.util.Collections JavaDoc;
33 import java.util.Comparator JavaDoc;
34 import java.util.HashMap JavaDoc;
35 import java.util.Iterator JavaDoc;
36 import java.util.StringTokenizer JavaDoc;
37 import javax.jmi.reflect.InvalidObjectException;
38 import org.netbeans.jmi.javamodel.Element;
39 import org.netbeans.jmi.javamodel.JavaClass;
40 import org.netbeans.jmi.javamodel.JavaModelPackage;
41 import org.netbeans.jmi.javamodel.Resource;
42 import org.netbeans.jmi.javamodel.TypeClass;
43 import org.netbeans.junit.diff.LineDiff;
44 import org.netbeans.junit.ide.ProjectSupport;
45 import org.netbeans.modules.refactoring.api.Problem;
46 import org.netbeans.modules.refactoring.api.RefactoringElement;
47 import org.netbeans.modules.refactoring.api.RefactoringSession;
48 import org.openide.filesystems.FileObject;
49 import org.openide.filesystems.FileUtil;
50
51
52 /** LogTestCase
53  * @author Jan Becicka
54  */

55 public class RefactoringTestCase extends LogTestCase {
56     
57     protected static TypeClass typeProxy;
58     protected static JavaClass jc;
59     
60     public RefactoringTestCase(java.lang.String JavaDoc testName) {
61         super(testName);
62     }
63     
64     protected void setUp() {
65         super.setUp();
66         setJavaClass("java.lang.String");
67     }
68     
69     protected void setJavaClass(String JavaDoc name) {
70         Utility.beginTrans(true);
71         try {
72             jc = Utility.findClass(name);
73             typeProxy = ((JavaModelPackage) jc.refOutermostPackage()).getType();
74         } finally {
75             Utility.endTrans();
76         }
77     }
78     
79     /**
80      * Stores problems into log file.
81      */

82     public void logProblems(Problem problem) {
83         Problem p=problem;
84         if (p != null) {
85             ArrayList JavaDoc list=new ArrayList JavaDoc();
86             while (p != null) {
87                 if (p.isFatal()) {
88                     list.add("Problem fatal: "+p.getMessage());
89                 } else {
90                     list.add("Problem: "+p.getMessage());
91                 }
92                 p=p.getNext();
93             }
94             Collections.sort(list);
95             for (int i=0;i < list.size();i++) {
96                 log(list.get(i));
97             }
98         }
99     }
100     
101     /**
102      * Stores problems into ref file. Problems should be sorted.
103      * @return true if problem is not null and one of them is fatal
104      */

105     public boolean refProblems(Problem problem) {
106         Problem p=problem;
107         boolean ret=false;
108         if (p != null) {
109             ArrayList JavaDoc list=new ArrayList JavaDoc();
110             while (p != null) {
111                 if (p.isFatal()) {
112                     ret=true;
113                     list.add("Problem fatal: "+p.getMessage());
114                 } else {
115                     list.add("Problem: "+p.getMessage());
116                 }
117                 p=p.getNext();
118             }
119             Collections.sort(list);
120             for (int i=0;i < list.size();i++) {
121                 ref(list.get(i));
122             }
123         }
124         return ret;
125     }
126     
127     /**
128      * Makes diffs of files in map (before refactoring) with refactored files.
129      * @param files map of resource to temporary file
130      * @param session refactoring session
131      * @param name original name
132      * @param renamed new name
133      */

134     protected void compareResources(HashMap JavaDoc files, RefactoringSession session, String JavaDoc name, String JavaDoc renamed) throws Exception JavaDoc {
135         Collection JavaDoc result = session.getRefactoringElements();
136         ref("Found "+String.valueOf(result.size())+" occurrence(s).");
137         Object JavaDoc[] ress=files.keySet().toArray();
138         Arrays.sort(ress);
139         for (int i=0;i < ress.length;i++) {
140             String JavaDoc key = (String JavaDoc) ress[i];
141             if (key.equals("empty")) {
142                 continue;
143             }
144             Res res=(Res)(files.get(key));
145             File JavaDoc oldfile=res.backup;
146             if (oldfile == null || !oldfile.exists()) { //resource has new name
147
log("compareResources: backuped old file is null - changed resource ");
148                 continue;
149             }
150             File JavaDoc actualfile;
151             boolean b = false;
152             if (key.endsWith(".xml")) {
153                 actualfile = new File JavaDoc(key);
154                 b = true;
155             } else if (res.resource != null) {
156                 try {
157                     actualfile = new File JavaDoc(classPathWorkDir, res.resource.getName());
158                 } catch (InvalidObjectException ioe) {
159                     actualfile = new File JavaDoc(classPathWorkDir, "xyz.abc");
160                 }
161             } else {
162                 actualfile = new File JavaDoc(classPathWorkDir, key);
163             }
164             if (!actualfile.exists()) { //moved
165
if (key.indexOf(name.replace('.','/')) == 0) { //package name
166
String JavaDoc rsnm=key; // a/b/c/A.java
167
String JavaDoc nm=name.replace('.','/'); // a/b/c
168
rsnm=renamed.replace('.','/')+rsnm.substring(nm.length()); // b/b/c/A.java
169
actualfile=new File JavaDoc(classPathWorkDir, rsnm);
170                 } else if (key.indexOf("-config.xml") > 0) { //need special handling for ws-config.xml file
171
// absolute/path/to/ws/config.xml
172
String JavaDoc rsnm=renamed.replace('.','/').substring(0, renamed.lastIndexOf('.'))
173                         + key.substring(key.lastIndexOf(File.separatorChar));
174                     actualfile=new File JavaDoc(classPathWorkDir, rsnm);
175                 }
176             }
177             LineDiff ldiff=new LineDiff();
178             File JavaDoc diff=File.createTempFile("xtest", "refactoring");
179             ldiff.diff(actualfile, oldfile, diff);
180             if (b) {
181                 ref("\n"+key.substring(
182                         classPathWorkDir.getParentFile().getParentFile()
183                         .getAbsolutePath().length() + 1).replace('\\', '/') +"\n");
184             } else {
185                 ref("\n"+key +"\n");
186             }
187             Collections.sort(res.texts);
188             for (int j=0;j < res.texts.size();j++) {
189                 String JavaDoc msg = (String JavaDoc) res.texts.get(j);
190                 String JavaDoc substr = "/qa-functional/data/projects/";
191                 if (msg.indexOf(substr) < 0) {
192                     //common case
193
ref(" " + msg);
194                 } else {
195                     //cannot use absolute paths in goldenfiles nor logs
196
StringTokenizer JavaDoc tok = new StringTokenizer JavaDoc(msg, " ");
197                     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
198                     while (tok.hasMoreTokens()) {
199                         String JavaDoc t = tok.nextToken();
200                         if (t.indexOf(substr) > 0) {
201                             boolean isWindows = File.pathSeparator.equals(";");
202                             int index = classPathWorkDir.getAbsolutePath().length();
203                             if (!isWindows) {
204                                 index--;
205                             }
206                             sb.append(t.substring(index).replace('/', '.'));
207                             sb.append(" ");
208                         } else {
209                             sb.append(t);
210                             sb.append(" ");
211                         }
212                     }
213                     ref(" " + sb.toString().trim());
214                 }
215             }
216             ref("\nFile diff:\n");
217             ref(diff);
218             diff.delete();
219             oldfile.delete();
220             Utility.copyFile(actualfile, new File JavaDoc(getWorkDir(), actualfile.getName()));
221         }
222         ref("");
223         Res empty=(Res)(files.get("empty"));
224         if (empty != null) {
225             for (int i=0;i < empty.texts.size();i++) {
226                 ref(empty.texts.get(i));
227             }
228         }
229     }
230     
231     /**
232      * makes map of files mapped to resources names of usages, files are backuped into tmp files
233      */

234     protected HashMap JavaDoc getResources(RefactoringSession session) throws Exception JavaDoc {
235         Collection JavaDoc result = session.getRefactoringElements();
236         ArrayList JavaDoc list=new ArrayList JavaDoc();
237         ArrayList JavaDoc xmlFiles = new ArrayList JavaDoc();
238         HashMap JavaDoc files=new HashMap JavaDoc();
239         for (Iterator JavaDoc it=result.iterator();it.hasNext();) {
240             Object JavaDoc o=it.next();
241             //we're interested in RefactoringElements
242
if (o instanceof RefactoringElement) {
243                 RefactoringElement wue=(RefactoringElement) o;
244                 Element el = wue.getJavaElement();
245                 if (el != null) {
246                     //we have java file
247
Resource resource = el.getResource();
248                     if (resource != null && resource.isValid()) {
249                         Res res;
250                         if (!list.contains(resource)) {
251                             list.add(resource);
252                             res=new Res();
253                             files.put(resource.getName(), res);
254                         } else {
255                             res=(Res)(files.get(resource.getName()));
256                         }
257                         res.resource = resource;
258                         res.texts.add(getDisplayText(wue));
259                     }
260                 } else {
261                     //we have DD (or other non-java file)
262
FileObject fo = wue.getParentFile();
263                     File JavaDoc f = FileUtil.toFile(fo);
264                     Res res;
265                     if (!xmlFiles.contains(f.getAbsolutePath())) {
266                         xmlFiles.add(f.getAbsolutePath());
267                         res=new Res();
268                         files.put(f.getAbsolutePath(), res);
269                     } else {
270                         res=(Res)(files.get(f.getAbsolutePath()));
271                     }
272                     res.texts.add(getDisplayText(wue));
273                 }
274             } // if (o instanceof RefactoringElement)
275
}
276         files.put("empty", new Res());
277         Collections.sort(list, new Comparator JavaDoc() {
278             public int compare(Object JavaDoc o1, Object JavaDoc o2) {
279                 return ((Resource)o1).getName().compareTo(((Resource)o2).getName());
280             }
281         });
282         Collections.sort(xmlFiles);
283         File JavaDoc folder=getWorkDir();
284         for (int i=0;i < list.size();i++) {
285             Resource r=(Resource)(list.get(i));
286             Res res=(Res)(files.get(r.getName()));
287             String JavaDoc name=r.getName().replace('/', '_')+".test";
288             name=name.replace('\\', '_');
289             File JavaDoc fl=new File JavaDoc(folder, name);
290             if (!fl.getParentFile().exists()) {
291                 fl.getParentFile().mkdirs();
292             }
293             PrintStream JavaDoc ps=new PrintStream JavaDoc(new FileOutputStream JavaDoc(fl));
294             ps.print(r.getSourceText());
295             ps.close();
296             res.backup=fl;
297         }
298         for (int i=0;i < xmlFiles.size();i++) {
299             String JavaDoc s = (String JavaDoc) xmlFiles.get(i);
300             File JavaDoc f = new File JavaDoc(s);
301             Res res=(Res)(files.get(s));
302             String JavaDoc name=s.substring(s.lastIndexOf(File.separatorChar) + 1).replace('/', '_')+".test";
303             name=name.replace('\\', '_');
304             File JavaDoc fl=new File JavaDoc(folder, name);
305             if (!fl.getParentFile().exists()) {
306                 fl.getParentFile().mkdirs();
307             }
308             try {
309                 copyFile(f, fl);
310             } catch (Exception JavaDoc e) {
311                 e.printStackTrace(System.err);
312             }
313             res.backup=fl;
314         }
315         return files;
316     }
317     
318     protected void refUsages(RefactoringSession session) {
319         Collection JavaDoc result = session.getRefactoringElements();
320         ArrayList JavaDoc list;
321         HashMap JavaDoc map=new HashMap JavaDoc();
322         for (Iterator JavaDoc it=result.iterator();it.hasNext();) {
323             Object JavaDoc o=it.next();
324             if (o instanceof RefactoringElement) {
325                 RefactoringElement wue=(RefactoringElement) o;
326                 Element el = wue.getJavaElement();
327                 String JavaDoc s = null;
328                 if (el != null && el.getResource() != null) {
329                     s=el.getResource().getName().replace(File.separatorChar,'/');
330                 } else {
331                     FileObject fo = wue.getParentFile();
332                     if (fo != null) {
333                         String JavaDoc tmp = FileUtil.toFile(fo).getAbsolutePath();
334                         int i = classPathWorkDir.getParentFile().getParentFile()
335                         .getAbsolutePath().length();
336                         s = tmp.substring(i + 1).replace(File.separatorChar, '/');
337                     }
338                 }
339                 if (s != null) {
340                     list=(ArrayList JavaDoc)(map.get(s));
341                     if (list == null) {
342                         list=new ArrayList JavaDoc();
343                         map.put(s, list);
344                     }
345                     list.add(getDisplayText(wue));
346                 } else {
347                     log("refUsages without resource");
348                     log(getDisplayText(wue));
349                     map.put(getDisplayText(wue), "");
350                 }
351             }
352         }
353         ref("Found "+String.valueOf(result.size())+" occurrence(s).");
354         Object JavaDoc[] keys=map.keySet().toArray();
355         Arrays.sort(keys);
356         for (int i=0;i < keys.length;i++) {
357             ref("");
358             if (map.get(keys[i]) instanceof ArrayList JavaDoc) {
359                 ref(keys[i]);
360                 list=(ArrayList JavaDoc)(map.get(keys[i]));
361                 Collections.sort(list);
362                 for (int j=0;j < list.size();j++) {
363                     ref(" "+list.get(j));
364                 }
365             } else {
366                 ref(keys[i]);
367             }
368         }
369         ref("");
370     }
371     
372     protected String JavaDoc getDisplayText(RefactoringElement elm) {
373         String JavaDoc app="";
374         if (elm.getStatus() == RefactoringElement.WARNING) {
375             app=" [ warning! ]";
376         } else if (elm.getStatus() == RefactoringElement.GUARDED) {
377             app=" [ error: code is in guarded block ]";
378         }
379         return elm.getDisplayText()+app;
380     }
381     
382     protected String JavaDoc getModifier(int modifier) {
383         String JavaDoc ret="";
384         if (Modifier.isPublic(modifier)) {
385             ret+="public";
386         } else if (Modifier.isProtected(modifier)) {
387             ret+="protected";
388         } else if (Modifier.isPrivate(modifier)) {
389             ret+="private";
390         }
391         if (Modifier.isAbstract(modifier)) {
392             ret+=" abstract";
393         } else if (Modifier.isFinal(modifier)) {
394             ret+=" final";
395         } else if (Modifier.isInterface(modifier)) {
396             ret+=" interface";
397         } else if (Modifier.isNative(modifier)) {
398             ret+=" native";
399         } else if (Modifier.isStatic(modifier)) {
400             ret+=" static";
401         } else if (Modifier.isSynchronized(modifier)) {
402             ret+=" synchronized";
403         } else if (Modifier.isTransient(modifier)) {
404             ret+=" transient";
405         } else if (Modifier.isVolatile(modifier)) {
406             ret+=" volatile";
407         }
408         return ret.trim();
409     }
410     
411     public void prepareProject() {
412         File JavaDoc projectDir = new File JavaDoc(getDataDir(), "projects/EJBModule");
413         ProjectSupport.openProject(projectDir);
414         classPathWorkDir= new File JavaDoc(projectDir, "src/java");
415     }
416     
417     
418     private static void copyFile(File JavaDoc src, File JavaDoc dest) {
419         try {
420             dest.createNewFile();
421             FileChannel JavaDoc srcChannel = new FileInputStream JavaDoc(src).getChannel();
422             FileChannel JavaDoc dstChannel = new FileOutputStream JavaDoc(dest).getChannel();
423             dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
424             srcChannel.close();
425             dstChannel.close();
426         } catch (IOException JavaDoc e) {
427             //ignore
428
e.printStackTrace(System.out);
429         }
430     }
431     
432     
433     
434     class Res {
435         public File JavaDoc backup;
436         public ArrayList JavaDoc texts;
437         public Resource resource = null;
438         
439         public Res() {
440             texts=new ArrayList JavaDoc();
441         }
442         
443         public String JavaDoc toString() {
444             return "\nRes[backup: " + backup + ", texts: " + texts + "]\n\n";
445         }
446     }
447 }
448
449
Popular Tags