1 19 package org.netbeans.modules.java.editor.semantic; 20 21 import com.sun.source.tree.CompilationUnitTree; 22 import com.sun.source.tree.ImportTree; 23 import com.sun.source.util.TreePath; 24 import java.io.IOException ; 25 import java.util.Collections ; 26 import java.util.List ; 27 import java.util.logging.Logger ; 28 import org.netbeans.api.java.source.CancellableTask; 29 import org.netbeans.api.java.source.JavaSource; 30 import org.netbeans.api.java.source.JavaSource.Phase; 31 import org.netbeans.api.java.source.TreePathHandle; 32 import org.netbeans.api.java.source.WorkingCopy; 33 import org.netbeans.spi.editor.hints.ChangeInfo; 34 import org.netbeans.spi.editor.hints.Fix; 35 import org.openide.filesystems.FileObject; 36 import org.openide.util.Exceptions; 37 import org.openide.util.NbBundle; 38 39 43 public class RemoveUnusedImportFix implements Fix { 44 45 public static RemoveUnusedImportFix create(FileObject file, TreePathHandle importToRemove) { 46 return new RemoveUnusedImportFix(file, Collections.singletonList(importToRemove), "FIX_Remove_Unused_Import"); 47 } 48 49 public static RemoveUnusedImportFix create(FileObject file, List <TreePathHandle> importsToRemove) { 50 return new RemoveUnusedImportFix(file, importsToRemove, "FIX_All_Remove_Unused_Import"); 51 } 52 53 private FileObject file; 54 private List <TreePathHandle> importsToRemove; 55 private String bundleKey; 56 57 private RemoveUnusedImportFix(FileObject file, List <TreePathHandle> importsToRemove, String bundleKey) { 58 this.file = file; 59 this.importsToRemove = importsToRemove; 60 this.bundleKey = bundleKey; 61 } 62 63 public String getText() { 64 return NbBundle.getMessage(RemoveUnusedImportFix.class, bundleKey); 65 } 66 67 public ChangeInfo implement() { 68 JavaSource js = JavaSource.forFileObject(file); 69 70 try { 71 js.runModificationTask(new CancellableTask<WorkingCopy>() { 72 public void cancel() {} 73 public void run(WorkingCopy copy) throws Exception { 74 copy.toPhase(Phase.PARSED); 75 76 CompilationUnitTree nueCUT = copy.getCompilationUnit(); 77 78 for (TreePathHandle handle : importsToRemove) { 79 TreePath tp = handle.resolve(copy); 80 81 if (tp == null) { 82 Logger.getLogger(RemoveUnusedImportFix.class.getName()).info("Cannot resolve import to remove."); return ; 85 } 86 87 nueCUT = copy.getTreeMaker().removeCompUnitImport(nueCUT, (ImportTree) tp.getLeaf()); 88 } 89 90 copy.rewrite(copy.getCompilationUnit(), nueCUT); 91 } 92 }).commit(); 93 } catch (IOException ex) { 94 Exceptions.printStackTrace(ex); 95 } 96 97 return null; 98 } 99 100 } 101 | Popular Tags |