KickJava   Java API By Example, From Geeks To Geeks.

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


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.File JavaDoc;
24 import java.io.FileInputStream JavaDoc;
25 import java.io.FileOutputStream JavaDoc;
26 import java.io.FileReader JavaDoc;
27 import java.io.IOException JavaDoc;
28 import java.io.PrintStream 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.HashMap JavaDoc;
34 import java.util.Iterator JavaDoc;
35 import java.util.List JavaDoc;
36 import org.netbeans.modules.refactoring.api.Problem;
37 import org.netbeans.modules.refactoring.api.RefactoringElement;
38 import org.netbeans.modules.refactoring.api.WhereUsedQuery;
39 import org.netbeans.modules.refactoring.api.RefactoringSession;
40 import org.netbeans.jmi.javamodel.*;
41 import org.netbeans.junit.NbTestCase;
42 import org.netbeans.junit.NbTestSuite;
43 import org.netbeans.modules.refactoring.api.RenameRefactoring;
44 import org.openide.filesystems.FileStateInvalidException;
45
46  
47 /**
48  *
49  * @author Petr Zajac
50  */

51 public class RenameTest extends NbTestCase {
52         
53  
54     private static String JavaDoc[] resultFiles = {
55         "src/testRename/RenamedAction.java",
56         "src/testRename/layer.xml",
57         "src/testRename/RenamedLoader.java",
58         "manifest.mf",
59         "src/META-INF/services/org.openide.loaders.UniFileLoader"
60     };
61     private static String JavaDoc[] goldenFiles = {
62         "RenamedAction.java.pass",
63         "layer.xml.pass",
64         "RenamedLoader.java.pass",
65         "manifest.mf.pass",
66         "org.openide.loaders.UniFileLoader.pass"
67     };
68     
69     private String JavaDoc PATH_PREFIX = "";
70     
71     private static TypeClass typeProxy;
72     private static JavaClass jc;
73
74     private PrintStream JavaDoc refPs;
75
76     
77     /** Creates a new instance of Signature1Test */
78     public RenameTest(String JavaDoc name) {
79         super(name);
80     }
81     
82     public static NbTestSuite suite() {
83         NbTestSuite suite = new NbTestSuite();
84         suite.addTestSuite(RenameTest.class);
85         return suite;
86     }
87     
88     public void testRename() throws FileStateInvalidException, IOException JavaDoc {
89             jc = (JavaClass) TestUtility.findClass("testRename.MyAction");
90             typeProxy = ((JavaModelPackage) jc.refOutermostPackage()).getType();
91
92             jc = (JavaClass) typeProxy.resolve("testRename.MyAction");
93             RenameRefactoring refactoring = new RenameRefactoring(jc);
94             refactoring.setNewName("RenamedAction");
95             refactoring.checkParameters();
96             RefactoringSession result = RefactoringSession.create("rename class");
97             refactoring.prepare(result);
98             result.doRefactoring(true);
99
100             jc = (JavaClass) TestUtility.findClass("testRename.MyDataLoader");
101             typeProxy = ((JavaModelPackage) jc.refOutermostPackage()).getType();
102
103             jc = (JavaClass) typeProxy.resolve("testRename.MyDataLoader");
104              refactoring = new RenameRefactoring(jc);
105             refactoring.setNewName("RenamedLoader");
106             refactoring.checkParameters();
107             result = RefactoringSession.create("rename class");
108             refactoring.prepare(result);
109             result.doRefactoring(true);
110
111             // check modified files
112
for (int x = 0; x < resultFiles.length; x++) {
113                 String JavaDoc fileName = PATH_PREFIX + resultFiles[x] ;
114                 log("assertFile " + fileName);
115                 File JavaDoc resF = TestUtility.getFile(getDataDir(),"testRename", fileName);
116                 File JavaDoc goldenF = getGoldenFile(goldenFiles[x]);
117                 File JavaDoc f1 = writeToWorkDir(resF,resF.getName() + ".result");
118                 File JavaDoc f2 = writeToWorkDir(goldenF,goldenF.getName() + ".pass");
119                 assertFile(f1,f2);
120                 f1.delete();
121                 f2.delete();
122             }
123     }
124     public void testWhereUsed() throws Exception JavaDoc {
125        
126         File JavaDoc f = new File JavaDoc(getWorkDir(),"whereUsed.ref" );
127         refPs = new PrintStream JavaDoc(new FileOutputStream JavaDoc(f));
128         jc = (JavaClass) TestUtility.findClass("testRename.WhereUsedDataLoader");
129         ref("testrename.MyDataLoader");
130         WhereUsedQuery wu= new WhereUsedQuery(jc);
131         wu.setSearchInComments(true);
132         findClass(wu);
133         wu = new WhereUsedQuery(TestUtility.findClass("testRename.WhereUsedAction"));
134         ref("testrename.WhereUsedAction");
135         findClass(wu);
136         refPs.close();
137         assertFile(f, getGoldenFile("whereUsed.ref"));
138                 
139     }
140 //
141
//
142
// public static String getAsString(String file) {
143
// String result;
144
// try {
145
// FileObject testFile = Repository.getDefault().findResource(file);
146
// DataObject dob = DataObject.find(testFile);
147
//
148
// EditorCookie ec = (EditorCookie) dob.getCookie(EditorCookie.class);
149
// StyledDocument doc = ec.openDocument();
150
// result = doc.getText(0, doc.getLength());
151
// }
152
// catch (Exception e) {
153
// throw new AssertionFailedErrorException(e);
154
// }
155
// return result;
156
// }
157

158     protected void findClass(WhereUsedQuery wu) {
159         RefactoringSession result = RefactoringSession.create(null);
160         refProblems(wu.prepare(result));
161         refUsages(result);
162         ref("");
163     }
164
165     /**
166      * Stores problems into ref file. Problems should be sorted.
167      * @return true if problem is not null and one of them is fatal
168      */

169     public boolean refProblems(Problem problem) {
170         Problem p=problem;
171         boolean ret=false;
172         if (p != null) {
173             ArrayList JavaDoc list=new ArrayList JavaDoc();
174             while (p != null) {
175                 if (p.isFatal()) {
176                     ret=true;
177                     list.add("Problem fatal: "+p.getMessage());
178                 } else {
179                     list.add("Problem: "+p.getMessage());
180                 }
181                 p=p.getNext();
182             }
183             Collections.sort(list);
184             for (int i=0;i < list.size();i++) {
185                 ref(list.get(i));
186             }
187         }
188         return ret;
189     }
190      protected void refUsages(RefactoringSession session) {
191         Collection JavaDoc result = session.getRefactoringElements();
192         ArrayList JavaDoc list=new ArrayList JavaDoc();
193         HashMap JavaDoc map=new HashMap JavaDoc();
194         for (Iterator JavaDoc it=result.iterator();it.hasNext();) {
195             Object JavaDoc o=it.next();
196             if (o instanceof RefactoringElement) {
197                 RefactoringElement wue=(RefactoringElement) o;
198                 Element el = wue.getJavaElement();
199                 if (el != null && el.getResource() != null) {
200                     String JavaDoc s;
201                     s=el.getResource().getName().replace(File.separatorChar,'/');
202                     list=(ArrayList JavaDoc)(map.get(s));
203                     if (list == null) {
204                         list=new ArrayList JavaDoc();
205                         map.put(s, list);
206                     }
207                     list.add(getDisplayText(wue));
208                 } else {
209                     log("refUsages without resource");
210                     log(getDisplayText(wue));
211                     map.put(getDisplayText(wue), "");
212                 }
213             }
214         }
215         ref("Found "+String.valueOf(result.size())+" occurance(s).");
216         Object JavaDoc[] keys=map.keySet().toArray();
217         Arrays.sort(keys);
218         for (int i=0;i < keys.length;i++) {
219             ref("");
220             if (map.get(keys[i]) instanceof ArrayList JavaDoc) {
221                 ref(keys[i]);
222                 list=(ArrayList JavaDoc)(map.get(keys[i]));
223                 Collections.sort(list);
224                 for (int j=0;j < list.size();j++) {
225                     ref(" "+list.get(j));
226                 }
227             } else {
228                 ref(keys[i]);
229             }
230         }
231         ref("");
232     }
233    public void ref(String JavaDoc s) {
234        refPs.println(s);
235     }
236     
237     public void ref(Object JavaDoc o) {
238         ref(o.toString());
239     }
240     
241     public void ref(File JavaDoc file) throws Exception JavaDoc {
242         BufferedReader JavaDoc br=new BufferedReader JavaDoc(new FileReader JavaDoc(file));
243         String JavaDoc line;
244         while ((line=br.readLine()) != null) {
245             ref(line);
246         }
247         br.close();
248     }
249      protected String JavaDoc getDisplayText(RefactoringElement elm) {
250         String JavaDoc app="";
251         if (elm.getStatus() == RefactoringElement.WARNING) {
252             app=" [ warning! ]";
253         } else if (elm.getStatus() == RefactoringElement.GUARDED) {
254             app=" [ error: code is in guarded block ]";
255         }
256         return elm.getDisplayText()+app;
257      }
258
259     private File JavaDoc writeToWorkDir(File JavaDoc resF, String JavaDoc name) throws IOException JavaDoc {
260        byte buff[] = new byte[(int)resF.length()];
261        FileInputStream JavaDoc fis = new FileInputStream JavaDoc(resF);
262        File JavaDoc retF = new File JavaDoc(getWorkDir(),name);
263        FileOutputStream JavaDoc fos = new FileOutputStream JavaDoc(retF);
264        try {
265            fis.read(buff);
266            fos.write(buff);
267        } finally {
268            fis.close();
269            fos.close();
270        }
271        return retF;
272     }
273 }
Popular Tags