KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > refactoring > java > plugins > MoveRefactoringPlugin


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 package org.netbeans.modules.refactoring.java.plugins;
20
21 import com.sun.source.tree.ClassTree;
22 import com.sun.source.tree.CompilationUnitTree;
23 import com.sun.source.tree.Tree;
24 import com.sun.source.util.TreePath;
25 import java.io.IOException JavaDoc;
26 import java.net.URL JavaDoc;
27 import java.util.*;
28 import org.netbeans.api.fileinfo.NonRecursiveFolder;
29 import org.netbeans.api.java.classpath.ClassPath;
30 import org.netbeans.api.java.source.*;
31 import org.netbeans.api.queries.VisibilityQuery;
32 import org.netbeans.modules.refactoring.api.*;
33 import org.netbeans.modules.refactoring.java.*;
34 import org.netbeans.modules.refactoring.java.classpath.RefactoringClassPathImplementation;
35 import org.netbeans.modules.refactoring.java.ui.tree.ElementGripFactory;
36 import org.netbeans.modules.refactoring.spi.RefactoringElementsBag;
37 import org.openide.ErrorManager;
38 import org.openide.filesystems.FileObject;
39 import org.openide.filesystems.FileUtil;
40
41 public class MoveRefactoringPlugin extends JavaRefactoringPlugin {
42
43     private Map packagePostfix = new HashMap();
44     private AbstractRefactoring refactoring;
45     ArrayList<FileObject> filesToMove = new ArrayList();
46     HashMap<FileObject,ElementHandle> classes;
47     Map<FileObject, Set<FileObject>> whoReferences = new HashMap();
48     private FileObject[] origFilesToMove;
49     public MoveRefactoringPlugin(MoveRefactoring move) {
50         this.refactoring = move;
51         setup(move.getRefactoringSource().lookupAll(FileObject.class), "", true);
52     }
53     
54     public MoveRefactoringPlugin(RenameRefactoring rename) {
55         this.refactoring = rename;
56         FileObject fo = rename.getRefactoringSource().lookup(FileObject.class);
57         if (fo!=null) {
58             setup(Collections.singletonList(fo), "", true);
59         } else {
60             setup(Collections.singletonList(((NonRecursiveFolder)rename.getRefactoringSource().lookup(NonRecursiveFolder.class)).getFolder()), "", false);
61         }
62     }
63     
64     public Problem preCheck() {
65         return null;
66     }
67
68     public Problem checkParameters() {
69         return null;
70     }
71
72     public Problem fastCheckParameters() {
73         return null;
74     }
75
76     private Set<FileObject> getRelevantFiles() {
77         ClasspathInfo cpInfo = refactoring.getContext().lookup(ClasspathInfo.class);
78         ClassIndex idx = cpInfo.getClassIndex();
79         Set<FileObject> set = new HashSet<FileObject>();
80         for (Map.Entry<FileObject, ElementHandle> entry : classes.entrySet()) {
81             //set.add(SourceUtils.getFile(el, cpInfo));
82
Set<FileObject> files = idx.getResources(entry.getValue(), EnumSet.of(ClassIndex.SearchKind.TYPE_REFERENCES, ClassIndex.SearchKind.IMPLEMENTORS),EnumSet.of(ClassIndex.SearchScope.SOURCE));
83             set.addAll(files);
84             whoReferences.put(entry.getKey(), files);
85         }
86         set.addAll(filesToMove);
87         return set;
88     }
89
90     private ClasspathInfo getClasspathInfo(CompilationInfo info) {
91         //ClassPath boot = info.getClasspathInfo().getClassPath(ClasspathInfo.PathKind.BOOT);
92
ClassPath rcp = RefactoringClassPathImplementation.getCustom(filesToMove);
93         ClasspathInfo cpi = ClasspathInfo.create(rcp, rcp, rcp);
94         return cpi;
95     }
96     
97     private void initClasses() {
98         classes = new HashMap();
99         for (int i=0;i<filesToMove.size();i++) {
100             final int j = i;
101             try {
102                 JavaSource source = JavaSource.forFileObject(filesToMove.get(i));
103                 
104                 source.runUserActionTask(new CancellableTask<CompilationController>() {
105                     
106                     public void cancel() {
107                         throw new UnsupportedOperationException JavaDoc("Not supported yet.");
108                     }
109                     
110                     public void run(final CompilationController parameter) throws Exception JavaDoc {
111                         parameter.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
112                         List<? extends Tree> trees= parameter.getCompilationUnit().getTypeDecls();
113                         for (Tree t: trees) {
114                             if (t.getKind() == Tree.Kind.CLASS) {
115                                 if (((ClassTree) t).getSimpleName().toString().equals(filesToMove.get(j).getName())) {
116                                     classes.put(filesToMove.get(j), ElementHandle.create(parameter.getTrees().getElement(TreePath.getPath(parameter.getCompilationUnit(), t))));
117                                     return ;
118                                 }
119                             }
120                         }
121                               
122                     }
123                 }, true);
124             } catch (IOException JavaDoc ex) {
125                 java.util.logging.Logger.getLogger("global").log(java.util.logging.Level.SEVERE, ex.getMessage(), ex);
126             };
127             
128         }
129     }
130     
131     public Problem prepare(RefactoringElementsBag elements) {
132         ClasspathInfo cpInfo = refactoring.getContext().lookup(ClasspathInfo.class);
133         final CompilationInfo mainInfo = refactoring.getContext().lookup(CompilationInfo.class);
134         
135         if (cpInfo==null) {
136             cpInfo = getClasspathInfo(mainInfo);
137             refactoring.getContext().add(cpInfo);
138         }
139         
140         initClasses();
141         
142         Set<FileObject> a = getRelevantFiles();
143         fireProgressListenerStart(ProgressEvent.START, a.size());
144         if (!a.isEmpty()) {
145             final Collection<ModificationResult> results = processFiles(a, new UpdateReferences());
146             elements.registerTransaction(new RetoucheCommit(results));
147             for (ModificationResult result:results) {
148                 for (FileObject jfo : result.getModifiedFileObjects()) {
149                     for (ModificationResult.Difference dif: result.getDifferences(jfo)) {
150                         elements.add(refactoring,DiffElement.create(dif, jfo,result));
151                     }
152                 }
153             }
154             
155         }
156         fireProgressListenerStop();
157         return null;
158     }
159     String JavaDoc getNewPackageName() {
160         if (refactoring instanceof MoveRefactoring) {
161             return RetoucheUtils.getPackageName(((MoveRefactoring) refactoring).getTarget().lookup(URL JavaDoc.class));
162         } else {
163             return ((RenameRefactoring) refactoring).getNewName();
164         }
165     }
166     
167     String JavaDoc getTargetPackageName(FileObject fo) {
168         if (refactoring instanceof RenameRefactoring) {
169             if (refactoring.getRefactoringSource().lookup(NonRecursiveFolder.class) !=null)
170                 //package rename
171
return getNewPackageName();
172             else {
173                 //folder rename
174
FileObject folder = refactoring.getRefactoringSource().lookup(FileObject.class);
175                 ClassPath cp = ClassPath.getClassPath(folder, ClassPath.SOURCE);
176                 FileObject root = cp.findOwnerRoot(folder);
177                 String JavaDoc prefix = FileUtil.getRelativePath(root, folder.getParent()).replace('/','.');
178                 String JavaDoc postfix = FileUtil.getRelativePath(folder, fo.getParent()).replace('/', '.');
179                 String JavaDoc t = concat(prefix, getNewPackageName(), postfix);
180                 return t;
181             }
182         } else if (packagePostfix != null) {
183             String JavaDoc postfix = (String JavaDoc) packagePostfix.get(fo);
184             String JavaDoc packageName = concat(null, getNewPackageName(), postfix);
185             return packageName;
186         } else
187             return getNewPackageName();
188     }
189     
190     private void setup(Collection fileObjects, String JavaDoc postfix, boolean recursively) {
191         for (Iterator i = fileObjects.iterator(); i.hasNext(); ) {
192             FileObject fo = (FileObject) i.next();
193             if (RetoucheUtils.isJavaFile(fo)) {
194                 packagePostfix.put(fo, postfix.replace('/', '.'));
195                 filesToMove.add(fo);
196             } else if (!(fo.isFolder())) {
197                 packagePostfix.put(fo, postfix.replace('/', '.'));
198             } else if (VisibilityQuery.getDefault().isVisible(fo)) {
199                 //o instanceof DataFolder
200
//CVS folders are ignored
201
boolean addDot = !"".equals(postfix);
202                 Collection col = new ArrayList();
203                 for (FileObject fo2: fo.getChildren()) {
204                     col.add(fo2);
205                 }
206                 if (recursively)
207                     setup(col, postfix +(addDot?".":"") +fo.getName(), true); // NOI18N
208
}
209         }
210     }
211  
212     private String JavaDoc concat(String JavaDoc s1, String JavaDoc s2, String JavaDoc s3) {
213         String JavaDoc result = "";
214         if (s1 != null && !"".equals(s1)) {
215             result += s1 + "."; // NOI18N
216
}
217         result +=s2;
218         if (s3 != null && !"".equals(s3)) {
219             result += ("".equals(result)? "" : ".") + s3; // NOI18N
220
}
221         return result;
222     }
223     private class UpdateReferences implements CancellableTask<WorkingCopy> {
224
225         public UpdateReferences() {
226         }
227
228         public void cancel() {
229         }
230
231         public void run(WorkingCopy compiler) throws IOException JavaDoc {
232             compiler.toPhase(JavaSource.Phase.RESOLVED);
233             CompilationUnitTree cu = compiler.getCompilationUnit();
234             if (cu == null) {
235                 ErrorManager.getDefault().log(ErrorManager.ERROR, "compiler.getCompilationUnit() is null " + compiler);
236                 return;
237             }
238             
239             MoveTransformer findVisitor = new MoveTransformer(compiler, MoveRefactoringPlugin.this);
240             findVisitor.scan(compiler.getCompilationUnit(), null);
241
242             for (TreePath tree : findVisitor.getUsages()) {
243                     ElementGripFactory.getDefault().put(compiler.getFileObject(), tree, compiler);
244           }
245             fireProgressListenerStep();
246         }
247     }
248 }
249
Popular Tags