1 11 package org.eclipse.jdt.internal.corext.refactoring.reorg; 12 13 import java.util.ArrayList ; 14 import java.util.Arrays ; 15 import java.util.HashMap ; 16 import java.util.HashSet ; 17 import java.util.Iterator ; 18 import java.util.List ; 19 import java.util.Map ; 20 import java.util.Set ; 21 import java.util.StringTokenizer ; 22 23 import org.eclipse.core.runtime.Assert; 24 import org.eclipse.core.runtime.CoreException; 25 import org.eclipse.core.runtime.IPath; 26 import org.eclipse.core.runtime.IProgressMonitor; 27 import org.eclipse.core.runtime.IStatus; 28 import org.eclipse.core.runtime.OperationCanceledException; 29 import org.eclipse.core.runtime.SubProgressMonitor; 30 31 import org.eclipse.core.filebuffers.ITextFileBuffer; 32 33 import org.eclipse.core.resources.IContainer; 34 import org.eclipse.core.resources.IFile; 35 import org.eclipse.core.resources.IFolder; 36 import org.eclipse.core.resources.IProject; 37 import org.eclipse.core.resources.IResource; 38 import org.eclipse.core.resources.ResourceAttributes; 39 import org.eclipse.core.resources.mapping.IResourceChangeDescriptionFactory; 40 41 import org.eclipse.jface.text.BadLocationException; 42 import org.eclipse.jface.text.IDocument; 43 44 import org.eclipse.ltk.core.refactoring.Change; 45 import org.eclipse.ltk.core.refactoring.ChangeDescriptor; 46 import org.eclipse.ltk.core.refactoring.CompositeChange; 47 import org.eclipse.ltk.core.refactoring.NullChange; 48 import org.eclipse.ltk.core.refactoring.RefactoringChangeDescriptor; 49 import org.eclipse.ltk.core.refactoring.RefactoringDescriptor; 50 import org.eclipse.ltk.core.refactoring.RefactoringStatus; 51 import org.eclipse.ltk.core.refactoring.TextFileChange; 52 import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext; 53 import org.eclipse.ltk.core.refactoring.participants.CopyArguments; 54 import org.eclipse.ltk.core.refactoring.participants.MoveArguments; 55 import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments; 56 import org.eclipse.ltk.core.refactoring.participants.RefactoringParticipant; 57 import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor; 58 import org.eclipse.ltk.core.refactoring.participants.ReorgExecutionLog; 59 import org.eclipse.ltk.core.refactoring.participants.ResourceChangeChecker; 60 import org.eclipse.ltk.core.refactoring.participants.SharableParticipants; 61 import org.eclipse.ltk.core.refactoring.participants.ValidateEditChecker; 62 63 import org.eclipse.jdt.core.IClassFile; 64 import org.eclipse.jdt.core.ICompilationUnit; 65 import org.eclipse.jdt.core.IField; 66 import org.eclipse.jdt.core.IImportContainer; 67 import org.eclipse.jdt.core.IImportDeclaration; 68 import org.eclipse.jdt.core.IInitializer; 69 import org.eclipse.jdt.core.IJavaElement; 70 import org.eclipse.jdt.core.IJavaModel; 71 import org.eclipse.jdt.core.IJavaProject; 72 import org.eclipse.jdt.core.IMember; 73 import org.eclipse.jdt.core.IMethod; 74 import org.eclipse.jdt.core.IOpenable; 75 import org.eclipse.jdt.core.IPackageDeclaration; 76 import org.eclipse.jdt.core.IPackageFragment; 77 import org.eclipse.jdt.core.IPackageFragmentRoot; 78 import org.eclipse.jdt.core.ISourceReference; 79 import org.eclipse.jdt.core.IType; 80 import org.eclipse.jdt.core.JavaConventions; 81 import org.eclipse.jdt.core.JavaCore; 82 import org.eclipse.jdt.core.JavaModelException; 83 import org.eclipse.jdt.core.dom.AST; 84 import org.eclipse.jdt.core.dom.ASTNode; 85 import org.eclipse.jdt.core.dom.ASTParser; 86 import org.eclipse.jdt.core.dom.AbstractTypeDeclaration; 87 import org.eclipse.jdt.core.dom.AnonymousClassDeclaration; 88 import org.eclipse.jdt.core.dom.BodyDeclaration; 89 import org.eclipse.jdt.core.dom.CompilationUnit; 90 import org.eclipse.jdt.core.dom.EnumConstantDeclaration; 91 import org.eclipse.jdt.core.dom.EnumDeclaration; 92 import org.eclipse.jdt.core.dom.FieldDeclaration; 93 import org.eclipse.jdt.core.dom.ImportDeclaration; 94 import org.eclipse.jdt.core.dom.Javadoc; 95 import org.eclipse.jdt.core.dom.PackageDeclaration; 96 import org.eclipse.jdt.core.dom.SimpleName; 97 import org.eclipse.jdt.core.dom.Type; 98 import org.eclipse.jdt.core.dom.VariableDeclarationFragment; 99 import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; 100 import org.eclipse.jdt.core.dom.rewrite.ListRewrite; 101 import org.eclipse.jdt.core.refactoring.IJavaRefactorings; 102 import org.eclipse.jdt.core.refactoring.descriptors.JavaRefactoringDescriptor; 103 104 import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; 105 import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory; 106 import org.eclipse.jdt.internal.corext.dom.ASTNodes; 107 import org.eclipse.jdt.internal.corext.refactoring.Checks; 108 import org.eclipse.jdt.internal.corext.refactoring.JDTRefactoringDescriptor; 109 import org.eclipse.jdt.internal.corext.refactoring.JDTRefactoringDescriptorComment; 110 import org.eclipse.jdt.internal.corext.refactoring.JavaRefactoringArguments; 111 import org.eclipse.jdt.internal.corext.refactoring.RefactoringCoreMessages; 112 import org.eclipse.jdt.internal.corext.refactoring.changes.CompilationUnitChange; 113 import org.eclipse.jdt.internal.corext.refactoring.changes.CopyCompilationUnitChange; 114 import org.eclipse.jdt.internal.corext.refactoring.changes.CopyPackageChange; 115 import org.eclipse.jdt.internal.corext.refactoring.changes.CopyPackageFragmentRootChange; 116 import org.eclipse.jdt.internal.corext.refactoring.changes.CopyResourceChange; 117 import org.eclipse.jdt.internal.corext.refactoring.changes.DynamicValidationStateChange; 118 import org.eclipse.jdt.internal.corext.refactoring.changes.MoveCompilationUnitChange; 119 import org.eclipse.jdt.internal.corext.refactoring.changes.MovePackageChange; 120 import org.eclipse.jdt.internal.corext.refactoring.changes.MovePackageFragmentRootChange; 121 import org.eclipse.jdt.internal.corext.refactoring.changes.MoveResourceChange; 122 import org.eclipse.jdt.internal.corext.refactoring.code.ScriptableRefactoring; 123 import org.eclipse.jdt.internal.corext.refactoring.reorg.IReorgPolicy.ICopyPolicy; 124 import org.eclipse.jdt.internal.corext.refactoring.reorg.IReorgPolicy.IMovePolicy; 125 import org.eclipse.jdt.internal.corext.refactoring.structure.ASTNodeSearchUtil; 126 import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; 127 import org.eclipse.jdt.internal.corext.refactoring.structure.ImportRewriteUtil; 128 import org.eclipse.jdt.internal.corext.refactoring.util.Changes; 129 import org.eclipse.jdt.internal.corext.refactoring.util.JavaElementUtil; 130 import org.eclipse.jdt.internal.corext.refactoring.util.QualifiedNameFinder; 131 import org.eclipse.jdt.internal.corext.refactoring.util.QualifiedNameSearchResult; 132 import org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser; 133 import org.eclipse.jdt.internal.corext.refactoring.util.RefactoringFileBuffers; 134 import org.eclipse.jdt.internal.corext.refactoring.util.ResourceUtil; 135 import org.eclipse.jdt.internal.corext.refactoring.util.TextChangeManager; 136 import org.eclipse.jdt.internal.corext.util.JavaElementResourceMapping; 137 import org.eclipse.jdt.internal.corext.util.JavaModelUtil; 138 import org.eclipse.jdt.internal.corext.util.Messages; 139 import org.eclipse.jdt.internal.corext.util.Strings; 140 141 import org.eclipse.jdt.ui.JavaElementLabels; 142 143 import org.eclipse.jdt.internal.ui.JavaPlugin; 144 145 public final class ReorgPolicyFactory { 146 147 private static final class ActualSelectionComputer { 148 149 private final IJavaElement[] fJavaElements; 150 151 private final IResource[] fResources; 152 153 public ActualSelectionComputer(IJavaElement[] javaElements, IResource[] resources) { 154 fJavaElements= javaElements; 155 fResources= resources; 156 } 157 158 public IJavaElement[] getActualJavaElementsToReorg() throws JavaModelException { 159 List result= new ArrayList (); 160 for (int i= 0; i < fJavaElements.length; i++) { 161 IJavaElement element= fJavaElements[i]; 162 if (element == null) 163 continue; 164 if (element instanceof IType) { 165 IType type= (IType) element; 166 ICompilationUnit cu= type.getCompilationUnit(); 167 if (cu != null && type.getDeclaringType() == null && cu.exists() && cu.getTypes().length == 1 && !result.contains(cu)) 168 result.add(cu); 169 else if (!result.contains(type)) 170 result.add(type); 171 } else if (!result.contains(element)) { 172 result.add(element); 173 } 174 } 175 return (IJavaElement[]) result.toArray(new IJavaElement[result.size()]); 176 } 177 178 public IResource[] getActualResourcesToReorg() { 179 Set javaElementSet= new HashSet (Arrays.asList(fJavaElements)); 180 List result= new ArrayList (); 181 for (int i= 0; i < fResources.length; i++) { 182 if (fResources[i] == null) 183 continue; 184 IJavaElement element= JavaCore.create(fResources[i]); 185 if (element == null || !element.exists() || !javaElementSet.contains(element)) 186 if (!result.contains(fResources[i])) 187 result.add(fResources[i]); 188 } 189 return (IResource[]) result.toArray(new IResource[result.size()]); 190 191 } 192 } 193 194 private static final class CopyFilesFoldersAndCusPolicy extends FilesFoldersAndCusReorgPolicy implements ICopyPolicy { 195 196 private static final String POLICY_COPY_RESOURCE= "org.eclipse.jdt.ui.copyResources"; 198 private static Change copyCuToPackage(ICompilationUnit cu, IPackageFragment dest, NewNameProposer nameProposer, INewNameQueries copyQueries) { 199 IResource res= ReorgUtils.getResource(cu); 202 if (res != null && res.isLinked()) { 203 if (ResourceUtil.getResource(dest) instanceof IContainer) 204 return copyFileToContainer(cu, (IContainer) ResourceUtil.getResource(dest), nameProposer, copyQueries); 205 } 206 207 String newName= nameProposer.createNewName(cu, dest); 208 Change simpleCopy= new CopyCompilationUnitChange(cu, dest, copyQueries.createStaticQuery(newName)); 209 if (newName == null || newName.equals(cu.getElementName())) 210 return simpleCopy; 211 212 try { 213 IPath newPath= cu.getResource().getParent().getFullPath().append(JavaModelUtil.getRenamedCUName(cu, newName)); 214 INewNameQuery nameQuery= copyQueries.createNewCompilationUnitNameQuery(cu, newName); 215 return new CreateCopyOfCompilationUnitChange(newPath, cu.getSource(), cu, nameQuery); 216 } catch (CoreException e) { 217 return simpleCopy; 219 } 220 } 221 222 private static Change copyFileToContainer(ICompilationUnit cu, IContainer dest, NewNameProposer nameProposer, INewNameQueries copyQueries) { 223 IResource resource= ReorgUtils.getResource(cu); 224 return createCopyResourceChange(resource, nameProposer, copyQueries, dest); 225 } 226 227 private static Change createCopyResourceChange(IResource resource, NewNameProposer nameProposer, INewNameQueries copyQueries, IContainer destination) { 228 if (resource == null || destination == null) 229 return new NullChange(); 230 INewNameQuery nameQuery; 231 String name= nameProposer.createNewName(resource, destination); 232 if (name == null) 233 nameQuery= copyQueries.createNullQuery(); 234 else 235 nameQuery= copyQueries.createNewResourceNameQuery(resource, name); 236 return new CopyResourceChange(resource, destination, nameQuery); 237 } 238 239 private CopyModifications fModifications; 240 241 private ReorgExecutionLog fReorgExecutionLog; 242 243 CopyFilesFoldersAndCusPolicy(IFile[] files, IFolder[] folders, ICompilationUnit[] cus) { 244 super(files, folders, cus); 245 } 246 247 private Change createChange(ICompilationUnit unit, NewNameProposer nameProposer, INewNameQueries copyQueries) { 248 IPackageFragment pack= getDestinationAsPackageFragment(); 249 if (pack != null) 250 return copyCuToPackage(unit, pack, nameProposer, copyQueries); 251 IContainer container= getDestinationAsContainer(); 252 return copyFileToContainer(unit, container, nameProposer, copyQueries); 253 } 254 255 public Change createChange(IProgressMonitor pm, INewNameQueries copyQueries) { 256 IFile[] file= getFiles(); 257 IFolder[] folders= getFolders(); 258 ICompilationUnit[] cus= getCus(); 259 pm.beginTask("", cus.length + file.length + folders.length); NewNameProposer nameProposer= new NewNameProposer(); 261 CompositeChange composite= new DynamicValidationStateChange(RefactoringCoreMessages.ReorgPolicy_copy); 262 composite.markAsSynthetic(); 263 for (int i= 0; i < cus.length; i++) { 264 composite.add(createChange(cus[i], nameProposer, copyQueries)); 265 pm.worked(1); 266 } 267 if (pm.isCanceled()) 268 throw new OperationCanceledException(); 269 for (int i= 0; i < file.length; i++) { 270 composite.add(createChange(file[i], nameProposer, copyQueries)); 271 pm.worked(1); 272 } 273 if (pm.isCanceled()) 274 throw new OperationCanceledException(); 275 for (int i= 0; i < folders.length; i++) { 276 composite.add(createChange(folders[i], nameProposer, copyQueries)); 277 pm.worked(1); 278 } 279 pm.done(); 280 return composite; 281 } 282 283 private Change createChange(IResource resource, NewNameProposer nameProposer, INewNameQueries copyQueries) { 284 IContainer dest= getDestinationAsContainer(); 285 return createCopyResourceChange(resource, nameProposer, copyQueries, dest); 286 } 287 288 protected JDTRefactoringDescriptor createRefactoringDescriptor(JDTRefactoringDescriptorComment comment, Map arguments, String description, String project, int flags) { 289 return new JDTCopyRefactoringDescriptor(getReorgExecutionLog(), getProcessorId(), project, description, comment.asString(), arguments, flags); 290 } 291 292 protected String getDescriptionPlural() { 293 final int kind= getContentKind(); 294 switch (kind) { 295 case ONLY_FOLDERS: 296 return RefactoringCoreMessages.ReorgPolicyFactory_copy_folders; 297 case ONLY_FILES: 298 return RefactoringCoreMessages.ReorgPolicyFactory_copy_files; 299 case ONLY_CUS: 300 return RefactoringCoreMessages.ReorgPolicyFactory_copy_compilation_units; 301 } 302 return RefactoringCoreMessages.ReorgPolicyFactory_copy_description_plural; 303 } 304 305 protected String getDescriptionSingular() { 306 final int kind= getContentKind(); 307 switch (kind) { 308 case ONLY_FOLDERS: 309 return RefactoringCoreMessages.ReorgPolicyFactory_copy_folder; 310 case ONLY_FILES: 311 return RefactoringCoreMessages.ReorgPolicyFactory_copy_file; 312 case ONLY_CUS: 313 return RefactoringCoreMessages.ReorgPolicyFactory_copy_compilation_unit; 314 } 315 return RefactoringCoreMessages.ReorgPolicyFactory_copy_description_singular; 316 } 317 318 private Object getDestination() { 319 Object result= getDestinationAsPackageFragment(); 320 if (result != null) 321 return result; 322 return getDestinationAsContainer(); 323 } 324 325 protected String getHeaderPattern() { 326 return RefactoringCoreMessages.ReorgPolicyFactory_copy_header; 327 } 328 329 protected RefactoringModifications getModifications() throws CoreException { 330 if (fModifications != null) 331 return fModifications; 332 fModifications= new CopyModifications(); 333 fReorgExecutionLog= new ReorgExecutionLog(); 334 CopyArguments jArgs= new CopyArguments(getDestination(), fReorgExecutionLog); 335 CopyArguments rArgs= new CopyArguments(getDestinationAsContainer(), fReorgExecutionLog); 336 ICompilationUnit[] cus= getCus(); 337 for (int i= 0; i < cus.length; i++) { 338 fModifications.copy(cus[i], jArgs, rArgs); 339 } 340 IResource[] resources= ReorgUtils.union(getFiles(), getFolders()); 341 for (int i= 0; i < resources.length; i++) { 342 fModifications.copy(resources[i], rArgs); 343 } 344 return fModifications; 345 } 346 347 public String getPolicyId() { 348 return POLICY_COPY_RESOURCE; 349 } 350 351 protected String getProcessorId() { 352 return IJavaRefactorings.COPY; 353 } 354 355 protected String getRefactoringId() { 356 return IJavaRefactorings.COPY; 357 } 358 359 public ReorgExecutionLog getReorgExecutionLog() { 360 return fReorgExecutionLog; 361 } 362 } 363 364 private static final class CopyPackageFragmentRootsPolicy extends PackageFragmentRootsReorgPolicy implements ICopyPolicy { 365 366 private static final String POLICY_COPY_ROOTS= "org.eclipse.jdt.ui.copyRoots"; 368 private CopyModifications fModifications; 369 370 private ReorgExecutionLog fReorgExecutionLog; 371 372 public CopyPackageFragmentRootsPolicy(IPackageFragmentRoot[] roots) { 373 super(roots); 374 } 375 376 private Change createChange(IPackageFragmentRoot root, IJavaProject destination, NewNameProposer nameProposer, INewNameQueries copyQueries) { 377 IResource res= root.getResource(); 378 IProject destinationProject= destination.getProject(); 379 String newName= nameProposer.createNewName(res, destinationProject); 380 INewNameQuery nameQuery; 381 if (newName == null) 382 nameQuery= copyQueries.createNullQuery(); 383 else 384 nameQuery= copyQueries.createNewPackageFragmentRootNameQuery(root, newName); 385 return new CopyPackageFragmentRootChange(root, destinationProject, nameQuery, null); 387 } 388 389 public Change createChange(IProgressMonitor pm, INewNameQueries copyQueries) { 390 NewNameProposer nameProposer= new NewNameProposer(); 391 IPackageFragmentRoot[] roots= getPackageFragmentRoots(); 392 pm.beginTask("", roots.length); CompositeChange composite= new DynamicValidationStateChange(RefactoringCoreMessages.ReorgPolicy_copy_source_folder); 394 composite.markAsSynthetic(); 395 IJavaProject destination= getDestinationJavaProject(); 396 Assert.isNotNull(destination); 397 for (int i= 0; i < roots.length; i++) { 398 composite.add(createChange(roots[i], destination, nameProposer, copyQueries)); 399 pm.worked(1); 400 } 401 pm.done(); 402 return composite; 403 } 404 405 protected JDTRefactoringDescriptor createRefactoringDescriptor(JDTRefactoringDescriptorComment comment, Map arguments, String description, String project, int flags) { 406 return new JDTCopyRefactoringDescriptor(getReorgExecutionLog(), getProcessorId(), project, description, comment.asString(), arguments, flags); 407 } 408 409 protected String getDescriptionPlural() { 410 return RefactoringCoreMessages.ReorgPolicyFactory_copy_roots_plural; 411 } 412 413 protected String getDescriptionSingular() { 414 return RefactoringCoreMessages.ReorgPolicyFactory_copy_roots_singular; 415 } 416 417 protected String getHeaderPattern() { 418 return RefactoringCoreMessages.ReorgPolicyFactory_copy_roots_header; 419 } 420 421 protected RefactoringModifications getModifications() throws CoreException { 422 if (fModifications != null) 423 return fModifications; 424 425 fModifications= new CopyModifications(); 426 fReorgExecutionLog= new ReorgExecutionLog(); 427 CopyArguments javaArgs= new CopyArguments(getDestinationJavaProject(), fReorgExecutionLog); 428 CopyArguments resourceArgs= new CopyArguments(getDestinationJavaProject().getProject(), fReorgExecutionLog); 429 IPackageFragmentRoot[] roots= getRoots(); 430 for (int i= 0; i < roots.length; i++) { 431 fModifications.copy(roots[i], javaArgs, resourceArgs); 432 } 433 return fModifications; 434 } 435 436 public String getPolicyId() { 437 return POLICY_COPY_ROOTS; 438 } 439 440 protected String getProcessorId() { 441 return IJavaRefactorings.COPY; 442 } 443 444 protected String getRefactoringId() { 445 return IJavaRefactorings.COPY; 446 } 447 448 public ReorgExecutionLog getReorgExecutionLog() { 449 return fReorgExecutionLog; 450 } 451 } 452 453 private static final class CopyPackagesPolicy extends PackagesReorgPolicy implements ICopyPolicy { 454 455 private static final String POLICY_COPY_PACKAGES= "org.eclipse.jdt.ui.copyPackages"; 457 private CopyModifications fModifications; 458 459 private ReorgExecutionLog fReorgExecutionLog; 460 461 public CopyPackagesPolicy(IPackageFragment[] packageFragments) { 462 super(packageFragments); 463 } 464 465 private Change createChange(IPackageFragment pack, IPackageFragmentRoot destination, NewNameProposer nameProposer, INewNameQueries copyQueries) { 466 String newName= nameProposer.createNewName(pack, destination); 467 if (newName == null || JavaConventions.validatePackageName(newName).getSeverity() < IStatus.ERROR) { 468 INewNameQuery nameQuery; 469 if (newName == null) 470 nameQuery= copyQueries.createNullQuery(); 471 else 472 nameQuery= copyQueries.createNewPackageNameQuery(pack, newName); 473 return new CopyPackageChange(pack, destination, nameQuery); 474 } else { 475 if (destination.getResource() instanceof IContainer) { 476 IContainer dest= (IContainer) destination.getResource(); 477 IResource res= pack.getResource(); 478 INewNameQuery nameQuery= copyQueries.createNewResourceNameQuery(res, newName); 479 return new CopyResourceChange(res, dest, nameQuery); 480 } else { 481 return new NullChange(); 482 } 483 } 484 } 485 486 public Change createChange(IProgressMonitor pm, INewNameQueries newNameQueries) throws JavaModelException { 487 NewNameProposer nameProposer= new NewNameProposer(); 488 IPackageFragment[] fragments= getPackages(); 489 pm.beginTask("", fragments.length); CompositeChange composite= new DynamicValidationStateChange(RefactoringCoreMessages.ReorgPolicy_copy_package); 491 composite.markAsSynthetic(); 492 IPackageFragmentRoot root= getDestinationAsPackageFragmentRoot(); 493 for (int i= 0; i < fragments.length; i++) { 494 composite.add(createChange(fragments[i], root, nameProposer, newNameQueries)); 495 pm.worked(1); 496 } 497 pm.done(); 498 return composite; 499 } 500 501 protected JDTRefactoringDescriptor createRefactoringDescriptor(JDTRefactoringDescriptorComment comment, Map arguments, String description, String project, int flags) { 502 return new JDTCopyRefactoringDescriptor(getReorgExecutionLog(), getProcessorId(), project, description, comment.asString(), arguments, flags); 503 } 504 505 protected String getDescriptionPlural() { 506 return RefactoringCoreMessages.ReorgPolicyFactory_copy_packages_plural; 507 } 508 509 protected String getDescriptionSingular() { 510 return RefactoringCoreMessages.ReorgPolicyFactory_copy_package_singular; 511 } 512 513 protected String getHeaderPattern() { 514 return RefactoringCoreMessages.ReorgPolicyFactory_copy_packages_header; 515 } 516 517 protected RefactoringModifications getModifications() throws CoreException { 518 if (fModifications != null) 519 return fModifications; 520 521 fModifications= new CopyModifications(); 522 fReorgExecutionLog= new ReorgExecutionLog(); 523 IPackageFragmentRoot destination= getDestinationAsPackageFragmentRoot(); 524 CopyArguments javaArgs= new CopyArguments(destination, fReorgExecutionLog); 525 CopyArguments resourceArgs= new CopyArguments(destination.getResource(), fReorgExecutionLog); 526 IPackageFragment[] packages= getPackages(); 527 for (int i= 0; i < packages.length; i++) { 528 fModifications.copy(packages[i], javaArgs, resourceArgs); 529 } 530 return fModifications; 531 } 532 533 public String getPolicyId() { 534 return POLICY_COPY_PACKAGES; 535 } 536 537 protected String getProcessorId() { 538 return IJavaRefactorings.COPY; 539 } 540 541 protected String getRefactoringId() { 542 return IJavaRefactorings.COPY; 543 } 544 545 public ReorgExecutionLog getReorgExecutionLog() { 546 return fReorgExecutionLog; 547 } 548 } 549 550 private static final class CopySubCuElementsPolicy extends SubCuElementReorgPolicy implements ICopyPolicy { 551 552 private static final String POLICY_COPY_MEMBERS= "org.eclipse.jdt.ui.copyMembers"; 554 private CopyModifications fModifications; 555 556 private ReorgExecutionLog fReorgExecutionLog; 557 558 CopySubCuElementsPolicy(IJavaElement[] javaElements) { 559 super(javaElements); 560 } 561 562 public boolean canEnable() throws JavaModelException { 563 return super.canEnable() && (getSourceCu() != null || getSourceClassFile() != null); 564 } 565 566 public Change createChange(IProgressMonitor pm, INewNameQueries copyQueries) throws JavaModelException { 567 try { 568 CompilationUnit sourceCuNode= createSourceCuNode(); 569 ICompilationUnit targetCu= getDestinationCu(); 570 CompilationUnitRewrite targetRewriter= new CompilationUnitRewrite(targetCu); 571 IJavaElement[] javaElements= getJavaElements(); 572 for (int i= 0; i < javaElements.length; i++) { 573 copyToDestination(javaElements[i], targetRewriter, sourceCuNode, targetRewriter.getRoot()); 574 } 575 return createCompilationUnitChange(targetCu, targetRewriter); 576 } catch (JavaModelException e) { 577 throw e; 578 } catch (CoreException e) { 579 throw new JavaModelException(e); 580 } 581 } 582 583 protected JDTRefactoringDescriptor createRefactoringDescriptor(JDTRefactoringDescriptorComment comment, Map arguments, String description, String project, int flags) { 584 return new JDTCopyRefactoringDescriptor(getReorgExecutionLog(), getProcessorId(), project, description, comment.asString(), arguments, flags); 585 } 586 587 private CompilationUnit createSourceCuNode() { 588 Assert.isTrue(getSourceCu() != null || getSourceClassFile() != null); 589 Assert.isTrue(getSourceCu() == null || getSourceClassFile() == null); 590 ASTParser parser= ASTParser.newParser(AST.JLS3); 591 if (getSourceCu() != null) 592 parser.setSource(getSourceCu()); 593 else 594 parser.setSource(getSourceClassFile()); 595 return (CompilationUnit) parser.createAST(null); 596 } 597 598 public IFile[] getAllModifiedFiles() { 599 return ReorgUtils.getFiles(new IResource[] { ReorgUtils.getResource(getDestinationCu())}); 600 } 601 602 protected String getDescriptionPlural() { 603 final int kind= getContentKind(); 604 switch (kind) { 605 case ONLY_TYPES: 606 return RefactoringCoreMessages.ReorgPolicyFactory_copy_types; 607 case ONLY_FIELDS: 608 return RefactoringCoreMessages.ReorgPolicyFactory_copy_fields; 609 case ONLY_METHODS: 610 return RefactoringCoreMessages.ReorgPolicyFactory_copy_methods; 611 case ONLY_INITIALIZERS: 612 return RefactoringCoreMessages.ReorgPolicyFactory_copy_initializers; 613 case ONLY_PACKAGE_DECLARATIONS: 614 return RefactoringCoreMessages.ReorgPolicyFactory_copy_package_declarations; 615 case ONLY_IMPORT_CONTAINERS: 616 return RefactoringCoreMessages.ReorgPolicyFactory_copy_import_containers; 617 case ONLY_IMPORT_DECLARATIONS: 618 return RefactoringCoreMessages.ReorgPolicyFactory_copy_imports; 619 } 620 return RefactoringCoreMessages.ReorgPolicyFactory_move_elements_plural; 621 } 622 623 protected String getDescriptionSingular() { 624 final int kind= getContentKind(); 625 switch (kind) { 626 case ONLY_TYPES: 627 return RefactoringCoreMessages.ReorgPolicyFactory_copy_type; 628 case ONLY_FIELDS: 629 return RefactoringCoreMessages.ReorgPolicyFactory_copy_field; 630 case ONLY_METHODS: 631 return RefactoringCoreMessages.ReorgPolicyFactory_copy_method; 632 case ONLY_INITIALIZERS: 633 return RefactoringCoreMessages.ReorgPolicyFactory_copy_initializer; 634 case ONLY_PACKAGE_DECLARATIONS: 635 return RefactoringCoreMessages.ReorgPolicyFactory_copy_package; 636 case ONLY_IMPORT_CONTAINERS: 637 return RefactoringCoreMessages.ReorgPolicyFactory_copy_import_section; 638 case ONLY_IMPORT_DECLARATIONS: 639 return RefactoringCoreMessages.ReorgPolicyFactory_copy_import; 640 } 641 return RefactoringCoreMessages.ReorgPolicyFactory_copy_elements_singular; 642 } 643 644 protected String getHeaderPattern() { 645 return RefactoringCoreMessages.ReorgPolicyFactory_copy_elements_header; 646 } 647 648 protected RefactoringModifications getModifications() throws CoreException { 649 if (fModifications != null) 650 return fModifications; 651 652 fModifications= new CopyModifications(); 653 fReorgExecutionLog= new ReorgExecutionLog(); 654 CopyArguments args= new CopyArguments(getJavaElementDestination(), fReorgExecutionLog); 655 IJavaElement[] javaElements= getJavaElements(); 656 for (int i= 0; i < javaElements.length; i++) { 657 fModifications.copy(javaElements[i], args, null); 658 } 659 return fModifications; 660 } 661 662 public String getPolicyId() { 663 return POLICY_COPY_MEMBERS; 664 } 665 666 protected String getProcessorId() { 667 return IJavaRefactorings.COPY; 668 } 669 670 protected String getRefactoringId() { 671 return IJavaRefactorings.COPY; 672 } 673 674 public ReorgExecutionLog getReorgExecutionLog() { 675 return fReorgExecutionLog; 676 } 677 678 private IClassFile getSourceClassFile() { 679 return (IClassFile) getJavaElements()[0].getAncestor(IJavaElement.CLASS_FILE); 682 } 683 } 684 685 private static abstract class FilesFoldersAndCusReorgPolicy extends ReorgPolicy { 686 687 protected static final int ONLY_CUS= 2; 688 689 protected static final int ONLY_FILES= 1; 690 691 protected static final int ONLY_FOLDERS= 0; 692 693 private static IContainer getAsContainer(IResource resDest) { 694 if (resDest instanceof IContainer) 695 return (IContainer) resDest; 696 if (resDest instanceof IFile) 697 return ((IFile) resDest).getParent(); 698 return null; 699 } 700 701 private ICompilationUnit[] fCus; 702 703 private IFile[] fFiles; 704 705 private IFolder[] fFolders; 706 707 public FilesFoldersAndCusReorgPolicy(IFile[] files, IFolder[] folders, ICompilationUnit[] cus) { 708 fFiles= files; 709 fFolders= folders; 710 fCus= cus; 711 } 712 713 public boolean canChildrenBeDestinations(IJavaElement javaElement) { 714 switch (javaElement.getElementType()) { 715 case IJavaElement.JAVA_MODEL: 716 case IJavaElement.JAVA_PROJECT: 717 case IJavaElement.PACKAGE_FRAGMENT_ROOT: 718 return true; 719 default: 720 return false; 721 } 722 } 723 724 public boolean canChildrenBeDestinations(IResource resource) { 725 return resource instanceof IContainer; 726 } 727 728 public boolean canElementBeDestination(IJavaElement javaElement) { 729 switch (javaElement.getElementType()) { 730 case IJavaElement.PACKAGE_FRAGMENT: 731 return true; 732 default: 733 return false; 734 } 735 } 736 737 public boolean canElementBeDestination(IResource resource) { 738 return resource instanceof IProject || resource instanceof IFolder; 739 } 740 741 public RefactoringStatus checkFinalConditions(IProgressMonitor pm, CheckConditionsContext context, IReorgQueries reorgQueries) throws CoreException { 742 RefactoringStatus status= super.checkFinalConditions(pm, context, reorgQueries); 743 confirmOverwriting(reorgQueries); 744 return status; 745 } 746 747 private void confirmOverwriting(IReorgQueries reorgQueries) { 748 OverwriteHelper helper= new OverwriteHelper(); 749 helper.setFiles(fFiles); 750 helper.setFolders(fFolders); 751 helper.setCus(fCus); 752 IPackageFragment destPack= getDestinationAsPackageFragment(); 753 if (destPack != null) { 754 helper.confirmOverwriting(reorgQueries, destPack); 755 } else { 756 IContainer destinationAsContainer= getDestinationAsContainer(); 757 if (destinationAsContainer != null) 758 helper.confirmOverwriting(reorgQueries, destinationAsContainer); 759 } 760 fFiles= helper.getFilesWithoutUnconfirmedOnes(); 761 fFolders= helper.getFoldersWithoutUnconfirmedOnes(); 762 fCus= helper.getCusWithoutUnconfirmedOnes(); 763 } 764 765 protected boolean containsLinkedResources() { 766 return ReorgUtils.containsLinkedResources(fFiles) || ReorgUtils.containsLinkedResources(fFolders) || ReorgUtils.containsLinkedResources(fCus); 767 } 768 769 protected JDTRefactoringDescriptor createRefactoringDescriptor(final JDTRefactoringDescriptorComment comment, final Map arguments, final String description, final String project, int flags) { 770 return new JDTRefactoringDescriptor(getProcessorId(), project, description, comment.asString(), arguments, flags); 771 } 772 773 protected final int getContentKind() { 774 final int length= fCus.length + fFiles.length + fFolders.length; 775 if (length == fCus.length) 776 return ONLY_CUS; 777 else if (length == fFiles.length) 778 return ONLY_FILES; 779 else if (length == fFolders.length) 780 return ONLY_FOLDERS; 781 return -1; 782 } 783 784 protected final ICompilationUnit[] getCus() { 785 return fCus; 786 } 787 788 public final ChangeDescriptor getDescriptor() { 789 final Map arguments= new HashMap (); 790 final int length= fFiles.length + fFolders.length + fCus.length; 791 final String description= length == 1 ? getDescriptionSingular() : getDescriptionPlural(); 792 final IProject resource= getSingleProject(); 793 final String project= resource != null ? resource.getName() : null; 794 final String header= Messages.format(getHeaderPattern(), new String [] { String.valueOf(length), getDestinationLabel()}); 795 int flags= JavaRefactoringDescriptor.JAR_MIGRATION | JavaRefactoringDescriptor.JAR_REFACTORING | RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE; 796 final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header); 797 final JDTRefactoringDescriptor descriptor= createRefactoringDescriptor(comment, arguments, description, project, flags); 798 arguments.put(ATTRIBUTE_POLICY, getPolicyId()); 799 arguments.put(ATTRIBUTE_FILES, new Integer (fFiles.length).toString()); 800 for (int offset= 0; offset < fFiles.length; offset++) 801 arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (offset + 1), descriptor.resourceToHandle(fFiles[offset])); 802 arguments.put(ATTRIBUTE_FOLDERS, new Integer (fFolders.length).toString()); 803 for (int offset= 0; offset < fFolders.length; offset++) 804 arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (offset + fFiles.length + 1), descriptor.resourceToHandle(fFolders[offset])); 805 arguments.put(ATTRIBUTE_UNITS, new Integer (fCus.length).toString()); 806 for (int offset= 0; offset < fCus.length; offset++) 807 arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (offset + fFolders.length + fFiles.length + 1), descriptor.elementToHandle(fCus[offset])); 808 arguments.putAll(getRefactoringArguments(project)); 809 return new RefactoringChangeDescriptor(descriptor); 810 } 811 812 protected final IContainer getDestinationAsContainer() { 813 IResource resDest= getResourceDestination(); 814 if (resDest != null) 815 return getAsContainer(resDest); 816 IJavaElement jelDest= getJavaElementDestination(); 817 Assert.isNotNull(jelDest); 818 return getAsContainer(ReorgUtils.getResource(jelDest)); 819 } 820 821 protected final IPackageFragment getDestinationAsPackageFragment() { 822 IPackageFragment javaAsPackage= getJavaDestinationAsPackageFragment(getJavaElementDestination()); 823 if (javaAsPackage != null) 824 return javaAsPackage; 825 return getResourceDestinationAsPackageFragment(getResourceDestination()); 826 } 827 828 protected final IJavaElement getDestinationContainerAsJavaElement() { 829 if (getJavaElementDestination() != null) 830 return getJavaElementDestination(); 831 IContainer destinationAsContainer= getDestinationAsContainer(); 832 if (destinationAsContainer == null) 833 return null; 834 IJavaElement je= JavaCore.create(destinationAsContainer); 835 if (je != null && je.exists()) 836 return je; 837 return null; 838 } 839 840 protected final IFile[] getFiles() { 841 return fFiles; 842 } 843 844 protected final IFolder[] getFolders() { 845 return fFolders; 846 } 847 848 private IPackageFragment getJavaDestinationAsPackageFragment(IJavaElement javaDest) { 849 if (javaDest == null || (fCheckDestination && !javaDest.exists())) 850 return null; 851 if (javaDest instanceof IPackageFragment) 852 return (IPackageFragment) javaDest; 853 if (javaDest instanceof IPackageFragmentRoot) 854 return ((IPackageFragmentRoot) javaDest).getPackageFragment(""); if (javaDest instanceof IJavaProject) { 856 try { 857 IPackageFragmentRoot root= ReorgUtils.getCorrespondingPackageFragmentRoot((IJavaProject) javaDest); 858 if (root != null) 859 return root.getPackageFragment(""); } catch (JavaModelException e) { 861 } 863 } 864 return (IPackageFragment) javaDest.getAncestor(IJavaElement.PACKAGE_FRAGMENT); 865 } 866 867 public final IJavaElement[] getJavaElements() { 868 return fCus; 869 } 870 871 private IPackageFragment getResourceDestinationAsPackageFragment(IResource resource) { 872 if (resource instanceof IFile) 873 return getJavaDestinationAsPackageFragment(JavaCore.create(resource.getParent())); 874 return null; 875 } 876 877 public final IResource[] getResources() { 878 return ReorgUtils.union(fFiles, fFolders); 879 } 880 881 private IProject getSingleProject() { 882 IProject result= null; 883 for (int index= 0; index < fFiles.length; index++) { 884 if (result == null) 885 result= fFiles[index].getProject(); 886 else if (!result.equals(fFiles[index].getProject())) 887 return null; 888 } 889 for (int index= 0; index < fFolders.length; index++) { 890 if (result == null) 891 result= fFolders[index].getProject(); 892 else if (!result.equals(fFolders[index].getProject())) 893 return null; 894 } 895 for (int index= 0; index < fCus.length; index++) { 896 if (result == null) 897 result= fCus[index].getJavaProject().getProject(); 898 else if (!result.equals(fCus[index].getJavaProject().getProject())) 899 return null; 900 } 901 return result; 902 } 903 904 public RefactoringStatus initialize(RefactoringArguments arguments) { 905 final RefactoringStatus status= new RefactoringStatus(); 906 if (arguments instanceof JavaRefactoringArguments) { 907 final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments; 908 int fileCount= 0; 909 int folderCount= 0; 910 int unitCount= 0; 911 String value= extended.getAttribute(ATTRIBUTE_FILES); 912 if (value != null && !"".equals(value)) { try { 914 fileCount= Integer.parseInt(value); 915 } catch (NumberFormatException exception) { 916 return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_FILES)); 917 } 918 } else 919 return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_FILES)); 920 value= extended.getAttribute(ATTRIBUTE_FOLDERS); 921 if (value != null && !"".equals(value)) { try { 923 folderCount= Integer.parseInt(value); 924 } catch (NumberFormatException exception) { 925 return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_FOLDERS)); 926 } 927 } else 928 return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_FOLDERS)); 929 value= extended.getAttribute(ATTRIBUTE_UNITS); 930 if (value != null && !"".equals(value)) { try { 932 unitCount= Integer.parseInt(value); 933 } catch (NumberFormatException exception) { 934 return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_UNITS)); 935 } 936 } else 937 return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_UNITS)); 938 String handle= null; 939 List elements= new ArrayList (); 940 for (int index= 0; index < fileCount; index++) { 941 final String attribute= JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (index + 1); 942 handle= extended.getAttribute(attribute); 943 if (handle != null && !"".equals(handle)) { final IResource resource= JDTRefactoringDescriptor.handleToResource(extended.getProject(), handle); 945 if (resource == null || !resource.exists()) 946 status.merge(ScriptableRefactoring.createInputWarningStatus(resource, getProcessorId(), getRefactoringId())); 947 else 948 elements.add(resource); 949 } else 950 return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, attribute)); 951 } 952 fFiles= (IFile[]) elements.toArray(new IFile[elements.size()]); 953 elements= new ArrayList (); 954 for (int index= 0; index < folderCount; index++) { 955 final String attribute= JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (fileCount + index + 1); 956 handle= extended.getAttribute(attribute); 957 if (handle != null && !"".equals(handle)) { final IResource resource= JDTRefactoringDescriptor.handleToResource(extended.getProject(), handle); 959 if (resource == null || !resource.exists()) 960 status.merge(ScriptableRefactoring.createInputWarningStatus(resource, getProcessorId(), getRefactoringId())); 961 else 962 elements.add(resource); 963 } else 964 return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, attribute)); 965 } 966 fFolders= (IFolder[]) elements.toArray(new IFolder[elements.size()]); 967 elements= new ArrayList (); 968 for (int index= 0; index < unitCount; index++) { 969 final String attribute= JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (folderCount + fileCount + index + 1); 970 handle= extended.getAttribute(attribute); 971 if (handle != null && !"".equals(handle)) { final IJavaElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false); 973 if (element == null || !element.exists() || element.getElementType() != IJavaElement.COMPILATION_UNIT) 974 status.merge(ScriptableRefactoring.createInputWarningStatus(element, getProcessorId(), getRefactoringId())); 975 else 976 elements.add(element); 977 } else 978 return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, attribute)); 979 } 980 fCus= (ICompilationUnit[]) elements.toArray(new ICompilationUnit[elements.size()]); 981 } else 982 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments); 983 status.merge(super.initialize(arguments)); 984 return status; 985 } 986 987 private boolean isChildOfOrEqualToAnyFolder(IResource resource) { 988 for (int i= 0; i < fFolders.length; i++) { 989 IFolder folder= fFolders[i]; 990 if (folder.equals(resource) || ParentChecker.isDescendantOf(resource, folder)) 991 return true; 992 } 993 return false; 994 } 995 996 protected RefactoringStatus verifyDestination(IJavaElement javaElement) throws JavaModelException { 997 Assert.isNotNull(javaElement); 998 if (!fCheckDestination) 999 return new RefactoringStatus(); 1000 if (!javaElement.exists()) 1001 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_doesnotexist0); 1002 if (javaElement instanceof IJavaModel) 1003 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_jmodel); 1004 1005 if (javaElement.isReadOnly()) 1006 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_readonly); 1007 1008 if (!javaElement.isStructureKnown()) 1009 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_structure); 1010 1011 if (javaElement instanceof IOpenable) { 1012 IOpenable openable= (IOpenable) javaElement; 1013 if (!openable.isConsistent()) 1014 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_inconsistent); 1015 } 1016 1017 if (javaElement instanceof IPackageFragmentRoot) { 1018 IPackageFragmentRoot root= (IPackageFragmentRoot) javaElement; 1019 if (root.isArchive()) 1020 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_archive); 1021 if (root.isExternal()) 1022 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_external); 1023 } 1024 1025 if (ReorgUtils.isInsideCompilationUnit(javaElement)) { 1026 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot); 1027 } 1028 1029 IContainer destinationAsContainer= getDestinationAsContainer(); 1030 if (destinationAsContainer == null || isChildOfOrEqualToAnyFolder(destinationAsContainer)) 1031 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_not_this_resource); 1032 1033 if (containsLinkedResources() && !ReorgUtils.canBeDestinationForLinkedResources(javaElement)) 1034 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_linked); 1035 return new RefactoringStatus(); 1036 } 1037 1038 protected RefactoringStatus verifyDestination(IResource resource) throws JavaModelException { 1039 Assert.isNotNull(resource); 1040 if (!resource.exists() || resource.isPhantom()) 1041 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_phantom); 1042 if (!resource.isAccessible()) 1043 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_inaccessible); 1044 1045 if (resource.getType() == IResource.ROOT) 1046 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_not_this_resource); 1047 1048 if (isChildOfOrEqualToAnyFolder(resource)) 1049 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_not_this_resource); 1050 1051 if (containsLinkedResources() && !ReorgUtils.canBeDestinationForLinkedResources(resource)) 1052 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_linked); 1053 1054 return new RefactoringStatus(); 1055 } 1056 } 1057 1058 private static final class MoveFilesFoldersAndCusPolicy extends FilesFoldersAndCusReorgPolicy implements IMovePolicy { 1059 1060 private static final String POLICY_MOVE_RESOURCES= "org.eclipse.jdt.ui.moveResources"; 1062 private static Change moveCuToPackage(ICompilationUnit cu, IPackageFragment dest) { 1063 IResource resource= cu.getResource(); 1066 if (resource != null && resource.isLinked()) { 1067 if (ResourceUtil.getResource(dest) instanceof IContainer) 1068 return moveFileToContainer(cu, (IContainer) ResourceUtil.getResource(dest)); 1069 } 1070 return new MoveCompilationUnitChange(cu, dest); 1071 } 1072 1073 private static Change moveFileToContainer(ICompilationUnit cu, IContainer dest) { 1074 return new MoveResourceChange(cu.getResource(), dest); 1075 } 1076 1077 private TextChangeManager fChangeManager; 1078 1079 private CreateTargetExecutionLog fCreateTargetExecutionLog= new CreateTargetExecutionLog(); 1080 1081 private String fFilePatterns; 1082 1083 private MoveModifications fModifications; 1084 1085 private QualifiedNameSearchResult fQualifiedNameSearchResult; 1086 1087 private boolean fUpdateQualifiedNames; 1088 1089 private boolean fUpdateReferences; 1090 1091 MoveFilesFoldersAndCusPolicy(IFile[] files, IFolder[] folders, ICompilationUnit[] cus) { 1092 super(files, folders, cus); 1093 fUpdateReferences= true; 1094 fUpdateQualifiedNames= false; 1095 fQualifiedNameSearchResult= new QualifiedNameSearchResult(); 1096 } 1097 1098 public boolean canEnableQualifiedNameUpdating() { 1099 return getCus().length > 0 && !JavaElementUtil.isDefaultPackage(getCommonParent()); 1100 } 1101 1102 public boolean canEnableUpdateReferences() { 1103 return getCus().length > 0; 1104 } 1105 1106 public boolean canUpdateQualifiedNames() { 1107 IPackageFragment pack= getDestinationAsPackageFragment(); 1108 return (canEnableQualifiedNameUpdating() && pack != null && !pack.isDefaultPackage()); 1109 } 1110 1111 public boolean canUpdateReferences() { 1112 if (getCus().length == 0) 1113 return false; 1114 IPackageFragment pack= getDestinationAsPackageFragment(); 1115 if (pack != null && pack.isDefaultPackage()) 1116 return false; 1117 Object commonParent= getCommonParent(); 1118 if (JavaElementUtil.isDefaultPackage(commonParent)) 1119 return false; 1120 return true; 1121 } 1122 1123 public RefactoringStatus checkFinalConditions(IProgressMonitor pm, CheckConditionsContext context, IReorgQueries reorgQueries) throws CoreException { 1124 try { 1125 pm.beginTask("", fUpdateQualifiedNames ? 7 : 3); RefactoringStatus result= new RefactoringStatus(); 1127 confirmMovingReadOnly(reorgQueries); 1128 fChangeManager= createChangeManager(new SubProgressMonitor(pm, 2), result); 1129 if (fUpdateQualifiedNames) 1130 computeQualifiedNameMatches(new SubProgressMonitor(pm, 4)); 1131 result.merge(super.checkFinalConditions(new SubProgressMonitor(pm, 1), context, reorgQueries)); 1132 return result; 1133 } catch (JavaModelException e) { 1134 throw e; 1135 } catch (CoreException e) { 1136 throw new JavaModelException(e); 1137 } finally { 1138 pm.done(); 1139 } 1140 } 1141 1142 private void computeQualifiedNameMatches(IProgressMonitor pm) throws JavaModelException { 1143 if (!fUpdateQualifiedNames) 1144 return; 1145 IPackageFragment destination= getDestinationAsPackageFragment(); 1146 if (destination != null) { 1147 ICompilationUnit[] cus= getCus(); 1148 pm.beginTask("", cus.length); pm.subTask(RefactoringCoreMessages.MoveRefactoring_scanning_qualified_names); 1150 for (int i= 0; i < cus.length; i++) { 1151 ICompilationUnit cu= cus[i]; 1152 IType[] types= cu.getTypes(); 1153 IProgressMonitor typesMonitor= new SubProgressMonitor(pm, 1); 1154 typesMonitor.beginTask("", types.length); for (int j= 0; j < types.length; j++) { 1156 handleType(types[j], destination, new SubProgressMonitor(typesMonitor, 1)); 1157 if (typesMonitor.isCanceled()) 1158 throw new OperationCanceledException(); 1159 } 1160 typesMonitor.done(); 1161 } 1162 } 1163 pm.done(); 1164 } 1165 1166 private void confirmMovingReadOnly(IReorgQueries reorgQueries) throws CoreException { 1167 if (!ReadOnlyResourceFinder.confirmMoveOfReadOnlyElements(getJavaElements(), getResources(), reorgQueries)) 1168 throw new OperationCanceledException(); 1169 } 1170 1171 private Change createChange(ICompilationUnit cu) { 1172 IPackageFragment pack= getDestinationAsPackageFragment(); 1173 if (pack != null) 1174 return moveCuToPackage(cu, pack); 1175 IContainer container= getDestinationAsContainer(); 1176 if (container == null) 1177 return new NullChange(); 1178 return moveFileToContainer(cu, container); 1179 } 1180 1181 public Change createChange(IProgressMonitor pm) throws JavaModelException { 1182 if (!fUpdateReferences) { 1183 return createSimpleMoveChange(pm); 1184 } else { 1185 return createReferenceUpdatingMoveChange(pm); 1186 } 1187 } 1188 1189 private Change createChange(IResource res) { 1190 IContainer destinationAsContainer= getDestinationAsContainer(); 1191 if (destinationAsContainer == null) 1192 return new NullChange(); 1193 return new MoveResourceChange(res, destinationAsContainer); 1194 } 1195 1196 private TextChangeManager createChangeManager(IProgressMonitor pm, RefactoringStatus status) throws JavaModelException { 1197 pm.beginTask("", 1); try { 1199 if (!fUpdateReferences) 1200 return new TextChangeManager(); 1201 1202 IPackageFragment packageDest= getDestinationAsPackageFragment(); 1203 if (packageDest != null) { 1204 MoveCuUpdateCreator creator= new MoveCuUpdateCreator(getCus(), packageDest); 1205 return creator.createChangeManager(new SubProgressMonitor(pm, 1), status); 1206 } else 1207 return new TextChangeManager(); 1208 } finally { 1209 pm.done(); 1210 } 1211 } 1212 1213 protected JDTRefactoringDescriptor createRefactoringDescriptor(JDTRefactoringDescriptorComment comment, Map arguments, String description, String project, int flags) { 1214 return new JDTMoveRefactoringDescriptor(getCreateTargetExecutionLog(), getProcessorId(), project, description, comment.asString(), arguments, flags); 1215 } 1216 1217 private Change createReferenceUpdatingMoveChange(IProgressMonitor pm) throws JavaModelException { 1218 pm.beginTask("", 2 + (fUpdateQualifiedNames ? 1 : 0)); try { 1220 CompositeChange composite= new DynamicValidationStateChange(RefactoringCoreMessages.ReorgPolicy_move); 1221 composite.markAsSynthetic(); 1222 if (fChangeManager == null) { 1225 fChangeManager= createChangeManager(new SubProgressMonitor(pm, 1), new RefactoringStatus()); 1226 RefactoringStatus status= Checks.validateModifiesFiles(getAllModifiedFiles(), null); 1228 if (status.hasFatalError()) 1229 fChangeManager= new TextChangeManager(); 1230 } 1231 1233 composite.merge(new CompositeChange(RefactoringCoreMessages.MoveRefactoring_reorganize_elements, fChangeManager.getAllChanges())); 1234 1235 Change fileMove= createSimpleMoveChange(new SubProgressMonitor(pm, 1)); 1236 if (fileMove instanceof CompositeChange) { 1237 composite.merge(((CompositeChange) fileMove)); 1238 } else { 1239 composite.add(fileMove); 1240 } 1241 return composite; 1242 } finally { 1243 pm.done(); 1244 } 1245 } 1246 1247 private Change createSimpleMoveChange(IProgressMonitor pm) { 1248 CompositeChange result= new DynamicValidationStateChange(RefactoringCoreMessages.ReorgPolicy_move); 1249 result.markAsSynthetic(); 1250 IFile[] files= getFiles(); 1251 IFolder[] folders= getFolders(); 1252 ICompilationUnit[] cus= getCus(); 1253 pm.beginTask("", files.length + folders.length + cus.length); for (int i= 0; i < files.length; i++) { 1255 result.add(createChange(files[i])); 1256 pm.worked(1); 1257 } 1258 if (pm.isCanceled()) 1259 throw new OperationCanceledException(); 1260 for (int i= 0; i < folders.length; i++) { 1261 result.add(createChange(folders[i])); 1262 pm.worked(1); 1263 } 1264 if (pm.isCanceled()) 1265 throw new OperationCanceledException(); 1266 for (int i= 0; i < cus.length; i++) { 1267 result.add(createChange(cus[i])); 1268 pm.worked(1); 1269 } 1270 pm.done(); 1271 return result; 1272 } 1273 1274 public IFile[] getAllModifiedFiles() { 1275 Set result= new HashSet (); 1276 result.addAll(Arrays.asList(ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits()))); 1277 result.addAll(Arrays.asList(fQualifiedNameSearchResult.getAllFiles())); 1278 if (getDestinationAsPackageFragment() != null && getUpdateReferences()) 1279 result.addAll(Arrays.asList(ResourceUtil.getFiles(getCus()))); 1280 return (IFile[]) result.toArray(new IFile[result.size()]); 1281 } 1282 1283 private Object getCommonParent() { 1284 return new ParentChecker(getResources(), getJavaElements()).getCommonParent(); 1285 } 1286 1287 public CreateTargetExecutionLog getCreateTargetExecutionLog() { 1288 return fCreateTargetExecutionLog; 1289 } 1290 1291 public ICreateTargetQuery getCreateTargetQuery(ICreateTargetQueries createQueries) { 1292 return createQueries.createNewPackageQuery(); 1293 } 1294 1295 protected String getDescriptionPlural() { 1296 final int kind= getContentKind(); 1297 switch (kind) { 1298 case ONLY_FOLDERS: 1299 return RefactoringCoreMessages.ReorgPolicyFactory_move_folders; 1300 case ONLY_FILES: 1301 return RefactoringCoreMessages.ReorgPolicyFactory_move_files; 1302 case ONLY_CUS: 1303 return RefactoringCoreMessages.ReorgPolicyFactory_move_compilation_units; 1304 } 1305 return RefactoringCoreMessages.ReorgPolicyFactory_move_description_plural; 1306 } 1307 1308 protected String getDescriptionSingular() { 1309 final int kind= getContentKind(); 1310 switch (kind) { 1311 case ONLY_FOLDERS: 1312 return RefactoringCoreMessages.ReorgPolicyFactory_move_folder; 1313 case ONLY_FILES: 1314 return RefactoringCoreMessages.ReorgPolicyFactory_move_file; 1315 case ONLY_CUS: 1316 return RefactoringCoreMessages.ReorgPolicyFactory_move_compilation_unit; 1317 } 1318 return RefactoringCoreMessages.ReorgPolicyFactory_move_description_singular; 1319 } 1320 1321 public String getFilePatterns() { 1322 return fFilePatterns; 1323 } 1324 1325 protected String getHeaderPattern() { 1326 return RefactoringCoreMessages.ReorgPolicyFactory_move_header; 1327 } 1328 1329 protected RefactoringModifications getModifications() throws CoreException { 1330 if (fModifications != null) 1331 return fModifications; 1332 1333 fModifications= new MoveModifications(); 1334 IPackageFragment pack= getDestinationAsPackageFragment(); 1335 IContainer container= getDestinationAsContainer(); 1336 Object unitDestination= null; 1337 if (pack != null) 1338 unitDestination= pack; 1339 else 1340 unitDestination= container; 1341 1342 boolean updateReferenes= canUpdateReferences() && getUpdateReferences(); 1345 if (unitDestination != null) { 1346 ICompilationUnit[] units= getCus(); 1347 for (int i= 0; i < units.length; i++) { 1348 fModifications.move(units[i], new MoveArguments(unitDestination, updateReferenes)); 1349 } 1350 } 1351 if (container != null) { 1352 IFile[] files= getFiles(); 1353 for (int i= 0; i < files.length; i++) { 1354 fModifications.move(files[i], new MoveArguments(container, updateReferenes)); 1355 } 1356 IFolder[] folders= getFolders(); 1357 for (int i= 0; i < folders.length; i++) { 1358 fModifications.move(folders[i], new MoveArguments(container, updateReferenes)); 1359 } 1360 } 1361 return fModifications; 1362 } 1363 1364 public String getPolicyId() { 1365 return POLICY_MOVE_RESOURCES; 1366 } 1367 1368 protected String getProcessorId() { 1369 return IJavaRefactorings.MOVE; 1370 } 1371 1372 protected Map getRefactoringArguments(String project) { 1373 final Map arguments= new HashMap (); 1374 arguments.putAll(super.getRefactoringArguments(project)); 1375 if (fFilePatterns != null && !"".equals(fFilePatterns)) arguments.put(ATTRIBUTE_PATTERNS, fFilePatterns); 1377 arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_REFERENCES, Boolean.valueOf(fUpdateReferences).toString()); 1378 arguments.put(ATTRIBUTE_QUALIFIED, Boolean.valueOf(fUpdateQualifiedNames).toString()); 1379 return arguments; 1380 } 1381 1382 protected String getRefactoringId() { 1383 return IJavaRefactorings.MOVE; 1384 } 1385 1386 public boolean getUpdateQualifiedNames() { 1387 return fUpdateQualifiedNames; 1388 } 1389 1390 public boolean getUpdateReferences() { 1391 return fUpdateReferences; 1392 } 1393 1394 private void handleType(IType type, IPackageFragment destination, IProgressMonitor pm) { 1395 QualifiedNameFinder.process(fQualifiedNameSearchResult, type.getFullyQualifiedName(), destination.getElementName() + "." + type.getTypeQualifiedName(), fFilePatterns, type.getJavaProject().getProject(), pm); 1397 } 1398 1399 public boolean hasAllInputSet() { 1400 return super.hasAllInputSet() && !canUpdateReferences() && !canUpdateQualifiedNames(); 1401 } 1402 1403 public RefactoringStatus initialize(RefactoringArguments arguments) { 1404 if (arguments instanceof JavaRefactoringArguments) { 1405 final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments; 1406 final String patterns= extended.getAttribute(ATTRIBUTE_PATTERNS); 1407 if (patterns != null && !"".equals(patterns)) fFilePatterns= patterns; 1409 else 1410 fFilePatterns= ""; final String references= extended.getAttribute(JDTRefactoringDescriptor.ATTRIBUTE_REFERENCES); 1412 if (references != null) { 1413 fUpdateReferences= Boolean.valueOf(references).booleanValue(); 1414 } else 1415 return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_REFERENCES)); 1416 final String qualified= extended.getAttribute(ATTRIBUTE_QUALIFIED); 1417 if (qualified != null) { 1418 fUpdateQualifiedNames= Boolean.valueOf(qualified).booleanValue(); 1419 } else 1420 return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_QUALIFIED)); 1421 } else 1422 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments); 1423 return super.initialize(arguments); 1424 } 1425 1426 public boolean isTextualMove() { 1427 return false; 1428 } 1429 1430 public Change postCreateChange(Change[] participantChanges, IProgressMonitor pm) throws CoreException { 1431 if (fQualifiedNameSearchResult != null) { 1432 return fQualifiedNameSearchResult.getSingleChange(Changes.getModifiedFiles(participantChanges)); 1433 } else { 1434 return null; 1435 } 1436 } 1437 1438 public void setDestinationCheck(boolean check) { 1439 fCheckDestination= check; 1440 } 1441 1442 public void setFilePatterns(String patterns) { 1443 Assert.isNotNull(patterns); 1444 fFilePatterns= patterns; 1445 } 1446 1447 public void setUpdateQualifiedNames(boolean update) { 1448 fUpdateQualifiedNames= update; 1449 } 1450 1451 public void setUpdateReferences(boolean update) { 1452 fUpdateReferences= update; 1453 } 1454 1455 protected RefactoringStatus verifyDestination(IJavaElement destination) throws JavaModelException { 1456 RefactoringStatus superStatus= super.verifyDestination(destination); 1457 if (superStatus.hasFatalError()) 1458 return superStatus; 1459 1460 Object commonParent= new ParentChecker(getResources(), getJavaElements()).getCommonParent(); 1461 if (destination.equals(commonParent)) 1462 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_parent); 1463 IContainer destinationAsContainer= getDestinationAsContainer(); 1464 if (destinationAsContainer != null && destinationAsContainer.equals(commonParent)) 1465 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_parent); 1466 IPackageFragment destinationAsPackage= getDestinationAsPackageFragment(); 1467 if (destinationAsPackage != null && destinationAsPackage.equals(commonParent)) 1468 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_parent); 1469 1470 return superStatus; 1471 } 1472 1473 protected RefactoringStatus verifyDestination(IResource destination) throws JavaModelException { 1474 RefactoringStatus superStatus= super.verifyDestination(destination); 1475 if (superStatus.hasFatalError()) 1476 return superStatus; 1477 1478 Object commonParent= getCommonParent(); 1479 if (destination.equals(commonParent)) 1480 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_parent); 1481 IContainer destinationAsContainer= getDestinationAsContainer(); 1482 if (destinationAsContainer != null && destinationAsContainer.equals(commonParent)) 1483 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_parent); 1484 IJavaElement destinationContainerAsPackage= getDestinationContainerAsJavaElement(); 1485 if (destinationContainerAsPackage != null && destinationContainerAsPackage.equals(commonParent)) 1486 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_parent); 1487 1488 return superStatus; 1489 } 1490 } 1491 1492 private static final class MovePackageFragmentRootsPolicy extends PackageFragmentRootsReorgPolicy implements IMovePolicy { 1493 1494 private static final String POLICY_MOVE_ROOTS= "org.eclipse.jdt.ui.moveRoots"; 1496 private static boolean isParentOfAny(IJavaProject javaProject, IPackageFragmentRoot[] roots) { 1497 for (int i= 0; i < roots.length; i++) { 1498 if (ReorgUtils.isParentInWorkspaceOrOnDisk(roots[i], javaProject)) 1499 return true; 1500 } 1501 return false; 1502 } 1503 1504 private CreateTargetExecutionLog fCreateTargetExecutionLog= new CreateTargetExecutionLog(); 1505 1506 private MoveModifications fModifications; 1507 1508 MovePackageFragmentRootsPolicy(IPackageFragmentRoot[] roots) { 1509 super(roots); 1510 } 1511 1512 public boolean canEnable() throws JavaModelException { 1513 if (!super.canEnable()) 1514 return false; 1515 IPackageFragmentRoot[] roots= getPackageFragmentRoots(); 1516 for (int i= 0; i < roots.length; i++) { 1517 if (roots[i].isReadOnly() && !(roots[i].isArchive())) { 1518 final ResourceAttributes attributes= roots[i].getResource().getResourceAttributes(); 1519 if (attributes == null || attributes.isReadOnly()) 1520 return false; 1521 } 1522 } 1523 return true; 1524 } 1525 1526 public RefactoringStatus checkFinalConditions(IProgressMonitor pm, CheckConditionsContext context, IReorgQueries reorgQueries) throws CoreException { 1527 try { 1528 RefactoringStatus status= super.checkFinalConditions(pm, context, reorgQueries); 1529 confirmMovingReadOnly(reorgQueries); 1530 return status; 1531 } catch (JavaModelException e) { 1532 throw e; 1533 } catch (CoreException e) { 1534 throw new JavaModelException(e); 1535 } 1536 } 1537 1538 private void confirmMovingReadOnly(IReorgQueries reorgQueries) throws CoreException { 1539 if (!ReadOnlyResourceFinder.confirmMoveOfReadOnlyElements(getJavaElements(), getResources(), reorgQueries)) 1540 throw new OperationCanceledException(); 1541 } 1542 1543 private Change createChange(IPackageFragmentRoot root, IJavaProject destination) { 1544 return new MovePackageFragmentRootChange(root, destination.getProject(), null); 1546 } 1547 1548 public Change createChange(IProgressMonitor pm) throws JavaModelException { 1549 IPackageFragmentRoot[] roots= getPackageFragmentRoots(); 1550 pm.beginTask("", roots.length); CompositeChange composite= new DynamicValidationStateChange(RefactoringCoreMessages.ReorgPolicy_move_source_folder); 1552 composite.markAsSynthetic(); 1553 IJavaProject destination= getDestinationJavaProject(); 1554 Assert.isNotNull(destination); 1555 for (int i= 0; i < roots.length; i++) { 1556 composite.add(createChange(roots[i], destination)); 1557 pm.worked(1); 1558 } 1559 pm.done(); 1560 return composite; 1561 } 1562 1563 protected JDTRefactoringDescriptor createRefactoringDescriptor(JDTRefactoringDescriptorComment comment, Map arguments, String description, String project, int flags) { 1564 return new JDTMoveRefactoringDescriptor(getCreateTargetExecutionLog(), getProcessorId(), project, description, comment.asString(), arguments, flags); 1565 } 1566 1567 public CreateTargetExecutionLog getCreateTargetExecutionLog() { 1568 return fCreateTargetExecutionLog; 1569 } 1570 1571 public ICreateTargetQuery getCreateTargetQuery(ICreateTargetQueries createQueries) { 1572 return null; 1573 } 1574 1575 protected String getDescriptionPlural() { 1576 return RefactoringCoreMessages.ReorgPolicyFactory_move_roots_plural; 1577 } 1578 1579 protected String getDescriptionSingular() { 1580 return RefactoringCoreMessages.ReorgPolicyFactory_move_roots_singular; 1581 } 1582 1583 protected String getHeaderPattern() { 1584 return RefactoringCoreMessages.ReorgPolicyFactory_move_roots_header; 1585 } 1586 1587 protected RefactoringModifications getModifications() throws CoreException { 1588 if (fModifications != null) 1589 return fModifications; 1590 1591 fModifications= new MoveModifications(); 1592 IJavaProject destination= getDestinationJavaProject(); 1593 boolean updateReferences= canUpdateReferences() && getUpdateReferences(); 1594 if (destination != null) { 1595 IPackageFragmentRoot[] roots= getPackageFragmentRoots(); 1596 for (int i= 0; i < roots.length; i++) { 1597 fModifications.move(roots[i], new MoveArguments(destination, updateReferences)); 1598 } 1599 } 1600 return fModifications; 1601 } 1602 1603 public String getPolicyId() { 1604 return POLICY_MOVE_ROOTS; 1605 } 1606 1607 protected String getProcessorId() { 1608 return IJavaRefactorings.MOVE; 1609 } 1610 1611 protected String getRefactoringId() { 1612 return IJavaRefactorings.MOVE; 1613 } 1614 1615 public boolean isTextualMove() { 1616 return false; 1617 } 1618 1619 public Change postCreateChange(Change[] participantChanges, IProgressMonitor pm) throws CoreException { 1620 return null; 1621 } 1622 1623 public void setDestinationCheck(boolean check) { 1624 fCheckDestination= check; 1625 } 1626 1627 protected RefactoringStatus verifyDestination(IJavaElement javaElement) throws JavaModelException { 1628 RefactoringStatus superStatus= super.verifyDestination(javaElement); 1629 if (superStatus.hasFatalError()) 1630 return superStatus; 1631 IJavaProject javaProject= getDestinationJavaProject(); 1632 if (isParentOfAny(javaProject, getPackageFragmentRoots())) 1633 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_element2parent); 1634 return superStatus; 1635 } 1636 } 1637 1638 private static final class MovePackagesPolicy extends PackagesReorgPolicy implements IMovePolicy { 1639 1640 private static final String POLICY_MOVE_PACKAGES= "org.eclipse.jdt.ui.movePackages"; 1642 private static boolean isParentOfAny(IPackageFragmentRoot root, IPackageFragment[] fragments) { 1643 for (int i= 0; i < fragments.length; i++) { 1644 IPackageFragment fragment= fragments[i]; 1645 if (ReorgUtils.isParentInWorkspaceOrOnDisk(fragment, root)) 1646 return true; 1647 } 1648 return false; 1649 } 1650 1651 private CreateTargetExecutionLog fCreateTargetExecutionLog= new CreateTargetExecutionLog(); 1652 1653 private MoveModifications fModifications; 1654 1655 MovePackagesPolicy(IPackageFragment[] packageFragments) { 1656 super(packageFragments); 1657 } 1658 1659 public RefactoringStatus checkFinalConditions(IProgressMonitor pm, CheckConditionsContext context, IReorgQueries reorgQueries) throws CoreException { 1660 try { 1661 RefactoringStatus status= super.checkFinalConditions(pm, context, reorgQueries); 1662 confirmMovingReadOnly(reorgQueries); 1663 return status; 1664 } catch (JavaModelException e) { 1665 throw e; 1666 } catch (CoreException e) { 1667 throw new JavaModelException(e); 1668 } 1669 } 1670 1671 private void confirmMovingReadOnly(IReorgQueries reorgQueries) throws CoreException { 1672 if (!ReadOnlyResourceFinder.confirmMoveOfReadOnlyElements(getJavaElements(), getResources(), reorgQueries)) 1673 throw new OperationCanceledException(); 1674 } 1675 1676 private Change createChange(IPackageFragment pack, IPackageFragmentRoot destination) { 1677 return new MovePackageChange(pack, destination); 1678 } 1679 1680 public Change createChange(IProgressMonitor pm) throws JavaModelException { 1681 IPackageFragment[] fragments= getPackages(); 1682 pm.beginTask("", fragments.length); CompositeChange result= new DynamicValidationStateChange(RefactoringCoreMessages.ReorgPolicy_move_package); 1684 result.markAsSynthetic(); 1685 IPackageFragmentRoot root= getDestinationAsPackageFragmentRoot(); 1686 for (int i= 0; i < fragments.length; i++) { 1687 result.add(createChange(fragments[i], root)); 1688 pm.worked(1); 1689 if (pm.isCanceled()) 1690 throw new OperationCanceledException(); 1691 } 1692 pm.done(); 1693 return result; 1694 } 1695 1696 protected JDTRefactoringDescriptor createRefactoringDescriptor(JDTRefactoringDescriptorComment comment, Map arguments, String description, String project, int flags) { 1697 return new JDTMoveRefactoringDescriptor(getCreateTargetExecutionLog(), getProcessorId(), project, description, comment.asString(), arguments, flags); 1698 } 1699 1700 public CreateTargetExecutionLog getCreateTargetExecutionLog() { 1701 return fCreateTargetExecutionLog; 1702 } 1703 1704 public ICreateTargetQuery getCreateTargetQuery(ICreateTargetQueries createQueries) { 1705 return null; 1706 } 1707 1708 protected String getDescriptionPlural() { 1709 return RefactoringCoreMessages.ReorgPolicyFactory_move_packages_plural; 1710 } 1711 1712 protected String getDescriptionSingular() { 1713 return RefactoringCoreMessages.ReorgPolicyFactory_move_packages_singular; 1714 } 1715 1716 protected String getHeaderPattern() { 1717 return RefactoringCoreMessages.ReorgPolicyFactory_move_packages_header; 1718 } 1719 1720 protected RefactoringModifications getModifications() throws CoreException { 1721 if (fModifications != null) 1722 return fModifications; 1723 1724 fModifications= new MoveModifications(); 1725 boolean updateReferences= canUpdateReferences() && getUpdateReferences(); 1726 IPackageFragment[] packages= getPackages(); 1727 IPackageFragmentRoot javaDestination= getDestinationAsPackageFragmentRoot(); 1728 for (int i= 0; i < packages.length; i++) { 1729 fModifications.move(packages[i], new MoveArguments(javaDestination, updateReferences)); 1730 } 1731 return fModifications; 1732 } 1733 1734 public String getPolicyId() { 1735 return POLICY_MOVE_PACKAGES; 1736 } 1737 1738 protected String getProcessorId() { 1739 return IJavaRefactorings.MOVE; 1740 } 1741 1742 protected String getRefactoringId() { 1743 return IJavaRefactorings.MOVE; 1744 } 1745 1746 public boolean isTextualMove() { 1747 return false; 1748 } 1749 1750 public Change postCreateChange(Change[] participantChanges, IProgressMonitor pm) throws CoreException { 1751 return null; 1752 } 1753 1754 public void setDestinationCheck(boolean check) { 1755 fCheckDestination= check; 1756 } 1757 1758 protected RefactoringStatus verifyDestination(IJavaElement javaElement) throws JavaModelException { 1759 RefactoringStatus superStatus= super.verifyDestination(javaElement); 1760 if (superStatus.hasFatalError()) 1761 return superStatus; 1762 1763 IPackageFragmentRoot root= getDestinationAsPackageFragmentRoot(); 1764 if (isParentOfAny(root, getPackages())) 1765 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_package2parent); 1766 return superStatus; 1767 } 1768 } 1769 1770 private static final class MoveSubCuElementsPolicy extends SubCuElementReorgPolicy implements IMovePolicy { 1771 1772 private static final String POLICY_MOVE_MEMBERS= "org.eclipse.jdt.ui.moveMembers"; 1774 private CreateTargetExecutionLog fCreateTargetExecutionLog= new CreateTargetExecutionLog(); 1775 1776 MoveSubCuElementsPolicy(IJavaElement[] javaElements) { 1777 super(javaElements); 1778 } 1779 1780 public boolean canEnable() throws JavaModelException { 1781 return super.canEnable() && getSourceCu() != null; 1782 } 1783 1784 public Change createChange(IProgressMonitor pm) throws JavaModelException { 1785 pm.beginTask("", 3); try { 1787 final ICompilationUnit sourceCu= getSourceCu(); 1788 CompilationUnit sourceCuNode= RefactoringASTParser.parseWithASTProvider(sourceCu, false, new SubProgressMonitor(pm, 1)); 1789 CompilationUnitRewrite sourceRewriter= new CompilationUnitRewrite(sourceCu, sourceCuNode); 1790 ICompilationUnit destinationCu= getDestinationCu(); 1791 CompilationUnitRewrite targetRewriter; 1792 if (sourceCu.equals(destinationCu)) { 1793 targetRewriter= sourceRewriter; 1794 pm.worked(1); 1795 } else { 1796 CompilationUnit destinationCuNode= RefactoringASTParser.parseWithASTProvider(destinationCu, false, new SubProgressMonitor(pm, 1)); 1797 targetRewriter= new CompilationUnitRewrite(destinationCu, destinationCuNode); 1798 } 1799 IJavaElement[] javaElements= getJavaElements(); 1800 for (int i= 0; i < javaElements.length; i++) { 1801 copyToDestination(javaElements[i], targetRewriter, sourceRewriter.getRoot(), targetRewriter.getRoot()); 1802 } 1803 ASTNodeDeleteUtil.markAsDeleted(javaElements, sourceRewriter, null); 1804 Change targetCuChange= createCompilationUnitChange(destinationCu, targetRewriter); 1805 if (sourceCu.equals(destinationCu)) { 1806 return targetCuChange; 1807 } else { 1808 CompositeChange result= new DynamicValidationStateChange(RefactoringCoreMessages.ReorgPolicy_move_members); 1809 result.markAsSynthetic(); 1810 result.add(targetCuChange); 1811 if (Arrays.asList(getJavaElements()).containsAll(Arrays.asList(sourceCu.getTypes()))) 1812 result.add(DeleteChangeCreator.createDeleteChange(null, new IResource[0], new ICompilationUnit[] {sourceCu}, RefactoringCoreMessages.ReorgPolicy_move, null)); 1813 else 1814 result.add(createCompilationUnitChange(sourceCu, sourceRewriter)); 1815 return result; 1816 } 1817 } catch (JavaModelException e) { 1818 throw e; 1819 } catch (CoreException e) { 1820 throw new JavaModelException(e); 1821 } finally { 1822 pm.done(); 1823 } 1824 } 1825 1826 protected JDTRefactoringDescriptor createRefactoringDescriptor(JDTRefactoringDescriptorComment comment, Map arguments, String description, String project, int flags) { 1827 return new JDTMoveRefactoringDescriptor(getCreateTargetExecutionLog(), getProcessorId(), project, description, comment.asString(), arguments, flags); 1828 } 1829 1830 public IFile[] getAllModifiedFiles() { 1831 return ReorgUtils.getFiles(new IResource[] { ReorgUtils.getResource(getSourceCu()), ReorgUtils.getResource(getDestinationCu())}); 1832 } 1833 1834 public CreateTargetExecutionLog getCreateTargetExecutionLog() { 1835 return fCreateTargetExecutionLog; 1836 } 1837 1838 public ICreateTargetQuery getCreateTargetQuery(ICreateTargetQueries createQueries) { 1839 return null; 1840 } 1841 1842 protected String getDescriptionPlural() { 1843 final int kind= getContentKind(); 1844 switch (kind) { 1845 case ONLY_TYPES: 1846 return RefactoringCoreMessages.ReorgPolicyFactory_move_types; 1847 case ONLY_FIELDS: 1848 return RefactoringCoreMessages.ReorgPolicyFactory_move_fields; 1849 case ONLY_METHODS: 1850 return RefactoringCoreMessages.ReorgPolicyFactory_move_methods; 1851 case ONLY_INITIALIZERS: 1852 return RefactoringCoreMessages.ReorgPolicyFactory_move_initializers; 1853 case ONLY_PACKAGE_DECLARATIONS: 1854 return RefactoringCoreMessages.ReorgPolicyFactory_move_package_declarations; 1855 case ONLY_IMPORT_CONTAINERS: 1856 return RefactoringCoreMessages.ReorgPolicyFactory_move_import_containers; 1857 case ONLY_IMPORT_DECLARATIONS: 1858 return RefactoringCoreMessages.ReorgPolicyFactory_move_import_declarations; 1859 } 1860 return RefactoringCoreMessages.ReorgPolicyFactory_move_elements_plural; 1861 } 1862 1863 protected String getDescriptionSingular() { 1864 final int kind= getContentKind(); 1865 switch (kind) { 1866 case ONLY_TYPES: 1867 return RefactoringCoreMessages.ReorgPolicyFactory_move_type; 1868 case ONLY_FIELDS: 1869 return RefactoringCoreMessages.ReorgPolicyFactory_move_field; 1870 case ONLY_METHODS: 1871 return RefactoringCoreMessages.ReorgPolicyFactory_move_method; 1872 case ONLY_INITIALIZERS: 1873 return RefactoringCoreMessages.ReorgPolicyFactory_move_initializer; 1874 case ONLY_PACKAGE_DECLARATIONS: 1875 return RefactoringCoreMessages.ReorgPolicyFactory_move_package_declaration; 1876 case ONLY_IMPORT_CONTAINERS: 1877 return RefactoringCoreMessages.ReorgPolicyFactory_move_import_section; 1878 case ONLY_IMPORT_DECLARATIONS: 1879 return RefactoringCoreMessages.ReorgPolicyFactory_move_import_declaration; 1880 } 1881 return RefactoringCoreMessages.ReorgPolicyFactory_move_elements_singular; 1882 } 1883 1884 protected String getHeaderPattern() { 1885 return RefactoringCoreMessages.ReorgPolicyFactory_move_elements_header; 1886 } 1887 1888 public String getPolicyId() { 1889 return POLICY_MOVE_MEMBERS; 1890 } 1891 1892 protected String getProcessorId() { 1893 return IJavaRefactorings.MOVE; 1894 } 1895 1896 protected String getRefactoringId() { 1897 return IJavaRefactorings.MOVE; 1898 } 1899 1900 public boolean isTextualMove() { 1901 return true; 1902 } 1903 1904 public Change postCreateChange(Change[] participantChanges, IProgressMonitor pm) throws CoreException { 1905 return null; 1906 } 1907 1908 public void setDestinationCheck(boolean check) { 1909 fCheckDestination= check; 1910 } 1911 1912 protected RefactoringStatus verifyDestination(IJavaElement destination) throws JavaModelException { 1913 IJavaElement[] elements= getJavaElements(); 1914 for (int i= 0; i < elements.length; i++) { 1915 IJavaElement parent= destination.getParent(); 1916 while (parent != null) { 1917 if (parent.equals(elements[i])) 1918 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot); 1919 parent= parent.getParent(); 1920 } 1921 } 1922 1923 RefactoringStatus superStatus= super.verifyDestination(destination); 1924 if (superStatus.hasFatalError()) 1925 return superStatus; 1926 1927 Object commonParent= new ParentChecker(new IResource[0], getJavaElements()).getCommonParent(); 1928 if (destination.equals(commonParent) || Arrays.asList(getJavaElements()).contains(destination)) 1929 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_element2parent); 1930 return superStatus; 1931 } 1932 } 1933 1934 private static final class NewNameProposer { 1935 1936 private static boolean isNewNameOk(IContainer container, String newName) { 1937 return container.findMember(newName) == null; 1938 } 1939 1940 private static boolean isNewNameOk(IPackageFragment dest, String newName) { 1941 return !dest.getCompilationUnit(newName).exists(); 1942 } 1943 1944 private static boolean isNewNameOk(IPackageFragmentRoot root, String newName) { 1945 return !root.getPackageFragment(newName).exists(); 1946 } 1947 1948 private final Set fAutoGeneratedNewNames= new HashSet (2); 1949 1950 public String createNewName(ICompilationUnit cu, IPackageFragment destination) { 1951 if (isNewNameOk(destination, cu.getElementName())) 1952 return null; 1953 if (!ReorgUtils.isParentInWorkspaceOrOnDisk(cu, destination)) 1954 return null; 1955 int i= 1; 1956 while (true) { 1957 String newName; 1958 if (i == 1) 1959 newName= Messages.format(RefactoringCoreMessages.CopyRefactoring_cu_copyOf1, cu.getElementName()); 1960 else 1961 newName= Messages.format(RefactoringCoreMessages.CopyRefactoring_cu_copyOfMore, new String [] { String.valueOf(i), cu.getElementName()}); 1962 if (isNewNameOk(destination, newName) && !fAutoGeneratedNewNames.contains(newName)) { 1963 fAutoGeneratedNewNames.add(newName); 1964 return JavaCore.removeJavaLikeExtension(newName); 1965 } 1966 i++; 1967 } 1968 } 1969 1970 public String createNewName(IPackageFragment pack, IPackageFragmentRoot destination) { 1971 if (isNewNameOk(destination, pack.getElementName())) 1972 return null; 1973 if (!ReorgUtils.isParentInWorkspaceOrOnDisk(pack, destination)) 1974 return null; 1975 int i= 1; 1976 while (true) { 1977 String newName; 1978 if (i == 1) 1979 newName= Messages.format(RefactoringCoreMessages.CopyRefactoring_package_copyOf1, pack.getElementName()); 1980 else 1981 newName= Messages.format(RefactoringCoreMessages.CopyRefactoring_package_copyOfMore, new String [] { String.valueOf(i), pack.getElementName()}); 1982 if (isNewNameOk(destination, newName) && !fAutoGeneratedNewNames.contains(newName)) { 1983 fAutoGeneratedNewNames.add(newName); 1984 return newName; 1985 } 1986 i++; 1987 } 1988 } 1989 1990 public String createNewName(IResource res, IContainer destination) { 1991 if (isNewNameOk(destination, res.getName())) 1992 return null; 1993 if (!ReorgUtils.isParentInWorkspaceOrOnDisk(res, destination)) 1994 return null; 1995 int i= 1; 1996 while (true) { 1997 String newName; 1998 if (i == 1) 1999 newName= Messages.format(RefactoringCoreMessages.CopyRefactoring_resource_copyOf1, res.getName()); 2000 else 2001 newName= Messages.format(RefactoringCoreMessages.CopyRefactoring_resource_copyOfMore, new String [] { String.valueOf(i), res.getName()}); 2002 if (isNewNameOk(destination, newName) && !fAutoGeneratedNewNames.contains(newName)) { 2003 fAutoGeneratedNewNames.add(newName); 2004 return newName; 2005 } 2006 i++; 2007 } 2008 } 2009 } 2010 2011 private static final class NoCopyPolicy extends ReorgPolicy implements ICopyPolicy { 2012 2013 public boolean canEnable() throws JavaModelException { 2014 return false; 2015 } 2016 2017 public Change createChange(IProgressMonitor pm, INewNameQueries copyQueries) { 2018 return new NullChange(); 2019 } 2020 2021 protected String getDescriptionPlural() { 2022 return UNUSED_STRING; 2023 } 2024 2025 protected String getDescriptionSingular() { 2026 return UNUSED_STRING; 2027 } 2028 2029 public ChangeDescriptor getDescriptor() { 2030 return null; 2031 } 2032 2033 protected String getHeaderPattern() { 2034 return UNUSED_STRING; 2035 } 2036 2037 public IJavaElement[] getJavaElements() { 2038 return new IJavaElement[0]; 2039 } 2040 2041 public String getPolicyId() { 2042 return NO_POLICY; 2043 } 2044 2045 protected String getProcessorId() { 2046 return NO_ID; 2047 } 2048 2049 protected String getRefactoringId() { 2050 return NO_ID; 2051 } 2052 2053 public ReorgExecutionLog getReorgExecutionLog() { 2054 return null; 2055 } 2056 2057 public IResource[] getResources() { 2058 return new IResource[0]; 2059 } 2060 2061 public RefactoringStatus initialize(RefactoringArguments arguments) { 2062 return new RefactoringStatus(); 2063 } 2064 2065 protected RefactoringStatus verifyDestination(IJavaElement javaElement) throws JavaModelException { 2066 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_noCopying); 2067 } 2068 2069 protected RefactoringStatus verifyDestination(IResource resource) throws JavaModelException { 2070 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_noCopying); 2071 } 2072 } 2073 2074 private static final class NoMovePolicy extends ReorgPolicy implements IMovePolicy { 2075 2076 public boolean canEnable() throws JavaModelException { 2077 return false; 2078 } 2079 2080 public Change createChange(IProgressMonitor pm) { 2081 return new NullChange(); 2082 } 2083 2084 public CreateTargetExecutionLog getCreateTargetExecutionLog() { 2085 return new CreateTargetExecutionLog(); 2086 } 2087 2088 public ICreateTargetQuery getCreateTargetQuery(ICreateTargetQueries createQueries) { 2089 return null; 2090 } 2091 2092 protected String getDescriptionPlural() { 2093 return UNUSED_STRING; 2094 } 2095 2096 protected String getDescriptionSingular() { 2097 return UNUSED_STRING; 2098 } 2099 2100 public ChangeDescriptor getDescriptor() { 2101 return null; 2102 } 2103 2104 protected String getHeaderPattern() { 2105 return UNUSED_STRING; 2106 } 2107 2108 public IJavaElement[] getJavaElements() { 2109 return new IJavaElement[0]; 2110 } 2111 2112 public String getPolicyId() { 2113 return NO_POLICY; 2114 } 2115 2116 protected String getProcessorId() { 2117 return NO_ID; 2118 } 2119 2120 protected String getRefactoringId() { 2121 return NO_ID; 2122 } 2123 2124 public IResource[] getResources() { 2125 return new IResource[0]; 2126 } 2127 2128 public RefactoringStatus initialize(RefactoringArguments arguments) { 2129 return new RefactoringStatus(); 2130 } 2131 2132 public boolean isTextualMove() { 2133 return true; 2134 } 2135 2136 public Change postCreateChange(Change[] participantChanges, IProgressMonitor pm) throws CoreException { 2137 return null; 2138 } 2139 2140 public void setDestinationCheck(boolean check) { 2141 fCheckDestination= check; 2142 } 2143 2144 protected RefactoringStatus verifyDestination(IJavaElement javaElement) throws JavaModelException { 2145 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_noMoving); 2146 } 2147 2148 protected RefactoringStatus verifyDestination(IResource resource) throws JavaModelException { 2149 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_noMoving); 2150 } 2151 } 2152 2153 private static abstract class PackageFragmentRootsReorgPolicy extends ReorgPolicy { 2154 2155 private IPackageFragmentRoot[] fPackageFragmentRoots; 2156 2157 public PackageFragmentRootsReorgPolicy(IPackageFragmentRoot[] roots) { 2158 fPackageFragmentRoots= roots; 2159 } 2160 2161 public boolean canChildrenBeDestinations(IJavaElement javaElement) { 2162 switch (javaElement.getElementType()) { 2163 case IJavaElement.JAVA_MODEL: 2164 case IJavaElement.JAVA_PROJECT: 2165 return true; 2166 default: 2167 return false; 2168 } 2169 } 2170 2171 public boolean canChildrenBeDestinations(IResource resource) { 2172 return false; 2173 } 2174 2175 public boolean canElementBeDestination(IJavaElement javaElement) { 2176 return javaElement.getElementType() == IJavaElement.JAVA_PROJECT; 2177 } 2178 2179 public boolean canElementBeDestination(IResource resource) { 2180 return false; 2181 } 2182 2183 public boolean canEnable() throws JavaModelException { 2184 if (!super.canEnable()) 2185 return false; 2186 for (int i= 0; i < fPackageFragmentRoots.length; i++) { 2187 if (!(ReorgUtils.isSourceFolder(fPackageFragmentRoots[i]) || (fPackageFragmentRoots[i].isArchive() && !fPackageFragmentRoots[i].isExternal()))) 2188 return false; 2189 } 2190 if (ReorgUtils.containsLinkedResources(fPackageFragmentRoots)) 2191 return false; 2192 return true; 2193 } 2194 2195 public RefactoringStatus checkFinalConditions(IProgressMonitor pm, CheckConditionsContext context, IReorgQueries reorgQueries) throws CoreException { 2196 RefactoringStatus status= super.checkFinalConditions(pm, context, reorgQueries); 2197 confirmOverwriting(reorgQueries); 2198 return status; 2199 } 2200 2201 private void confirmOverwriting(IReorgQueries reorgQueries) { 2202 OverwriteHelper oh= new OverwriteHelper(); 2203 oh.setPackageFragmentRoots(fPackageFragmentRoots); 2204 IJavaProject javaProject= getDestinationJavaProject(); 2205 oh.confirmOverwriting(reorgQueries, javaProject); 2206 fPackageFragmentRoots= oh.getPackageFragmentRootsWithoutUnconfirmedOnes(); 2207 } 2208 2209 protected JDTRefactoringDescriptor createRefactoringDescriptor(final JDTRefactoringDescriptorComment comment, final Map arguments, final String description, final String project, int flags) { 2210 return new JDTRefactoringDescriptor(getProcessorId(), project, description, comment.asString(), arguments, flags); 2211 } 2212 2213 public final ChangeDescriptor getDescriptor() { 2214 final Map arguments= new HashMap (); 2215 final int length= fPackageFragmentRoots.length; 2216 final String description= length == 1 ? getDescriptionSingular() : getDescriptionPlural(); 2217 final IProject resource= getSingleProject(); 2218 final String project= resource != null ? resource.getName() : null; 2219 final String header= Messages.format(getHeaderPattern(), new String [] { String.valueOf(length), getDestinationLabel()}); 2220 int flags= RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE; 2221 final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header); 2222 final JDTRefactoringDescriptor descriptor= createRefactoringDescriptor(comment, arguments, description, project, flags); 2223 arguments.put(ATTRIBUTE_POLICY, getPolicyId()); 2224 arguments.put(ATTRIBUTE_ROOTS, new Integer (fPackageFragmentRoots.length).toString()); 2225 for (int offset= 0; offset < fPackageFragmentRoots.length; offset++) 2226 arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (offset + 1), descriptor.elementToHandle(fPackageFragmentRoots[offset])); 2227 arguments.putAll(getRefactoringArguments(project)); 2228 return new RefactoringChangeDescriptor(descriptor); 2229 } 2230 2231 private IJavaProject getDestinationAsJavaProject(IJavaElement javaElementDestination) { 2232 if (javaElementDestination == null) 2233 return null; 2234 else 2235 return javaElementDestination.getJavaProject(); 2236 } 2237 2238 protected IJavaProject getDestinationJavaProject() { 2239 return getDestinationAsJavaProject(getJavaElementDestination()); 2240 } 2241 2242 public IJavaElement[] getJavaElements() { 2243 return fPackageFragmentRoots; 2244 } 2245 2246 protected IPackageFragmentRoot[] getPackageFragmentRoots() { 2247 return fPackageFragmentRoots; 2248 } 2249 2250 public IResource[] getResources() { 2251 return new IResource[0]; 2252 } 2253 2254 public IPackageFragmentRoot[] getRoots() { 2255 return fPackageFragmentRoots; 2256 } 2257 2258 private IProject getSingleProject() { 2259 IProject result= null; 2260 for (int index= 0; index < fPackageFragmentRoots.length; index++) { 2261 if (result == null) 2262 result= fPackageFragmentRoots[index].getJavaProject().getProject(); 2263 else if (!result.equals(fPackageFragmentRoots[index].getJavaProject().getProject())) 2264 return null; 2265 } 2266 return result; 2267 } 2268 2269 public RefactoringStatus initialize(RefactoringArguments arguments) { 2270 final RefactoringStatus status= new RefactoringStatus(); 2271 if (arguments instanceof JavaRefactoringArguments) { 2272 final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments; 2273 int rootCount= 0; 2274 String value= extended.getAttribute(ATTRIBUTE_ROOTS); 2275 if (value != null && !"".equals(value)) { try { 2277 rootCount= Integer.parseInt(value); 2278 } catch (NumberFormatException exception) { 2279 return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_ROOTS)); 2280 } 2281 } else 2282 return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_ROOTS)); 2283 String handle= null; 2284 List elements= new ArrayList (); 2285 for (int index= 0; index < rootCount; index++) { 2286 final String attribute= JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (index + 1); 2287 handle= extended.getAttribute(attribute); 2288 if (handle != null && !"".equals(handle)) { final IJavaElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false); 2290 if (element == null || !element.exists() || element.getElementType() != IJavaElement.PACKAGE_FRAGMENT_ROOT) 2291 status.merge(ScriptableRefactoring.createInputWarningStatus(element, getProcessorId(), getRefactoringId())); 2292 else 2293 elements.add(element); 2294 } else 2295 return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, attribute)); 2296 } 2297 fPackageFragmentRoots= (IPackageFragmentRoot[]) elements.toArray(new IPackageFragmentRoot[elements.size()]); 2298 } else 2299 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments); 2300 status.merge(super.initialize(arguments)); 2301 return status; 2302 } 2303 2304 protected RefactoringStatus verifyDestination(IJavaElement javaElement) throws JavaModelException { 2305 Assert.isNotNull(javaElement); 2306 if (!fCheckDestination) 2307 return new RefactoringStatus(); 2308 if (!javaElement.exists()) 2309 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot1); 2310 if (javaElement instanceof IJavaModel) 2311 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_jmodel); 2312 if (!(javaElement instanceof IJavaProject || javaElement instanceof IPackageFragmentRoot)) 2313 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_src2proj); 2314 if (javaElement.isReadOnly()) 2315 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_src2writable); 2316 if (ReorgUtils.isPackageFragmentRoot(javaElement.getJavaProject())) 2317 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_src2nosrc); 2318 return new RefactoringStatus(); 2319 } 2320 2321 protected RefactoringStatus verifyDestination(IResource resource) { 2322 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_src2proj); 2323 } 2324 } 2325 2326 private static abstract class PackagesReorgPolicy extends ReorgPolicy { 2327 2328 private IPackageFragment[] fPackageFragments; 2329 2330 public PackagesReorgPolicy(IPackageFragment[] packageFragments) { 2331 fPackageFragments= packageFragments; 2332 } 2333 2334 public boolean canChildrenBeDestinations(IJavaElement javaElement) { 2335 switch (javaElement.getElementType()) { 2336 case IJavaElement.JAVA_MODEL: 2337 case IJavaElement.JAVA_PROJECT: 2338 case IJavaElement.PACKAGE_FRAGMENT_ROOT: 2339 return true; 2343 default: 2344 return false; 2345 } 2346 } 2347 2348 public boolean canChildrenBeDestinations(IResource resource) { 2349 return false; 2350 } 2351 2352 public boolean canElementBeDestination(IJavaElement javaElement) { 2353 switch (javaElement.getElementType()) { 2354 case IJavaElement.JAVA_PROJECT: 2355 case IJavaElement.PACKAGE_FRAGMENT_ROOT: 2356 return true; 2357 default: 2358 return false; 2359 } 2360 } 2361 2362 public boolean canElementBeDestination(IResource resource) { 2363 return false; 2364 } 2365 2366 public boolean canEnable() throws JavaModelException { 2367 for (int i= 0; i < fPackageFragments.length; i++) { 2368 if (JavaElementUtil.isDefaultPackage(fPackageFragments[i]) || fPackageFragments[i].isReadOnly()) 2369 return false; 2370 } 2371 if (ReorgUtils.containsLinkedResources(fPackageFragments)) 2372 return false; 2373 return true; 2374 } 2375 2376 public RefactoringStatus checkFinalConditions(IProgressMonitor pm, CheckConditionsContext context, IReorgQueries reorgQueries) throws CoreException { 2377 RefactoringStatus refactoringStatus= super.checkFinalConditions(pm, context, reorgQueries); 2378 confirmOverwriting(reorgQueries); 2379 return refactoringStatus; 2380 } 2381 2382 private void confirmOverwriting(IReorgQueries reorgQueries) throws JavaModelException { 2383 OverwriteHelper helper= new OverwriteHelper(); 2384 helper.setPackages(fPackageFragments); 2385 IPackageFragmentRoot destRoot= getDestinationAsPackageFragmentRoot(); 2386 helper.confirmOverwriting(reorgQueries, destRoot); 2387 fPackageFragments= helper.getPackagesWithoutUnconfirmedOnes(); 2388 } 2389 2390 protected JDTRefactoringDescriptor createRefactoringDescriptor(final JDTRefactoringDescriptorComment comment, final Map arguments, final String description, final String project, int flags) { 2391 return new JDTRefactoringDescriptor(getProcessorId(), project, description, comment.asString(), arguments, flags); 2392 } 2393 2394 public final ChangeDescriptor getDescriptor() { 2395 final Map arguments= new HashMap (); 2396 final int length= fPackageFragments.length; 2397 final String description= length == 1 ? getDescriptionSingular() : getDescriptionPlural(); 2398 final IProject resource= getSingleProject(); 2399 final String project= resource != null ? resource.getName() : null; 2400 final String header= Messages.format(getHeaderPattern(), new String [] { String.valueOf(length), getDestinationLabel()}); 2401 int flags= JavaRefactoringDescriptor.JAR_REFACTORING | JavaRefactoringDescriptor.JAR_MIGRATION | RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE; 2402 final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header); 2403 final JDTRefactoringDescriptor descriptor= createRefactoringDescriptor(comment, arguments, description, project, flags); 2404 arguments.put(ATTRIBUTE_POLICY, getPolicyId()); 2405 arguments.put(ATTRIBUTE_FRAGMENTS, new Integer (fPackageFragments.length).toString()); 2406 for (int offset= 0; offset < fPackageFragments.length; offset++) 2407 arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (offset + 1), descriptor.elementToHandle(fPackageFragments[offset])); 2408 arguments.putAll(getRefactoringArguments(project)); 2409 return new RefactoringChangeDescriptor(descriptor); 2410 } 2411 2412 protected IPackageFragmentRoot getDestinationAsPackageFragmentRoot() throws JavaModelException { 2413 return getDestinationAsPackageFragmentRoot(getJavaElementDestination()); 2414 } 2415 2416 private IPackageFragmentRoot getDestinationAsPackageFragmentRoot(IJavaElement javaElement) throws JavaModelException { 2417 if (javaElement == null) 2418 return null; 2419 2420 if (javaElement instanceof IPackageFragmentRoot) 2421 return (IPackageFragmentRoot) javaElement; 2422 2423 if (javaElement instanceof IPackageFragment) { 2424 IPackageFragment pack= (IPackageFragment) javaElement; 2425 if (pack.getParent() instanceof IPackageFragmentRoot) 2426 return (IPackageFragmentRoot) pack.getParent(); 2427 } 2428 2429 if (javaElement instanceof IJavaProject) 2430 return ReorgUtils.getCorrespondingPackageFragmentRoot((IJavaProject) javaElement); 2431 return null; 2432 } 2433 2434 public IJavaElement[] getJavaElements() { 2435 return fPackageFragments; 2436 } 2437 2438 protected IPackageFragment[] getPackages() { 2439 return fPackageFragments; 2440 } 2441 2442 public IResource[] getResources() { 2443 return new IResource[0]; 2444 } 2445 2446 private IProject getSingleProject() { 2447 IProject result= null; 2448 for (int index= 0; index < fPackageFragments.length; index++) { 2449 if (result == null) 2450 result= fPackageFragments[index].getJavaProject().getProject(); 2451 else if (!result.equals(fPackageFragments[index].getJavaProject().getProject())) 2452 return null; 2453 } 2454 return result; 2455 } 2456 2457 public RefactoringStatus initialize(RefactoringArguments arguments) { 2458 final RefactoringStatus status= new RefactoringStatus(); 2459 if (arguments instanceof JavaRefactoringArguments) { 2460 final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments; 2461 int fragmentCount= 0; 2462 String value= extended.getAttribute(ATTRIBUTE_FRAGMENTS); 2463 if (value != null && !"".equals(value)) { try { 2465 fragmentCount= Integer.parseInt(value); 2466 } catch (NumberFormatException exception) { 2467 return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_FRAGMENTS)); 2468 } 2469 } else 2470 return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_FRAGMENTS)); 2471 String handle= null; 2472 List elements= new ArrayList (); 2473 for (int index= 0; index < fragmentCount; index++) { 2474 final String attribute= JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (index + 1); 2475 handle= extended.getAttribute(attribute); 2476 if (handle != null && !"".equals(handle)) { final IJavaElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false); 2478 if (element == null || !element.exists() || element.getElementType() != IJavaElement.PACKAGE_FRAGMENT) 2479 status.merge(ScriptableRefactoring.createInputWarningStatus(element, getProcessorId(), getRefactoringId())); 2480 else 2481 elements.add(element); 2482 } else 2483 return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, attribute)); 2484 } 2485 fPackageFragments= (IPackageFragment[]) elements.toArray(new IPackageFragment[elements.size()]); 2486 } else 2487 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments); 2488 status.merge(super.initialize(arguments)); 2489 return status; 2490 } 2491 2492 protected RefactoringStatus verifyDestination(IJavaElement javaElement) throws JavaModelException { 2493 Assert.isNotNull(javaElement); 2494 if (!fCheckDestination) 2495 return new RefactoringStatus(); 2496 if (!javaElement.exists()) 2497 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot1); 2498 if (javaElement instanceof IJavaModel) 2499 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_jmodel); 2500 IPackageFragmentRoot destRoot= getDestinationAsPackageFragmentRoot(javaElement); 2501 if (!ReorgUtils.isSourceFolder(destRoot)) 2502 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_packages); 2503 return new RefactoringStatus(); 2504 } 2505 2506 protected RefactoringStatus verifyDestination(IResource resource) { 2507 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_packages); 2508 } 2509 } 2510 2511 private static abstract class ReorgPolicy implements IReorgPolicy { 2512 2513 private static final String ATTRIBUTE_DESTINATION= "destination"; 2515 private static final String ATTRIBUTE_TARGET= "target"; 2517 protected boolean fCheckDestination= true; 2518 2519 private IJavaElement fJavaElementDestination; 2520 2521 private IResource fResourceDestination; 2522 2523 public boolean canChildrenBeDestinations(IJavaElement javaElement) { 2524 return true; 2525 } 2526 2527 public boolean canChildrenBeDestinations(IResource resource) { 2528 return true; 2529 } 2530 2531 public boolean canElementBeDestination(IJavaElement javaElement) { 2532 return true; 2533 } 2534 2535 public boolean canElementBeDestination(IResource resource) { 2536 return true; 2537 } 2538 2539 public boolean canEnable() throws JavaModelException { 2540 IResource[] resources= getResources(); 2541 for (int i= 0; i < resources.length; i++) { 2542 IResource resource= resources[i]; 2543 if (!resource.exists() || resource.isPhantom() || !resource.isAccessible()) 2544 return false; 2545 } 2546 2547 IJavaElement[] javaElements= getJavaElements(); 2548 for (int i= 0; i < javaElements.length; i++) { 2549 IJavaElement element= javaElements[i]; 2550 if (!element.exists()) 2551 return false; 2552 } 2553 return true; 2554 } 2555 2556 public boolean canEnableQualifiedNameUpdating() { 2557 return false; 2558 } 2559 2560 public boolean canEnableUpdateReferences() { 2561 return false; 2562 } 2563 2564 public boolean canUpdateQualifiedNames() { 2565 Assert.isTrue(false); 2566 return false; 2570 } 2571 2572 public boolean canUpdateReferences() { 2573 return false; 2574 } 2575 2576 public RefactoringStatus checkFinalConditions(IProgressMonitor pm, CheckConditionsContext context, IReorgQueries reorgQueries) throws CoreException { 2577 Assert.isNotNull(reorgQueries); 2578 ResourceChangeChecker checker= (ResourceChangeChecker) context.getChecker(ResourceChangeChecker.class); 2579 IFile[] allModifiedFiles= getAllModifiedFiles(); 2580 RefactoringModifications modifications= getModifications(); 2581 IResourceChangeDescriptionFactory deltaFactory= checker.getDeltaFactory(); 2582 for (int i= 0; i < allModifiedFiles.length; i++) { 2583 deltaFactory.change(allModifiedFiles[i]); 2584 } 2585 if (modifications != null) { 2586 modifications.buildDelta(deltaFactory); 2587 modifications.buildValidateEdits((ValidateEditChecker) context.getChecker(ValidateEditChecker.class)); 2588 } 2589 return new RefactoringStatus(); 2590 } 2591 2592 public IFile[] getAllModifiedFiles() { 2593 return new IFile[0]; 2594 } 2595 2596 protected abstract String getDescriptionPlural(); 2597 2598 protected abstract String getDescriptionSingular(); 2599 2600 protected String getDestinationLabel() { 2601 Object destination= getJavaElementDestination(); 2602 if (destination == null) 2603 destination= getResourceDestination(); 2604 return JavaElementLabels.getTextLabel(destination, JavaElementLabels.ALL_FULLY_QUALIFIED); 2605 } 2606 2607 public String getFilePatterns() { 2608 Assert.isTrue(false); 2609 return null; 2613 } 2614 2615 protected abstract String getHeaderPattern(); 2616 2617 public final IJavaElement getJavaElementDestination() { 2618 return fJavaElementDestination; 2619 } 2620 2621 protected RefactoringModifications getModifications() throws CoreException { 2622 return null; 2623 } 2624 2625 protected abstract String getProcessorId(); 2626 2627 protected Map getRefactoringArguments(String project) { 2628 final Map arguments= new HashMap (); 2629 final IJavaElement element= getJavaElementDestination(); 2630 if (element != null) 2631 arguments.put(ATTRIBUTE_DESTINATION, JDTRefactoringDescriptor.elementToHandle(project, element)); 2632 else { 2633 final IResource resource= getResourceDestination(); 2635 if (resource != null) 2636 arguments.put(ATTRIBUTE_TARGET, JDTRefactoringDescriptor.resourceToHandle(null, resource)); 2637 } 2638 return arguments; 2639 } 2640 2641 protected abstract String getRefactoringId(); 2642 2643 public final IResource getResourceDestination() { 2644 return fResourceDestination; 2645 } 2646 2647 public boolean getUpdateQualifiedNames() { 2648 Assert.isTrue(false); 2649 return false; 2653 } 2654 2655 public boolean getUpdateReferences() { 2656 Assert.isTrue(false); 2657 return false; 2661 } 2662 2663 public boolean hasAllInputSet() { 2664 return fJavaElementDestination != null || fResourceDestination != null; 2665 } 2666 2667 public RefactoringStatus initialize(RefactoringArguments arguments) { 2668 if (arguments instanceof JavaRefactoringArguments) { 2669 final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments; 2670 String handle= extended.getAttribute(ATTRIBUTE_DESTINATION); 2671 if (handle != null) { 2672 final IJavaElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false); 2673 if (element != null) { 2674 if (fCheckDestination && !element.exists()) 2675 return ScriptableRefactoring.createInputFatalStatus(element, getProcessorId(), getRefactoringId()); 2676 else { 2677 try { 2678 return setDestination(element); 2679 } catch (JavaModelException exception) { 2680 JavaPlugin.log(exception); 2681 return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new String [] { handle, JDTRefactoringDescriptor.ATTRIBUTE_INPUT})); 2682 } 2683 } 2684 } else { 2685 final IResource resource= JDTRefactoringDescriptor.handleToResource(extended.getProject(), handle); 2688 if (resource == null || (fCheckDestination && !resource.exists())) 2689 return ScriptableRefactoring.createInputFatalStatus(resource, getProcessorId(), getRefactoringId()); 2690 else { 2691 try { 2692 return setDestination(resource); 2693 } catch (JavaModelException exception) { 2694 JavaPlugin.log(exception); 2695 return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new String [] { handle, JDTRefactoringDescriptor.ATTRIBUTE_INPUT})); 2696 } 2697 } 2698 } 2699 } else { 2700 handle= extended.getAttribute(ATTRIBUTE_TARGET); 2702 if (handle != null) { 2703 final IResource resource= JDTRefactoringDescriptor.handleToResource(null, handle); 2704 if (resource == null || (fCheckDestination && !resource.exists())) 2705 return ScriptableRefactoring.createInputFatalStatus(resource, getProcessorId(), getRefactoringId()); 2706 else { 2707 try { 2708 return setDestination(resource); 2709 } catch (JavaModelException exception) { 2710 JavaPlugin.log(exception); 2711 return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new String [] { handle, JDTRefactoringDescriptor.ATTRIBUTE_INPUT})); 2712 } 2713 } 2714 } else 2715 return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JDTRefactoringDescriptor.ATTRIBUTE_INPUT)); 2716 } 2717 } else 2718 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments); 2719 } 2720 2721 public final RefactoringParticipant[] loadParticipants(RefactoringStatus status, RefactoringProcessor processor, String [] natures, SharableParticipants shared) throws CoreException { 2722 RefactoringModifications modifications= getModifications(); 2723 if (modifications != null) { 2724 return modifications.loadParticipants(status, processor, natures, shared); 2725 } else { 2726 return new RefactoringParticipant[0]; 2727 } 2728 } 2729 2730 public final RefactoringStatus setDestination(IJavaElement destination) throws JavaModelException { 2731 Assert.isNotNull(destination); 2732 fJavaElementDestination= null; 2733 fResourceDestination= null; 2734 fJavaElementDestination= destination; 2735 return verifyDestination(destination); 2736 } 2737 2738 public final RefactoringStatus setDestination(IResource destination) throws JavaModelException { 2739 Assert.isNotNull(destination); 2740 fJavaElementDestination= null; 2741 fResourceDestination= null; 2742 fResourceDestination= destination; 2743 return verifyDestination(destination); 2744 } 2745 2746 public void setFilePatterns(String patterns) { 2747 Assert.isTrue(false); 2748 } 2752 2753 public void setUpdateQualifiedNames(boolean update) { 2754 Assert.isTrue(false); 2755 } 2759 2760 public void setUpdateReferences(boolean update) { 2761 Assert.isTrue(false); 2762 } 2766 2767 protected abstract RefactoringStatus verifyDestination(IJavaElement destination) throws JavaModelException; 2768 2769 protected abstract RefactoringStatus verifyDestination(IResource destination) throws JavaModelException; 2770 } 2771 2772 private static abstract class SubCuElementReorgPolicy extends ReorgPolicy { 2773 2774 protected static final int ONLY_FIELDS= 1; 2775 2776 protected static final int ONLY_IMPORT_CONTAINERS= 5; 2777 2778 protected static final int ONLY_IMPORT_DECLARATIONS= 6; 2779 2780 protected static final int ONLY_INITIALIZERS= 3; 2781 2782 protected static final int ONLY_METHODS= 2; 2783 2784 protected static final int ONLY_PACKAGE_DECLARATIONS= 4; 2785 2786 protected static final int ONLY_TYPES= 0; 2787 2788 protected static CompilationUnitChange createCompilationUnitChange(ICompilationUnit cu, CompilationUnitRewrite rewrite) throws CoreException { 2789 CompilationUnitChange change= rewrite.createChange(); 2790 if (change != null) { 2791 if (cu.isWorkingCopy()) 2792 change.setSaveMode(TextFileChange.LEAVE_DIRTY); 2793 } 2794 return change; 2795 } 2796 2797 protected static final ICompilationUnit getDestinationCu(IJavaElement destination) { 2798 if (destination instanceof ICompilationUnit) 2799 return (ICompilationUnit) destination; 2800 return (ICompilationUnit) destination.getAncestor(IJavaElement.COMPILATION_UNIT); 2801 } 2802 2803 private static ICompilationUnit getEnclosingCu(IJavaElement destination) { 2804 if (destination instanceof ICompilationUnit) 2805 return (ICompilationUnit) destination; 2806 return (ICompilationUnit) destination.getAncestor(IJavaElement.COMPILATION_UNIT); 2807 } 2808 2809 private static IType getEnclosingType(IJavaElement destination) { 2810 if (destination instanceof IType) 2811 return (IType) destination; 2812 return (IType) destination.getAncestor(IJavaElement.TYPE); 2813 } 2814 2815 private static String getUnindentedSource(ISourceReference sourceReference) throws JavaModelException { 2816 Assert.isTrue(sourceReference instanceof IJavaElement); 2817 String [] lines= Strings.convertIntoLines(sourceReference.getSource()); 2818 final IJavaProject project= ((IJavaElement) sourceReference).getJavaProject(); 2819 Strings.trimIndentation(lines, project, false); 2820 return Strings.concatenate(lines, StubUtility.getLineDelimiterUsed((IJavaElement) sourceReference)); 2821 } 2822 2823 private IJavaElement[] fJavaElements; 2824 2825 SubCuElementReorgPolicy(IJavaElement[] javaElements) { 2826 fJavaElements= javaElements; 2827 } 2828 2829 public boolean canChildrenBeDestinations(IResource resource) { 2830 return false; 2831 } 2832 2833 public boolean canElementBeDestination(IResource resource) { 2834 return false; 2835 } 2836 2837 public boolean canEnable() throws JavaModelException { 2838 if (!super.canEnable()) 2839 return false; 2840 for (int i= 0; i < fJavaElements.length; i++) { 2841 if (fJavaElements[i] instanceof IMember) { 2842 IMember member= (IMember) fJavaElements[i]; 2843 if (member.isBinary() && member.getSourceRange() == null) 2845 return false; 2846 } 2847 } 2848 return true; 2849 } 2850 2851 private void copyImportsToDestination(IImportContainer container, ASTRewrite rewrite, CompilationUnit sourceCuNode, CompilationUnit destinationCuNode) throws JavaModelException { 2852 IJavaElement[] importDeclarations= container.getChildren(); 2853 for (int i= 0; i < importDeclarations.length; i++) { 2854 Assert.isTrue(importDeclarations[i] instanceof IImportDeclaration); 2855 IImportDeclaration importDeclaration= (IImportDeclaration) importDeclarations[i]; 2856 copyImportToDestination(importDeclaration, rewrite, sourceCuNode, destinationCuNode); 2857 } 2858 } 2859 2860 private void copyImportToDestination(IImportDeclaration declaration, ASTRewrite targetRewrite, CompilationUnit sourceCuNode, CompilationUnit destinationCuNode) throws JavaModelException { 2861 ImportDeclaration sourceNode= ASTNodeSearchUtil.getImportDeclarationNode(declaration, sourceCuNode); 2862 ImportDeclaration copiedNode= (ImportDeclaration) ASTNode.copySubtree(targetRewrite.getAST(), sourceNode); 2863 targetRewrite.getListRewrite(destinationCuNode, CompilationUnit.IMPORTS_PROPERTY).insertLast(copiedNode, null); 2864 } 2865 2866 private void copyInitializerToDestination(IInitializer initializer, CompilationUnitRewrite targetRewriter, CompilationUnit sourceCuNode, CompilationUnit targetCuNode) throws JavaModelException { 2867 BodyDeclaration newInitializer= (BodyDeclaration) targetRewriter.getASTRewrite().createStringPlaceholder(getUnindentedSource(initializer), ASTNode.INITIALIZER); 2868 copyMemberToDestination(initializer, targetRewriter, sourceCuNode, targetCuNode, newInitializer); 2869 } 2870 2871 private void copyMemberToDestination(IMember member, CompilationUnitRewrite targetRewriter, CompilationUnit sourceCuNode, CompilationUnit targetCuNode, BodyDeclaration newMember) throws JavaModelException { 2872 IJavaElement javaElementDestination= getJavaElementDestination(); 2873 ASTNode nodeDestination; 2874 ASTNode destinationContainer; 2875 switch (javaElementDestination.getElementType()) { 2876 case IJavaElement.INITIALIZER: 2877 nodeDestination= ASTNodeSearchUtil.getInitializerNode((IInitializer) javaElementDestination, targetCuNode); 2878 destinationContainer= nodeDestination.getParent(); 2879 break; 2880 case IJavaElement.FIELD: 2881 nodeDestination= ASTNodeSearchUtil.getFieldOrEnumConstantDeclaration((IField) javaElementDestination, targetCuNode); 2882 destinationContainer= nodeDestination.getParent(); 2883 break; 2884 case IJavaElement.METHOD: 2885 nodeDestination= ASTNodeSearchUtil.getMethodOrAnnotationTypeMemberDeclarationNode((IMethod) javaElementDestination, targetCuNode); 2886 destinationContainer= nodeDestination.getParent(); 2887 break; 2888 case IJavaElement.TYPE: 2889 nodeDestination= null; 2890 IType typeDestination= (IType) javaElementDestination; 2891 if (typeDestination.isAnonymous()) 2892 destinationContainer= ASTNodeSearchUtil.getClassInstanceCreationNode(typeDestination, targetCuNode).getAnonymousClassDeclaration(); 2893 else 2894 destinationContainer= ASTNodeSearchUtil.getAbstractTypeDeclarationNode(typeDestination, targetCuNode); 2895 break; 2896 default: 2897 nodeDestination= null; 2898 destinationContainer= null; 2899 } 2900 if (!(member instanceof IInitializer)) { 2901 BodyDeclaration decl= ASTNodeSearchUtil.getBodyDeclarationNode(member, sourceCuNode); 2902 if (decl != null) 2903 ImportRewriteUtil.addImports(targetRewriter, decl, new HashMap (), new HashMap (), false); 2904 } 2905 if (destinationContainer != null) { 2906 ListRewrite listRewrite; 2907 if (destinationContainer instanceof AbstractTypeDeclaration) { 2908 if (newMember instanceof EnumConstantDeclaration && destinationContainer instanceof EnumDeclaration) 2909 listRewrite= targetRewriter.getASTRewrite().getListRewrite(destinationContainer, EnumDeclaration.ENUM_CONSTANTS_PROPERTY); 2910 else 2911 listRewrite= targetRewriter.getASTRewrite().getListRewrite(destinationContainer, ((AbstractTypeDeclaration) destinationContainer).getBodyDeclarationsProperty()); 2912 } else 2913 listRewrite= targetRewriter.getASTRewrite().getListRewrite(destinationContainer, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY); 2914 2915 if (nodeDestination != null) { 2916 final List list= listRewrite.getOriginalList(); 2917 final int index= list.indexOf(nodeDestination); 2918 if (index > 0 && index < list.size() - 1) { 2919 listRewrite.insertBefore(newMember, (ASTNode) list.get(index), null); 2920 } else 2921 listRewrite.insertLast(newMember, null); 2922 } else 2923 listRewrite.insertAt(newMember, ASTNodes.getInsertionIndex(newMember, listRewrite.getRewrittenList()), null); 2924 return; } 2926 final AbstractTypeDeclaration declaration= ASTNodeSearchUtil.getAbstractTypeDeclarationNode(getDestinationAsType(), targetCuNode); 2928 targetRewriter.getASTRewrite().getListRewrite(declaration, declaration.getBodyDeclarationsProperty()).insertLast(newMember, null); 2929 } 2930 2931 private void copyMethodToDestination(IMethod method, CompilationUnitRewrite targetRewriter, CompilationUnit sourceCuNode, CompilationUnit targetCuNode) throws JavaModelException { 2932 BodyDeclaration newMethod= (BodyDeclaration) targetRewriter.getASTRewrite().createStringPlaceholder(getUnindentedSource(method), ASTNode.METHOD_DECLARATION); 2933 copyMemberToDestination(method, targetRewriter, sourceCuNode, targetCuNode, newMethod); 2934 } 2935 2936 private void copyPackageDeclarationToDestination(IPackageDeclaration declaration, ASTRewrite targetRewrite, CompilationUnit sourceCuNode, CompilationUnit destinationCuNode) throws JavaModelException { 2937 if (destinationCuNode.getPackage() != null) 2938 return; 2939 PackageDeclaration sourceNode= ASTNodeSearchUtil.getPackageDeclarationNode(declaration, sourceCuNode); 2940 PackageDeclaration copiedNode= (PackageDeclaration) ASTNode.copySubtree(targetRewrite.getAST(), sourceNode); 2941 targetRewrite.set(destinationCuNode, CompilationUnit.PACKAGE_PROPERTY, copiedNode, null); 2942 } 2943 2944 protected void copyToDestination(IJavaElement element, CompilationUnitRewrite targetRewriter, CompilationUnit sourceCuNode, CompilationUnit targetCuNode) throws CoreException { 2945 final ASTRewrite rewrite= targetRewriter.getASTRewrite(); 2946 switch (element.getElementType()) { 2947 case IJavaElement.FIELD: 2948 copyMemberToDestination((IMember) element, targetRewriter, sourceCuNode, targetCuNode, createNewFieldDeclarationNode(((IField) element), rewrite, sourceCuNode)); 2949 break; 2950 case IJavaElement.IMPORT_CONTAINER: 2951 copyImportsToDestination((IImportContainer) element, rewrite, sourceCuNode, targetCuNode); 2952 break; 2953 case IJavaElement.IMPORT_DECLARATION: 2954 copyImportToDestination((IImportDeclaration) element, rewrite, sourceCuNode, targetCuNode); 2955 break; 2956 case IJavaElement.INITIALIZER: 2957 copyInitializerToDestination((IInitializer) element, targetRewriter, sourceCuNode, targetCuNode); 2958 break; 2959 case IJavaElement.METHOD: 2960 copyMethodToDestination((IMethod) element, targetRewriter, sourceCuNode, targetCuNode); 2961 break; 2962 case IJavaElement.PACKAGE_DECLARATION: 2963 copyPackageDeclarationToDestination((IPackageDeclaration) element, rewrite, sourceCuNode, targetCuNode); 2964 break; 2965 case IJavaElement.TYPE: 2966 copyTypeToDestination((IType) element, targetRewriter, sourceCuNode, targetCuNode); 2967 break; 2968 2969 default: 2970 Assert.isTrue(false); 2971 } 2972 } 2973 2974 private void copyTypeToDestination(IType type, CompilationUnitRewrite targetRewriter, CompilationUnit sourceCuNode, CompilationUnit targetCuNode) throws JavaModelException { 2975 AbstractTypeDeclaration newType= (AbstractTypeDeclaration) targetRewriter.getASTRewrite().createStringPlaceholder(getUnindentedSource(type), ASTNode.TYPE_DECLARATION); 2976 IType enclosingType= getEnclosingType(getJavaElementDestination()); 2977 if (enclosingType != null) { 2978 copyMemberToDestination(type, targetRewriter, sourceCuNode, targetCuNode, newType); 2979 } else { 2980 targetRewriter.getASTRewrite().getListRewrite(targetCuNode, CompilationUnit.TYPES_PROPERTY).insertLast(newType, null); 2981 } 2982 } 2983 2984 private BodyDeclaration createNewFieldDeclarationNode(IField field, ASTRewrite rewrite, CompilationUnit sourceCuNode) throws CoreException { 2985 AST targetAst= rewrite.getAST(); 2986 ITextFileBuffer buffer= null; 2987 BodyDeclaration newDeclaration= null; 2988 ICompilationUnit unit= field.getCompilationUnit(); 2989 try { 2990 buffer= RefactoringFileBuffers.acquire(unit); 2991 IDocument document= buffer.getDocument(); 2992 BodyDeclaration bodyDeclaration= ASTNodeSearchUtil.getFieldOrEnumConstantDeclaration(field, sourceCuNode); 2993 if (bodyDeclaration instanceof FieldDeclaration) { 2994 FieldDeclaration fieldDeclaration= (FieldDeclaration) bodyDeclaration; 2995 if (fieldDeclaration.fragments().size() == 1) 2996 return (FieldDeclaration) ASTNode.copySubtree(targetAst, fieldDeclaration); 2997 VariableDeclarationFragment originalFragment= ASTNodeSearchUtil.getFieldDeclarationFragmentNode(field, sourceCuNode); 2998 VariableDeclarationFragment copiedFragment= (VariableDeclarationFragment) ASTNode.copySubtree(targetAst, originalFragment); 2999 newDeclaration= targetAst.newFieldDeclaration(copiedFragment); 3000 ((FieldDeclaration) newDeclaration).setType((Type) ASTNode.copySubtree(targetAst, fieldDeclaration.getType())); 3001 } else if (bodyDeclaration instanceof EnumConstantDeclaration) { 3002 EnumConstantDeclaration constantDeclaration= (EnumConstantDeclaration) bodyDeclaration; 3003 EnumConstantDeclaration newConstDeclaration= targetAst.newEnumConstantDeclaration(); 3004 newConstDeclaration.setName((SimpleName) ASTNode.copySubtree(targetAst, constantDeclaration.getName())); 3005 AnonymousClassDeclaration anonymousDeclaration= constantDeclaration.getAnonymousClassDeclaration(); 3006 if (anonymousDeclaration != null) 3007 newConstDeclaration.setAnonymousClassDeclaration((AnonymousClassDeclaration) rewrite.createStringPlaceholder(document.get(anonymousDeclaration.getStartPosition(), anonymousDeclaration.getLength()), ASTNode.ANONYMOUS_CLASS_DECLARATION)); 3008 newDeclaration= newConstDeclaration; 3009 } else 3010 Assert.isTrue(false); 3011 if (newDeclaration != null) { 3012 newDeclaration.modifiers().addAll(ASTNodeFactory.newModifiers(targetAst, bodyDeclaration.getModifiers())); 3013 Javadoc javadoc= bodyDeclaration.getJavadoc(); 3014 if (javadoc != null) 3015 newDeclaration.setJavadoc((Javadoc) rewrite.createStringPlaceholder(document.get(javadoc.getStartPosition(), javadoc.getLength()), ASTNode.JAVADOC)); 3016 } 3017 } catch (BadLocationException exception) { 3018 JavaPlugin.log(exception); 3019 } finally { 3020 if (buffer != null) 3021 RefactoringFileBuffers.release(unit); 3022 } 3023 return newDeclaration; 3024 } 3025 3026 protected JDTRefactoringDescriptor createRefactoringDescriptor(final JDTRefactoringDescriptorComment comment, final Map arguments, final String description, final String project, int flags) { 3027 return new JDTRefactoringDescriptor(getProcessorId(), project, description, comment.asString(), arguments, flags); 3028 } 3029 3030 protected final int getContentKind() { 3031 final int types= ReorgUtils.getElementsOfType(fJavaElements, IJavaElement.TYPE).size(); 3032 final int fields= ReorgUtils.getElementsOfType(fJavaElements, IJavaElement.FIELD).size(); 3033 final int methods= ReorgUtils.getElementsOfType(fJavaElements, IJavaElement.METHOD).size(); 3034 final int initializers= ReorgUtils.getElementsOfType(fJavaElements, IJavaElement.INITIALIZER).size(); 3035 final int packages= ReorgUtils.getElementsOfType(fJavaElements, IJavaElement.PACKAGE_DECLARATION).size(); 3036 final int container= ReorgUtils.getElementsOfType(fJavaElements, IJavaElement.IMPORT_CONTAINER).size(); 3037 final int imp= ReorgUtils.getElementsOfType(fJavaElements, IJavaElement.IMPORT_DECLARATION).size(); 3038 final int length= types + fields + methods + initializers + packages + container + imp; 3039 if (length == types) 3040 return ONLY_TYPES; 3041 else if (length == fields) 3042 return ONLY_FIELDS; 3043 else if (length == methods) 3044 return ONLY_METHODS; 3045 else if (length == initializers) 3046 return ONLY_INITIALIZERS; 3047 else if (length == packages) 3048 return ONLY_PACKAGE_DECLARATIONS; 3049 else if (length == container) 3050 return ONLY_IMPORT_CONTAINERS; 3051 else if (length == imp) 3052 return ONLY_IMPORT_DECLARATIONS; 3053 return -1; 3054 } 3055 3056 public final ChangeDescriptor getDescriptor() { 3057 final Map arguments= new HashMap (); 3058 final int length= fJavaElements.length; 3059 final String description= length == 1 ? getDescriptionSingular() : getDescriptionPlural(); 3060 final IProject resource= getSingleProject(); 3061 final String project= resource != null ? resource.getName() : null; 3062 final String header= Messages.format(getHeaderPattern(), new String [] { String.valueOf(length), getDestinationLabel()}); 3063 int flags= JavaRefactoringDescriptor.JAR_REFACTORING | JavaRefactoringDescriptor.JAR_MIGRATION | RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE; 3064 final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header); 3065 final JDTRefactoringDescriptor descriptor= createRefactoringDescriptor(comment, arguments, description, project, flags); 3066 arguments.put(ATTRIBUTE_POLICY, getPolicyId()); 3067 arguments.put(ATTRIBUTE_MEMBERS, new Integer (fJavaElements.length).toString()); 3068 for (int offset= 0; offset < fJavaElements.length; offset++) 3069 arguments.put(JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (offset + 1), descriptor.elementToHandle(fJavaElements[offset])); 3070 arguments.putAll(getRefactoringArguments(project)); 3071 return new RefactoringChangeDescriptor(descriptor); 3072 } 3073 3074 private IType getDestinationAsType() throws JavaModelException { 3075 IJavaElement destination= getJavaElementDestination(); 3076 IType enclosingType= getEnclosingType(destination); 3077 if (enclosingType != null) 3078 return enclosingType; 3079 ICompilationUnit enclosingCu= getEnclosingCu(destination); 3080 Assert.isNotNull(enclosingCu); 3081 IType mainType= JavaElementUtil.getMainType(enclosingCu); 3082 Assert.isNotNull(mainType); 3083 return mainType; 3084 } 3085 3086 protected final ICompilationUnit getDestinationCu() { 3087 return getDestinationCu(getJavaElementDestination()); 3088 } 3089 3090 public final IJavaElement[] getJavaElements() { 3091 return fJavaElements; 3092 } 3093 3094 public final IResource[] getResources() { 3095 return new IResource[0]; 3096 } 3097 3098 private IProject getSingleProject() { 3099 IProject result= null; 3100 for (int index= 0; index < fJavaElements.length; index++) { 3101 if (result == null) 3102 result= fJavaElements[index].getJavaProject().getProject(); 3103 else if (!result.equals(fJavaElements[index].getJavaProject().getProject())) 3104 return null; 3105 } 3106 return result; 3107 } 3108 3109 protected final ICompilationUnit getSourceCu() { 3110 return (ICompilationUnit) fJavaElements[0].getAncestor(IJavaElement.COMPILATION_UNIT); 3113 } 3114 3115 public RefactoringStatus initialize(RefactoringArguments arguments) { 3116 final RefactoringStatus status= new RefactoringStatus(); 3117 if (arguments instanceof JavaRefactoringArguments) { 3118 final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments; 3119 int memberCount= 0; 3120 String value= extended.getAttribute(ATTRIBUTE_MEMBERS); 3121 if (value != null && !"".equals(value)) { try { 3123 memberCount= Integer.parseInt(value); 3124 } catch (NumberFormatException exception) { 3125 return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_MEMBERS)); 3126 } 3127 } else 3128 return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_MEMBERS)); 3129 String handle= null; 3130 List elements= new ArrayList (); 3131 for (int index= 0; index < memberCount; index++) { 3132 final String attribute= JDTRefactoringDescriptor.ATTRIBUTE_ELEMENT + (index + 1); 3133 handle= extended.getAttribute(attribute); 3134 if (handle != null && !"".equals(handle)) { final IJavaElement element= JDTRefactoringDescriptor.handleToElement(extended.getProject(), handle, false); 3136 if (element == null || !element.exists()) 3137 status.merge(ScriptableRefactoring.createInputWarningStatus(element, getProcessorId(), getRefactoringId())); 3138 else 3139 elements.add(element); 3140 } else 3141 return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, attribute)); 3142 } 3143 fJavaElements= (IJavaElement[]) elements.toArray(new IJavaElement[elements.size()]); 3144 } else 3145 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments); 3146 status.merge(super.initialize(arguments)); 3147 return status; 3148 } 3149 3150 private RefactoringStatus recursiveVerifyDestination(IJavaElement destination) throws JavaModelException { 3151 Assert.isNotNull(destination); 3152 if (!fCheckDestination) 3153 return new RefactoringStatus(); 3154 if (!destination.exists()) 3155 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_doesnotexist1); 3156 if (destination instanceof IJavaModel) 3157 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_jmodel); 3158 if (!(destination instanceof ICompilationUnit) && !ReorgUtils.isInsideCompilationUnit(destination)) 3159 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot); 3160 3161 ICompilationUnit destinationCu= getDestinationCu(destination); 3162 Assert.isNotNull(destinationCu); 3163 if (destinationCu.isReadOnly()) 3164 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot_modify); 3165 3166 switch (destination.getElementType()) { 3167 case IJavaElement.COMPILATION_UNIT: 3168 int[] types0= new int[] { IJavaElement.FIELD, IJavaElement.INITIALIZER, IJavaElement.METHOD}; 3169 if (ReorgUtils.hasElementsOfType(getJavaElements(), types0)) 3170 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot); 3171 break; 3172 case IJavaElement.PACKAGE_DECLARATION: 3173 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_package_decl); 3174 3175 case IJavaElement.IMPORT_CONTAINER: 3176 if (ReorgUtils.hasElementsNotOfType(getJavaElements(), IJavaElement.IMPORT_DECLARATION)) 3177 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot); 3178 break; 3179 3180 case IJavaElement.IMPORT_DECLARATION: 3181 if (ReorgUtils.hasElementsNotOfType(getJavaElements(), IJavaElement.IMPORT_DECLARATION)) 3182 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot); 3183 break; 3184 3185 case IJavaElement.FIELD: case IJavaElement.INITIALIZER: case IJavaElement.METHOD: return recursiveVerifyDestination(destination.getParent()); 3189 3190 case IJavaElement.TYPE: 3191 int[] types1= new int[] { IJavaElement.IMPORT_DECLARATION, IJavaElement.IMPORT_CONTAINER, IJavaElement.PACKAGE_DECLARATION}; 3192 if (ReorgUtils.hasElementsOfType(getJavaElements(), types1)) 3193 return recursiveVerifyDestination(destination.getParent()); 3194 break; 3195 } 3196 3197 return new RefactoringStatus(); 3198 } 3199 3200 protected RefactoringStatus verifyDestination(IJavaElement destination) throws JavaModelException { 3201 return recursiveVerifyDestination(destination); 3202 } 3203 3204 protected final RefactoringStatus verifyDestination(IResource destination) throws JavaModelException { 3205 return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_no_resource); 3206 } 3207 } 3208 3209 private static final String ATTRIBUTE_FILES= "files"; 3211 private static final String ATTRIBUTE_FOLDERS= "folders"; 3213 private static final String ATTRIBUTE_FRAGMENTS= "fragments"; 3215 private static final String ATTRIBUTE_LOG= "log"; 3217 private static final String ATTRIBUTE_MEMBERS= "members"; 3219 private static final String ATTRIBUTE_PATTERNS= "patterns"; 3221 private static final String ATTRIBUTE_POLICY= "policy"; 3223 private static final String ATTRIBUTE_QUALIFIED= "qualified"; 3225 private static final String ATTRIBUTE_ROOTS= "roots"; 3227 private static final String ATTRIBUTE_UNITS= "units"; 3229 private static final String DELIMITER_ELEMENT= "\t"; 3231 private static final String DELIMITER_RECORD= "\n"; 3233 private static final String NO_ID= "no_id"; 3235 private static final String NO_POLICY= "no_policy"; 3237 private static final String UNUSED_STRING= "unused"; 3239 private static boolean containsNull(Object [] objects) { 3240 for (int i= 0; i < objects.length; i++) { 3241 if (objects[i] == null) 3242 return true; 3243 } 3244 return false; 3245 } 3246 3247 public static ICopyPolicy createCopyPolicy(IResource[] resources, IJavaElement[] javaElements) throws JavaModelException { 3248 return (ICopyPolicy) createReorgPolicy(true, resources, javaElements); 3249 } 3250 3251 public static ICopyPolicy createCopyPolicy(RefactoringStatus status, RefactoringArguments arguments) { 3252 if (arguments instanceof JavaRefactoringArguments) { 3253 final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments; 3254 final String policy= extended.getAttribute(ATTRIBUTE_POLICY); 3255 if (policy != null && !"".equals(policy)) { if (CopyFilesFoldersAndCusPolicy.POLICY_COPY_RESOURCE.equals(policy)) { 3257 return new CopyFilesFoldersAndCusPolicy(null, null, null); 3258 } else if (CopyPackageFragmentRootsPolicy.POLICY_COPY_ROOTS.equals(policy)) { 3259 return new CopyPackageFragmentRootsPolicy(null); 3260 } else if (CopyPackagesPolicy.POLICY_COPY_PACKAGES.equals(policy)) { 3261 return new CopyPackagesPolicy(null); 3262 } else if (CopySubCuElementsPolicy.POLICY_COPY_MEMBERS.equals(policy)) { 3263 return new CopySubCuElementsPolicy(null); 3264 } else 3265 status.merge(RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new String [] { policy, ATTRIBUTE_POLICY}))); 3266 } else 3267 status.merge(RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_POLICY))); 3268 } else 3269 status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments)); 3270 return null; 3271 } 3272 3273 public static IMovePolicy createMovePolicy(IResource[] resources, IJavaElement[] javaElements) throws JavaModelException { 3274 return (IMovePolicy) createReorgPolicy(false, resources, javaElements); 3275 } 3276 3277 public static IMovePolicy createMovePolicy(RefactoringStatus status, RefactoringArguments arguments) { 3278 if (arguments instanceof JavaRefactoringArguments) { 3279 final JavaRefactoringArguments extended= (JavaRefactoringArguments) arguments; 3280 final String policy= extended.getAttribute(ATTRIBUTE_POLICY); 3281 if (policy != null && !"".equals(policy)) { if (MoveFilesFoldersAndCusPolicy.POLICY_MOVE_RESOURCES.equals(policy)) { 3283 return new MoveFilesFoldersAndCusPolicy(null, null, null); 3284 } else if (MovePackageFragmentRootsPolicy.POLICY_MOVE_ROOTS.equals(policy)) { 3285 return new MovePackageFragmentRootsPolicy(null); 3286 } else if (MovePackagesPolicy.POLICY_MOVE_PACKAGES.equals(policy)) { 3287 return new MovePackagesPolicy(null); 3288 } else if (MoveSubCuElementsPolicy.POLICY_MOVE_MEMBERS.equals(policy)) { 3289 return new MoveSubCuElementsPolicy(null); 3290 } else 3291 status.merge(RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new String [] { policy, ATTRIBUTE_POLICY}))); 3292 } else 3293 status.merge(RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_POLICY))); 3294 } else 3295 status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments)); 3296 return null; 3297 } 3298 3299 private static IReorgPolicy createReorgPolicy(boolean copy, IResource[] selectedResources, IJavaElement[] selectedJavaElements) throws JavaModelException { 3300 final IReorgPolicy NO; 3301 if (copy) 3302 NO= new NoCopyPolicy(); 3303 else 3304 NO= new NoMovePolicy(); 3305 3306 ActualSelectionComputer selectionComputer= new ActualSelectionComputer(selectedJavaElements, selectedResources); 3307 IResource[] resources= selectionComputer.getActualResourcesToReorg(); 3308 IJavaElement[] javaElements= selectionComputer.getActualJavaElementsToReorg(); 3309 3310 if ((resources.length + javaElements.length == 0) || containsNull(resources) || containsNull(javaElements) || ReorgUtils.isArchiveMember(javaElements) || ReorgUtils.hasElementsOfType(javaElements, IJavaElement.JAVA_PROJECT) || ReorgUtils.hasElementsOfType(javaElements, IJavaElement.JAVA_MODEL) || ReorgUtils.hasElementsOfType(resources, IResource.PROJECT | IResource.ROOT) || !new ParentChecker(resources, javaElements).haveCommonParent()) 3311 return NO; 3312 3313 if (ReorgUtils.hasElementsOfType(javaElements, IJavaElement.PACKAGE_FRAGMENT)) { 3314 if (resources.length != 0 || ReorgUtils.hasElementsNotOfType(javaElements, IJavaElement.PACKAGE_FRAGMENT)) 3315 return NO; 3316 if (copy) 3317 return new CopyPackagesPolicy(ArrayTypeConverter.toPackageArray(javaElements)); 3318 else 3319 return new MovePackagesPolicy(ArrayTypeConverter.toPackageArray(javaElements)); 3320 } 3321 3322 if (ReorgUtils.hasElementsOfType(javaElements, IJavaElement.PACKAGE_FRAGMENT_ROOT)) { 3323 if (resources.length != 0 || ReorgUtils.hasElementsNotOfType(javaElements, IJavaElement.PACKAGE_FRAGMENT_ROOT)) 3324 return NO; 3325 if (copy) 3326 return new CopyPackageFragmentRootsPolicy(ArrayTypeConverter.toPackageFragmentRootArray(javaElements)); 3327 else 3328 return new MovePackageFragmentRootsPolicy(ArrayTypeConverter.toPackageFragmentRootArray(javaElements)); 3329 } 3330 3331 if (ReorgUtils.hasElementsOfType(resources, IResource.FILE | IResource.FOLDER) || ReorgUtils.hasElementsOfType(javaElements, IJavaElement.COMPILATION_UNIT)) { 3332 if (ReorgUtils.hasElementsNotOfType(javaElements, IJavaElement.COMPILATION_UNIT)) 3333 return NO; 3334 if (ReorgUtils.hasElementsNotOfType(resources, IResource.FILE | IResource.FOLDER)) 3335 return NO; 3336 if (copy) 3337 return new CopyFilesFoldersAndCusPolicy(ReorgUtils.getFiles(resources), ReorgUtils.getFolders(resources), ArrayTypeConverter.toCuArray(javaElements)); 3338 else 3339 return new MoveFilesFoldersAndCusPolicy(ReorgUtils.getFiles(resources), ReorgUtils.getFolders(resources), ArrayTypeConverter.toCuArray(javaElements)); 3340 } 3341 3342 if (hasElementsSmallerThanCuOrClassFile(javaElements)) { 3343 Assert.isTrue(resources.length == 0); 3345 Assert.isTrue(!ReorgUtils.hasElementsOfType(javaElements, IJavaElement.COMPILATION_UNIT)); 3346 Assert.isTrue(!ReorgUtils.hasElementsOfType(javaElements, IJavaElement.CLASS_FILE)); 3347 Assert.isTrue(!hasElementsLargerThanCuOrClassFile(javaElements)); 3348 if (copy) 3349 return new CopySubCuElementsPolicy(javaElements); 3350 else 3351 return new MoveSubCuElementsPolicy(javaElements); 3352 } 3353 return NO; 3354 } 3355 3356 private static boolean hasElementsLargerThanCuOrClassFile(IJavaElement[] javaElements) { 3357 for (int i= 0; i < javaElements.length; i++) { 3358 if (!ReorgUtils.isInsideCompilationUnit(javaElements[i]) && !ReorgUtils.isInsideClassFile(javaElements[i])) 3359 return true; 3360 } 3361 return false; 3362 } 3363 3364 private static boolean hasElementsSmallerThanCuOrClassFile(IJavaElement[] javaElements) { 3365 for (int i= 0; i < javaElements.length; i++) { 3366 if (ReorgUtils.isInsideCompilationUnit(javaElements[i])) 3367 return true; 3368 if (ReorgUtils.isInsideClassFile(javaElements[i])) 3369 return true; 3370 } 3371 return false; 3372 } 3373 3374 public static CreateTargetExecutionLog loadCreateTargetExecutionLog(RefactoringStatus status, JavaRefactoringArguments arguments) { 3375 CreateTargetExecutionLog log= new CreateTargetExecutionLog(); 3376 final String value= arguments.getAttribute(ATTRIBUTE_LOG); 3377 if (value != null) { 3378 final StringTokenizer tokenizer= new StringTokenizer (value, DELIMITER_RECORD, false); 3379 while (tokenizer.hasMoreTokens()) { 3380 final String token= tokenizer.nextToken(); 3381 processCreateTargetExecutionRecord(log, arguments, token); 3382 } 3383 } 3384 return log; 3385 } 3386 3387 public static ReorgExecutionLog loadReorgExecutionLog(RefactoringStatus status, JavaRefactoringArguments arguments) { 3388 ReorgExecutionLog log= new ReorgExecutionLog(); 3389 final String value= arguments.getAttribute(ATTRIBUTE_LOG); 3390 if (value != null) { 3391 final StringTokenizer tokenizer= new StringTokenizer (value, DELIMITER_RECORD, false); 3392 while (tokenizer.hasMoreTokens()) { 3393 final String token= tokenizer.nextToken(); 3394 processReorgExecutionRecord(log, arguments, token); 3395 } 3396 } 3397 return log; 3398 } 3399 3400 private static void processCreateTargetExecutionRecord(CreateTargetExecutionLog log, JavaRefactoringArguments arguments, String token) { 3401 final StringTokenizer tokenizer= new StringTokenizer (token, DELIMITER_ELEMENT, false); 3402 String value= null; 3403 if (tokenizer.hasMoreTokens()) { 3404 value= tokenizer.nextToken(); 3405 Object selection= JDTRefactoringDescriptor.handleToElement(arguments.getProject(), value, false); 3406 if (selection == null) 3407 selection= JDTRefactoringDescriptor.handleToResource(arguments.getProject(), value); 3408 if (selection != null && tokenizer.hasMoreTokens()) { 3409 value= tokenizer.nextToken(); 3410 Object created= JDTRefactoringDescriptor.handleToElement(arguments.getProject(), value, false); 3411 if (created == null) 3412 created= JDTRefactoringDescriptor.handleToResource(arguments.getProject(), value); 3413 if (created != null) 3414 log.markAsCreated(selection, created); 3415 } 3416 } 3417 } 3418 3419 private static void processReorgExecutionRecord(ReorgExecutionLog log, JavaRefactoringArguments arguments, String token) { 3420 final StringTokenizer tokenizer= new StringTokenizer (token, DELIMITER_ELEMENT, false); 3421 String value= null; 3422 if (tokenizer.hasMoreTokens()) { 3423 value= tokenizer.nextToken(); 3424 Object element= JDTRefactoringDescriptor.handleToElement(arguments.getProject(), value); 3425 if (element == null) 3426 element= JDTRefactoringDescriptor.handleToResource(arguments.getProject(), value); 3427 if (tokenizer.hasMoreTokens()) { 3428 final boolean processed= Boolean.valueOf(tokenizer.nextToken()).booleanValue(); 3429 if (processed) { 3430 log.markAsProcessed(element); 3431 if (element instanceof IJavaElement) 3432 log.markAsProcessed(JavaElementResourceMapping.create((IJavaElement) element)); 3433 } 3434 if (tokenizer.hasMoreTokens()) { 3435 final boolean renamed= Boolean.valueOf(tokenizer.nextToken()).booleanValue(); 3436 if (renamed && tokenizer.hasMoreTokens()) { 3437 final String name= tokenizer.nextToken(); 3438 log.setNewName(element, name); 3439 if (element instanceof IJavaElement) 3440 log.setNewName(JavaElementResourceMapping.create((IJavaElement) element), name); 3441 } 3442 } 3443 } 3444 } 3445 } 3446 3447 public static void storeCreateTargetExecutionLog(String project, Map arguments, CreateTargetExecutionLog log) { 3448 if (log != null) { 3449 final StringBuffer buffer= new StringBuffer (64); 3450 final Object [] selections= log.getSelectedElements(); 3451 for (int index= 0; index < selections.length; index++) { 3452 final Object selection= selections[index]; 3453 if (selection != null) { 3454 final Object created= log.getCreatedElement(selection); 3455 if (created != null) { 3456 storeLogElement(buffer, project, selection); 3457 buffer.append(DELIMITER_ELEMENT); 3458 storeLogElement(buffer, project, created); 3459 buffer.append(DELIMITER_RECORD); 3460 } 3461 3462 } 3463 } 3464 final String value= new String (buffer.toString().trim()); 3465 if (!"".equals(value)) arguments.put(ATTRIBUTE_LOG, value); 3467 } 3468 } 3469 3470 private static boolean storeLogElement(StringBuffer buffer, String project, Object object) { 3471 if (object instanceof IJavaElement) { 3472 final IJavaElement element= (IJavaElement) object; 3473 buffer.append(JDTRefactoringDescriptor.elementToHandle(project, element)); 3474 return true; 3475 } else if (object instanceof IResource) { 3476 final IResource resource= (IResource) object; 3477 buffer.append(JDTRefactoringDescriptor.resourceToHandle(project, resource)); 3478 return true; 3479 } 3480 return false; 3481 } 3482 3483 public static void storeReorgExecutionLog(String project, Map arguments, ReorgExecutionLog log) { 3484 if (log != null) { 3485 final Set set= new HashSet (); 3486 set.addAll(Arrays.asList(log.getProcessedElements())); 3487 set.addAll(Arrays.asList(log.getRenamedElements())); 3488 final StringBuffer buffer= new StringBuffer (64); 3489 for (final Iterator iterator= set.iterator(); iterator.hasNext();) { 3490 final Object object= iterator.next(); 3491 if (storeLogElement(buffer, project, object)) { 3492 buffer.append(DELIMITER_ELEMENT); 3493 buffer.append(log.isProcessed(object)); 3494 buffer.append(DELIMITER_ELEMENT); 3495 final boolean renamed= log.isRenamed(object); 3496 buffer.append(renamed); 3497 if (renamed) { 3498 buffer.append(DELIMITER_ELEMENT); 3499 buffer.append(log.getNewName(object)); 3500 } 3501 buffer.append(DELIMITER_RECORD); 3502 } 3503 } 3504 final String value= new String (buffer.toString().trim()); 3505 if (!"".equals(value)) arguments.put(ATTRIBUTE_LOG, value); 3507 } 3508 } 3509 3510 private ReorgPolicyFactory() { 3511 } 3513} 3514 | Popular Tags |