0001: /*******************************************************************************
0002: * Copyright (c) 2000, 2007 IBM Corporation and others.
0003: * All rights reserved. This program and the accompanying materials
0004: * are made available under the terms of the Eclipse Public License v1.0
0005: * which accompanies this distribution, and is available at
0006: * http://www.eclipse.org/legal/epl-v10.html
0007: *
0008: * Contributors:
0009: * IBM Corporation - initial API and implementation
0010: *******************************************************************************/package org.eclipse.jdt.internal.corext.refactoring.reorg;
0011:
0012: import java.util.ArrayList;
0013: import java.util.Arrays;
0014: import java.util.Collections;
0015: import java.util.Comparator;
0016: import java.util.HashMap;
0017: import java.util.HashSet;
0018: import java.util.Iterator;
0019: import java.util.List;
0020: import java.util.Map;
0021: import java.util.Set;
0022: import java.util.StringTokenizer;
0023:
0024: import org.eclipse.core.runtime.Assert;
0025: import org.eclipse.core.runtime.CoreException;
0026: import org.eclipse.core.runtime.IPath;
0027: import org.eclipse.core.runtime.IProgressMonitor;
0028: import org.eclipse.core.runtime.IStatus;
0029: import org.eclipse.core.runtime.OperationCanceledException;
0030: import org.eclipse.core.runtime.SubProgressMonitor;
0031:
0032: import org.eclipse.core.resources.IContainer;
0033: import org.eclipse.core.resources.IFile;
0034: import org.eclipse.core.resources.IFolder;
0035: import org.eclipse.core.resources.IProject;
0036: import org.eclipse.core.resources.IResource;
0037: import org.eclipse.core.resources.ResourceAttributes;
0038: import org.eclipse.core.resources.mapping.IResourceChangeDescriptionFactory;
0039:
0040: import org.eclipse.ltk.core.refactoring.Change;
0041: import org.eclipse.ltk.core.refactoring.ChangeDescriptor;
0042: import org.eclipse.ltk.core.refactoring.CompositeChange;
0043: import org.eclipse.ltk.core.refactoring.NullChange;
0044: import org.eclipse.ltk.core.refactoring.RefactoringChangeDescriptor;
0045: import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
0046: import org.eclipse.ltk.core.refactoring.RefactoringStatus;
0047: import org.eclipse.ltk.core.refactoring.TextFileChange;
0048: import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
0049: import org.eclipse.ltk.core.refactoring.participants.CopyArguments;
0050: import org.eclipse.ltk.core.refactoring.participants.MoveArguments;
0051: import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
0052: import org.eclipse.ltk.core.refactoring.participants.RefactoringParticipant;
0053: import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor;
0054: import org.eclipse.ltk.core.refactoring.participants.ReorgExecutionLog;
0055: import org.eclipse.ltk.core.refactoring.participants.ResourceChangeChecker;
0056: import org.eclipse.ltk.core.refactoring.participants.SharableParticipants;
0057: import org.eclipse.ltk.core.refactoring.participants.ValidateEditChecker;
0058:
0059: import org.eclipse.jdt.core.IClassFile;
0060: import org.eclipse.jdt.core.ICompilationUnit;
0061: import org.eclipse.jdt.core.IField;
0062: import org.eclipse.jdt.core.IImportContainer;
0063: import org.eclipse.jdt.core.IImportDeclaration;
0064: import org.eclipse.jdt.core.IInitializer;
0065: import org.eclipse.jdt.core.IJavaElement;
0066: import org.eclipse.jdt.core.IJavaModel;
0067: import org.eclipse.jdt.core.IJavaProject;
0068: import org.eclipse.jdt.core.IMember;
0069: import org.eclipse.jdt.core.IMethod;
0070: import org.eclipse.jdt.core.IOpenable;
0071: import org.eclipse.jdt.core.IPackageDeclaration;
0072: import org.eclipse.jdt.core.IPackageFragment;
0073: import org.eclipse.jdt.core.IPackageFragmentRoot;
0074: import org.eclipse.jdt.core.ISourceRange;
0075: import org.eclipse.jdt.core.ISourceReference;
0076: import org.eclipse.jdt.core.IType;
0077: import org.eclipse.jdt.core.JavaCore;
0078: import org.eclipse.jdt.core.JavaModelException;
0079: import org.eclipse.jdt.core.dom.AST;
0080: import org.eclipse.jdt.core.dom.ASTNode;
0081: import org.eclipse.jdt.core.dom.ASTParser;
0082: import org.eclipse.jdt.core.dom.AbstractTypeDeclaration;
0083: import org.eclipse.jdt.core.dom.AnonymousClassDeclaration;
0084: import org.eclipse.jdt.core.dom.Block;
0085: import org.eclipse.jdt.core.dom.BodyDeclaration;
0086: import org.eclipse.jdt.core.dom.CompilationUnit;
0087: import org.eclipse.jdt.core.dom.EnumConstantDeclaration;
0088: import org.eclipse.jdt.core.dom.EnumDeclaration;
0089: import org.eclipse.jdt.core.dom.FieldDeclaration;
0090: import org.eclipse.jdt.core.dom.ImportDeclaration;
0091: import org.eclipse.jdt.core.dom.Javadoc;
0092: import org.eclipse.jdt.core.dom.MethodDeclaration;
0093: import org.eclipse.jdt.core.dom.PackageDeclaration;
0094: import org.eclipse.jdt.core.dom.SimpleName;
0095: import org.eclipse.jdt.core.dom.Type;
0096: import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
0097: import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
0098: import org.eclipse.jdt.core.dom.rewrite.ListRewrite;
0099: import org.eclipse.jdt.core.refactoring.IJavaRefactorings;
0100: import org.eclipse.jdt.core.refactoring.descriptors.CopyDescriptor;
0101: import org.eclipse.jdt.core.refactoring.descriptors.JavaRefactoringDescriptor;
0102: import org.eclipse.jdt.core.refactoring.descriptors.MoveDescriptor;
0103:
0104: import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
0105: import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory;
0106: import org.eclipse.jdt.internal.corext.dom.ASTNodes;
0107: import org.eclipse.jdt.internal.corext.refactoring.Checks;
0108: import org.eclipse.jdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
0109: import org.eclipse.jdt.internal.corext.refactoring.JavaRefactoringArguments;
0110: import org.eclipse.jdt.internal.corext.refactoring.JavaRefactoringDescriptorUtil;
0111: import org.eclipse.jdt.internal.corext.refactoring.RefactoringCoreMessages;
0112: import org.eclipse.jdt.internal.corext.refactoring.changes.CompilationUnitChange;
0113: import org.eclipse.jdt.internal.corext.refactoring.changes.CopyCompilationUnitChange;
0114: import org.eclipse.jdt.internal.corext.refactoring.changes.CopyPackageChange;
0115: import org.eclipse.jdt.internal.corext.refactoring.changes.CopyPackageFragmentRootChange;
0116: import org.eclipse.jdt.internal.corext.refactoring.changes.CopyResourceChange;
0117: import org.eclipse.jdt.internal.corext.refactoring.changes.DynamicValidationStateChange;
0118: import org.eclipse.jdt.internal.corext.refactoring.changes.MoveCompilationUnitChange;
0119: import org.eclipse.jdt.internal.corext.refactoring.changes.MovePackageChange;
0120: import org.eclipse.jdt.internal.corext.refactoring.changes.MovePackageFragmentRootChange;
0121: import org.eclipse.jdt.internal.corext.refactoring.changes.MoveResourceChange;
0122: import org.eclipse.jdt.internal.corext.refactoring.code.ScriptableRefactoring;
0123: import org.eclipse.jdt.internal.corext.refactoring.reorg.IReorgPolicy.ICopyPolicy;
0124: import org.eclipse.jdt.internal.corext.refactoring.reorg.IReorgPolicy.IMovePolicy;
0125: import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgDestinationFactory.JavaElementDestination;
0126: import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgDestinationFactory.ResourceDestination;
0127: import org.eclipse.jdt.internal.corext.refactoring.structure.ASTNodeSearchUtil;
0128: import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
0129: import org.eclipse.jdt.internal.corext.refactoring.structure.ImportRewriteUtil;
0130: import org.eclipse.jdt.internal.corext.refactoring.util.Changes;
0131: import org.eclipse.jdt.internal.corext.refactoring.util.JavaElementUtil;
0132: import org.eclipse.jdt.internal.corext.refactoring.util.QualifiedNameFinder;
0133: import org.eclipse.jdt.internal.corext.refactoring.util.QualifiedNameSearchResult;
0134: import org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser;
0135: import org.eclipse.jdt.internal.corext.refactoring.util.ResourceUtil;
0136: import org.eclipse.jdt.internal.corext.refactoring.util.TextChangeManager;
0137: import org.eclipse.jdt.internal.corext.util.JavaConventionsUtil;
0138: import org.eclipse.jdt.internal.corext.util.JavaElementResourceMapping;
0139: import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
0140: import org.eclipse.jdt.internal.corext.util.Messages;
0141: import org.eclipse.jdt.internal.corext.util.Strings;
0142:
0143: import org.eclipse.jdt.ui.JavaElementLabels;
0144:
0145: import org.eclipse.jdt.internal.ui.JavaPlugin;
0146: import org.eclipse.jdt.internal.ui.refactoring.RefactoringSaveHelper;
0147:
0148: public final class ReorgPolicyFactory {
0149:
0150: private static final class ActualSelectionComputer {
0151:
0152: private final IJavaElement[] fJavaElements;
0153:
0154: private final IResource[] fResources;
0155:
0156: public ActualSelectionComputer(IJavaElement[] javaElements,
0157: IResource[] resources) {
0158: fJavaElements = javaElements;
0159: fResources = resources;
0160: }
0161:
0162: public IJavaElement[] getActualJavaElementsToReorg()
0163: throws JavaModelException {
0164: List result = new ArrayList();
0165: for (int i = 0; i < fJavaElements.length; i++) {
0166: IJavaElement element = fJavaElements[i];
0167: if (element == null)
0168: continue;
0169: if (element instanceof IType) {
0170: IType type = (IType) element;
0171: ICompilationUnit cu = type.getCompilationUnit();
0172: if (cu != null && type.getDeclaringType() == null
0173: && cu.exists() && cu.getTypes().length == 1
0174: && !result.contains(cu))
0175: result.add(cu);
0176: else if (!result.contains(type))
0177: result.add(type);
0178: } else if (!result.contains(element)) {
0179: result.add(element);
0180: }
0181: }
0182: return (IJavaElement[]) result
0183: .toArray(new IJavaElement[result.size()]);
0184: }
0185:
0186: public IResource[] getActualResourcesToReorg() {
0187: Set javaElementSet = new HashSet(Arrays
0188: .asList(fJavaElements));
0189: List result = new ArrayList();
0190: for (int i = 0; i < fResources.length; i++) {
0191: if (fResources[i] == null)
0192: continue;
0193: IJavaElement element = JavaCore.create(fResources[i]);
0194: if (element == null || !element.exists()
0195: || !javaElementSet.contains(element))
0196: if (!result.contains(fResources[i]))
0197: result.add(fResources[i]);
0198: }
0199: return (IResource[]) result.toArray(new IResource[result
0200: .size()]);
0201:
0202: }
0203: }
0204:
0205: private static final class CopyFilesFoldersAndCusPolicy extends
0206: FilesFoldersAndCusReorgPolicy implements ICopyPolicy {
0207:
0208: private static final String POLICY_COPY_RESOURCE = "org.eclipse.jdt.ui.copyResources"; //$NON-NLS-1$
0209:
0210: private static Change copyCuToPackage(ICompilationUnit cu,
0211: IPackageFragment dest, NewNameProposer nameProposer,
0212: INewNameQueries copyQueries) {
0213: // XXX workaround for bug 31998 we will have to disable renaming of
0214: // linked packages (and cus)
0215: IResource res = ReorgUtils.getResource(cu);
0216: if (res != null && res.isLinked()) {
0217: if (ResourceUtil.getResource(dest) instanceof IContainer)
0218: return copyFileToContainer(
0219: cu,
0220: (IContainer) ResourceUtil.getResource(dest),
0221: nameProposer, copyQueries);
0222: }
0223:
0224: String newName = nameProposer.createNewName(cu, dest);
0225: Change simpleCopy = new CopyCompilationUnitChange(cu, dest,
0226: copyQueries.createStaticQuery(newName));
0227: if (newName == null || newName.equals(cu.getElementName()))
0228: return simpleCopy;
0229:
0230: try {
0231: IPath newPath = cu.getResource().getParent()
0232: .getFullPath().append(
0233: JavaModelUtil.getRenamedCUName(cu,
0234: newName));
0235: INewNameQuery nameQuery = copyQueries
0236: .createNewCompilationUnitNameQuery(cu, newName);
0237: return new CreateCopyOfCompilationUnitChange(newPath,
0238: cu.getSource(), cu, nameQuery);
0239: } catch (CoreException e) {
0240: // Using inferred change
0241: return simpleCopy;
0242: }
0243: }
0244:
0245: private static Change copyFileToContainer(ICompilationUnit cu,
0246: IContainer dest, NewNameProposer nameProposer,
0247: INewNameQueries copyQueries) {
0248: IResource resource = ReorgUtils.getResource(cu);
0249: return createCopyResourceChange(resource, nameProposer,
0250: copyQueries, dest);
0251: }
0252:
0253: private static Change createCopyResourceChange(
0254: IResource resource, NewNameProposer nameProposer,
0255: INewNameQueries copyQueries, IContainer destination) {
0256: if (resource == null || destination == null)
0257: return new NullChange();
0258: INewNameQuery nameQuery;
0259: String name = nameProposer.createNewName(resource,
0260: destination);
0261: if (name == null)
0262: nameQuery = copyQueries.createNullQuery();
0263: else
0264: nameQuery = copyQueries.createNewResourceNameQuery(
0265: resource, name);
0266: return new CopyResourceChange(resource, destination,
0267: nameQuery);
0268: }
0269:
0270: private CopyModifications fModifications;
0271:
0272: private ReorgExecutionLog fReorgExecutionLog;
0273:
0274: CopyFilesFoldersAndCusPolicy(IFile[] files, IFolder[] folders,
0275: ICompilationUnit[] cus) {
0276: super (files, folders, cus);
0277: }
0278:
0279: private Change createChange(ICompilationUnit unit,
0280: NewNameProposer nameProposer,
0281: INewNameQueries copyQueries) {
0282: IPackageFragment pack = getDestinationAsPackageFragment();
0283: if (pack != null)
0284: return copyCuToPackage(unit, pack, nameProposer,
0285: copyQueries);
0286: IContainer container = getDestinationAsContainer();
0287: return copyFileToContainer(unit, container, nameProposer,
0288: copyQueries);
0289: }
0290:
0291: public Change createChange(IProgressMonitor pm,
0292: INewNameQueries copyQueries) {
0293: IFile[] file = getFiles();
0294: IFolder[] folders = getFolders();
0295: ICompilationUnit[] cus = getCus();
0296: pm.beginTask("", cus.length + file.length + folders.length); //$NON-NLS-1$
0297: NewNameProposer nameProposer = new NewNameProposer();
0298: CompositeChange composite = new DynamicValidationStateChange(
0299: RefactoringCoreMessages.ReorgPolicy_copy);
0300: composite.markAsSynthetic();
0301: for (int i = 0; i < cus.length; i++) {
0302: composite.add(createChange(cus[i], nameProposer,
0303: copyQueries));
0304: pm.worked(1);
0305: }
0306: if (pm.isCanceled())
0307: throw new OperationCanceledException();
0308: for (int i = 0; i < file.length; i++) {
0309: composite.add(createChange(file[i], nameProposer,
0310: copyQueries));
0311: pm.worked(1);
0312: }
0313: if (pm.isCanceled())
0314: throw new OperationCanceledException();
0315: for (int i = 0; i < folders.length; i++) {
0316: composite.add(createChange(folders[i], nameProposer,
0317: copyQueries));
0318: pm.worked(1);
0319: }
0320: pm.done();
0321: return composite;
0322: }
0323:
0324: private Change createChange(IResource resource,
0325: NewNameProposer nameProposer,
0326: INewNameQueries copyQueries) {
0327: IContainer dest = getDestinationAsContainer();
0328: return createCopyResourceChange(resource, nameProposer,
0329: copyQueries, dest);
0330: }
0331:
0332: protected JavaRefactoringDescriptor createRefactoringDescriptor(
0333: JDTRefactoringDescriptorComment comment, Map arguments,
0334: String description, String project, int flags) {
0335: ReorgExecutionLog log = getReorgExecutionLog();
0336: storeReorgExecutionLog(project, arguments, log);
0337: return new CopyDescriptor(project, description, comment
0338: .asString(), arguments, flags);
0339: }
0340:
0341: protected String getDescriptionPlural() {
0342: final int kind = getContentKind();
0343: switch (kind) {
0344: case ONLY_FOLDERS:
0345: return RefactoringCoreMessages.ReorgPolicyFactory_copy_folders;
0346: case ONLY_FILES:
0347: return RefactoringCoreMessages.ReorgPolicyFactory_copy_files;
0348: case ONLY_CUS:
0349: return RefactoringCoreMessages.ReorgPolicyFactory_copy_compilation_units;
0350: }
0351: return RefactoringCoreMessages.ReorgPolicyFactory_copy_description_plural;
0352: }
0353:
0354: protected String getDescriptionSingular() {
0355: final int kind = getContentKind();
0356: switch (kind) {
0357: case ONLY_FOLDERS:
0358: return RefactoringCoreMessages.ReorgPolicyFactory_copy_folder;
0359: case ONLY_FILES:
0360: return RefactoringCoreMessages.ReorgPolicyFactory_copy_file;
0361: case ONLY_CUS:
0362: return RefactoringCoreMessages.ReorgPolicyFactory_copy_compilation_unit;
0363: }
0364: return RefactoringCoreMessages.ReorgPolicyFactory_copy_description_singular;
0365: }
0366:
0367: private Object getDestination() {
0368: Object result = getDestinationAsPackageFragment();
0369: if (result != null)
0370: return result;
0371: return getDestinationAsContainer();
0372: }
0373:
0374: protected String getHeaderPattern() {
0375: return RefactoringCoreMessages.ReorgPolicyFactory_copy_header;
0376: }
0377:
0378: protected RefactoringModifications getModifications()
0379: throws CoreException {
0380: if (fModifications != null)
0381: return fModifications;
0382: fModifications = new CopyModifications();
0383: fReorgExecutionLog = new ReorgExecutionLog();
0384: CopyArguments jArgs = new CopyArguments(getDestination(),
0385: fReorgExecutionLog);
0386: CopyArguments rArgs = new CopyArguments(
0387: getDestinationAsContainer(), fReorgExecutionLog);
0388: ICompilationUnit[] cus = getCus();
0389: for (int i = 0; i < cus.length; i++) {
0390: fModifications.copy(cus[i], jArgs, rArgs);
0391: }
0392: IResource[] resources = ReorgUtils.union(getFiles(),
0393: getFolders());
0394: for (int i = 0; i < resources.length; i++) {
0395: fModifications.copy(resources[i], rArgs);
0396: }
0397: return fModifications;
0398: }
0399:
0400: public String getPolicyId() {
0401: return POLICY_COPY_RESOURCE;
0402: }
0403:
0404: protected String getProcessorId() {
0405: return IJavaRefactorings.COPY;
0406: }
0407:
0408: protected String getRefactoringId() {
0409: return IJavaRefactorings.COPY;
0410: }
0411:
0412: public ReorgExecutionLog getReorgExecutionLog() {
0413: return fReorgExecutionLog;
0414: }
0415: }
0416:
0417: private static final class CopyPackageFragmentRootsPolicy extends
0418: PackageFragmentRootsReorgPolicy implements ICopyPolicy {
0419:
0420: private static final String POLICY_COPY_ROOTS = "org.eclipse.jdt.ui.copyRoots"; //$NON-NLS-1$
0421:
0422: private CopyModifications fModifications;
0423:
0424: private ReorgExecutionLog fReorgExecutionLog;
0425:
0426: public CopyPackageFragmentRootsPolicy(
0427: IPackageFragmentRoot[] roots) {
0428: super (roots);
0429: }
0430:
0431: private Change createChange(IPackageFragmentRoot root,
0432: IJavaProject destination, NewNameProposer nameProposer,
0433: INewNameQueries copyQueries) {
0434: IResource res = root.getResource();
0435: IProject destinationProject = destination.getProject();
0436: String newName = nameProposer.createNewName(res,
0437: destinationProject);
0438: INewNameQuery nameQuery;
0439: if (newName == null)
0440: nameQuery = copyQueries.createNullQuery();
0441: else
0442: nameQuery = copyQueries
0443: .createNewPackageFragmentRootNameQuery(root,
0444: newName);
0445: // TODO fix the query problem
0446: return new CopyPackageFragmentRootChange(root,
0447: destinationProject, nameQuery, null);
0448: }
0449:
0450: private Change createChange(IPackageFragmentRoot root,
0451: IContainer destination, NewNameProposer nameProposer,
0452: INewNameQueries copyQueries) {
0453: IResource res = root.getResource();
0454:
0455: String newName = nameProposer.createNewName(res,
0456: destination);
0457: INewNameQuery nameQuery;
0458: if (newName == null) {
0459: nameQuery = copyQueries.createNullQuery();
0460: } else {
0461: nameQuery = copyQueries.createNewResourceNameQuery(res,
0462: newName);
0463: }
0464:
0465: return new CopyResourceChange(res, destination, nameQuery);
0466: }
0467:
0468: public Change createChange(IProgressMonitor pm,
0469: INewNameQueries copyQueries) {
0470: NewNameProposer nameProposer = new NewNameProposer();
0471: IPackageFragmentRoot[] roots = getPackageFragmentRoots();
0472: pm.beginTask("", roots.length); //$NON-NLS-1$
0473: CompositeChange composite = new DynamicValidationStateChange(
0474: RefactoringCoreMessages.ReorgPolicy_copy_source_folder);
0475: composite.markAsSynthetic();
0476: IJavaProject destination = getDestinationJavaProject();
0477: for (int i = 0; i < roots.length; i++) {
0478: if (destination == null) {
0479: composite.add(createChange(roots[i],
0480: (IContainer) getResourceDestination(),
0481: nameProposer, copyQueries));
0482: } else {
0483: composite.add(createChange(roots[i], destination,
0484: nameProposer, copyQueries));
0485: }
0486: pm.worked(1);
0487: }
0488: pm.done();
0489: return composite;
0490: }
0491:
0492: protected JavaRefactoringDescriptor createRefactoringDescriptor(
0493: JDTRefactoringDescriptorComment comment, Map arguments,
0494: String description, String project, int flags) {
0495: ReorgExecutionLog log = getReorgExecutionLog();
0496: storeReorgExecutionLog(project, arguments, log);
0497: return new CopyDescriptor(project, description, comment
0498: .asString(), arguments, flags);
0499: }
0500:
0501: protected String getDescriptionPlural() {
0502: return RefactoringCoreMessages.ReorgPolicyFactory_copy_roots_plural;
0503: }
0504:
0505: protected String getDescriptionSingular() {
0506: return RefactoringCoreMessages.ReorgPolicyFactory_copy_roots_singular;
0507: }
0508:
0509: protected String getHeaderPattern() {
0510: return RefactoringCoreMessages.ReorgPolicyFactory_copy_roots_header;
0511: }
0512:
0513: protected RefactoringModifications getModifications()
0514: throws CoreException {
0515: if (fModifications != null)
0516: return fModifications;
0517:
0518: fModifications = new CopyModifications();
0519: fReorgExecutionLog = new ReorgExecutionLog();
0520: IJavaProject destination = getDestinationJavaProject();
0521: if (destination == null) {
0522: IPackageFragmentRoot[] roots = getRoots();
0523: for (int i = 0; i < roots.length; i++) {
0524: fModifications.copy(roots[i].getResource(),
0525: new CopyArguments(getResourceDestination(),
0526: fReorgExecutionLog));
0527: }
0528: } else {
0529: CopyArguments javaArgs = new CopyArguments(destination,
0530: fReorgExecutionLog);
0531: CopyArguments resourceArgs = new CopyArguments(
0532: destination.getProject(), fReorgExecutionLog);
0533: IPackageFragmentRoot[] roots = getRoots();
0534: for (int i = 0; i < roots.length; i++) {
0535: fModifications.copy(roots[i], javaArgs,
0536: resourceArgs);
0537: }
0538: }
0539: return fModifications;
0540: }
0541:
0542: public String getPolicyId() {
0543: return POLICY_COPY_ROOTS;
0544: }
0545:
0546: protected String getProcessorId() {
0547: return IJavaRefactorings.COPY;
0548: }
0549:
0550: protected String getRefactoringId() {
0551: return IJavaRefactorings.COPY;
0552: }
0553:
0554: public ReorgExecutionLog getReorgExecutionLog() {
0555: return fReorgExecutionLog;
0556: }
0557: }
0558:
0559: private static final class CopyPackagesPolicy extends
0560: PackagesReorgPolicy implements ICopyPolicy {
0561:
0562: private static final String POLICY_COPY_PACKAGES = "org.eclipse.jdt.ui.copyPackages"; //$NON-NLS-1$
0563:
0564: private CopyModifications fModifications;
0565:
0566: private ReorgExecutionLog fReorgExecutionLog;
0567:
0568: public CopyPackagesPolicy(IPackageFragment[] packageFragments) {
0569: super (packageFragments);
0570: }
0571:
0572: private Change createChange(IPackageFragment pack,
0573: IPackageFragmentRoot destination,
0574: NewNameProposer nameProposer,
0575: INewNameQueries copyQueries) {
0576: String newName = nameProposer.createNewName(pack,
0577: destination);
0578: if (newName == null
0579: || JavaConventionsUtil.validatePackageName(newName,
0580: destination).getSeverity() < IStatus.ERROR) {
0581: INewNameQuery nameQuery;
0582: if (newName == null)
0583: nameQuery = copyQueries.createNullQuery();
0584: else
0585: nameQuery = copyQueries.createNewPackageNameQuery(
0586: pack, newName);
0587: return new CopyPackageChange(pack, destination,
0588: nameQuery);
0589: } else {
0590: if (destination.getResource() instanceof IContainer) {
0591: IContainer dest = (IContainer) destination
0592: .getResource();
0593: IResource res = pack.getResource();
0594: INewNameQuery nameQuery = copyQueries
0595: .createNewResourceNameQuery(res, newName);
0596: return new CopyResourceChange(res, dest, nameQuery);
0597: } else {
0598: return new NullChange();
0599: }
0600: }
0601: }
0602:
0603: private Change createChange(IPackageFragment pack,
0604: IContainer container, NewNameProposer nameProposer,
0605: INewNameQueries copyQueries) {
0606: String newName = nameProposer.createNewName(pack
0607: .getResource(), container);
0608: if (newName == null) {
0609: return new CopyResourceChange(pack.getResource(),
0610: container, copyQueries.createNullQuery());
0611: } else {
0612: IResource res = pack.getResource();
0613: INewNameQuery nameQuery = copyQueries
0614: .createNewResourceNameQuery(res, newName);
0615: return new CopyResourceChange(res, container, nameQuery);
0616: }
0617: }
0618:
0619: public Change createChange(IProgressMonitor pm,
0620: INewNameQueries newNameQueries)
0621: throws JavaModelException {
0622: NewNameProposer nameProposer = new NewNameProposer();
0623: IPackageFragment[] fragments = getPackages();
0624: pm.beginTask("", fragments.length); //$NON-NLS-1$
0625: CompositeChange composite = new DynamicValidationStateChange(
0626: RefactoringCoreMessages.ReorgPolicy_copy_package);
0627: composite.markAsSynthetic();
0628: IPackageFragmentRoot root = getDestinationAsPackageFragmentRoot();
0629: for (int i = 0; i < fragments.length; i++) {
0630: if (root == null) {
0631: composite.add(createChange(fragments[i],
0632: (IContainer) getResourceDestination(),
0633: nameProposer, newNameQueries));
0634: } else {
0635: composite.add(createChange(fragments[i], root,
0636: nameProposer, newNameQueries));
0637: }
0638: pm.worked(1);
0639: }
0640: pm.done();
0641: return composite;
0642: }
0643:
0644: protected JavaRefactoringDescriptor createRefactoringDescriptor(
0645: JDTRefactoringDescriptorComment comment, Map arguments,
0646: String description, String project, int flags) {
0647: ReorgExecutionLog log = getReorgExecutionLog();
0648: storeReorgExecutionLog(project, arguments, log);
0649: return new CopyDescriptor(project, description, comment
0650: .asString(), arguments, flags);
0651: }
0652:
0653: protected String getDescriptionPlural() {
0654: return RefactoringCoreMessages.ReorgPolicyFactory_copy_packages_plural;
0655: }
0656:
0657: protected String getDescriptionSingular() {
0658: return RefactoringCoreMessages.ReorgPolicyFactory_copy_package_singular;
0659: }
0660:
0661: protected String getHeaderPattern() {
0662: return RefactoringCoreMessages.ReorgPolicyFactory_copy_packages_header;
0663: }
0664:
0665: protected RefactoringModifications getModifications()
0666: throws CoreException {
0667: if (fModifications != null)
0668: return fModifications;
0669:
0670: fModifications = new CopyModifications();
0671: fReorgExecutionLog = new ReorgExecutionLog();
0672: IPackageFragmentRoot destination = getDestinationAsPackageFragmentRoot();
0673: if (destination == null) {
0674: IPackageFragment[] packages = getPackages();
0675: for (int i = 0; i < packages.length; i++) {
0676: fModifications.copy(packages[i].getResource(),
0677: new CopyArguments(getResourceDestination(),
0678: fReorgExecutionLog));
0679: }
0680: } else {
0681: CopyArguments javaArgs = new CopyArguments(destination,
0682: fReorgExecutionLog);
0683: CopyArguments resourceArgs = new CopyArguments(
0684: destination.getResource(), fReorgExecutionLog);
0685: IPackageFragment[] packages = getPackages();
0686: for (int i = 0; i < packages.length; i++) {
0687: fModifications.copy(packages[i], javaArgs,
0688: resourceArgs);
0689: }
0690: }
0691: return fModifications;
0692: }
0693:
0694: public String getPolicyId() {
0695: return POLICY_COPY_PACKAGES;
0696: }
0697:
0698: protected String getProcessorId() {
0699: return IJavaRefactorings.COPY;
0700: }
0701:
0702: protected String getRefactoringId() {
0703: return IJavaRefactorings.COPY;
0704: }
0705:
0706: public ReorgExecutionLog getReorgExecutionLog() {
0707: return fReorgExecutionLog;
0708: }
0709: }
0710:
0711: private static final class CopySubCuElementsPolicy extends
0712: SubCuElementReorgPolicy implements ICopyPolicy {
0713:
0714: private static final String POLICY_COPY_MEMBERS = "org.eclipse.jdt.ui.copyMembers"; //$NON-NLS-1$
0715:
0716: private CopyModifications fModifications;
0717:
0718: private ReorgExecutionLog fReorgExecutionLog;
0719:
0720: CopySubCuElementsPolicy(IJavaElement[] javaElements) {
0721: super (javaElements);
0722: }
0723:
0724: public boolean canEnable() throws JavaModelException {
0725: return super .canEnable()
0726: && (getSourceCu() != null || getSourceClassFile() != null);
0727: }
0728:
0729: public Change createChange(IProgressMonitor pm,
0730: INewNameQueries copyQueries) throws JavaModelException {
0731: try {
0732: CompilationUnit sourceCuNode = createSourceCuNode();
0733: ICompilationUnit targetCu = getEnclosingCompilationUnit(getJavaElementDestination());
0734: CompilationUnitRewrite targetRewriter = new CompilationUnitRewrite(
0735: targetCu);
0736: IJavaElement[] javaElements = getJavaElements();
0737: for (int i = 0; i < javaElements.length; i++) {
0738: copyToDestination(javaElements[i], targetRewriter,
0739: sourceCuNode, targetRewriter.getRoot());
0740: }
0741: return createCompilationUnitChange(targetRewriter);
0742: } catch (JavaModelException e) {
0743: throw e;
0744: } catch (CoreException e) {
0745: throw new JavaModelException(e);
0746: }
0747: }
0748:
0749: protected JavaRefactoringDescriptor createRefactoringDescriptor(
0750: JDTRefactoringDescriptorComment comment, Map arguments,
0751: String description, String project, int flags) {
0752: ReorgExecutionLog log = getReorgExecutionLog();
0753: storeReorgExecutionLog(project, arguments, log);
0754: return new CopyDescriptor(project, description, comment
0755: .asString(), arguments, flags);
0756: }
0757:
0758: private CompilationUnit createSourceCuNode() {
0759: Assert.isTrue(getSourceCu() != null
0760: || getSourceClassFile() != null);
0761: Assert.isTrue(getSourceCu() == null
0762: || getSourceClassFile() == null);
0763: ASTParser parser = ASTParser.newParser(AST.JLS3);
0764: parser.setBindingsRecovery(true);
0765: parser.setResolveBindings(true);
0766: if (getSourceCu() != null)
0767: parser.setSource(getSourceCu());
0768: else
0769: parser.setSource(getSourceClassFile());
0770: return (CompilationUnit) parser.createAST(null);
0771: }
0772:
0773: public IFile[] getAllModifiedFiles() {
0774: return ReorgUtils
0775: .getFiles(new IResource[] { ReorgUtils
0776: .getResource(getEnclosingCompilationUnit(getJavaElementDestination())) });
0777: }
0778:
0779: protected String getDescriptionPlural() {
0780: if (!ReorgUtils.hasElementsNotOfType(getJavaElements(),
0781: IJavaElement.TYPE)) {
0782: return RefactoringCoreMessages.ReorgPolicyFactory_copy_types;
0783: } else if (!ReorgUtils.hasElementsNotOfType(
0784: getJavaElements(), IJavaElement.FIELD)) {
0785: return RefactoringCoreMessages.ReorgPolicyFactory_copy_fields;
0786: } else if (!ReorgUtils.hasElementsNotOfType(
0787: getJavaElements(), IJavaElement.METHOD)) {
0788: return RefactoringCoreMessages.ReorgPolicyFactory_copy_methods;
0789: } else if (!ReorgUtils.hasElementsNotOfType(
0790: getJavaElements(), IJavaElement.INITIALIZER)) {
0791: return RefactoringCoreMessages.ReorgPolicyFactory_copy_initializers;
0792: } else if (!ReorgUtils
0793: .hasElementsNotOfType(getJavaElements(),
0794: IJavaElement.PACKAGE_DECLARATION)) {
0795: return RefactoringCoreMessages.ReorgPolicyFactory_copy_package_declarations;
0796: } else if (!ReorgUtils.hasElementsNotOfType(
0797: getJavaElements(), IJavaElement.IMPORT_CONTAINER)) {
0798: return RefactoringCoreMessages.ReorgPolicyFactory_copy_import_containers;
0799: } else if (!ReorgUtils.hasElementsNotOfType(
0800: getJavaElements(), IJavaElement.IMPORT_DECLARATION)) {
0801: return RefactoringCoreMessages.ReorgPolicyFactory_copy_imports;
0802: } else {
0803: return RefactoringCoreMessages.ReorgPolicyFactory_copy_elements_plural;
0804: }
0805: }
0806:
0807: protected String getDescriptionSingular() {
0808: if (!ReorgUtils.hasElementsNotOfType(getJavaElements(),
0809: IJavaElement.TYPE)) {
0810: return RefactoringCoreMessages.ReorgPolicyFactory_copy_type;
0811: } else if (!ReorgUtils.hasElementsNotOfType(
0812: getJavaElements(), IJavaElement.FIELD)) {
0813: return RefactoringCoreMessages.ReorgPolicyFactory_copy_field;
0814: } else if (!ReorgUtils.hasElementsNotOfType(
0815: getJavaElements(), IJavaElement.METHOD)) {
0816: return RefactoringCoreMessages.ReorgPolicyFactory_copy_method;
0817: } else if (!ReorgUtils.hasElementsNotOfType(
0818: getJavaElements(), IJavaElement.INITIALIZER)) {
0819: return RefactoringCoreMessages.ReorgPolicyFactory_copy_initializer;
0820: } else if (!ReorgUtils
0821: .hasElementsNotOfType(getJavaElements(),
0822: IJavaElement.PACKAGE_DECLARATION)) {
0823: return RefactoringCoreMessages.ReorgPolicyFactory_copy_package;
0824: } else if (!ReorgUtils.hasElementsNotOfType(
0825: getJavaElements(), IJavaElement.IMPORT_CONTAINER)) {
0826: return RefactoringCoreMessages.ReorgPolicyFactory_copy_import_section;
0827: } else if (!ReorgUtils.hasElementsNotOfType(
0828: getJavaElements(), IJavaElement.IMPORT_DECLARATION)) {
0829: return RefactoringCoreMessages.ReorgPolicyFactory_copy_import;
0830: } else {
0831: return RefactoringCoreMessages.ReorgPolicyFactory_copy_elements_singular;
0832: }
0833: }
0834:
0835: protected String getHeaderPattern() {
0836: return RefactoringCoreMessages.ReorgPolicyFactory_copy_elements_header;
0837: }
0838:
0839: protected RefactoringModifications getModifications()
0840: throws CoreException {
0841: if (fModifications != null)
0842: return fModifications;
0843:
0844: fModifications = new CopyModifications();
0845: fReorgExecutionLog = new ReorgExecutionLog();
0846: CopyArguments args = new CopyArguments(
0847: getJavaElementDestination(), fReorgExecutionLog);
0848: IJavaElement[] javaElements = getJavaElements();
0849: for (int i = 0; i < javaElements.length; i++) {
0850: fModifications.copy(javaElements[i], args, null);
0851: }
0852: return fModifications;
0853: }
0854:
0855: public String getPolicyId() {
0856: return POLICY_COPY_MEMBERS;
0857: }
0858:
0859: protected String getProcessorId() {
0860: return IJavaRefactorings.COPY;
0861: }
0862:
0863: protected String getRefactoringId() {
0864: return IJavaRefactorings.COPY;
0865: }
0866:
0867: public ReorgExecutionLog getReorgExecutionLog() {
0868: return fReorgExecutionLog;
0869: }
0870:
0871: private IClassFile getSourceClassFile() {
0872: // all have a common parent, so all must be in the same classfile
0873: // we checked before that the array in not null and not empty
0874: return (IClassFile) getJavaElements()[0]
0875: .getAncestor(IJavaElement.CLASS_FILE);
0876: }
0877: }
0878:
0879: private static abstract class FilesFoldersAndCusReorgPolicy extends
0880: ReorgPolicy {
0881:
0882: protected static final int ONLY_CUS = 2;
0883:
0884: protected static final int ONLY_FILES = 1;
0885:
0886: protected static final int ONLY_FOLDERS = 0;
0887:
0888: private static IContainer getAsContainer(IResource resDest) {
0889: if (resDest instanceof IContainer)
0890: return (IContainer) resDest;
0891: if (resDest instanceof IFile)
0892: return ((IFile) resDest).getParent();
0893: return null;
0894: }
0895:
0896: private ICompilationUnit[] fCus;
0897:
0898: private IFile[] fFiles;
0899:
0900: private IFolder[] fFolders;
0901:
0902: public FilesFoldersAndCusReorgPolicy(IFile[] files,
0903: IFolder[] folders, ICompilationUnit[] cus) {
0904: fFiles = files;
0905: fFolders = folders;
0906: fCus = cus;
0907: }
0908:
0909: public boolean canChildrenBeDestinations(
0910: IJavaElement javaElement) {
0911: switch (javaElement.getElementType()) {
0912: case IJavaElement.JAVA_MODEL:
0913: case IJavaElement.JAVA_PROJECT:
0914: return true;
0915: case IJavaElement.PACKAGE_FRAGMENT_ROOT:
0916: return !((IPackageFragmentRoot) javaElement)
0917: .isArchive();
0918: default:
0919: return false;
0920: }
0921: }
0922:
0923: public boolean canChildrenBeDestinations(IResource resource) {
0924: return resource instanceof IContainer;
0925: }
0926:
0927: public boolean canElementBeDestination(IJavaElement javaElement) {
0928: switch (javaElement.getElementType()) {
0929: case IJavaElement.PACKAGE_FRAGMENT:
0930: return true;
0931: default:
0932: return false;
0933: }
0934: }
0935:
0936: public boolean canElementBeDestination(IResource resource) {
0937: return resource instanceof IProject
0938: || resource instanceof IFolder;
0939: }
0940:
0941: public RefactoringStatus checkFinalConditions(
0942: IProgressMonitor pm, CheckConditionsContext context,
0943: IReorgQueries reorgQueries) throws CoreException {
0944: RefactoringStatus status = super .checkFinalConditions(pm,
0945: context, reorgQueries);
0946: confirmOverwriting(reorgQueries);
0947: return status;
0948: }
0949:
0950: private void confirmOverwriting(IReorgQueries reorgQueries) {
0951: OverwriteHelper helper = new OverwriteHelper();
0952: helper.setFiles(fFiles);
0953: helper.setFolders(fFolders);
0954: helper.setCus(fCus);
0955: IPackageFragment destPack = getDestinationAsPackageFragment();
0956: if (destPack != null) {
0957: helper.confirmOverwriting(reorgQueries, destPack);
0958: } else {
0959: IContainer destinationAsContainer = getDestinationAsContainer();
0960: if (destinationAsContainer != null)
0961: helper.confirmOverwriting(reorgQueries,
0962: destinationAsContainer);
0963: }
0964: fFiles = helper.getFilesWithoutUnconfirmedOnes();
0965: fFolders = helper.getFoldersWithoutUnconfirmedOnes();
0966: fCus = helper.getCusWithoutUnconfirmedOnes();
0967: }
0968:
0969: protected boolean containsLinkedResources() {
0970: return ReorgUtils.containsLinkedResources(fFiles)
0971: || ReorgUtils.containsLinkedResources(fFolders)
0972: || ReorgUtils.containsLinkedResources(fCus);
0973: }
0974:
0975: protected abstract JavaRefactoringDescriptor createRefactoringDescriptor(
0976: final JDTRefactoringDescriptorComment comment,
0977: final Map arguments, final String description,
0978: final String project, int flags);
0979:
0980: protected final int getContentKind() {
0981: final int length = fCus.length + fFiles.length
0982: + fFolders.length;
0983: if (length == fCus.length)
0984: return ONLY_CUS;
0985: else if (length == fFiles.length)
0986: return ONLY_FILES;
0987: else if (length == fFolders.length)
0988: return ONLY_FOLDERS;
0989: return -1;
0990: }
0991:
0992: protected final ICompilationUnit[] getCus() {
0993: return fCus;
0994: }
0995:
0996: public final ChangeDescriptor getDescriptor() {
0997: final Map arguments = new HashMap();
0998: final int length = fFiles.length + fFolders.length
0999: + fCus.length;
1000: final String description = length == 1 ? getDescriptionSingular()
1001: : getDescriptionPlural();
1002: final IProject resource = getSingleProject();
1003: final String project = resource != null ? resource
1004: .getName() : null;
1005: final String header = Messages.format(getHeaderPattern(),
1006: new String[] { String.valueOf(length),
1007: getDestinationLabel() });
1008: int flags = JavaRefactoringDescriptor.JAR_MIGRATION
1009: | JavaRefactoringDescriptor.JAR_REFACTORING
1010: | RefactoringDescriptor.STRUCTURAL_CHANGE
1011: | RefactoringDescriptor.MULTI_CHANGE;
1012: final JDTRefactoringDescriptorComment comment = new JDTRefactoringDescriptorComment(
1013: project, this , header);
1014: arguments.put(ATTRIBUTE_POLICY, getPolicyId());
1015: arguments.put(ATTRIBUTE_FILES, new Integer(fFiles.length)
1016: .toString());
1017: for (int offset = 0; offset < fFiles.length; offset++)
1018: arguments.put(
1019: JavaRefactoringDescriptorUtil.ATTRIBUTE_ELEMENT
1020: + (offset + 1),
1021: JavaRefactoringDescriptorUtil.resourceToHandle(
1022: project, fFiles[offset]));
1023: arguments.put(ATTRIBUTE_FOLDERS, new Integer(
1024: fFolders.length).toString());
1025: for (int offset = 0; offset < fFolders.length; offset++)
1026: arguments.put(
1027: JavaRefactoringDescriptorUtil.ATTRIBUTE_ELEMENT
1028: + (offset + fFiles.length + 1),
1029: JavaRefactoringDescriptorUtil.resourceToHandle(
1030: project, fFolders[offset]));
1031: arguments.put(ATTRIBUTE_UNITS, new Integer(fCus.length)
1032: .toString());
1033: for (int offset = 0; offset < fCus.length; offset++)
1034: arguments.put(
1035: JavaRefactoringDescriptorUtil.ATTRIBUTE_ELEMENT
1036: + (offset + fFolders.length
1037: + fFiles.length + 1),
1038: JavaRefactoringDescriptorUtil.elementToHandle(
1039: project, fCus[offset]));
1040: arguments.putAll(getRefactoringArguments(project));
1041: final JavaRefactoringDescriptor descriptor = createRefactoringDescriptor(
1042: comment, arguments, description, project, flags);
1043: return new RefactoringChangeDescriptor(descriptor);
1044: }
1045:
1046: protected final IContainer getDestinationAsContainer() {
1047: IResource resDest = getResourceDestination();
1048: if (resDest != null)
1049: return getAsContainer(resDest);
1050: IJavaElement jelDest = getJavaElementDestination();
1051: Assert.isNotNull(jelDest);
1052: return getAsContainer(ReorgUtils.getResource(jelDest));
1053: }
1054:
1055: protected IPackageFragment getDestinationAsPackageFragment() {
1056: IPackageFragment javaAsPackage = getJavaDestinationAsPackageFragment(getJavaElementDestination());
1057: if (javaAsPackage != null)
1058: return javaAsPackage;
1059: return getResourceDestinationAsPackageFragment(getResourceDestination());
1060: }
1061:
1062: protected final IJavaElement getDestinationContainerAsJavaElement() {
1063: if (getJavaElementDestination() != null)
1064: return getJavaElementDestination();
1065: IContainer destinationAsContainer = getDestinationAsContainer();
1066: if (destinationAsContainer == null)
1067: return null;
1068: IJavaElement je = JavaCore.create(destinationAsContainer);
1069: if (je != null && je.exists())
1070: return je;
1071: return null;
1072: }
1073:
1074: protected final IFile[] getFiles() {
1075: return fFiles;
1076: }
1077:
1078: protected final IFolder[] getFolders() {
1079: return fFolders;
1080: }
1081:
1082: private IPackageFragment getJavaDestinationAsPackageFragment(
1083: IJavaElement javaDest) {
1084: if (javaDest == null
1085: || (fCheckDestination && !javaDest.exists()))
1086: return null;
1087: if (javaDest instanceof IPackageFragment)
1088: return (IPackageFragment) javaDest;
1089: if (javaDest instanceof IPackageFragmentRoot)
1090: return ((IPackageFragmentRoot) javaDest)
1091: .getPackageFragment(""); //$NON-NLS-1$
1092: if (javaDest instanceof IJavaProject) {
1093: try {
1094: IPackageFragmentRoot root = ReorgUtils
1095: .getCorrespondingPackageFragmentRoot((IJavaProject) javaDest);
1096: if (root != null)
1097: return root.getPackageFragment(""); //$NON-NLS-1$
1098: } catch (JavaModelException e) {
1099: // fall through
1100: }
1101: }
1102: return (IPackageFragment) javaDest
1103: .getAncestor(IJavaElement.PACKAGE_FRAGMENT);
1104: }
1105:
1106: public final IJavaElement[] getJavaElements() {
1107: return fCus;
1108: }
1109:
1110: private IPackageFragment getResourceDestinationAsPackageFragment(
1111: IResource resource) {
1112: if (resource instanceof IFile)
1113: return getJavaDestinationAsPackageFragment(JavaCore
1114: .create(resource.getParent()));
1115: return null;
1116: }
1117:
1118: public final IResource[] getResources() {
1119: return ReorgUtils.union(fFiles, fFolders);
1120: }
1121:
1122: private IProject getSingleProject() {
1123: IProject result = null;
1124: for (int index = 0; index < fFiles.length; index++) {
1125: if (result == null)
1126: result = fFiles[index].getProject();
1127: else if (!result.equals(fFiles[index].getProject()))
1128: return null;
1129: }
1130: for (int index = 0; index < fFolders.length; index++) {
1131: if (result == null)
1132: result = fFolders[index].getProject();
1133: else if (!result.equals(fFolders[index].getProject()))
1134: return null;
1135: }
1136: for (int index = 0; index < fCus.length; index++) {
1137: if (result == null)
1138: result = fCus[index].getJavaProject().getProject();
1139: else if (!result.equals(fCus[index].getJavaProject()
1140: .getProject()))
1141: return null;
1142: }
1143: return result;
1144: }
1145:
1146: public RefactoringStatus initialize(
1147: RefactoringArguments arguments) {
1148: final RefactoringStatus status = new RefactoringStatus();
1149: if (arguments instanceof JavaRefactoringArguments) {
1150: final JavaRefactoringArguments extended = (JavaRefactoringArguments) arguments;
1151: int fileCount = 0;
1152: int folderCount = 0;
1153: int unitCount = 0;
1154: String value = extended.getAttribute(ATTRIBUTE_FILES);
1155: if (value != null && !"".equals(value)) {//$NON-NLS-1$
1156: try {
1157: fileCount = Integer.parseInt(value);
1158: } catch (NumberFormatException exception) {
1159: return RefactoringStatus
1160: .createFatalErrorStatus(Messages
1161: .format(
1162: RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
1163: ATTRIBUTE_FILES));
1164: }
1165: } else
1166: return RefactoringStatus
1167: .createFatalErrorStatus(Messages
1168: .format(
1169: RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
1170: ATTRIBUTE_FILES));
1171: value = extended.getAttribute(ATTRIBUTE_FOLDERS);
1172: if (value != null && !"".equals(value)) {//$NON-NLS-1$
1173: try {
1174: folderCount = Integer.parseInt(value);
1175: } catch (NumberFormatException exception) {
1176: return RefactoringStatus
1177: .createFatalErrorStatus(Messages
1178: .format(
1179: RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
1180: ATTRIBUTE_FOLDERS));
1181: }
1182: } else
1183: return RefactoringStatus
1184: .createFatalErrorStatus(Messages
1185: .format(
1186: RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
1187: ATTRIBUTE_FOLDERS));
1188: value = extended.getAttribute(ATTRIBUTE_UNITS);
1189: if (value != null && !"".equals(value)) {//$NON-NLS-1$
1190: try {
1191: unitCount = Integer.parseInt(value);
1192: } catch (NumberFormatException exception) {
1193: return RefactoringStatus
1194: .createFatalErrorStatus(Messages
1195: .format(
1196: RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
1197: ATTRIBUTE_UNITS));
1198: }
1199: } else
1200: return RefactoringStatus
1201: .createFatalErrorStatus(Messages
1202: .format(
1203: RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
1204: ATTRIBUTE_UNITS));
1205: String handle = null;
1206: List elements = new ArrayList();
1207: for (int index = 0; index < fileCount; index++) {
1208: final String attribute = JavaRefactoringDescriptorUtil.ATTRIBUTE_ELEMENT
1209: + (index + 1);
1210: handle = extended.getAttribute(attribute);
1211: if (handle != null && !"".equals(handle)) { //$NON-NLS-1$
1212: final IResource resource = JavaRefactoringDescriptorUtil
1213: .handleToResource(
1214: extended.getProject(), handle);
1215: if (resource == null || !resource.exists())
1216: status.merge(ScriptableRefactoring
1217: .createInputWarningStatus(resource,
1218: getProcessorId(),
1219: getRefactoringId()));
1220: else
1221: elements.add(resource);
1222: } else
1223: return RefactoringStatus
1224: .createFatalErrorStatus(Messages
1225: .format(
1226: RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
1227: attribute));
1228: }
1229: fFiles = (IFile[]) elements.toArray(new IFile[elements
1230: .size()]);
1231: elements = new ArrayList();
1232: for (int index = 0; index < folderCount; index++) {
1233: final String attribute = JavaRefactoringDescriptorUtil.ATTRIBUTE_ELEMENT
1234: + (fileCount + index + 1);
1235: handle = extended.getAttribute(attribute);
1236: if (handle != null && !"".equals(handle)) { //$NON-NLS-1$
1237: final IResource resource = JavaRefactoringDescriptorUtil
1238: .handleToResource(
1239: extended.getProject(), handle);
1240: if (resource == null || !resource.exists())
1241: status.merge(ScriptableRefactoring
1242: .createInputWarningStatus(resource,
1243: getProcessorId(),
1244: getRefactoringId()));
1245: else
1246: elements.add(resource);
1247: } else
1248: return RefactoringStatus
1249: .createFatalErrorStatus(Messages
1250: .format(
1251: RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
1252: attribute));
1253: }
1254: fFolders = (IFolder[]) elements
1255: .toArray(new IFolder[elements.size()]);
1256: elements = new ArrayList();
1257: for (int index = 0; index < unitCount; index++) {
1258: final String attribute = JavaRefactoringDescriptorUtil.ATTRIBUTE_ELEMENT
1259: + (folderCount + fileCount + index + 1);
1260: handle = extended.getAttribute(attribute);
1261: if (handle != null && !"".equals(handle)) { //$NON-NLS-1$
1262: final IJavaElement element = JavaRefactoringDescriptorUtil
1263: .handleToElement(extended.getProject(),
1264: handle, false);
1265: if (element == null
1266: || !element.exists()
1267: || element.getElementType() != IJavaElement.COMPILATION_UNIT)
1268: status.merge(ScriptableRefactoring
1269: .createInputWarningStatus(element,
1270: getProcessorId(),
1271: getRefactoringId()));
1272: else
1273: elements.add(element);
1274: } else
1275: return RefactoringStatus
1276: .createFatalErrorStatus(Messages
1277: .format(
1278: RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
1279: attribute));
1280: }
1281: fCus = (ICompilationUnit[]) elements
1282: .toArray(new ICompilationUnit[elements.size()]);
1283: } else
1284: return RefactoringStatus
1285: .createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
1286: status.merge(super .initialize(arguments));
1287: return status;
1288: }
1289:
1290: private boolean isChildOfOrEqualToAnyFolder(IResource resource) {
1291: for (int i = 0; i < fFolders.length; i++) {
1292: IFolder folder = fFolders[i];
1293: if (folder.equals(resource)
1294: || ParentChecker.isDescendantOf(resource,
1295: folder))
1296: return true;
1297: }
1298: return false;
1299: }
1300:
1301: protected RefactoringStatus verifyDestination(
1302: IJavaElement javaElement) throws JavaModelException {
1303: Assert.isNotNull(javaElement);
1304: if (!fCheckDestination)
1305: return new RefactoringStatus();
1306: if (!javaElement.exists())
1307: return RefactoringStatus
1308: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_doesnotexist0);
1309: if (javaElement instanceof IJavaModel)
1310: return RefactoringStatus
1311: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_jmodel);
1312:
1313: if (javaElement.isReadOnly())
1314: return RefactoringStatus
1315: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_readonly);
1316:
1317: if (!javaElement.isStructureKnown())
1318: return RefactoringStatus
1319: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_structure);
1320:
1321: if (javaElement instanceof IOpenable) {
1322: IOpenable openable = (IOpenable) javaElement;
1323: if (!openable.isConsistent())
1324: return RefactoringStatus
1325: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_inconsistent);
1326: }
1327:
1328: if (javaElement instanceof IPackageFragmentRoot) {
1329: IPackageFragmentRoot root = (IPackageFragmentRoot) javaElement;
1330: if (root.isArchive())
1331: return RefactoringStatus
1332: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_archive);
1333: if (root.isExternal())
1334: return RefactoringStatus
1335: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_external);
1336: }
1337:
1338: if (ReorgUtils.isInsideCompilationUnit(javaElement)) {
1339: return RefactoringStatus
1340: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot);
1341: }
1342:
1343: IContainer destinationAsContainer = getDestinationAsContainer();
1344: if (destinationAsContainer == null
1345: || isChildOfOrEqualToAnyFolder(destinationAsContainer))
1346: return RefactoringStatus
1347: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_not_this _resource);
1348:
1349: if (containsLinkedResources()
1350: && !ReorgUtils
1351: .canBeDestinationForLinkedResources(javaElement))
1352: return RefactoringStatus
1353: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_linked);
1354: return new RefactoringStatus();
1355: }
1356:
1357: protected RefactoringStatus verifyDestination(IResource resource)
1358: throws JavaModelException {
1359: Assert.isNotNull(resource);
1360: if (!resource.exists() || resource.isPhantom())
1361: return RefactoringStatus
1362: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_phantom);
1363: if (!resource.isAccessible())
1364: return RefactoringStatus
1365: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_inaccessible);
1366:
1367: if (resource.getType() == IResource.ROOT)
1368: return RefactoringStatus
1369: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_not_this _resource);
1370:
1371: if (isChildOfOrEqualToAnyFolder(resource))
1372: return RefactoringStatus
1373: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_not_this _resource);
1374:
1375: if (containsLinkedResources()
1376: && !ReorgUtils
1377: .canBeDestinationForLinkedResources(resource))
1378: return RefactoringStatus
1379: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_linked);
1380:
1381: return new RefactoringStatus();
1382: }
1383: }
1384:
1385: private static final class MoveFilesFoldersAndCusPolicy extends
1386: FilesFoldersAndCusReorgPolicy implements IMovePolicy {
1387:
1388: private static final String POLICY_MOVE_RESOURCES = "org.eclipse.jdt.ui.moveResources"; //$NON-NLS-1$
1389:
1390: private static Change moveCuToPackage(ICompilationUnit cu,
1391: IPackageFragment dest) {
1392: // XXX workaround for bug 31998 we will have to disable renaming of
1393: // linked packages (and cus)
1394: IResource resource = cu.getResource();
1395: if (resource != null && resource.isLinked()) {
1396: if (ResourceUtil.getResource(dest) instanceof IContainer)
1397: return moveFileToContainer(cu,
1398: (IContainer) ResourceUtil.getResource(dest));
1399: }
1400: return new MoveCompilationUnitChange(cu, dest);
1401: }
1402:
1403: private static Change moveFileToContainer(ICompilationUnit cu,
1404: IContainer dest) {
1405: return new MoveResourceChange(cu.getResource(), dest);
1406: }
1407:
1408: private TextChangeManager fChangeManager;
1409:
1410: private CreateTargetExecutionLog fCreateTargetExecutionLog = new CreateTargetExecutionLog();
1411:
1412: private String fFilePatterns;
1413:
1414: private MoveModifications fModifications;
1415:
1416: private QualifiedNameSearchResult fQualifiedNameSearchResult;
1417:
1418: private boolean fUpdateQualifiedNames;
1419:
1420: private boolean fUpdateReferences;
1421:
1422: MoveFilesFoldersAndCusPolicy(IFile[] files, IFolder[] folders,
1423: ICompilationUnit[] cus) {
1424: super (files, folders, cus);
1425: fUpdateReferences = true;
1426: fUpdateQualifiedNames = false;
1427: fQualifiedNameSearchResult = new QualifiedNameSearchResult();
1428: }
1429:
1430: public boolean canEnableQualifiedNameUpdating() {
1431: return getCus().length > 0
1432: && !JavaElementUtil
1433: .isDefaultPackage(getCommonParent());
1434: }
1435:
1436: public boolean canEnableUpdateReferences() {
1437: return getCus().length > 0;
1438: }
1439:
1440: public boolean canUpdateQualifiedNames() {
1441: if (!canEnableQualifiedNameUpdating())
1442: return false;
1443:
1444: IPackageFragment pack = getDestinationAsPackageFragment();
1445: if (pack == null)
1446: return false;
1447:
1448: if (pack.isDefaultPackage())
1449: return false;
1450:
1451: IJavaElement destination = getJavaElementDestination();
1452: if (destination instanceof IPackageFragmentRoot
1453: && getCus().length > 0) {
1454: return false;
1455: }
1456:
1457: return true;
1458: }
1459:
1460: public boolean canUpdateReferences() {
1461: if (getCus().length == 0)
1462: return false;
1463: IPackageFragment pack = getDestinationAsPackageFragment();
1464: if (pack == null || pack.isDefaultPackage())
1465: return false;
1466:
1467: IJavaElement destination = getJavaElementDestination();
1468: if (destination instanceof IPackageFragmentRoot
1469: && getCus().length > 0) {
1470: return false;
1471: }
1472:
1473: Object commonParent = getCommonParent();
1474: if (JavaElementUtil.isDefaultPackage(commonParent))
1475: return false;
1476: return true;
1477: }
1478:
1479: public RefactoringStatus checkFinalConditions(
1480: IProgressMonitor pm, CheckConditionsContext context,
1481: IReorgQueries reorgQueries) throws CoreException {
1482: try {
1483: pm.beginTask("", fUpdateQualifiedNames ? 7 : 3); //$NON-NLS-1$
1484: RefactoringStatus result = new RefactoringStatus();
1485: confirmMovingReadOnly(reorgQueries);
1486: fChangeManager = createChangeManager(
1487: new SubProgressMonitor(pm, 2), result);
1488: if (fUpdateQualifiedNames)
1489: computeQualifiedNameMatches(new SubProgressMonitor(
1490: pm, 4));
1491: result.merge(super .checkFinalConditions(
1492: new SubProgressMonitor(pm, 1), context,
1493: reorgQueries));
1494: return result;
1495: } catch (JavaModelException e) {
1496: throw e;
1497: } catch (CoreException e) {
1498: throw new JavaModelException(e);
1499: } finally {
1500: pm.done();
1501: }
1502: }
1503:
1504: /**
1505: * {@inheritDoc}
1506: */
1507: protected IPackageFragment getDestinationAsPackageFragment() {
1508: IJavaElement destination = getJavaElementDestination();
1509: if (destination instanceof IPackageFragmentRoot
1510: && getCus().length > 0) {
1511: String packageName = ((IPackageFragment) getCus()[0]
1512: .getParent()).getElementName();
1513: return ((IPackageFragmentRoot) destination)
1514: .getPackageFragment(packageName);
1515: }
1516:
1517: return super .getDestinationAsPackageFragment();
1518: }
1519:
1520: private void computeQualifiedNameMatches(IProgressMonitor pm)
1521: throws JavaModelException {
1522: if (!fUpdateQualifiedNames)
1523: return;
1524: IPackageFragment destination = getDestinationAsPackageFragment();
1525: if (destination != null) {
1526: ICompilationUnit[] cus = getCus();
1527: pm.beginTask("", cus.length); //$NON-NLS-1$
1528: pm
1529: .subTask(RefactoringCoreMessages.MoveRefactoring_scanning_qualified_names);
1530: for (int i = 0; i < cus.length; i++) {
1531: ICompilationUnit cu = cus[i];
1532: IType[] types = cu.getTypes();
1533: IProgressMonitor typesMonitor = new SubProgressMonitor(
1534: pm, 1);
1535: typesMonitor.beginTask("", types.length); //$NON-NLS-1$
1536: for (int j = 0; j < types.length; j++) {
1537: handleType(types[j], destination,
1538: new SubProgressMonitor(typesMonitor, 1));
1539: if (typesMonitor.isCanceled())
1540: throw new OperationCanceledException();
1541: }
1542: typesMonitor.done();
1543: }
1544: }
1545: pm.done();
1546: }
1547:
1548: private void confirmMovingReadOnly(IReorgQueries reorgQueries)
1549: throws CoreException {
1550: if (!ReadOnlyResourceFinder.confirmMoveOfReadOnlyElements(
1551: getJavaElements(), getResources(), reorgQueries))
1552: throw new OperationCanceledException();
1553: }
1554:
1555: private Change createChange(ICompilationUnit cu) {
1556: IPackageFragment pack = getDestinationAsPackageFragment();
1557: if (pack != null)
1558: return moveCuToPackage(cu, pack);
1559: IContainer container = getDestinationAsContainer();
1560: if (container == null)
1561: return new NullChange();
1562: return moveFileToContainer(cu, container);
1563: }
1564:
1565: public Change createChange(IProgressMonitor pm)
1566: throws JavaModelException {
1567: if (!fUpdateReferences) {
1568: return createSimpleMoveChange(pm);
1569: } else {
1570: return createReferenceUpdatingMoveChange(pm);
1571: }
1572: }
1573:
1574: private Change createChange(IResource res) {
1575: IContainer destinationAsContainer = getDestinationAsContainer();
1576: if (destinationAsContainer == null)
1577: return new NullChange();
1578: return new MoveResourceChange(res, destinationAsContainer);
1579: }
1580:
1581: private TextChangeManager createChangeManager(
1582: IProgressMonitor pm, RefactoringStatus status)
1583: throws JavaModelException {
1584: pm.beginTask("", 1);//$NON-NLS-1$
1585: try {
1586: if (!fUpdateReferences)
1587: return new TextChangeManager();
1588:
1589: IPackageFragment packageDest = getDestinationAsPackageFragment();
1590: if (packageDest != null) {
1591: MoveCuUpdateCreator creator = new MoveCuUpdateCreator(
1592: getCus(), packageDest);
1593: return creator.createChangeManager(
1594: new SubProgressMonitor(pm, 1), status);
1595: } else
1596: return new TextChangeManager();
1597: } finally {
1598: pm.done();
1599: }
1600: }
1601:
1602: protected JavaRefactoringDescriptor createRefactoringDescriptor(
1603: JDTRefactoringDescriptorComment comment, Map arguments,
1604: String description, String project, int flags) {
1605: CreateTargetExecutionLog log = getCreateTargetExecutionLog();
1606: storeCreateTargetExecutionLog(project, arguments, log);
1607: return new MoveDescriptor(project, description, comment
1608: .asString(), arguments, flags);
1609: }
1610:
1611: private Change createReferenceUpdatingMoveChange(
1612: IProgressMonitor pm) throws JavaModelException {
1613: pm.beginTask("", 2 + (fUpdateQualifiedNames ? 1 : 0)); //$NON-NLS-1$
1614: try {
1615: CompositeChange composite = new DynamicValidationStateChange(
1616: RefactoringCoreMessages.ReorgPolicy_move);
1617: composite.markAsSynthetic();
1618: // XX workaround for bug 13558
1619: // <workaround>
1620: if (fChangeManager == null) {
1621: fChangeManager = createChangeManager(
1622: new SubProgressMonitor(pm, 1),
1623: new RefactoringStatus());
1624: // TODO: non-CU matches silently dropped
1625: RefactoringStatus status = Checks
1626: .validateModifiesFiles(
1627: getAllModifiedFiles(), null);
1628: if (status.hasFatalError())
1629: fChangeManager = new TextChangeManager();
1630: }
1631: // </workaround>
1632:
1633: composite
1634: .merge(new CompositeChange(
1635: RefactoringCoreMessages.MoveRefactoring_reorganize_elements,
1636: fChangeManager.getAllChanges()));
1637:
1638: Change fileMove = createSimpleMoveChange(new SubProgressMonitor(
1639: pm, 1));
1640: if (fileMove instanceof CompositeChange) {
1641: composite.merge(((CompositeChange) fileMove));
1642: } else {
1643: composite.add(fileMove);
1644: }
1645: return composite;
1646: } finally {
1647: pm.done();
1648: }
1649: }
1650:
1651: private Change createSimpleMoveChange(IProgressMonitor pm) {
1652: CompositeChange result = new DynamicValidationStateChange(
1653: RefactoringCoreMessages.ReorgPolicy_move);
1654: result.markAsSynthetic();
1655: IFile[] files = getFiles();
1656: IFolder[] folders = getFolders();
1657: ICompilationUnit[] cus = getCus();
1658: pm
1659: .beginTask(
1660: "", files.length + folders.length + cus.length); //$NON-NLS-1$
1661: for (int i = 0; i < files.length; i++) {
1662: result.add(createChange(files[i]));
1663: pm.worked(1);
1664: }
1665: if (pm.isCanceled())
1666: throw new OperationCanceledException();
1667: for (int i = 0; i < folders.length; i++) {
1668: result.add(createChange(folders[i]));
1669: pm.worked(1);
1670: }
1671: if (pm.isCanceled())
1672: throw new OperationCanceledException();
1673: for (int i = 0; i < cus.length; i++) {
1674: result.add(createChange(cus[i]));
1675: pm.worked(1);
1676: }
1677: pm.done();
1678: return result;
1679: }
1680:
1681: public IFile[] getAllModifiedFiles() {
1682: Set result = new HashSet();
1683: result
1684: .addAll(Arrays.asList(ResourceUtil
1685: .getFiles(fChangeManager
1686: .getAllCompilationUnits())));
1687: result.addAll(Arrays.asList(fQualifiedNameSearchResult
1688: .getAllFiles()));
1689: if (!(getJavaElementDestination() instanceof IPackageFragmentRoot)
1690: && getDestinationAsPackageFragment() != null
1691: && getUpdateReferences())
1692: result.addAll(Arrays.asList(ResourceUtil
1693: .getFiles(getCus())));
1694: return (IFile[]) result.toArray(new IFile[result.size()]);
1695: }
1696:
1697: private Object getCommonParent() {
1698: return new ParentChecker(getResources(), getJavaElements())
1699: .getCommonParent();
1700: }
1701:
1702: public CreateTargetExecutionLog getCreateTargetExecutionLog() {
1703: return fCreateTargetExecutionLog;
1704: }
1705:
1706: public ICreateTargetQuery getCreateTargetQuery(
1707: ICreateTargetQueries createQueries) {
1708: return createQueries.createNewPackageQuery();
1709: }
1710:
1711: protected String getDescriptionPlural() {
1712: final int kind = getContentKind();
1713: switch (kind) {
1714: case ONLY_FOLDERS:
1715: return RefactoringCoreMessages.ReorgPolicyFactory_move_folders;
1716: case ONLY_FILES:
1717: return RefactoringCoreMessages.ReorgPolicyFactory_move_files;
1718: case ONLY_CUS:
1719: return RefactoringCoreMessages.ReorgPolicyFactory_move_compilation_units;
1720: }
1721: return RefactoringCoreMessages.ReorgPolicyFactory_move_description_plural;
1722: }
1723:
1724: protected String getDescriptionSingular() {
1725: final int kind = getContentKind();
1726: switch (kind) {
1727: case ONLY_FOLDERS:
1728: return RefactoringCoreMessages.ReorgPolicyFactory_move_folder;
1729: case ONLY_FILES:
1730: return RefactoringCoreMessages.ReorgPolicyFactory_move_file;
1731: case ONLY_CUS:
1732: return RefactoringCoreMessages.ReorgPolicyFactory_move_compilation_unit;
1733: }
1734: return RefactoringCoreMessages.ReorgPolicyFactory_move_description_singular;
1735: }
1736:
1737: public String getFilePatterns() {
1738: return fFilePatterns;
1739: }
1740:
1741: protected String getHeaderPattern() {
1742: return RefactoringCoreMessages.ReorgPolicyFactory_move_header;
1743: }
1744:
1745: protected RefactoringModifications getModifications()
1746: throws CoreException {
1747: if (fModifications != null)
1748: return fModifications;
1749:
1750: fModifications = new MoveModifications();
1751: IPackageFragment pack = getDestinationAsPackageFragment();
1752: IContainer container = getDestinationAsContainer();
1753: Object unitDestination = null;
1754: if (pack != null)
1755: unitDestination = pack;
1756: else
1757: unitDestination = container;
1758:
1759: // don't use fUpdateReferences directly since it is only valid if
1760: // canUpdateReferences is true
1761: boolean updateReferenes = canUpdateReferences()
1762: && getUpdateReferences();
1763: if (unitDestination != null) {
1764: ICompilationUnit[] units = getCus();
1765: for (int i = 0; i < units.length; i++) {
1766: fModifications.move(units[i], new MoveArguments(
1767: unitDestination, updateReferenes));
1768: }
1769: }
1770: if (container != null) {
1771: IFile[] files = getFiles();
1772: for (int i = 0; i < files.length; i++) {
1773: fModifications.move(files[i], new MoveArguments(
1774: container, updateReferenes));
1775: }
1776: IFolder[] folders = getFolders();
1777: for (int i = 0; i < folders.length; i++) {
1778: fModifications.move(folders[i], new MoveArguments(
1779: container, updateReferenes));
1780: }
1781: }
1782: return fModifications;
1783: }
1784:
1785: public String getPolicyId() {
1786: return POLICY_MOVE_RESOURCES;
1787: }
1788:
1789: protected String getProcessorId() {
1790: return IJavaRefactorings.MOVE;
1791: }
1792:
1793: protected Map getRefactoringArguments(String project) {
1794: final Map arguments = new HashMap();
1795: arguments.putAll(super .getRefactoringArguments(project));
1796: if (fFilePatterns != null && !"".equals(fFilePatterns)) //$NON-NLS-1$
1797: arguments.put(ATTRIBUTE_PATTERNS, fFilePatterns);
1798: arguments.put(
1799: JavaRefactoringDescriptorUtil.ATTRIBUTE_REFERENCES,
1800: Boolean.valueOf(fUpdateReferences).toString());
1801: arguments.put(ATTRIBUTE_QUALIFIED, Boolean.valueOf(
1802: fUpdateQualifiedNames).toString());
1803: return arguments;
1804: }
1805:
1806: protected String getRefactoringId() {
1807: return IJavaRefactorings.MOVE;
1808: }
1809:
1810: public boolean getUpdateQualifiedNames() {
1811: return fUpdateQualifiedNames;
1812: }
1813:
1814: public boolean getUpdateReferences() {
1815: return fUpdateReferences;
1816: }
1817:
1818: private void handleType(IType type,
1819: IPackageFragment destination, IProgressMonitor pm) {
1820: QualifiedNameFinder.process(fQualifiedNameSearchResult,
1821: type.getFullyQualifiedName(),
1822: destination.getElementName()
1823: + "." + type.getTypeQualifiedName(), //$NON-NLS-1$
1824: fFilePatterns, type.getJavaProject().getProject(),
1825: pm);
1826: }
1827:
1828: public boolean hasAllInputSet() {
1829: if (getResourceDestination() == null
1830: && getJavaElementDestination() == null)
1831: return false;
1832:
1833: return !canUpdateReferences() && !canUpdateQualifiedNames();
1834: }
1835:
1836: public RefactoringStatus initialize(
1837: RefactoringArguments arguments) {
1838: if (arguments instanceof JavaRefactoringArguments) {
1839: final JavaRefactoringArguments extended = (JavaRefactoringArguments) arguments;
1840: final String patterns = extended
1841: .getAttribute(ATTRIBUTE_PATTERNS);
1842: if (patterns != null && !"".equals(patterns)) //$NON-NLS-1$
1843: fFilePatterns = patterns;
1844: else
1845: fFilePatterns = ""; //$NON-NLS-1$
1846: final String references = extended
1847: .getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_REFERENCES);
1848: if (references != null) {
1849: fUpdateReferences = Boolean.valueOf(references)
1850: .booleanValue();
1851: } else
1852: return RefactoringStatus
1853: .createFatalErrorStatus(Messages
1854: .format(
1855: RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
1856: JavaRefactoringDescriptorUtil.ATTRIBUTE_REFERENCES));
1857: final String qualified = extended
1858: .getAttribute(ATTRIBUTE_QUALIFIED);
1859: if (qualified != null) {
1860: fUpdateQualifiedNames = Boolean.valueOf(qualified)
1861: .booleanValue();
1862: } else
1863: return RefactoringStatus
1864: .createFatalErrorStatus(Messages
1865: .format(
1866: RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
1867: ATTRIBUTE_QUALIFIED));
1868: } else
1869: return RefactoringStatus
1870: .createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
1871: return super .initialize(arguments);
1872: }
1873:
1874: public boolean isTextualMove() {
1875: return false;
1876: }
1877:
1878: public Change postCreateChange(Change[] participantChanges,
1879: IProgressMonitor pm) throws CoreException {
1880: if (fQualifiedNameSearchResult != null) {
1881: return fQualifiedNameSearchResult
1882: .getSingleChange(Changes
1883: .getModifiedFiles(participantChanges));
1884: } else {
1885: return null;
1886: }
1887: }
1888:
1889: public void setDestinationCheck(boolean check) {
1890: fCheckDestination = check;
1891: }
1892:
1893: public void setFilePatterns(String patterns) {
1894: Assert.isNotNull(patterns);
1895: fFilePatterns = patterns;
1896: }
1897:
1898: public void setUpdateQualifiedNames(boolean update) {
1899: fUpdateQualifiedNames = update;
1900: }
1901:
1902: public void setUpdateReferences(boolean update) {
1903: fUpdateReferences = update;
1904: }
1905:
1906: protected RefactoringStatus verifyDestination(
1907: IJavaElement destination) throws JavaModelException {
1908: RefactoringStatus super Status = super
1909: .verifyDestination(destination);
1910: if (super Status.hasFatalError())
1911: return super Status;
1912:
1913: Object commonParent = new ParentChecker(getResources(),
1914: getJavaElements()).getCommonParent();
1915: if (destination.equals(commonParent))
1916: return RefactoringStatus
1917: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_parent);
1918: IContainer destinationAsContainer = getDestinationAsContainer();
1919: if (destinationAsContainer != null
1920: && destinationAsContainer.equals(commonParent))
1921: return RefactoringStatus
1922: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_parent);
1923: IPackageFragment destinationAsPackage = getDestinationAsPackageFragment();
1924: if (destinationAsPackage != null
1925: && destinationAsPackage.equals(commonParent))
1926: return RefactoringStatus
1927: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_parent);
1928:
1929: return super Status;
1930: }
1931:
1932: protected RefactoringStatus verifyDestination(
1933: IResource destination) throws JavaModelException {
1934: RefactoringStatus super Status = super
1935: .verifyDestination(destination);
1936: if (super Status.hasFatalError())
1937: return super Status;
1938:
1939: Object commonParent = getCommonParent();
1940: if (destination.equals(commonParent))
1941: return RefactoringStatus
1942: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_parent);
1943: IContainer destinationAsContainer = getDestinationAsContainer();
1944: if (destinationAsContainer != null
1945: && destinationAsContainer.equals(commonParent))
1946: return RefactoringStatus
1947: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_parent);
1948: IJavaElement destinationContainerAsPackage = getDestinationContainerAsJavaElement();
1949: if (destinationContainerAsPackage != null
1950: && destinationContainerAsPackage
1951: .equals(commonParent))
1952: return RefactoringStatus
1953: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_parent);
1954:
1955: return super Status;
1956: }
1957: }
1958:
1959: private static final class MovePackageFragmentRootsPolicy extends
1960: PackageFragmentRootsReorgPolicy implements IMovePolicy {
1961:
1962: private static final String POLICY_MOVE_ROOTS = "org.eclipse.jdt.ui.moveRoots"; //$NON-NLS-1$
1963:
1964: private static boolean isParentOfAny(IJavaProject javaProject,
1965: IPackageFragmentRoot[] roots) {
1966: for (int i = 0; i < roots.length; i++) {
1967: if (ReorgUtils.isParentInWorkspaceOrOnDisk(roots[i],
1968: javaProject))
1969: return true;
1970: }
1971: return false;
1972: }
1973:
1974: private CreateTargetExecutionLog fCreateTargetExecutionLog = new CreateTargetExecutionLog();
1975:
1976: private MoveModifications fModifications;
1977:
1978: MovePackageFragmentRootsPolicy(IPackageFragmentRoot[] roots) {
1979: super (roots);
1980: }
1981:
1982: public boolean canEnable() throws JavaModelException {
1983: if (!super .canEnable())
1984: return false;
1985: IPackageFragmentRoot[] roots = getPackageFragmentRoots();
1986: for (int i = 0; i < roots.length; i++) {
1987: if (roots[i].isReadOnly() && !(roots[i].isArchive())) {
1988: final ResourceAttributes attributes = roots[i]
1989: .getResource().getResourceAttributes();
1990: if (attributes == null || attributes.isReadOnly())
1991: return false;
1992: }
1993: }
1994: return true;
1995: }
1996:
1997: public RefactoringStatus checkFinalConditions(
1998: IProgressMonitor pm, CheckConditionsContext context,
1999: IReorgQueries reorgQueries) throws CoreException {
2000: try {
2001: RefactoringStatus status = super .checkFinalConditions(
2002: pm, context, reorgQueries);
2003: confirmMovingReadOnly(reorgQueries);
2004: return status;
2005: } catch (JavaModelException e) {
2006: throw e;
2007: } catch (CoreException e) {
2008: throw new JavaModelException(e);
2009: }
2010: }
2011:
2012: private void confirmMovingReadOnly(IReorgQueries reorgQueries)
2013: throws CoreException {
2014: if (!ReadOnlyResourceFinder.confirmMoveOfReadOnlyElements(
2015: getJavaElements(), getResources(), reorgQueries))
2016: throw new OperationCanceledException();
2017: }
2018:
2019: private Change createChange(IPackageFragmentRoot root,
2020: IJavaProject destination) {
2021: // /XXX fix the query
2022: return new MovePackageFragmentRootChange(root, destination
2023: .getProject(), null);
2024: }
2025:
2026: public Change createChange(IProgressMonitor pm)
2027: throws JavaModelException {
2028: IPackageFragmentRoot[] roots = getPackageFragmentRoots();
2029: pm.beginTask("", roots.length); //$NON-NLS-1$
2030: CompositeChange composite = new DynamicValidationStateChange(
2031: RefactoringCoreMessages.ReorgPolicy_move_source_folder);
2032: composite.markAsSynthetic();
2033: IJavaProject destination = getDestinationJavaProject();
2034: for (int i = 0; i < roots.length; i++) {
2035: if (destination == null) {
2036: composite
2037: .add(new MovePackageFragmentRootChange(
2038: roots[i],
2039: (IContainer) getResourceDestination(),
2040: null));
2041: } else {
2042: composite.add(createChange(roots[i], destination));
2043: }
2044: pm.worked(1);
2045: }
2046: pm.done();
2047: return composite;
2048: }
2049:
2050: protected JavaRefactoringDescriptor createRefactoringDescriptor(
2051: JDTRefactoringDescriptorComment comment, Map arguments,
2052: String description, String project, int flags) {
2053: CreateTargetExecutionLog log = getCreateTargetExecutionLog();
2054: storeCreateTargetExecutionLog(project, arguments, log);
2055: return new MoveDescriptor(project, description, comment
2056: .asString(), arguments, flags);
2057: }
2058:
2059: public CreateTargetExecutionLog getCreateTargetExecutionLog() {
2060: return fCreateTargetExecutionLog;
2061: }
2062:
2063: public ICreateTargetQuery getCreateTargetQuery(
2064: ICreateTargetQueries createQueries) {
2065: return null;
2066: }
2067:
2068: protected String getDescriptionPlural() {
2069: return RefactoringCoreMessages.ReorgPolicyFactory_move_roots_plural;
2070: }
2071:
2072: protected String getDescriptionSingular() {
2073: return RefactoringCoreMessages.ReorgPolicyFactory_move_roots_singular;
2074: }
2075:
2076: protected String getHeaderPattern() {
2077: return RefactoringCoreMessages.ReorgPolicyFactory_move_roots_header;
2078: }
2079:
2080: protected RefactoringModifications getModifications()
2081: throws CoreException {
2082: if (fModifications != null)
2083: return fModifications;
2084:
2085: fModifications = new MoveModifications();
2086: IJavaProject destination = getDestinationJavaProject();
2087: boolean updateReferences = canUpdateReferences()
2088: && getUpdateReferences();
2089: if (destination != null) {
2090: IPackageFragmentRoot[] roots = getPackageFragmentRoots();
2091: for (int i = 0; i < roots.length; i++) {
2092: fModifications.move(roots[i], new MoveArguments(
2093: destination, updateReferences));
2094: }
2095: } else {
2096: IPackageFragmentRoot[] roots = getPackageFragmentRoots();
2097: for (int i = 0; i < roots.length; i++) {
2098: fModifications
2099: .move(roots[i], new MoveArguments(
2100: getResourceDestination(),
2101: updateReferences));
2102: }
2103: }
2104: return fModifications;
2105: }
2106:
2107: public String getPolicyId() {
2108: return POLICY_MOVE_ROOTS;
2109: }
2110:
2111: protected String getProcessorId() {
2112: return IJavaRefactorings.MOVE;
2113: }
2114:
2115: protected String getRefactoringId() {
2116: return IJavaRefactorings.MOVE;
2117: }
2118:
2119: public boolean isTextualMove() {
2120: return false;
2121: }
2122:
2123: public Change postCreateChange(Change[] participantChanges,
2124: IProgressMonitor pm) throws CoreException {
2125: return null;
2126: }
2127:
2128: public void setDestinationCheck(boolean check) {
2129: fCheckDestination = check;
2130: }
2131:
2132: /**
2133: * {@inheritDoc}
2134: */
2135: protected RefactoringStatus verifyDestination(
2136: IJavaElement javaElement) throws JavaModelException {
2137: RefactoringStatus super Status = super
2138: .verifyDestination(javaElement);
2139: if (super Status.hasFatalError())
2140: return super Status;
2141: IJavaProject javaProject = getDestinationJavaProject();
2142: if (isParentOfAny(javaProject, getPackageFragmentRoots()))
2143: return RefactoringStatus
2144: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_element2parent);
2145: return super Status;
2146: }
2147:
2148: /**
2149: * {@inheritDoc}
2150: */
2151: protected RefactoringStatus verifyDestination(
2152: IResource destination) {
2153: RefactoringStatus super Status = super
2154: .verifyDestination(destination);
2155: if (super Status.hasFatalError())
2156: return super Status;
2157:
2158: Object commonParent = new ParentChecker(getResources(),
2159: getJavaElements()).getCommonParent();
2160: if (destination.equals(commonParent))
2161: return RefactoringStatus
2162: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot_move_source_to_parent);
2163:
2164: return super Status;
2165: }
2166:
2167: /**
2168: * {@inheritDoc}
2169: */
2170: public boolean canEnableQualifiedNameUpdating() {
2171: return false;
2172: }
2173:
2174: /**
2175: * {@inheritDoc}
2176: */
2177: public boolean getUpdateQualifiedNames() {
2178: return false;
2179: }
2180:
2181: /**
2182: * {@inheritDoc}
2183: */
2184: public boolean canUpdateQualifiedNames() {
2185: return false;
2186: }
2187:
2188: /**
2189: * {@inheritDoc}
2190: */
2191: public void setUpdateQualifiedNames(boolean update) {
2192: }
2193:
2194: /**
2195: * {@inheritDoc}
2196: */
2197: public void setFilePatterns(String patterns) {
2198: }
2199:
2200: /**
2201: * {@inheritDoc}
2202: */
2203: public String getFilePatterns() {
2204: return null;
2205: }
2206:
2207: /**
2208: * {@inheritDoc}
2209: */
2210: public boolean canEnableUpdateReferences() {
2211: return false;
2212: }
2213:
2214: /**
2215: * {@inheritDoc}
2216: */
2217: public boolean canUpdateReferences() {
2218: return false;
2219: }
2220:
2221: /**
2222: * {@inheritDoc}
2223: */
2224: public boolean getUpdateReferences() {
2225: return false;
2226: }
2227:
2228: /**
2229: * {@inheritDoc}
2230: */
2231: public void setUpdateReferences(boolean update) {
2232: }
2233:
2234: /**
2235: * {@inheritDoc}
2236: */
2237: public boolean hasAllInputSet() {
2238: return getJavaElementDestination() != null
2239: || getResourceDestination() != null;
2240: }
2241: }
2242:
2243: private static final class MovePackagesPolicy extends
2244: PackagesReorgPolicy implements IMovePolicy {
2245:
2246: private static final String POLICY_MOVE_PACKAGES = "org.eclipse.jdt.ui.movePackages"; //$NON-NLS-1$
2247:
2248: private static boolean isParentOfAny(IPackageFragmentRoot root,
2249: IPackageFragment[] fragments) {
2250: for (int i = 0; i < fragments.length; i++) {
2251: IPackageFragment fragment = fragments[i];
2252: if (ReorgUtils.isParentInWorkspaceOrOnDisk(fragment,
2253: root))
2254: return true;
2255: }
2256: return false;
2257: }
2258:
2259: private CreateTargetExecutionLog fCreateTargetExecutionLog = new CreateTargetExecutionLog();
2260:
2261: private MoveModifications fModifications;
2262:
2263: MovePackagesPolicy(IPackageFragment[] packageFragments) {
2264: super (packageFragments);
2265: }
2266:
2267: public RefactoringStatus checkFinalConditions(
2268: IProgressMonitor pm, CheckConditionsContext context,
2269: IReorgQueries reorgQueries) throws CoreException {
2270: try {
2271: RefactoringStatus status = super .checkFinalConditions(
2272: pm, context, reorgQueries);
2273: confirmMovingReadOnly(reorgQueries);
2274: return status;
2275: } catch (JavaModelException e) {
2276: throw e;
2277: } catch (CoreException e) {
2278: throw new JavaModelException(e);
2279: }
2280: }
2281:
2282: private void confirmMovingReadOnly(IReorgQueries reorgQueries)
2283: throws CoreException {
2284: if (!ReadOnlyResourceFinder.confirmMoveOfReadOnlyElements(
2285: getJavaElements(), getResources(), reorgQueries))
2286: throw new OperationCanceledException();
2287: }
2288:
2289: private Change createChange(IPackageFragment pack,
2290: IPackageFragmentRoot destination) {
2291: return new MovePackageChange(pack, destination);
2292: }
2293:
2294: private Change createChange(IPackageFragment pack,
2295: IContainer destination) {
2296: return new MoveResourceChange(pack.getResource(),
2297: destination);
2298: }
2299:
2300: public Change createChange(IProgressMonitor pm)
2301: throws JavaModelException {
2302: IPackageFragment[] fragments = getPackages();
2303: pm.beginTask("", fragments.length); //$NON-NLS-1$
2304: CompositeChange result = new DynamicValidationStateChange(
2305: RefactoringCoreMessages.ReorgPolicy_move_package);
2306: result.markAsSynthetic();
2307: IPackageFragmentRoot root = getDestinationAsPackageFragmentRoot();
2308: for (int i = 0; i < fragments.length; i++) {
2309: if (root == null) {
2310: result.add(createChange(fragments[i],
2311: (IContainer) getResourceDestination()));
2312: } else {
2313: result.add(createChange(fragments[i], root));
2314: }
2315: pm.worked(1);
2316: if (pm.isCanceled())
2317: throw new OperationCanceledException();
2318: }
2319: pm.done();
2320: return result;
2321: }
2322:
2323: protected JavaRefactoringDescriptor createRefactoringDescriptor(
2324: JDTRefactoringDescriptorComment comment, Map arguments,
2325: String description, String project, int flags) {
2326: CreateTargetExecutionLog log = getCreateTargetExecutionLog();
2327: storeCreateTargetExecutionLog(project, arguments, log);
2328: return new MoveDescriptor(project, description, comment
2329: .asString(), arguments, flags);
2330: }
2331:
2332: public CreateTargetExecutionLog getCreateTargetExecutionLog() {
2333: return fCreateTargetExecutionLog;
2334: }
2335:
2336: public ICreateTargetQuery getCreateTargetQuery(
2337: ICreateTargetQueries createQueries) {
2338: return null;
2339: }
2340:
2341: protected String getDescriptionPlural() {
2342: return RefactoringCoreMessages.ReorgPolicyFactory_move_packages_plural;
2343: }
2344:
2345: protected String getDescriptionSingular() {
2346: return RefactoringCoreMessages.ReorgPolicyFactory_move_packages_singular;
2347: }
2348:
2349: protected String getHeaderPattern() {
2350: return RefactoringCoreMessages.ReorgPolicyFactory_move_packages_header;
2351: }
2352:
2353: protected RefactoringModifications getModifications()
2354: throws CoreException {
2355: if (fModifications != null)
2356: return fModifications;
2357:
2358: fModifications = new MoveModifications();
2359: boolean updateReferences = canUpdateReferences()
2360: && getUpdateReferences();
2361: IPackageFragment[] packages = getPackages();
2362: IPackageFragmentRoot javaDestination = getDestinationAsPackageFragmentRoot();
2363: for (int i = 0; i < packages.length; i++) {
2364: if (javaDestination == null) {
2365: fModifications.move(packages[i].getResource(),
2366: new MoveArguments(getResourceDestination(),
2367: updateReferences));
2368: } else {
2369: fModifications.move(packages[i], new MoveArguments(
2370: javaDestination, updateReferences));
2371: }
2372: }
2373: return fModifications;
2374: }
2375:
2376: public String getPolicyId() {
2377: return POLICY_MOVE_PACKAGES;
2378: }
2379:
2380: protected String getProcessorId() {
2381: return IJavaRefactorings.MOVE;
2382: }
2383:
2384: protected String getRefactoringId() {
2385: return IJavaRefactorings.MOVE;
2386: }
2387:
2388: public boolean isTextualMove() {
2389: return false;
2390: }
2391:
2392: public Change postCreateChange(Change[] participantChanges,
2393: IProgressMonitor pm) throws CoreException {
2394: return null;
2395: }
2396:
2397: public void setDestinationCheck(boolean check) {
2398: fCheckDestination = check;
2399: }
2400:
2401: protected RefactoringStatus verifyDestination(
2402: IJavaElement javaElement) throws JavaModelException {
2403: RefactoringStatus super Status = super
2404: .verifyDestination(javaElement);
2405: if (super Status.hasFatalError())
2406: return super Status;
2407:
2408: IPackageFragmentRoot root = getDestinationAsPackageFragmentRoot();
2409: if (isParentOfAny(root, getPackages()))
2410: return RefactoringStatus
2411: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_package2parent);
2412: return super Status;
2413: }
2414:
2415: /**
2416: * {@inheritDoc}
2417: */
2418: protected RefactoringStatus verifyDestination(
2419: IResource destination) {
2420: RefactoringStatus super Status = super
2421: .verifyDestination(destination);
2422: if (super Status.hasFatalError())
2423: return super Status;
2424:
2425: Object commonParent = new ParentChecker(getResources(),
2426: getJavaElements()).getCommonParent();
2427: if (destination.equals(commonParent))
2428: return RefactoringStatus
2429: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot_move_package_to_parent);
2430:
2431: return super Status;
2432: }
2433:
2434: /**
2435: * {@inheritDoc}
2436: */
2437: public boolean canEnableQualifiedNameUpdating() {
2438: return false;
2439: }
2440:
2441: /**
2442: * {@inheritDoc}
2443: */
2444: public boolean getUpdateQualifiedNames() {
2445: return false;
2446: }
2447:
2448: /**
2449: * {@inheritDoc}
2450: */
2451: public boolean canUpdateQualifiedNames() {
2452: return false;
2453: }
2454:
2455: /**
2456: * {@inheritDoc}
2457: */
2458: public void setUpdateQualifiedNames(boolean update) {
2459: }
2460:
2461: /**
2462: * {@inheritDoc}
2463: */
2464: public void setFilePatterns(String patterns) {
2465: }
2466:
2467: /**
2468: * {@inheritDoc}
2469: */
2470: public String getFilePatterns() {
2471: return null;
2472: }
2473:
2474: /**
2475: * {@inheritDoc}
2476: */
2477: public boolean canEnableUpdateReferences() {
2478: return false;
2479: }
2480:
2481: /**
2482: * {@inheritDoc}
2483: */
2484: public boolean canUpdateReferences() {
2485: return false;
2486: }
2487:
2488: /**
2489: * {@inheritDoc}
2490: */
2491: public boolean getUpdateReferences() {
2492: return false;
2493: }
2494:
2495: /**
2496: * {@inheritDoc}
2497: */
2498: public void setUpdateReferences(boolean update) {
2499: }
2500:
2501: /**
2502: * {@inheritDoc}
2503: */
2504: public boolean hasAllInputSet() {
2505: return getJavaElementDestination() != null
2506: || getResourceDestination() != null;
2507: }
2508: }
2509:
2510: private static abstract class MoveSubCuElementsPolicy extends
2511: SubCuElementReorgPolicy implements IMovePolicy {
2512:
2513: private CreateTargetExecutionLog fCreateTargetExecutionLog = new CreateTargetExecutionLog();
2514:
2515: MoveSubCuElementsPolicy(IJavaElement[] javaElements) {
2516: super (javaElements);
2517: }
2518:
2519: public boolean canEnable() throws JavaModelException {
2520: return super .canEnable() && getSourceCu() != null;
2521: }
2522:
2523: public Change createChange(IProgressMonitor pm)
2524: throws JavaModelException {
2525: pm.beginTask("", 3); //$NON-NLS-1$
2526: try {
2527: final ICompilationUnit sourceCu = getSourceCu();
2528: CompilationUnit sourceCuNode = RefactoringASTParser
2529: .parseWithASTProvider(sourceCu, true,
2530: new SubProgressMonitor(pm, 1));
2531: CompilationUnitRewrite sourceRewriter = new CompilationUnitRewrite(
2532: sourceCu, sourceCuNode);
2533: ICompilationUnit destinationCu = getEnclosingCompilationUnit(getJavaElementDestination());
2534: CompilationUnitRewrite targetRewriter;
2535: if (sourceCu.equals(destinationCu)) {
2536: targetRewriter = sourceRewriter;
2537: pm.worked(1);
2538: } else {
2539: CompilationUnit destinationCuNode = RefactoringASTParser
2540: .parseWithASTProvider(destinationCu, true,
2541: new SubProgressMonitor(pm, 1));
2542: targetRewriter = new CompilationUnitRewrite(
2543: destinationCu, destinationCuNode);
2544: }
2545: IJavaElement[] javaElements = getJavaElements();
2546: for (int i = 0; i < javaElements.length; i++) {
2547: copyToDestination(javaElements[i], targetRewriter,
2548: sourceRewriter.getRoot(), targetRewriter
2549: .getRoot());
2550: }
2551: ASTNodeDeleteUtil.markAsDeleted(javaElements,
2552: sourceRewriter, null);
2553: Change targetCuChange = createCompilationUnitChange(targetRewriter);
2554: if (sourceCu.equals(destinationCu)) {
2555: return targetCuChange;
2556: } else {
2557: CompositeChange result = new DynamicValidationStateChange(
2558: RefactoringCoreMessages.ReorgPolicy_move_members);
2559: result.markAsSynthetic();
2560: result.add(targetCuChange);
2561: if (Arrays.asList(getJavaElements()).containsAll(
2562: Arrays.asList(sourceCu.getTypes()))) {
2563: result
2564: .add(DeleteChangeCreator
2565: .createDeleteChange(
2566: null,
2567: new IResource[0],
2568: new ICompilationUnit[] { sourceCu },
2569: RefactoringCoreMessages.ReorgPolicy_move,
2570: Collections.EMPTY_LIST));
2571: } else {
2572: result
2573: .add(createCompilationUnitChange(sourceRewriter));
2574: }
2575: return result;
2576: }
2577: } catch (JavaModelException e) {
2578: throw e;
2579: } catch (CoreException e) {
2580: throw new JavaModelException(e);
2581: } finally {
2582: pm.done();
2583: }
2584: }
2585:
2586: protected JavaRefactoringDescriptor createRefactoringDescriptor(
2587: JDTRefactoringDescriptorComment comment, Map arguments,
2588: String description, String project, int flags) {
2589: CreateTargetExecutionLog log = getCreateTargetExecutionLog();
2590: storeCreateTargetExecutionLog(project, arguments, log);
2591: return new MoveDescriptor(project, description, comment
2592: .asString(), arguments, flags);
2593: }
2594:
2595: public IFile[] getAllModifiedFiles() {
2596: return ReorgUtils
2597: .getFiles(new IResource[] {
2598: ReorgUtils.getResource(getSourceCu()),
2599: ReorgUtils
2600: .getResource(getEnclosingCompilationUnit(getJavaElementDestination())) });
2601: }
2602:
2603: public CreateTargetExecutionLog getCreateTargetExecutionLog() {
2604: return fCreateTargetExecutionLog;
2605: }
2606:
2607: public ICreateTargetQuery getCreateTargetQuery(
2608: ICreateTargetQueries createQueries) {
2609: return null;
2610: }
2611:
2612: protected String getDescriptionPlural() {
2613: if (!ReorgUtils.hasElementsNotOfType(getJavaElements(),
2614: IJavaElement.TYPE)) {
2615: return RefactoringCoreMessages.ReorgPolicyFactory_move_types;
2616: } else if (!ReorgUtils.hasElementsNotOfType(
2617: getJavaElements(), IJavaElement.FIELD)) {
2618: return RefactoringCoreMessages.ReorgPolicyFactory_move_fields;
2619: } else if (!ReorgUtils.hasElementsNotOfType(
2620: getJavaElements(), IJavaElement.METHOD)) {
2621: return RefactoringCoreMessages.ReorgPolicyFactory_move_methods;
2622: } else if (!ReorgUtils.hasElementsNotOfType(
2623: getJavaElements(), IJavaElement.INITIALIZER)) {
2624: return RefactoringCoreMessages.ReorgPolicyFactory_move_initializers;
2625: } else if (!ReorgUtils
2626: .hasElementsNotOfType(getJavaElements(),
2627: IJavaElement.PACKAGE_DECLARATION)) {
2628: return RefactoringCoreMessages.ReorgPolicyFactory_move_package_declarations;
2629: } else if (!ReorgUtils.hasElementsNotOfType(
2630: getJavaElements(), IJavaElement.IMPORT_CONTAINER)) {
2631: return RefactoringCoreMessages.ReorgPolicyFactory_move_import_containers;
2632: } else if (!ReorgUtils.hasElementsNotOfType(
2633: getJavaElements(), IJavaElement.IMPORT_DECLARATION)) {
2634: return RefactoringCoreMessages.ReorgPolicyFactory_move_import_declarations;
2635: } else {
2636: return RefactoringCoreMessages.ReorgPolicyFactory_move_elements_plural;
2637: }
2638: }
2639:
2640: protected String getDescriptionSingular() {
2641: if (!ReorgUtils.hasElementsNotOfType(getJavaElements(),
2642: IJavaElement.TYPE)) {
2643: return RefactoringCoreMessages.ReorgPolicyFactory_move_type;
2644: } else if (!ReorgUtils.hasElementsNotOfType(
2645: getJavaElements(), IJavaElement.FIELD)) {
2646: return RefactoringCoreMessages.ReorgPolicyFactory_move_field;
2647: } else if (!ReorgUtils.hasElementsNotOfType(
2648: getJavaElements(), IJavaElement.METHOD)) {
2649: return RefactoringCoreMessages.ReorgPolicyFactory_move_method;
2650: } else if (!ReorgUtils.hasElementsNotOfType(
2651: getJavaElements(), IJavaElement.INITIALIZER)) {
2652: return RefactoringCoreMessages.ReorgPolicyFactory_move_initializer;
2653: } else if (!ReorgUtils
2654: .hasElementsNotOfType(getJavaElements(),
2655: IJavaElement.PACKAGE_DECLARATION)) {
2656: return RefactoringCoreMessages.ReorgPolicyFactory_move_package_declaration;
2657: } else if (!ReorgUtils.hasElementsNotOfType(
2658: getJavaElements(), IJavaElement.IMPORT_CONTAINER)) {
2659: return RefactoringCoreMessages.ReorgPolicyFactory_move_import_section;
2660: } else if (!ReorgUtils.hasElementsNotOfType(
2661: getJavaElements(), IJavaElement.IMPORT_DECLARATION)) {
2662: return RefactoringCoreMessages.ReorgPolicyFactory_move_import_declaration;
2663: } else {
2664: return RefactoringCoreMessages.ReorgPolicyFactory_move_elements_singular;
2665: }
2666: }
2667:
2668: protected String getHeaderPattern() {
2669: return RefactoringCoreMessages.ReorgPolicyFactory_move_elements_header;
2670: }
2671:
2672: protected String getProcessorId() {
2673: return IJavaRefactorings.MOVE;
2674: }
2675:
2676: protected String getRefactoringId() {
2677: return IJavaRefactorings.MOVE;
2678: }
2679:
2680: public boolean isTextualMove() {
2681: return true;
2682: }
2683:
2684: public Change postCreateChange(Change[] participantChanges,
2685: IProgressMonitor pm) throws CoreException {
2686: return null;
2687: }
2688:
2689: public void setDestinationCheck(boolean check) {
2690: fCheckDestination = check;
2691: }
2692:
2693: protected RefactoringStatus verifyDestination(
2694: IJavaElement destination, int location)
2695: throws JavaModelException {
2696: IJavaElement[] elements = getJavaElements();
2697: for (int i = 0; i < elements.length; i++) {
2698: IJavaElement parent = destination.getParent();
2699: while (parent != null) {
2700: if (parent.equals(elements[i]))
2701: return RefactoringStatus
2702: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot);
2703: parent = parent.getParent();
2704: }
2705: }
2706:
2707: RefactoringStatus super Status = super .verifyDestination(
2708: destination, location);
2709: if (super Status.hasFatalError())
2710: return super Status;
2711:
2712: if (location == IReorgDestination.LOCATION_ON) {
2713: Object commonParent = new ParentChecker(
2714: new IResource[0], getJavaElements())
2715: .getCommonParent();
2716: if (destination.equals(commonParent)
2717: || Arrays.asList(getJavaElements()).contains(
2718: destination))
2719: return RefactoringStatus
2720: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_element2parent);
2721:
2722: return super Status;
2723: } else {
2724: if (contains(elements, destination))
2725: return RefactoringStatus
2726: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot);
2727:
2728: IJavaElement parent = destination.getParent();
2729: if (!(parent instanceof IType))
2730: return super Status;
2731:
2732: if (!allInSameParent(elements, parent))
2733: return super Status;
2734:
2735: ArrayList sortedChildren = getSortedChildren((IType) parent);
2736:
2737: int destinationIndex = sortedChildren
2738: .indexOf(destination);
2739:
2740: for (int i = 0; i < elements.length; i++) {
2741: int elementIndex = sortedChildren
2742: .indexOf(elements[i]);
2743: if (location == IReorgDestination.LOCATION_AFTER
2744: && elementIndex == destinationIndex + 1)
2745: return RefactoringStatus
2746: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot);
2747:
2748: if (location == IReorgDestination.LOCATION_BEFORE
2749: && elementIndex == destinationIndex - 1)
2750: return RefactoringStatus
2751: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot);
2752: }
2753:
2754: return super Status;
2755: }
2756: }
2757:
2758: private ArrayList getSortedChildren(IType parent)
2759: throws JavaModelException {
2760: IJavaElement[] children = parent.getChildren();
2761: ArrayList sortedChildren = new ArrayList(Arrays
2762: .asList(children));
2763: Collections.sort(sortedChildren, new Comparator() {
2764: public int compare(Object e1, Object e2) {
2765: if (!(e1 instanceof ISourceReference))
2766: return 0;
2767: if (!(e2 instanceof ISourceReference))
2768: return 0;
2769:
2770: try {
2771: ISourceRange sr1 = ((ISourceReference) e1)
2772: .getSourceRange();
2773: ISourceRange sr2 = ((ISourceReference) e2)
2774: .getSourceRange();
2775: if (sr1 == null || sr2 == null)
2776: return 0;
2777:
2778: return sr1.getOffset() - sr2.getOffset();
2779:
2780: } catch (JavaModelException e) {
2781: return 0;
2782: }
2783: }
2784: });
2785: return sortedChildren;
2786: }
2787:
2788: private boolean contains(IJavaElement[] elements,
2789: IJavaElement element) {
2790: for (int i = 0; i < elements.length; i++) {
2791: if (element.equals(elements[i]))
2792: return true;
2793: }
2794:
2795: return false;
2796: }
2797:
2798: private boolean allInSameParent(IJavaElement[] elements,
2799: IJavaElement parent) {
2800: for (int i = 0; i < elements.length; i++) {
2801: if (!elements[i].getParent().equals(parent))
2802: return false;
2803: }
2804:
2805: return true;
2806: }
2807:
2808: /**
2809: * {@inheritDoc}
2810: */
2811: public boolean canEnableQualifiedNameUpdating() {
2812: return false;
2813: }
2814:
2815: /**
2816: * {@inheritDoc}
2817: */
2818: public boolean getUpdateQualifiedNames() {
2819: return false;
2820: }
2821:
2822: /**
2823: * {@inheritDoc}
2824: */
2825: public boolean canUpdateQualifiedNames() {
2826: return false;
2827: }
2828:
2829: /**
2830: * {@inheritDoc}
2831: */
2832: public void setUpdateQualifiedNames(boolean update) {
2833: }
2834:
2835: /**
2836: * {@inheritDoc}
2837: */
2838: public void setFilePatterns(String patterns) {
2839: }
2840:
2841: /**
2842: * {@inheritDoc}
2843: */
2844: public String getFilePatterns() {
2845: return null;
2846: }
2847:
2848: /**
2849: * {@inheritDoc}
2850: */
2851: public boolean canEnableUpdateReferences() {
2852: return false;
2853: }
2854:
2855: /**
2856: * {@inheritDoc}
2857: */
2858: public boolean canUpdateReferences() {
2859: return false;
2860: }
2861:
2862: /**
2863: * {@inheritDoc}
2864: */
2865: public boolean getUpdateReferences() {
2866: return false;
2867: }
2868:
2869: /**
2870: * {@inheritDoc}
2871: */
2872: public void setUpdateReferences(boolean update) {
2873: }
2874:
2875: /**
2876: * {@inheritDoc}
2877: */
2878: public boolean hasAllInputSet() {
2879: return getJavaElementDestination() != null
2880: || getResourceDestination() != null;
2881: }
2882: }
2883:
2884: private static final class MoveMembersPolicy extends
2885: MoveSubCuElementsPolicy {
2886:
2887: MoveMembersPolicy(IMember[] members) {
2888: super (members);
2889: }
2890:
2891: private static final String POLICY_MOVE_MEMBERS = "org.eclipse.jdt.ui.moveMembers"; //$NON-NLS-1$
2892:
2893: /**
2894: * {@inheritDoc}
2895: */
2896: public String getPolicyId() {
2897: return POLICY_MOVE_MEMBERS;
2898: }
2899:
2900: }
2901:
2902: private static final class MoveImportDeclarationsPolicy extends
2903: MoveSubCuElementsPolicy {
2904:
2905: MoveImportDeclarationsPolicy(
2906: IImportDeclaration[] importDeclarations) {
2907: super (importDeclarations);
2908: }
2909:
2910: private static final String POLICY_MOVE_IMPORT_DECLARATIONS = "org.eclipse.jdt.ui.moveImportDeclarations"; //$NON-NLS-1$
2911:
2912: /**
2913: * {@inheritDoc}
2914: */
2915: public String getPolicyId() {
2916: return POLICY_MOVE_IMPORT_DECLARATIONS;
2917: }
2918:
2919: }
2920:
2921: private static final class NewNameProposer {
2922:
2923: private static boolean isNewNameOk(IContainer container,
2924: String newName) {
2925: return container.findMember(newName) == null;
2926: }
2927:
2928: private static boolean isNewNameOk(IPackageFragment dest,
2929: String newName) {
2930: return !dest.getCompilationUnit(newName).exists();
2931: }
2932:
2933: private static boolean isNewNameOk(IPackageFragmentRoot root,
2934: String newName) {
2935: return !root.getPackageFragment(newName).exists();
2936: }
2937:
2938: private final Set fAutoGeneratedNewNames = new HashSet(2);
2939:
2940: public String createNewName(ICompilationUnit cu,
2941: IPackageFragment destination) {
2942: if (isNewNameOk(destination, cu.getElementName()))
2943: return null;
2944: if (!ReorgUtils
2945: .isParentInWorkspaceOrOnDisk(cu, destination))
2946: return null;
2947: int i = 1;
2948: while (true) {
2949: String newName;
2950: if (i == 1)
2951: newName = Messages
2952: .format(
2953: RefactoringCoreMessages.CopyRefactoring_cu_copyOf1,
2954: cu.getElementName());
2955: else
2956: newName = Messages
2957: .format(
2958: RefactoringCoreMessages.CopyRefactoring_cu_copyOfMore,
2959: new String[] { String.valueOf(i),
2960: cu.getElementName() });
2961: if (isNewNameOk(destination, newName)
2962: && !fAutoGeneratedNewNames.contains(newName)) {
2963: fAutoGeneratedNewNames.add(newName);
2964: return JavaCore.removeJavaLikeExtension(newName);
2965: }
2966: i++;
2967: }
2968: }
2969:
2970: public String createNewName(IPackageFragment pack,
2971: IPackageFragmentRoot destination) {
2972: if (isNewNameOk(destination, pack.getElementName()))
2973: return null;
2974: if (!ReorgUtils.isParentInWorkspaceOrOnDisk(pack,
2975: destination))
2976: return null;
2977: int i = 1;
2978: while (true) {
2979: String newName;
2980: if (i == 1)
2981: newName = Messages
2982: .format(
2983: RefactoringCoreMessages.CopyRefactoring_package_copyOf1,
2984: pack.getElementName());
2985: else
2986: newName = Messages
2987: .format(
2988: RefactoringCoreMessages.CopyRefactoring_package_copyOfMore,
2989: new String[] { String.valueOf(i),
2990: pack.getElementName() });
2991: if (isNewNameOk(destination, newName)
2992: && !fAutoGeneratedNewNames.contains(newName)) {
2993: fAutoGeneratedNewNames.add(newName);
2994: return newName;
2995: }
2996: i++;
2997: }
2998: }
2999:
3000: public String createNewName(IResource res,
3001: IContainer destination) {
3002: if (isNewNameOk(destination, res.getName()))
3003: return null;
3004: if (!ReorgUtils.isParentInWorkspaceOrOnDisk(res,
3005: destination))
3006: return null;
3007: int i = 1;
3008: while (true) {
3009: String newName;
3010: if (i == 1)
3011: newName = Messages
3012: .format(
3013: RefactoringCoreMessages.CopyRefactoring_resource_copyOf1,
3014: res.getName());
3015: else
3016: newName = Messages
3017: .format(
3018: RefactoringCoreMessages.CopyRefactoring_resource_copyOfMore,
3019: new String[] { String.valueOf(i),
3020: res.getName() });
3021: if (isNewNameOk(destination, newName)
3022: && !fAutoGeneratedNewNames.contains(newName)) {
3023: fAutoGeneratedNewNames.add(newName);
3024: return newName;
3025: }
3026: i++;
3027: }
3028: }
3029: }
3030:
3031: private static final class NoCopyPolicy extends ReorgPolicy
3032: implements ICopyPolicy {
3033:
3034: public boolean canEnable() throws JavaModelException {
3035: return false;
3036: }
3037:
3038: public Change createChange(IProgressMonitor pm,
3039: INewNameQueries copyQueries) {
3040: return new NullChange();
3041: }
3042:
3043: protected String getDescriptionPlural() {
3044: return UNUSED_STRING;
3045: }
3046:
3047: protected String getDescriptionSingular() {
3048: return UNUSED_STRING;
3049: }
3050:
3051: public ChangeDescriptor getDescriptor() {
3052: return null;
3053: }
3054:
3055: protected String getHeaderPattern() {
3056: return UNUSED_STRING;
3057: }
3058:
3059: public IJavaElement[] getJavaElements() {
3060: return new IJavaElement[0];
3061: }
3062:
3063: public String getPolicyId() {
3064: return NO_POLICY;
3065: }
3066:
3067: protected String getProcessorId() {
3068: return NO_ID;
3069: }
3070:
3071: protected String getRefactoringId() {
3072: return NO_ID;
3073: }
3074:
3075: public ReorgExecutionLog getReorgExecutionLog() {
3076: return null;
3077: }
3078:
3079: public IResource[] getResources() {
3080: return new IResource[0];
3081: }
3082:
3083: public RefactoringStatus initialize(
3084: RefactoringArguments arguments) {
3085: return new RefactoringStatus();
3086: }
3087:
3088: protected RefactoringStatus verifyDestination(
3089: IJavaElement javaElement) throws JavaModelException {
3090: return RefactoringStatus
3091: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_noCopying);
3092: }
3093:
3094: protected RefactoringStatus verifyDestination(IResource resource)
3095: throws JavaModelException {
3096: return RefactoringStatus
3097: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_noCopying);
3098: }
3099: }
3100:
3101: private static final class NoMovePolicy extends ReorgPolicy
3102: implements IMovePolicy {
3103:
3104: public boolean canEnable() throws JavaModelException {
3105: return false;
3106: }
3107:
3108: public Change createChange(IProgressMonitor pm) {
3109: return new NullChange();
3110: }
3111:
3112: public CreateTargetExecutionLog getCreateTargetExecutionLog() {
3113: return new CreateTargetExecutionLog();
3114: }
3115:
3116: public ICreateTargetQuery getCreateTargetQuery(
3117: ICreateTargetQueries createQueries) {
3118: return null;
3119: }
3120:
3121: protected String getDescriptionPlural() {
3122: return UNUSED_STRING;
3123: }
3124:
3125: protected String getDescriptionSingular() {
3126: return UNUSED_STRING;
3127: }
3128:
3129: public ChangeDescriptor getDescriptor() {
3130: return null;
3131: }
3132:
3133: protected String getHeaderPattern() {
3134: return UNUSED_STRING;
3135: }
3136:
3137: public IJavaElement[] getJavaElements() {
3138: return new IJavaElement[0];
3139: }
3140:
3141: public String getPolicyId() {
3142: return NO_POLICY;
3143: }
3144:
3145: protected String getProcessorId() {
3146: return NO_ID;
3147: }
3148:
3149: protected String getRefactoringId() {
3150: return NO_ID;
3151: }
3152:
3153: public IResource[] getResources() {
3154: return new IResource[0];
3155: }
3156:
3157: public RefactoringStatus initialize(
3158: RefactoringArguments arguments) {
3159: return new RefactoringStatus();
3160: }
3161:
3162: public boolean isTextualMove() {
3163: return true;
3164: }
3165:
3166: public Change postCreateChange(Change[] participantChanges,
3167: IProgressMonitor pm) throws CoreException {
3168: return null;
3169: }
3170:
3171: public void setDestinationCheck(boolean check) {
3172: fCheckDestination = check;
3173: }
3174:
3175: protected RefactoringStatus verifyDestination(
3176: IJavaElement javaElement) throws JavaModelException {
3177: return RefactoringStatus
3178: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_noMoving);
3179: }
3180:
3181: protected RefactoringStatus verifyDestination(IResource resource)
3182: throws JavaModelException {
3183: return RefactoringStatus
3184: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_noMoving);
3185: }
3186:
3187: /**
3188: * {@inheritDoc}
3189: */
3190: public boolean canEnableQualifiedNameUpdating() {
3191: return false;
3192: }
3193:
3194: /**
3195: * {@inheritDoc}
3196: */
3197: public boolean getUpdateQualifiedNames() {
3198: return false;
3199: }
3200:
3201: /**
3202: * {@inheritDoc}
3203: */
3204: public boolean canUpdateQualifiedNames() {
3205: return false;
3206: }
3207:
3208: /**
3209: * {@inheritDoc}
3210: */
3211: public void setUpdateQualifiedNames(boolean update) {
3212: }
3213:
3214: /**
3215: * {@inheritDoc}
3216: */
3217: public void setFilePatterns(String patterns) {
3218: }
3219:
3220: /**
3221: * {@inheritDoc}
3222: */
3223: public String getFilePatterns() {
3224: return null;
3225: }
3226:
3227: /**
3228: * {@inheritDoc}
3229: */
3230: public boolean canEnableUpdateReferences() {
3231: return false;
3232: }
3233:
3234: /**
3235: * {@inheritDoc}
3236: */
3237: public boolean canUpdateReferences() {
3238: return false;
3239: }
3240:
3241: /**
3242: * {@inheritDoc}
3243: */
3244: public boolean getUpdateReferences() {
3245: return false;
3246: }
3247:
3248: /**
3249: * {@inheritDoc}
3250: */
3251: public void setUpdateReferences(boolean update) {
3252: }
3253:
3254: /**
3255: * {@inheritDoc}
3256: */
3257: public boolean hasAllInputSet() {
3258: return getJavaElementDestination() != null
3259: || getResourceDestination() != null;
3260: }
3261: }
3262:
3263: private static abstract class PackageFragmentRootsReorgPolicy
3264: extends ReorgPolicy {
3265:
3266: private IPackageFragmentRoot[] fPackageFragmentRoots;
3267:
3268: public PackageFragmentRootsReorgPolicy(
3269: IPackageFragmentRoot[] roots) {
3270: fPackageFragmentRoots = roots;
3271: }
3272:
3273: public boolean canChildrenBeDestinations(
3274: IJavaElement javaElement) {
3275: switch (javaElement.getElementType()) {
3276: case IJavaElement.JAVA_MODEL:
3277: case IJavaElement.JAVA_PROJECT:
3278: return true;
3279: default:
3280: return false;
3281: }
3282: }
3283:
3284: public boolean canChildrenBeDestinations(IResource resource) {
3285: return resource instanceof IContainer;
3286: }
3287:
3288: public boolean canElementBeDestination(IJavaElement javaElement) {
3289: return javaElement.getElementType() == IJavaElement.JAVA_PROJECT;
3290: }
3291:
3292: public boolean canElementBeDestination(IResource resource) {
3293: return resource instanceof IContainer;
3294: }
3295:
3296: public boolean canEnable() throws JavaModelException {
3297: if (!super .canEnable())
3298: return false;
3299: for (int i = 0; i < fPackageFragmentRoots.length; i++) {
3300: if (!(ReorgUtils
3301: .isSourceFolder(fPackageFragmentRoots[i]) || (fPackageFragmentRoots[i]
3302: .isArchive() && !fPackageFragmentRoots[i]
3303: .isExternal())))
3304: return false;
3305: }
3306: if (ReorgUtils
3307: .containsLinkedResources(fPackageFragmentRoots))
3308: return false;
3309: return true;
3310: }
3311:
3312: public RefactoringStatus checkFinalConditions(
3313: IProgressMonitor pm, CheckConditionsContext context,
3314: IReorgQueries reorgQueries) throws CoreException {
3315: RefactoringStatus status = super .checkFinalConditions(pm,
3316: context, reorgQueries);
3317: confirmOverwriting(reorgQueries);
3318: return status;
3319: }
3320:
3321: private void confirmOverwriting(IReorgQueries reorgQueries) {
3322: OverwriteHelper oh = new OverwriteHelper();
3323: oh.setPackageFragmentRoots(fPackageFragmentRoots);
3324: IJavaProject javaProject = getDestinationJavaProject();
3325: if (javaProject == null) {
3326: oh.confirmOverwriting(reorgQueries,
3327: getResourceDestination());
3328: } else {
3329: oh.confirmOverwriting(reorgQueries, javaProject);
3330: }
3331: fPackageFragmentRoots = oh
3332: .getPackageFragmentRootsWithoutUnconfirmedOnes();
3333: }
3334:
3335: protected abstract JavaRefactoringDescriptor createRefactoringDescriptor(
3336: final JDTRefactoringDescriptorComment comment,
3337: final Map arguments, final String description,
3338: final String project, int flags);
3339:
3340: public final ChangeDescriptor getDescriptor() {
3341: final Map arguments = new HashMap();
3342: final int length = fPackageFragmentRoots.length;
3343: final String description = length == 1 ? getDescriptionSingular()
3344: : getDescriptionPlural();
3345: final IProject resource = getSingleProject();
3346: final String project = resource != null ? resource
3347: .getName() : null;
3348: final String header = Messages.format(getHeaderPattern(),
3349: new String[] { String.valueOf(length),
3350: getDestinationLabel() });
3351: int flags = RefactoringDescriptor.STRUCTURAL_CHANGE
3352: | RefactoringDescriptor.MULTI_CHANGE;
3353: final JDTRefactoringDescriptorComment comment = new JDTRefactoringDescriptorComment(
3354: project, this , header);
3355: arguments.put(ATTRIBUTE_POLICY, getPolicyId());
3356: arguments.put(ATTRIBUTE_ROOTS, new Integer(
3357: fPackageFragmentRoots.length).toString());
3358: for (int offset = 0; offset < fPackageFragmentRoots.length; offset++)
3359: arguments
3360: .put(
3361: JavaRefactoringDescriptorUtil.ATTRIBUTE_ELEMENT
3362: + (offset + 1),
3363: JavaRefactoringDescriptorUtil
3364: .elementToHandle(
3365: project,
3366: fPackageFragmentRoots[offset]));
3367: arguments.putAll(getRefactoringArguments(project));
3368: final JavaRefactoringDescriptor descriptor = createRefactoringDescriptor(
3369: comment, arguments, description, project, flags);
3370: return new RefactoringChangeDescriptor(descriptor);
3371: }
3372:
3373: private IJavaProject getDestinationAsJavaProject(
3374: IJavaElement javaElementDestination) {
3375: if (javaElementDestination == null)
3376: return null;
3377: else
3378: return javaElementDestination.getJavaProject();
3379: }
3380:
3381: protected IJavaProject getDestinationJavaProject() {
3382: return getDestinationAsJavaProject(getJavaElementDestination());
3383: }
3384:
3385: public IJavaElement[] getJavaElements() {
3386: return fPackageFragmentRoots;
3387: }
3388:
3389: protected IPackageFragmentRoot[] getPackageFragmentRoots() {
3390: return fPackageFragmentRoots;
3391: }
3392:
3393: public IResource[] getResources() {
3394: return new IResource[0];
3395: }
3396:
3397: public IPackageFragmentRoot[] getRoots() {
3398: return fPackageFragmentRoots;
3399: }
3400:
3401: private IProject getSingleProject() {
3402: IProject result = null;
3403: for (int index = 0; index < fPackageFragmentRoots.length; index++) {
3404: if (result == null)
3405: result = fPackageFragmentRoots[index]
3406: .getJavaProject().getProject();
3407: else if (!result.equals(fPackageFragmentRoots[index]
3408: .getJavaProject().getProject()))
3409: return null;
3410: }
3411: return result;
3412: }
3413:
3414: public RefactoringStatus initialize(
3415: RefactoringArguments arguments) {
3416: final RefactoringStatus status = new RefactoringStatus();
3417: if (arguments instanceof JavaRefactoringArguments) {
3418: final JavaRefactoringArguments extended = (JavaRefactoringArguments) arguments;
3419: int rootCount = 0;
3420: String value = extended.getAttribute(ATTRIBUTE_ROOTS);
3421: if (value != null && !"".equals(value)) {//$NON-NLS-1$
3422: try {
3423: rootCount = Integer.parseInt(value);
3424: } catch (NumberFormatException exception) {
3425: return RefactoringStatus
3426: .createFatalErrorStatus(Messages
3427: .format(
3428: RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
3429: ATTRIBUTE_ROOTS));
3430: }
3431: } else
3432: return RefactoringStatus
3433: .createFatalErrorStatus(Messages
3434: .format(
3435: RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
3436: ATTRIBUTE_ROOTS));
3437: String handle = null;
3438: List elements = new ArrayList();
3439: for (int index = 0; index < rootCount; index++) {
3440: final String attribute = JavaRefactoringDescriptorUtil.ATTRIBUTE_ELEMENT
3441: + (index + 1);
3442: handle = extended.getAttribute(attribute);
3443: if (handle != null && !"".equals(handle)) { //$NON-NLS-1$
3444: final IJavaElement element = JavaRefactoringDescriptorUtil
3445: .handleToElement(extended.getProject(),
3446: handle, false);
3447: if (element == null
3448: || !element.exists()
3449: || element.getElementType() != IJavaElement.PACKAGE_FRAGMENT_ROOT)
3450: status.merge(ScriptableRefactoring
3451: .createInputWarningStatus(element,
3452: getProcessorId(),
3453: getRefactoringId()));
3454: else
3455: elements.add(element);
3456: } else
3457: return RefactoringStatus
3458: .createFatalErrorStatus(Messages
3459: .format(
3460: RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
3461: attribute));
3462: }
3463: fPackageFragmentRoots = (IPackageFragmentRoot[]) elements
3464: .toArray(new IPackageFragmentRoot[elements
3465: .size()]);
3466: } else
3467: return RefactoringStatus
3468: .createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
3469: status.merge(super .initialize(arguments));
3470: return status;
3471: }
3472:
3473: protected RefactoringStatus verifyDestination(
3474: IJavaElement javaElement) throws JavaModelException {
3475: Assert.isNotNull(javaElement);
3476: if (!fCheckDestination)
3477: return new RefactoringStatus();
3478: if (!javaElement.exists())
3479: return RefactoringStatus
3480: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot1);
3481: if (javaElement instanceof IJavaModel)
3482: return RefactoringStatus
3483: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_jmodel);
3484: if (!(javaElement instanceof IJavaProject))
3485: return RefactoringStatus
3486: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_src2proj);
3487: if (javaElement.isReadOnly())
3488: return RefactoringStatus
3489: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_src2writable);
3490: if (ReorgUtils.isPackageFragmentRoot(javaElement
3491: .getJavaProject()))
3492: return RefactoringStatus
3493: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_src2nosrc);
3494: return new RefactoringStatus();
3495: }
3496:
3497: protected RefactoringStatus verifyDestination(IResource resource) {
3498: Assert.isNotNull(resource);
3499: if (!resource.exists() || resource.isPhantom())
3500: return RefactoringStatus
3501: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_phantom);
3502: if (!resource.isAccessible())
3503: return RefactoringStatus
3504: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_inaccessible);
3505:
3506: if (!(resource instanceof IContainer))
3507: return RefactoringStatus
3508: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_not_this _resource);
3509:
3510: if (resource.getType() == IResource.ROOT)
3511: return RefactoringStatus
3512: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_not_this _resource);
3513:
3514: if (isChildOfOrEqualToAnyFolder(resource))
3515: return RefactoringStatus
3516: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_not_this _resource);
3517:
3518: if (containsLinkedResources()
3519: && !ReorgUtils
3520: .canBeDestinationForLinkedResources(resource))
3521: return RefactoringStatus
3522: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_linked);
3523:
3524: return new RefactoringStatus();
3525: }
3526:
3527: private boolean isChildOfOrEqualToAnyFolder(IResource resource) {
3528: for (int i = 0; i < fPackageFragmentRoots.length; i++) {
3529: IResource fragmentRootResource = fPackageFragmentRoots[i]
3530: .getResource();
3531: if (fragmentRootResource.equals(resource)
3532: || ParentChecker.isDescendantOf(resource,
3533: fragmentRootResource))
3534: return true;
3535: }
3536: return false;
3537: }
3538:
3539: protected boolean containsLinkedResources() {
3540: for (int i = 0; i < fPackageFragmentRoots.length; i++) {
3541: if (fPackageFragmentRoots[i].getResource().isLinked())
3542: return true;
3543: }
3544: return false;
3545: }
3546: }
3547:
3548: private static abstract class PackagesReorgPolicy extends
3549: ReorgPolicy {
3550:
3551: private IPackageFragment[] fPackageFragments;
3552:
3553: public PackagesReorgPolicy(IPackageFragment[] packageFragments) {
3554: fPackageFragments = packageFragments;
3555: }
3556:
3557: public boolean canChildrenBeDestinations(
3558: IJavaElement javaElement) {
3559: switch (javaElement.getElementType()) {
3560: case IJavaElement.JAVA_MODEL:
3561: case IJavaElement.JAVA_PROJECT:
3562: case IJavaElement.PACKAGE_FRAGMENT_ROOT:
3563: // can be nested
3564: // (with exclusion
3565: // filters)
3566: return true;
3567: default:
3568: return false;
3569: }
3570: }
3571:
3572: public boolean canChildrenBeDestinations(IResource resource) {
3573: return resource instanceof IContainer;
3574: }
3575:
3576: public boolean canElementBeDestination(IJavaElement javaElement) {
3577: switch (javaElement.getElementType()) {
3578: case IJavaElement.JAVA_PROJECT:
3579: case IJavaElement.PACKAGE_FRAGMENT_ROOT:
3580: return true;
3581: default:
3582: return false;
3583: }
3584: }
3585:
3586: public boolean canElementBeDestination(IResource resource) {
3587: return resource instanceof IContainer;
3588: }
3589:
3590: public boolean canEnable() throws JavaModelException {
3591: for (int i = 0; i < fPackageFragments.length; i++) {
3592: if (JavaElementUtil
3593: .isDefaultPackage(fPackageFragments[i])
3594: || fPackageFragments[i].isReadOnly())
3595: return false;
3596: }
3597: if (ReorgUtils.containsLinkedResources(fPackageFragments))
3598: return false;
3599: return true;
3600: }
3601:
3602: public RefactoringStatus checkFinalConditions(
3603: IProgressMonitor pm, CheckConditionsContext context,
3604: IReorgQueries reorgQueries) throws CoreException {
3605: RefactoringStatus refactoringStatus = super
3606: .checkFinalConditions(pm, context, reorgQueries);
3607: confirmOverwriting(reorgQueries);
3608: return refactoringStatus;
3609: }
3610:
3611: private void confirmOverwriting(IReorgQueries reorgQueries)
3612: throws JavaModelException {
3613: OverwriteHelper helper = new OverwriteHelper();
3614: helper.setPackages(fPackageFragments);
3615: IPackageFragmentRoot destRoot = getDestinationAsPackageFragmentRoot();
3616: if (destRoot == null) {
3617: helper.confirmOverwriting(reorgQueries,
3618: getResourceDestination());
3619: } else {
3620: helper.confirmOverwriting(reorgQueries, destRoot);
3621: }
3622: fPackageFragments = helper
3623: .getPackagesWithoutUnconfirmedOnes();
3624: }
3625:
3626: protected abstract JavaRefactoringDescriptor createRefactoringDescriptor(
3627: final JDTRefactoringDescriptorComment comment,
3628: final Map arguments, final String description,
3629: final String project, int flags);
3630:
3631: public final ChangeDescriptor getDescriptor() {
3632: final Map arguments = new HashMap();
3633: final int length = fPackageFragments.length;
3634: final String description = length == 1 ? getDescriptionSingular()
3635: : getDescriptionPlural();
3636: final IProject resource = getSingleProject();
3637: final String project = resource != null ? resource
3638: .getName() : null;
3639: final String header = Messages.format(getHeaderPattern(),
3640: new String[] { String.valueOf(length),
3641: getDestinationLabel() });
3642: int flags = JavaRefactoringDescriptor.JAR_REFACTORING
3643: | JavaRefactoringDescriptor.JAR_MIGRATION
3644: | RefactoringDescriptor.STRUCTURAL_CHANGE
3645: | RefactoringDescriptor.MULTI_CHANGE;
3646: final JDTRefactoringDescriptorComment comment = new JDTRefactoringDescriptorComment(
3647: project, this , header);
3648: arguments.put(ATTRIBUTE_POLICY, getPolicyId());
3649: arguments.put(ATTRIBUTE_FRAGMENTS, new Integer(
3650: fPackageFragments.length).toString());
3651: for (int offset = 0; offset < fPackageFragments.length; offset++)
3652: arguments.put(
3653: JavaRefactoringDescriptorUtil.ATTRIBUTE_ELEMENT
3654: + (offset + 1),
3655: JavaRefactoringDescriptorUtil.elementToHandle(
3656: project, fPackageFragments[offset]));
3657: arguments.putAll(getRefactoringArguments(project));
3658: final JavaRefactoringDescriptor descriptor = createRefactoringDescriptor(
3659: comment, arguments, description, project, flags);
3660: return new RefactoringChangeDescriptor(descriptor);
3661: }
3662:
3663: protected IPackageFragmentRoot getDestinationAsPackageFragmentRoot()
3664: throws JavaModelException {
3665: return getDestinationAsPackageFragmentRoot(getJavaElementDestination());
3666: }
3667:
3668: private IPackageFragmentRoot getDestinationAsPackageFragmentRoot(
3669: IJavaElement javaElement) throws JavaModelException {
3670: if (javaElement == null)
3671: return null;
3672:
3673: if (javaElement instanceof IPackageFragmentRoot)
3674: return (IPackageFragmentRoot) javaElement;
3675:
3676: if (javaElement instanceof IPackageFragment) {
3677: IPackageFragment pack = (IPackageFragment) javaElement;
3678: if (pack.getParent() instanceof IPackageFragmentRoot)
3679: return (IPackageFragmentRoot) pack.getParent();
3680: }
3681:
3682: if (javaElement instanceof IJavaProject)
3683: return ReorgUtils
3684: .getCorrespondingPackageFragmentRoot((IJavaProject) javaElement);
3685: return null;
3686: }
3687:
3688: public IJavaElement[] getJavaElements() {
3689: return fPackageFragments;
3690: }
3691:
3692: protected IPackageFragment[] getPackages() {
3693: return fPackageFragments;
3694: }
3695:
3696: public IResource[] getResources() {
3697: return new IResource[0];
3698: }
3699:
3700: private IProject getSingleProject() {
3701: IProject result = null;
3702: for (int index = 0; index < fPackageFragments.length; index++) {
3703: if (result == null)
3704: result = fPackageFragments[index].getJavaProject()
3705: .getProject();
3706: else if (!result.equals(fPackageFragments[index]
3707: .getJavaProject().getProject()))
3708: return null;
3709: }
3710: return result;
3711: }
3712:
3713: public RefactoringStatus initialize(
3714: RefactoringArguments arguments) {
3715: final RefactoringStatus status = new RefactoringStatus();
3716: if (arguments instanceof JavaRefactoringArguments) {
3717: final JavaRefactoringArguments extended = (JavaRefactoringArguments) arguments;
3718: int fragmentCount = 0;
3719: String value = extended
3720: .getAttribute(ATTRIBUTE_FRAGMENTS);
3721: if (value != null && !"".equals(value)) {//$NON-NLS-1$
3722: try {
3723: fragmentCount = Integer.parseInt(value);
3724: } catch (NumberFormatException exception) {
3725: return RefactoringStatus
3726: .createFatalErrorStatus(Messages
3727: .format(
3728: RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
3729: ATTRIBUTE_FRAGMENTS));
3730: }
3731: } else
3732: return RefactoringStatus
3733: .createFatalErrorStatus(Messages
3734: .format(
3735: RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
3736: ATTRIBUTE_FRAGMENTS));
3737: String handle = null;
3738: List elements = new ArrayList();
3739: for (int index = 0; index < fragmentCount; index++) {
3740: final String attribute = JavaRefactoringDescriptorUtil.ATTRIBUTE_ELEMENT
3741: + (index + 1);
3742: handle = extended.getAttribute(attribute);
3743: if (handle != null && !"".equals(handle)) { //$NON-NLS-1$
3744: final IJavaElement element = JavaRefactoringDescriptorUtil
3745: .handleToElement(extended.getProject(),
3746: handle, false);
3747: if (element == null
3748: || !element.exists()
3749: || element.getElementType() != IJavaElement.PACKAGE_FRAGMENT)
3750: status.merge(ScriptableRefactoring
3751: .createInputWarningStatus(element,
3752: getProcessorId(),
3753: getRefactoringId()));
3754: else
3755: elements.add(element);
3756: } else
3757: return RefactoringStatus
3758: .createFatalErrorStatus(Messages
3759: .format(
3760: RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
3761: attribute));
3762: }
3763: fPackageFragments = (IPackageFragment[]) elements
3764: .toArray(new IPackageFragment[elements.size()]);
3765: } else
3766: return RefactoringStatus
3767: .createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
3768: status.merge(super .initialize(arguments));
3769: return status;
3770: }
3771:
3772: protected RefactoringStatus verifyDestination(
3773: IJavaElement javaElement) throws JavaModelException {
3774: Assert.isNotNull(javaElement);
3775: if (!fCheckDestination)
3776: return new RefactoringStatus();
3777: if (!javaElement.exists())
3778: return RefactoringStatus
3779: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot1);
3780: if (javaElement instanceof IJavaModel)
3781: return RefactoringStatus
3782: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_jmodel);
3783: IPackageFragmentRoot destRoot = getDestinationAsPackageFragmentRoot(javaElement);
3784: if (!ReorgUtils.isSourceFolder(destRoot))
3785: return RefactoringStatus
3786: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_packages);
3787: return new RefactoringStatus();
3788: }
3789:
3790: protected RefactoringStatus verifyDestination(IResource resource) {
3791: Assert.isNotNull(resource);
3792: if (!resource.exists() || resource.isPhantom())
3793: return RefactoringStatus
3794: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_phantom);
3795: if (!resource.isAccessible())
3796: return RefactoringStatus
3797: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_inaccessible);
3798:
3799: if (!(resource instanceof IContainer))
3800: return RefactoringStatus
3801: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_not_this _resource);
3802:
3803: if (resource.getType() == IResource.ROOT)
3804: return RefactoringStatus
3805: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_not_this _resource);
3806:
3807: if (isChildOfOrEqualToAnyFolder(resource))
3808: return RefactoringStatus
3809: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_not_this _resource);
3810:
3811: if (containsLinkedResources()
3812: && !ReorgUtils
3813: .canBeDestinationForLinkedResources(resource))
3814: return RefactoringStatus
3815: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_linked);
3816:
3817: return new RefactoringStatus();
3818: }
3819:
3820: private boolean isChildOfOrEqualToAnyFolder(IResource resource) {
3821: for (int i = 0; i < fPackageFragments.length; i++) {
3822: IFolder folder = (IFolder) fPackageFragments[i]
3823: .getResource();
3824: if (folder.equals(resource)
3825: || ParentChecker.isDescendantOf(resource,
3826: folder))
3827: return true;
3828: }
3829: return false;
3830: }
3831:
3832: protected boolean containsLinkedResources() {
3833: for (int i = 0; i < fPackageFragments.length; i++) {
3834: if (fPackageFragments[i].getResource().isLinked())
3835: return true;
3836: }
3837: return false;
3838: }
3839: }
3840:
3841: private static abstract class ReorgPolicy implements IReorgPolicy {
3842:
3843: private static final String ATTRIBUTE_DESTINATION = "destination"; //$NON-NLS-1$
3844:
3845: private static final String ATTRIBUTE_TARGET = "target"; //$NON-NLS-1$
3846:
3847: protected boolean fCheckDestination = true;
3848:
3849: private IReorgDestination fDestination;
3850:
3851: /**
3852: * {@inheritDoc}
3853: */
3854: public boolean canChildrenBeDestinations(
3855: IReorgDestination destination) {
3856: if (destination instanceof JavaElementDestination) {
3857: return canChildrenBeDestinations(((JavaElementDestination) destination)
3858: .getJavaElement());
3859: } else if (destination instanceof ResourceDestination) {
3860: return canChildrenBeDestinations(((ResourceDestination) destination)
3861: .getResource());
3862: }
3863:
3864: return false;
3865: }
3866:
3867: /**
3868: * Is it possible, that resource contains valid destinations
3869: * as children?
3870: *
3871: * @param resource the resource to verify
3872: * @return true if resource can have valid destinations
3873: */
3874: public boolean canChildrenBeDestinations(IResource resource) {
3875: return true;
3876: }
3877:
3878: /**
3879: * Is it possible, that resource contains valid destinations
3880: * as children?
3881: *
3882: * @param javaElement the java element to verify
3883: * @return true if resource can have valid destinations
3884: */
3885: public boolean canChildrenBeDestinations(
3886: IJavaElement javaElement) {
3887: return true;
3888: }
3889:
3890: /**
3891: * {@inheritDoc}
3892: */
3893: public boolean canElementBeDestination(
3894: IReorgDestination destination) {
3895: if (destination instanceof JavaElementDestination) {
3896: return canElementBeDestination(((JavaElementDestination) destination)
3897: .getJavaElement());
3898: } else if (destination instanceof ResourceDestination) {
3899: return canElementBeDestination(((ResourceDestination) destination)
3900: .getResource());
3901: }
3902:
3903: return false;
3904: }
3905:
3906: /**
3907: * Is it possible, that sources can be reorged to this kind of resource?
3908: *
3909: * This is less strict then {@link #verifyDestination(IResource)} where
3910: * the resource itself is verified to be a valid destination.
3911: *
3912: * @param resource the resource to move to
3913: * @return true if possible
3914: */
3915: public boolean canElementBeDestination(IResource resource) {
3916: return true;
3917: }
3918:
3919: /**
3920: * Is it possible, that sources can be reorged to this kind of javaElement?
3921: *
3922: * This is less strict then {@link #verifyDestination(IJavaElement)} where
3923: * the java element itself is verified to be a valid destination.
3924: *
3925: * @param javaElement the java element to move to
3926: * @return true if possible
3927: */
3928: public boolean canElementBeDestination(IJavaElement javaElement) {
3929: return true;
3930: }
3931:
3932: public boolean canEnable() throws JavaModelException {
3933: IResource[] resources = getResources();
3934: for (int i = 0; i < resources.length; i++) {
3935: IResource resource = resources[i];
3936: if (!resource.exists() || resource.isPhantom()
3937: || !resource.isAccessible())
3938: return false;
3939: }
3940:
3941: IJavaElement[] javaElements = getJavaElements();
3942: for (int i = 0; i < javaElements.length; i++) {
3943: IJavaElement element = javaElements[i];
3944: if (!element.exists())
3945: return false;
3946: }
3947: return true;
3948: }
3949:
3950: /**
3951: * {@inheritDoc}
3952: */
3953: public int getSaveMode() {
3954: return RefactoringSaveHelper.SAVE_ALL;
3955: }
3956:
3957: public RefactoringStatus checkFinalConditions(
3958: IProgressMonitor pm, CheckConditionsContext context,
3959: IReorgQueries reorgQueries) throws CoreException {
3960: Assert.isNotNull(reorgQueries);
3961: ResourceChangeChecker checker = (ResourceChangeChecker) context
3962: .getChecker(ResourceChangeChecker.class);
3963: IFile[] allModifiedFiles = getAllModifiedFiles();
3964: RefactoringModifications modifications = getModifications();
3965: IResourceChangeDescriptionFactory deltaFactory = checker
3966: .getDeltaFactory();
3967: for (int i = 0; i < allModifiedFiles.length; i++) {
3968: deltaFactory.change(allModifiedFiles[i]);
3969: }
3970: if (modifications != null) {
3971: modifications.buildDelta(deltaFactory);
3972: modifications
3973: .buildValidateEdits((ValidateEditChecker) context
3974: .getChecker(ValidateEditChecker.class));
3975: }
3976: return new RefactoringStatus();
3977: }
3978:
3979: protected IFile[] getAllModifiedFiles() {
3980: return new IFile[0];
3981: }
3982:
3983: protected abstract String getDescriptionPlural();
3984:
3985: protected abstract String getDescriptionSingular();
3986:
3987: protected String getDestinationLabel() {
3988: Object destination = getJavaElementDestination();
3989: if (destination == null)
3990: destination = getResourceDestination();
3991: return JavaElementLabels.getTextLabel(destination,
3992: JavaElementLabels.ALL_FULLY_QUALIFIED);
3993: }
3994:
3995: protected abstract String getHeaderPattern();
3996:
3997: public final IJavaElement getJavaElementDestination() {
3998: if (!(fDestination instanceof JavaElementDestination))
3999: return null;
4000:
4001: JavaElementDestination javaElementDestination = (JavaElementDestination) fDestination;
4002: return javaElementDestination.getJavaElement();
4003: }
4004:
4005: public final int getLocation() {
4006: return fDestination.getLocation();
4007: }
4008:
4009: protected RefactoringModifications getModifications()
4010: throws CoreException {
4011: return null;
4012: }
4013:
4014: protected abstract String getProcessorId();
4015:
4016: protected Map getRefactoringArguments(String project) {
4017: final Map arguments = new HashMap();
4018: final IJavaElement element = getJavaElementDestination();
4019: if (element != null)
4020: arguments.put(ATTRIBUTE_DESTINATION,
4021: JavaRefactoringDescriptorUtil.elementToHandle(
4022: project, element));
4023: else {
4024: // https://bugs.eclipse.org/bugs/show_bug.cgi?id=157479
4025: final IResource resource = getResourceDestination();
4026: if (resource != null)
4027: arguments.put(ATTRIBUTE_TARGET,
4028: JavaRefactoringDescriptorUtil
4029: .resourceToHandle(null, resource));
4030: }
4031: return arguments;
4032: }
4033:
4034: protected abstract String getRefactoringId();
4035:
4036: public final IResource getResourceDestination() {
4037: if (!(fDestination instanceof ResourceDestination))
4038: return null;
4039:
4040: ResourceDestination resourceDestination = (ResourceDestination) fDestination;
4041: return resourceDestination.getResource();
4042: }
4043:
4044: public RefactoringStatus initialize(
4045: RefactoringArguments arguments) {
4046: if (arguments instanceof JavaRefactoringArguments) {
4047: final JavaRefactoringArguments extended = (JavaRefactoringArguments) arguments;
4048: String handle = extended
4049: .getAttribute(ATTRIBUTE_DESTINATION);
4050: if (handle != null) {
4051: final IJavaElement element = JavaRefactoringDescriptorUtil
4052: .handleToElement(extended.getProject(),
4053: handle, false);
4054: if (element != null) {
4055: if (fCheckDestination && !element.exists())
4056: return ScriptableRefactoring
4057: .createInputFatalStatus(element,
4058: getProcessorId(),
4059: getRefactoringId());
4060: else {
4061: try {
4062: IReorgDestination destination = ReorgDestinationFactory
4063: .createDestination(element);
4064: setDestination(destination);
4065: return verifyDestination(destination);
4066: } catch (JavaModelException exception) {
4067: JavaPlugin.log(exception);
4068: return RefactoringStatus
4069: .createFatalErrorStatus(Messages
4070: .format(
4071: RefactoringCoreMessages.InitializableRefactoring_illegal_argument,
4072: new String[] {
4073: handle,
4074: JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT }));
4075: }
4076: }
4077: } else {
4078: // Leave for compatibility
4079: // https://bugs.eclipse.org/bugs/show_bug.cgi?id=157479
4080: final IResource resource = JavaRefactoringDescriptorUtil
4081: .handleToResource(
4082: extended.getProject(), handle);
4083: if (resource == null
4084: || (fCheckDestination && !resource
4085: .exists()))
4086: return ScriptableRefactoring
4087: .createInputFatalStatus(resource,
4088: getProcessorId(),
4089: getRefactoringId());
4090: else {
4091: try {
4092: IReorgDestination destination = ReorgDestinationFactory
4093: .createDestination(resource);
4094: setDestination(destination);
4095: return verifyDestination(destination);
4096: } catch (JavaModelException exception) {
4097: JavaPlugin.log(exception);
4098: return RefactoringStatus
4099: .createFatalErrorStatus(Messages
4100: .format(
4101: RefactoringCoreMessages.InitializableRefactoring_illegal_argument,
4102: new String[] {
4103: handle,
4104: JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT }));
4105: }
4106: }
4107: }
4108: } else {
4109: // https://bugs.eclipse.org/bugs/show_bug.cgi?id=157479
4110: handle = extended.getAttribute(ATTRIBUTE_TARGET);
4111: if (handle != null) {
4112: final IResource resource = JavaRefactoringDescriptorUtil
4113: .handleToResource(
4114: extended.getProject(), handle);
4115: if (resource == null
4116: || (fCheckDestination && !resource
4117: .exists()))
4118: return ScriptableRefactoring
4119: .createInputFatalStatus(resource,
4120: getProcessorId(),
4121: getRefactoringId());
4122: else {
4123: try {
4124: IReorgDestination destination = ReorgDestinationFactory
4125: .createDestination(resource);
4126: setDestination(destination);
4127: return verifyDestination(destination);
4128: } catch (JavaModelException exception) {
4129: JavaPlugin.log(exception);
4130: return RefactoringStatus
4131: .createFatalErrorStatus(Messages
4132: .format(
4133: RefactoringCoreMessages.InitializableRefactoring_illegal_argument,
4134: new String[] {
4135: handle,
4136: JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT }));
4137: }
4138: }
4139: } else
4140: return RefactoringStatus
4141: .createFatalErrorStatus(Messages
4142: .format(
4143: RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
4144: JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT));
4145: }
4146: } else
4147: return RefactoringStatus
4148: .createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
4149: }
4150:
4151: public final RefactoringParticipant[] loadParticipants(
4152: RefactoringStatus status,
4153: RefactoringProcessor processor, String[] natures,
4154: SharableParticipants shared) throws CoreException {
4155: RefactoringModifications modifications = getModifications();
4156: if (modifications != null) {
4157: return modifications.loadParticipants(status,
4158: processor, natures, shared);
4159: } else {
4160: return new RefactoringParticipant[0];
4161: }
4162: }
4163:
4164: /**
4165: * {@inheritDoc}
4166: */
4167: public final void setDestination(IReorgDestination destination) {
4168: fDestination = destination;
4169: }
4170:
4171: /**
4172: * {@inheritDoc}
4173: */
4174: public RefactoringStatus verifyDestination(
4175: IReorgDestination destination)
4176: throws JavaModelException {
4177: if (destination instanceof JavaElementDestination) {
4178: return verifyDestination(((JavaElementDestination) destination)
4179: .getJavaElement());
4180: } else if (destination instanceof ResourceDestination) {
4181: return verifyDestination(((ResourceDestination) destination)
4182: .getResource());
4183: }
4184:
4185: return RefactoringStatus
4186: .createErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_invalidDestinationKind);
4187: }
4188:
4189: /**
4190: * Can destination be a target for the given source elements?
4191: *
4192: * @param destination the destination to verify
4193: * @return OK status if valid destination
4194: * @throws JavaModelException
4195: */
4196: protected RefactoringStatus verifyDestination(
4197: IJavaElement destination) throws JavaModelException {
4198: return RefactoringStatus
4199: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_no_java_element);
4200: }
4201:
4202: /**
4203: * Can destination be a target for the given source elements?
4204: *
4205: * @param destination the destination to verify
4206: * @return OK status if valid destination
4207: * @throws JavaModelException
4208: */
4209: protected RefactoringStatus verifyDestination(
4210: IResource destination) throws JavaModelException {
4211: return RefactoringStatus
4212: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_no_resource);
4213: }
4214: }
4215:
4216: private static abstract class SubCuElementReorgPolicy extends
4217: ReorgPolicy {
4218:
4219: protected static CompilationUnitChange createCompilationUnitChange(
4220: CompilationUnitRewrite rewrite) throws CoreException {
4221: CompilationUnitChange change = rewrite.createChange();
4222: if (change != null)
4223: change.setSaveMode(TextFileChange.KEEP_SAVE_STATE);
4224:
4225: return change;
4226: }
4227:
4228: /*
4229: * The CU which does contain element
4230: */
4231: protected static final ICompilationUnit getEnclosingCompilationUnit(
4232: IJavaElement element) {
4233: if (element instanceof ICompilationUnit)
4234: return (ICompilationUnit) element;
4235:
4236: return (ICompilationUnit) element
4237: .getAncestor(IJavaElement.COMPILATION_UNIT);
4238: }
4239:
4240: private static IType getEnclosingType(IJavaElement element) {
4241: if (element instanceof IType)
4242: return (IType) element;
4243:
4244: return (IType) element.getAncestor(IJavaElement.TYPE);
4245: }
4246:
4247: private static String getUnindentedSource(
4248: ISourceReference sourceReference)
4249: throws JavaModelException {
4250:
4251: String[] lines = Strings.convertIntoLines(sourceReference
4252: .getSource());
4253: final IJavaProject project = ((IJavaElement) sourceReference)
4254: .getJavaProject();
4255: Strings.trimIndentation(lines, project, false);
4256: return Strings
4257: .concatenate(
4258: lines,
4259: StubUtility
4260: .getLineDelimiterUsed((IJavaElement) sourceReference));
4261: }
4262:
4263: private IJavaElement[] fJavaElements;
4264:
4265: SubCuElementReorgPolicy(IJavaElement[] javaElements) {
4266: fJavaElements = javaElements;
4267: }
4268:
4269: /**
4270: * {@inheritDoc}
4271: */
4272: public boolean canChildrenBeDestinations(IResource resource) {
4273: return false;
4274: }
4275:
4276: /**
4277: * {@inheritDoc}
4278: */
4279: public boolean canElementBeDestination(IJavaElement javaElement) {
4280: return true;
4281: }
4282:
4283: public boolean canEnable() throws JavaModelException {
4284: if (!super .canEnable())
4285: return false;
4286:
4287: for (int i = 0; i < fJavaElements.length; i++) {
4288: if (fJavaElements[i] instanceof IMember) {
4289: IMember member = (IMember) fJavaElements[i];
4290: // we can copy some binary members, but not all
4291: if (member.isBinary()
4292: && member.getSourceRange() == null)
4293: return false;
4294: }
4295: }
4296:
4297: return true;
4298: }
4299:
4300: /**
4301: * {@inheritDoc}
4302: */
4303: public int getSaveMode() {
4304: return RefactoringSaveHelper.SAVE_JAVA_ONLY_UPDATES;
4305: }
4306:
4307: private void copyImportsToDestination(
4308: IImportContainer container, ASTRewrite rewrite,
4309: CompilationUnit sourceCuNode,
4310: CompilationUnit destinationCuNode)
4311: throws JavaModelException {
4312: ListRewrite listRewrite = rewrite
4313: .getListRewrite(destinationCuNode,
4314: CompilationUnit.IMPORTS_PROPERTY);
4315:
4316: IJavaElement[] importDeclarations = container.getChildren();
4317: for (int i = 0; i < importDeclarations.length; i++) {
4318: IImportDeclaration declaration = (IImportDeclaration) importDeclarations[i];
4319:
4320: ImportDeclaration sourceNode = ASTNodeSearchUtil
4321: .getImportDeclarationNode(declaration,
4322: sourceCuNode);
4323: ImportDeclaration copiedNode = (ImportDeclaration) ASTNode
4324: .copySubtree(rewrite.getAST(), sourceNode);
4325:
4326: if (getLocation() == IReorgDestination.LOCATION_BEFORE) {
4327: listRewrite.insertFirst(copiedNode, null);
4328: } else {
4329: listRewrite.insertLast(copiedNode, null);
4330: }
4331: }
4332: }
4333:
4334: private void copyImportToDestination(
4335: IImportDeclaration declaration,
4336: ASTRewrite targetRewrite, CompilationUnit sourceCuNode,
4337: CompilationUnit destinationCuNode)
4338: throws JavaModelException {
4339: ImportDeclaration sourceNode = ASTNodeSearchUtil
4340: .getImportDeclarationNode(declaration, sourceCuNode);
4341: ImportDeclaration copiedNode = (ImportDeclaration) ASTNode
4342: .copySubtree(targetRewrite.getAST(), sourceNode);
4343: ListRewrite listRewrite = targetRewrite
4344: .getListRewrite(destinationCuNode,
4345: CompilationUnit.IMPORTS_PROPERTY);
4346:
4347: if (getJavaElementDestination() instanceof IImportDeclaration) {
4348: ImportDeclaration destinationNode = ASTNodeSearchUtil
4349: .getImportDeclarationNode(
4350: (IImportDeclaration) getJavaElementDestination(),
4351: destinationCuNode);
4352: insertRelative(copiedNode, destinationNode, listRewrite);
4353: } else {
4354: //dropped on container, we could be better here
4355: listRewrite.insertLast(copiedNode, null);
4356: }
4357: }
4358:
4359: private void copyInitializerToDestination(
4360: IInitializer initializer,
4361: CompilationUnitRewrite targetRewriter,
4362: CompilationUnit sourceCuNode,
4363: CompilationUnit targetCuNode) throws JavaModelException {
4364: BodyDeclaration newInitializer = (BodyDeclaration) targetRewriter
4365: .getASTRewrite().createStringPlaceholder(
4366: getUnindentedSource(initializer),
4367: ASTNode.INITIALIZER);
4368: copyMemberToDestination(initializer, targetRewriter,
4369: sourceCuNode, targetCuNode, newInitializer);
4370: }
4371:
4372: private void copyMemberToDestination(IMember member,
4373: CompilationUnitRewrite targetRewriter,
4374: CompilationUnit sourceCuNode,
4375: CompilationUnit targetCuNode, BodyDeclaration newMember)
4376: throws JavaModelException {
4377: IJavaElement javaElementDestination = getJavaElementDestination();
4378: ASTNode nodeDestination = getDestinationNode(
4379: javaElementDestination, targetCuNode);
4380: ASTNode destinationContainer;
4381: if (getLocation() == IReorgDestination.LOCATION_ON
4382: && javaElementDestination instanceof IType) {
4383: destinationContainer = nodeDestination;
4384: } else {
4385: destinationContainer = nodeDestination.getParent();
4386: }
4387:
4388: ListRewrite listRewrite;
4389: if (destinationContainer instanceof AbstractTypeDeclaration) {
4390: if (newMember instanceof EnumConstantDeclaration
4391: && destinationContainer instanceof EnumDeclaration) {
4392: listRewrite = targetRewriter
4393: .getASTRewrite()
4394: .getListRewrite(
4395: destinationContainer,
4396: EnumDeclaration.ENUM_CONSTANTS_PROPERTY);
4397: } else {
4398: listRewrite = targetRewriter
4399: .getASTRewrite()
4400: .getListRewrite(
4401: destinationContainer,
4402: ((AbstractTypeDeclaration) destinationContainer)
4403: .getBodyDeclarationsProperty());
4404: }
4405: } else if (destinationContainer instanceof CompilationUnit) {
4406: listRewrite = targetRewriter.getASTRewrite()
4407: .getListRewrite(destinationContainer,
4408: CompilationUnit.TYPES_PROPERTY);
4409: } else if (destinationContainer instanceof Block) {
4410: listRewrite = targetRewriter.getASTRewrite()
4411: .getListRewrite(destinationContainer,
4412: Block.STATEMENTS_PROPERTY);
4413: } else if (destinationContainer instanceof AnonymousClassDeclaration) {
4414: listRewrite = targetRewriter
4415: .getASTRewrite()
4416: .getListRewrite(
4417: destinationContainer,
4418: AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY);
4419: } else {
4420: listRewrite = null;
4421: Assert.isLegal(false);
4422: }
4423:
4424: if (getLocation() == IReorgDestination.LOCATION_ON) {
4425: listRewrite.insertAt(newMember, ASTNodes
4426: .getInsertionIndex(newMember, listRewrite
4427: .getRewrittenList()), null);
4428: } else {
4429: insertRelative(newMember, nodeDestination, listRewrite);
4430: }
4431:
4432: if (!(member instanceof IInitializer)) {
4433: BodyDeclaration decl = ASTNodeSearchUtil
4434: .getBodyDeclarationNode(member, sourceCuNode);
4435: if (decl != null)
4436: ImportRewriteUtil.addImports(targetRewriter, decl,
4437: new HashMap(), new HashMap(), false);
4438: }
4439: }
4440:
4441: /*
4442: * Get the 'destination' in 'target' as ASTNode or 'null'
4443: */
4444: private ASTNode getDestinationNode(IJavaElement destination,
4445: CompilationUnit target) throws JavaModelException {
4446: switch (destination.getElementType()) {
4447: case IJavaElement.INITIALIZER:
4448: return ASTNodeSearchUtil.getInitializerNode(
4449: (IInitializer) destination, target);
4450: case IJavaElement.FIELD:
4451: return ASTNodeSearchUtil
4452: .getFieldOrEnumConstantDeclaration(
4453: (IField) destination, target);
4454: case IJavaElement.METHOD:
4455: return ASTNodeSearchUtil
4456: .getMethodOrAnnotationTypeMemberDeclarationNode(
4457: (IMethod) destination, target);
4458: case IJavaElement.TYPE:
4459: IType typeDestination = (IType) destination;
4460: if (typeDestination.isAnonymous()) {
4461: return ASTNodeSearchUtil
4462: .getClassInstanceCreationNode(
4463: typeDestination, target)
4464: .getAnonymousClassDeclaration();
4465: } else {
4466: return ASTNodeSearchUtil
4467: .getAbstractTypeDeclarationNode(
4468: typeDestination, target);
4469: }
4470: default:
4471: return null;
4472: }
4473: }
4474:
4475: private void insertRelative(ASTNode newNode,
4476: ASTNode relativeNode, ListRewrite listRewrite) {
4477: final List list = listRewrite.getOriginalList();
4478: final int index = list.indexOf(relativeNode);
4479:
4480: if (getLocation() == IReorgDestination.LOCATION_BEFORE) {
4481: listRewrite.insertBefore(newNode, (ASTNode) list
4482: .get(index), null);
4483: } else if (index + 1 < list.size()) {
4484: listRewrite.insertBefore(newNode, (ASTNode) list
4485: .get(index + 1), null);
4486: } else {
4487: listRewrite.insertLast(newNode, null);
4488: }
4489: }
4490:
4491: private void copyMethodToDestination(IMethod method,
4492: CompilationUnitRewrite targetRewriter,
4493: CompilationUnit sourceCuNode,
4494: CompilationUnit targetCuNode) throws JavaModelException {
4495: MethodDeclaration newMethod = (MethodDeclaration) targetRewriter
4496: .getASTRewrite().createStringPlaceholder(
4497: getUnindentedSource(method),
4498: ASTNode.METHOD_DECLARATION);
4499: newMethod.setConstructor(method.isConstructor());
4500: copyMemberToDestination(method, targetRewriter,
4501: sourceCuNode, targetCuNode, newMethod);
4502: }
4503:
4504: private void copyPackageDeclarationToDestination(
4505: IPackageDeclaration declaration,
4506: ASTRewrite targetRewrite, CompilationUnit sourceCuNode,
4507: CompilationUnit destinationCuNode)
4508: throws JavaModelException {
4509: if (destinationCuNode.getPackage() != null)
4510: return;
4511: PackageDeclaration sourceNode = ASTNodeSearchUtil
4512: .getPackageDeclarationNode(declaration,
4513: sourceCuNode);
4514: PackageDeclaration copiedNode = (PackageDeclaration) ASTNode
4515: .copySubtree(targetRewrite.getAST(), sourceNode);
4516: targetRewrite.set(destinationCuNode,
4517: CompilationUnit.PACKAGE_PROPERTY, copiedNode, null);
4518: }
4519:
4520: protected void copyToDestination(IJavaElement element,
4521: CompilationUnitRewrite targetRewriter,
4522: CompilationUnit sourceCuNode,
4523: CompilationUnit targetCuNode) throws CoreException {
4524: final ASTRewrite rewrite = targetRewriter.getASTRewrite();
4525: switch (element.getElementType()) {
4526: case IJavaElement.FIELD:
4527: copyMemberToDestination((IMember) element,
4528: targetRewriter, sourceCuNode, targetCuNode,
4529: createNewFieldDeclarationNode(
4530: ((IField) element), rewrite,
4531: sourceCuNode));
4532: break;
4533: case IJavaElement.IMPORT_CONTAINER:
4534: copyImportsToDestination((IImportContainer) element,
4535: rewrite, sourceCuNode, targetCuNode);
4536: break;
4537: case IJavaElement.IMPORT_DECLARATION:
4538: copyImportToDestination((IImportDeclaration) element,
4539: rewrite, sourceCuNode, targetCuNode);
4540: break;
4541: case IJavaElement.INITIALIZER:
4542: copyInitializerToDestination((IInitializer) element,
4543: targetRewriter, sourceCuNode, targetCuNode);
4544: break;
4545: case IJavaElement.METHOD:
4546: copyMethodToDestination((IMethod) element,
4547: targetRewriter, sourceCuNode, targetCuNode);
4548: break;
4549: case IJavaElement.PACKAGE_DECLARATION:
4550: copyPackageDeclarationToDestination(
4551: (IPackageDeclaration) element, rewrite,
4552: sourceCuNode, targetCuNode);
4553: break;
4554: case IJavaElement.TYPE:
4555: copyTypeToDestination((IType) element, targetRewriter,
4556: sourceCuNode, targetCuNode);
4557: break;
4558:
4559: default:
4560: Assert.isTrue(false);
4561: }
4562: }
4563:
4564: private void copyTypeToDestination(IType type,
4565: CompilationUnitRewrite targetRewriter,
4566: CompilationUnit sourceCuNode,
4567: CompilationUnit targetCuNode) throws JavaModelException {
4568: AbstractTypeDeclaration newType = (AbstractTypeDeclaration) targetRewriter
4569: .getASTRewrite().createStringPlaceholder(
4570: getUnindentedSource(type),
4571: ASTNode.TYPE_DECLARATION);
4572: IType enclosingType = getEnclosingType(getJavaElementDestination());
4573: if (enclosingType != null) {
4574: copyMemberToDestination(type, targetRewriter,
4575: sourceCuNode, targetCuNode, newType);
4576: } else {
4577: targetRewriter.getASTRewrite().getListRewrite(
4578: targetCuNode, CompilationUnit.TYPES_PROPERTY)
4579: .insertLast(newType, null);
4580: }
4581: }
4582:
4583: private BodyDeclaration createNewFieldDeclarationNode(
4584: IField field, ASTRewrite rewrite,
4585: CompilationUnit sourceCuNode) throws CoreException {
4586: AST targetAst = rewrite.getAST();
4587: BodyDeclaration newDeclaration = null;
4588:
4589: BodyDeclaration bodyDeclaration = ASTNodeSearchUtil
4590: .getFieldOrEnumConstantDeclaration(field,
4591: sourceCuNode);
4592: if (bodyDeclaration instanceof FieldDeclaration) {
4593: FieldDeclaration fieldDeclaration = (FieldDeclaration) bodyDeclaration;
4594: if (fieldDeclaration.fragments().size() == 1)
4595: return (FieldDeclaration) rewrite
4596: .createStringPlaceholder(
4597: getUnindentedSource(field),
4598: ASTNode.FIELD_DECLARATION);
4599: VariableDeclarationFragment originalFragment = ASTNodeSearchUtil
4600: .getFieldDeclarationFragmentNode(field,
4601: sourceCuNode);
4602: VariableDeclarationFragment copiedFragment = (VariableDeclarationFragment) ASTNode
4603: .copySubtree(targetAst, originalFragment);
4604: newDeclaration = targetAst
4605: .newFieldDeclaration(copiedFragment);
4606: ((FieldDeclaration) newDeclaration)
4607: .setType((Type) ASTNode.copySubtree(targetAst,
4608: fieldDeclaration.getType()));
4609: } else if (bodyDeclaration instanceof EnumConstantDeclaration) {
4610: EnumConstantDeclaration constantDeclaration = (EnumConstantDeclaration) bodyDeclaration;
4611: EnumConstantDeclaration newConstDeclaration = targetAst
4612: .newEnumConstantDeclaration();
4613: newConstDeclaration.setName((SimpleName) ASTNode
4614: .copySubtree(targetAst, constantDeclaration
4615: .getName()));
4616: AnonymousClassDeclaration anonymousDeclaration = constantDeclaration
4617: .getAnonymousClassDeclaration();
4618: if (anonymousDeclaration != null) {
4619: String content = ASTNodes.getNodeSource(
4620: anonymousDeclaration, false, true);
4621: if (content != null) {
4622: newConstDeclaration
4623: .setAnonymousClassDeclaration((AnonymousClassDeclaration) rewrite
4624: .createStringPlaceholder(
4625: content,
4626: ASTNode.ANONYMOUS_CLASS_DECLARATION));
4627: }
4628: }
4629: newDeclaration = newConstDeclaration;
4630: } else
4631: Assert.isTrue(false);
4632: if (newDeclaration != null) {
4633: newDeclaration.modifiers().addAll(
4634: ASTNodeFactory.newModifiers(targetAst,
4635: bodyDeclaration.getModifiers()));
4636: Javadoc javadoc = bodyDeclaration.getJavadoc();
4637: if (javadoc != null) {
4638: String content = ASTNodes.getNodeSource(javadoc,
4639: false, true);
4640: if (content != null) {
4641: newDeclaration.setJavadoc((Javadoc) rewrite
4642: .createStringPlaceholder(content,
4643: ASTNode.JAVADOC));
4644: }
4645: }
4646: }
4647:
4648: return newDeclaration;
4649: }
4650:
4651: protected abstract JavaRefactoringDescriptor createRefactoringDescriptor(
4652: final JDTRefactoringDescriptorComment comment,
4653: final Map arguments, final String description,
4654: final String project, int flags);
4655:
4656: public final ChangeDescriptor getDescriptor() {
4657: final Map arguments = new HashMap();
4658: final int length = fJavaElements.length;
4659: final String description = length == 1 ? getDescriptionSingular()
4660: : getDescriptionPlural();
4661: final IProject resource = getSingleProject();
4662: final String project = resource != null ? resource
4663: .getName() : null;
4664: final String header = Messages.format(getHeaderPattern(),
4665: new String[] { String.valueOf(length),
4666: getDestinationLabel() });
4667: int flags = JavaRefactoringDescriptor.JAR_REFACTORING
4668: | JavaRefactoringDescriptor.JAR_MIGRATION
4669: | RefactoringDescriptor.STRUCTURAL_CHANGE
4670: | RefactoringDescriptor.MULTI_CHANGE;
4671: final JDTRefactoringDescriptorComment comment = new JDTRefactoringDescriptorComment(
4672: project, this , header);
4673: arguments.put(ATTRIBUTE_POLICY, getPolicyId());
4674: arguments.put(ATTRIBUTE_MEMBERS, new Integer(
4675: fJavaElements.length).toString());
4676: for (int offset = 0; offset < fJavaElements.length; offset++)
4677: arguments.put(
4678: JavaRefactoringDescriptorUtil.ATTRIBUTE_ELEMENT
4679: + (offset + 1),
4680: JavaRefactoringDescriptorUtil.elementToHandle(
4681: project, fJavaElements[offset]));
4682: arguments.putAll(getRefactoringArguments(project));
4683: final JavaRefactoringDescriptor descriptor = createRefactoringDescriptor(
4684: comment, arguments, description, project, flags);
4685: return new RefactoringChangeDescriptor(descriptor);
4686: }
4687:
4688: public final IJavaElement[] getJavaElements() {
4689: return fJavaElements;
4690: }
4691:
4692: public final IResource[] getResources() {
4693: return new IResource[0];
4694: }
4695:
4696: private IProject getSingleProject() {
4697: IProject result = null;
4698: for (int index = 0; index < fJavaElements.length; index++) {
4699: if (result == null)
4700: result = fJavaElements[index].getJavaProject()
4701: .getProject();
4702: else if (!result.equals(fJavaElements[index]
4703: .getJavaProject().getProject()))
4704: return null;
4705: }
4706: return result;
4707: }
4708:
4709: protected final ICompilationUnit getSourceCu() {
4710: // all have a common parent, so all must be in the same cu
4711: // we checked before that the array in not null and not empty
4712: return getEnclosingCompilationUnit(fJavaElements[0]);
4713: }
4714:
4715: public RefactoringStatus initialize(
4716: RefactoringArguments arguments) {
4717: final RefactoringStatus status = new RefactoringStatus();
4718: if (arguments instanceof JavaRefactoringArguments) {
4719: final JavaRefactoringArguments extended = (JavaRefactoringArguments) arguments;
4720: int memberCount = 0;
4721: String value = extended.getAttribute(ATTRIBUTE_MEMBERS);
4722: if (value != null && !"".equals(value)) {//$NON-NLS-1$
4723: try {
4724: memberCount = Integer.parseInt(value);
4725: } catch (NumberFormatException exception) {
4726: return RefactoringStatus
4727: .createFatalErrorStatus(Messages
4728: .format(
4729: RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
4730: ATTRIBUTE_MEMBERS));
4731: }
4732: } else
4733: return RefactoringStatus
4734: .createFatalErrorStatus(Messages
4735: .format(
4736: RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
4737: ATTRIBUTE_MEMBERS));
4738: String handle = null;
4739: List elements = new ArrayList();
4740: for (int index = 0; index < memberCount; index++) {
4741: final String attribute = JavaRefactoringDescriptorUtil.ATTRIBUTE_ELEMENT
4742: + (index + 1);
4743: handle = extended.getAttribute(attribute);
4744: if (handle != null && !"".equals(handle)) { //$NON-NLS-1$
4745: final IJavaElement element = JavaRefactoringDescriptorUtil
4746: .handleToElement(extended.getProject(),
4747: handle, false);
4748: if (element == null || !element.exists())
4749: status.merge(ScriptableRefactoring
4750: .createInputWarningStatus(element,
4751: getProcessorId(),
4752: getRefactoringId()));
4753: else
4754: elements.add(element);
4755: } else
4756: return RefactoringStatus
4757: .createFatalErrorStatus(Messages
4758: .format(
4759: RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
4760: attribute));
4761: }
4762: fJavaElements = (IJavaElement[]) elements
4763: .toArray(new IJavaElement[elements.size()]);
4764: } else
4765: return RefactoringStatus
4766: .createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
4767: status.merge(super .initialize(arguments));
4768: return status;
4769: }
4770:
4771: protected RefactoringStatus verifyDestination(
4772: IJavaElement destination, int location)
4773: throws JavaModelException {
4774: Assert.isNotNull(destination);
4775: if (!fCheckDestination)
4776: return new RefactoringStatus();
4777: if (!destination.exists())
4778: return RefactoringStatus
4779: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_doesnotexist1);
4780: if (destination instanceof IJavaModel)
4781: return RefactoringStatus
4782: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_jmodel);
4783: if (!(destination instanceof ICompilationUnit)
4784: && !ReorgUtils.isInsideCompilationUnit(destination))
4785: return RefactoringStatus
4786: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot);
4787:
4788: ICompilationUnit destinationCu = getEnclosingCompilationUnit(destination);
4789: Assert.isNotNull(destinationCu);
4790: if (destinationCu.isReadOnly())
4791: return RefactoringStatus
4792: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot_modify);
4793:
4794: switch (destination.getElementType()) {
4795: case IJavaElement.COMPILATION_UNIT:
4796: if (location != IReorgDestination.LOCATION_ON)
4797: return RefactoringStatus
4798: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot);
4799:
4800: int[] types0 = new int[] { IJavaElement.TYPE,
4801: IJavaElement.PACKAGE_DECLARATION,
4802: IJavaElement.IMPORT_CONTAINER,
4803: IJavaElement.IMPORT_DECLARATION };
4804: if (!ReorgUtils.hasOnlyElementsOfType(
4805: getJavaElements(), types0))
4806: return RefactoringStatus
4807: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot);
4808:
4809: break;
4810: case IJavaElement.PACKAGE_DECLARATION: //drop nothing
4811: return RefactoringStatus
4812: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_package_decl);
4813: case IJavaElement.IMPORT_CONTAINER:
4814: if (location == IReorgDestination.LOCATION_ON) {
4815: if (ReorgUtils.hasElementsNotOfType(
4816: getJavaElements(),
4817: IJavaElement.IMPORT_DECLARATION))
4818: return RefactoringStatus
4819: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot);
4820: } else {
4821: if (ReorgUtils.hasElementsNotOfType(
4822: getJavaElements(),
4823: IJavaElement.IMPORT_CONTAINER))
4824: return RefactoringStatus
4825: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot);
4826: }
4827:
4828: break;
4829: case IJavaElement.IMPORT_DECLARATION: //drop import declarations before/after
4830: if (location == IReorgDestination.LOCATION_ON)
4831: return RefactoringStatus
4832: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot);
4833:
4834: if (ReorgUtils.hasElementsNotOfType(getJavaElements(),
4835: IJavaElement.IMPORT_DECLARATION))
4836: return RefactoringStatus
4837: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot);
4838:
4839: break;
4840: case IJavaElement.FIELD:// fall thru
4841: case IJavaElement.INITIALIZER:// fall thru
4842: case IJavaElement.METHOD:// fall thru
4843: if (location == IReorgDestination.LOCATION_ON) {
4844: //can paste on itself (drop on itself is disabled in the SelectionTransferDropAdapter)
4845: if (getJavaElements().length != 1)
4846: return RefactoringStatus
4847: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot);
4848:
4849: if (!(destination.equals(getJavaElements()[0])))
4850: return RefactoringStatus
4851: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot);
4852: } else {
4853: int[] types = new int[] { IJavaElement.FIELD,
4854: IJavaElement.INITIALIZER,
4855: IJavaElement.METHOD, IJavaElement.TYPE };
4856: if (!ReorgUtils.hasOnlyElementsOfType(
4857: getJavaElements(), types))
4858: return RefactoringStatus
4859: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot);
4860: }
4861:
4862: break;
4863: case IJavaElement.TYPE:
4864: if (location == IReorgDestination.LOCATION_ON) {//can drop type members
4865: int[] types1 = new int[] { IJavaElement.FIELD,
4866: IJavaElement.INITIALIZER,
4867: IJavaElement.METHOD, IJavaElement.TYPE };
4868: if (!ReorgUtils.hasOnlyElementsOfType(
4869: getJavaElements(), types1))
4870: return RefactoringStatus
4871: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot);
4872: } else {//can drop type before/after
4873: if (destination.getParent() instanceof IMethod)
4874: return RefactoringStatus
4875: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot);
4876:
4877: int[] types = new int[] { IJavaElement.FIELD,
4878: IJavaElement.INITIALIZER,
4879: IJavaElement.METHOD, IJavaElement.TYPE };
4880: if (!ReorgUtils.hasOnlyElementsOfType(
4881: getJavaElements(), types))
4882: return RefactoringStatus
4883: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot);
4884: }
4885:
4886: break;
4887: }
4888:
4889: return new RefactoringStatus();
4890: }
4891:
4892: /**
4893: * {@inheritDoc}
4894: */
4895: public RefactoringStatus verifyDestination(
4896: IReorgDestination destination)
4897: throws JavaModelException {
4898: if (!(destination instanceof JavaElementDestination))
4899: return RefactoringStatus
4900: .createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_invalidDestinationKind);
4901:
4902: JavaElementDestination javaElementDestination = (JavaElementDestination) destination;
4903: return verifyDestination(javaElementDestination
4904: .getJavaElement(), javaElementDestination
4905: .getLocation());
4906: }
4907:
4908: }
4909:
4910: private static final String ATTRIBUTE_FILES = "files"; //$NON-NLS-1$
4911:
4912: private static final String ATTRIBUTE_FOLDERS = "folders"; //$NON-NLS-1$
4913:
4914: private static final String ATTRIBUTE_FRAGMENTS = "fragments"; //$NON-NLS-1$
4915:
4916: private static final String ATTRIBUTE_LOG = "log"; //$NON-NLS-1$
4917:
4918: private static final String ATTRIBUTE_MEMBERS = "members"; //$NON-NLS-1$
4919:
4920: private static final String ATTRIBUTE_PATTERNS = "patterns"; //$NON-NLS-1$
4921:
4922: private static final String ATTRIBUTE_POLICY = "policy"; //$NON-NLS-1$
4923:
4924: private static final String ATTRIBUTE_QUALIFIED = "qualified"; //$NON-NLS-1$
4925:
4926: private static final String ATTRIBUTE_ROOTS = "roots"; //$NON-NLS-1$
4927:
4928: private static final String ATTRIBUTE_UNITS = "units"; //$NON-NLS-1$
4929:
4930: private static final String DELIMITER_ELEMENT = "\t"; //$NON-NLS-1$
4931:
4932: private static final String DELIMITER_RECORD = "\n"; //$NON-NLS-1$
4933:
4934: private static final String NO_ID = "no_id"; //$NON-NLS-1$
4935:
4936: private static final String NO_POLICY = "no_policy"; //$NON-NLS-1$
4937:
4938: private static final String UNUSED_STRING = "unused"; //$NON-NLS-1$
4939:
4940: private static boolean containsNull(Object[] objects) {
4941: for (int i = 0; i < objects.length; i++) {
4942: if (objects[i] == null)
4943: return true;
4944: }
4945: return false;
4946: }
4947:
4948: public static ICopyPolicy createCopyPolicy(IResource[] resources,
4949: IJavaElement[] javaElements) throws JavaModelException {
4950: return (ICopyPolicy) createReorgPolicy(true, resources,
4951: javaElements);
4952: }
4953:
4954: public static ICopyPolicy createCopyPolicy(
4955: RefactoringStatus status, RefactoringArguments arguments) {
4956: if (arguments instanceof JavaRefactoringArguments) {
4957: final JavaRefactoringArguments extended = (JavaRefactoringArguments) arguments;
4958: final String policy = extended
4959: .getAttribute(ATTRIBUTE_POLICY);
4960: if (policy != null && !"".equals(policy)) { //$NON-NLS-1$
4961: if (CopyFilesFoldersAndCusPolicy.POLICY_COPY_RESOURCE
4962: .equals(policy)) {
4963: return new CopyFilesFoldersAndCusPolicy(null, null,
4964: null);
4965: } else if (CopyPackageFragmentRootsPolicy.POLICY_COPY_ROOTS
4966: .equals(policy)) {
4967: return new CopyPackageFragmentRootsPolicy(null);
4968: } else if (CopyPackagesPolicy.POLICY_COPY_PACKAGES
4969: .equals(policy)) {
4970: return new CopyPackagesPolicy(null);
4971: } else if (CopySubCuElementsPolicy.POLICY_COPY_MEMBERS
4972: .equals(policy)) {
4973: return new CopySubCuElementsPolicy(null);
4974: } else
4975: status
4976: .merge(RefactoringStatus
4977: .createFatalErrorStatus(Messages
4978: .format(
4979: RefactoringCoreMessages.InitializableRefactoring_illegal_argument,
4980: new String[] {
4981: policy,
4982: ATTRIBUTE_POLICY })));
4983: } else
4984: status
4985: .merge(RefactoringStatus
4986: .createFatalErrorStatus(Messages
4987: .format(
4988: RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
4989: ATTRIBUTE_POLICY)));
4990: } else
4991: status
4992: .merge(RefactoringStatus
4993: .createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments));
4994: return null;
4995: }
4996:
4997: public static IMovePolicy createMovePolicy(IResource[] resources,
4998: IJavaElement[] javaElements) throws JavaModelException {
4999: return (IMovePolicy) createReorgPolicy(false, resources,
5000: javaElements);
5001: }
5002:
5003: public static IMovePolicy createMovePolicy(
5004: RefactoringStatus status, RefactoringArguments arguments) {
5005: if (arguments instanceof JavaRefactoringArguments) {
5006: final JavaRefactoringArguments extended = (JavaRefactoringArguments) arguments;
5007: final String policy = extended
5008: .getAttribute(ATTRIBUTE_POLICY);
5009: if (policy != null && !"".equals(policy)) { //$NON-NLS-1$
5010: if (MoveFilesFoldersAndCusPolicy.POLICY_MOVE_RESOURCES
5011: .equals(policy)) {
5012: return new MoveFilesFoldersAndCusPolicy(null, null,
5013: null);
5014: } else if (MovePackageFragmentRootsPolicy.POLICY_MOVE_ROOTS
5015: .equals(policy)) {
5016: return new MovePackageFragmentRootsPolicy(null);
5017: } else if (MovePackagesPolicy.POLICY_MOVE_PACKAGES
5018: .equals(policy)) {
5019: return new MovePackagesPolicy(null);
5020: } else if (MoveMembersPolicy.POLICY_MOVE_MEMBERS
5021: .equals(policy)) {
5022: return new MoveMembersPolicy(null);
5023: } else if (MoveImportDeclarationsPolicy.POLICY_MOVE_IMPORT_DECLARATIONS
5024: .equals(policy)) {
5025: return new MoveImportDeclarationsPolicy(null);
5026: } else
5027: status
5028: .merge(RefactoringStatus
5029: .createFatalErrorStatus(Messages
5030: .format(
5031: RefactoringCoreMessages.InitializableRefactoring_illegal_argument,
5032: new String[] {
5033: policy,
5034: ATTRIBUTE_POLICY })));
5035: } else
5036: status
5037: .merge(RefactoringStatus
5038: .createFatalErrorStatus(Messages
5039: .format(
5040: RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
5041: ATTRIBUTE_POLICY)));
5042: } else
5043: status
5044: .merge(RefactoringStatus
5045: .createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments));
5046: return null;
5047: }
5048:
5049: private static IReorgPolicy createReorgPolicy(boolean copy,
5050: IResource[] selectedResources,
5051: IJavaElement[] selectedJavaElements)
5052: throws JavaModelException {
5053: final IReorgPolicy NO;
5054: if (copy)
5055: NO = new NoCopyPolicy();
5056: else
5057: NO = new NoMovePolicy();
5058:
5059: ActualSelectionComputer selectionComputer = new ActualSelectionComputer(
5060: selectedJavaElements, selectedResources);
5061: IResource[] resources = selectionComputer
5062: .getActualResourcesToReorg();
5063: IJavaElement[] javaElements = selectionComputer
5064: .getActualJavaElementsToReorg();
5065:
5066: if (resources.length == 0 && javaElements.length == 0)
5067: return NO;
5068:
5069: if (containsNull(resources))
5070: return NO;
5071:
5072: if (containsNull(javaElements))
5073: return NO;
5074:
5075: if (ReorgUtils.isArchiveMember(javaElements)
5076: && ReorgUtils.getElementsOfType(javaElements,
5077: IJavaElement.PACKAGE_FRAGMENT_ROOT).size() != javaElements.length)
5078: return NO;
5079:
5080: if (ReorgUtils.hasElementsOfType(javaElements,
5081: IJavaElement.JAVA_PROJECT))
5082: return NO;
5083:
5084: if (ReorgUtils.hasElementsOfType(javaElements,
5085: IJavaElement.JAVA_MODEL))
5086: return NO;
5087:
5088: if (ReorgUtils.hasElementsOfType(resources, IResource.PROJECT
5089: | IResource.ROOT))
5090: return NO;
5091:
5092: if (!new ParentChecker(resources, javaElements)
5093: .haveCommonParent())
5094: return NO;
5095:
5096: if (ReorgUtils.hasElementsOfType(javaElements,
5097: IJavaElement.PACKAGE_FRAGMENT)) {
5098: if (resources.length != 0
5099: || ReorgUtils.hasElementsNotOfType(javaElements,
5100: IJavaElement.PACKAGE_FRAGMENT))
5101: return NO;
5102: if (copy)
5103: return new CopyPackagesPolicy(ArrayTypeConverter
5104: .toPackageArray(javaElements));
5105: else
5106: return new MovePackagesPolicy(ArrayTypeConverter
5107: .toPackageArray(javaElements));
5108: }
5109:
5110: if (ReorgUtils.hasElementsOfType(javaElements,
5111: IJavaElement.PACKAGE_FRAGMENT_ROOT)) {
5112: if (resources.length != 0
5113: || ReorgUtils.hasElementsNotOfType(javaElements,
5114: IJavaElement.PACKAGE_FRAGMENT_ROOT))
5115: return NO;
5116: if (copy)
5117: return new CopyPackageFragmentRootsPolicy(
5118: ArrayTypeConverter
5119: .toPackageFragmentRootArray(javaElements));
5120: else
5121: return new MovePackageFragmentRootsPolicy(
5122: ArrayTypeConverter
5123: .toPackageFragmentRootArray(javaElements));
5124: }
5125:
5126: if (ReorgUtils.hasElementsOfType(resources, IResource.FILE
5127: | IResource.FOLDER)
5128: || ReorgUtils.hasElementsOfType(javaElements,
5129: IJavaElement.COMPILATION_UNIT)) {
5130: if (ReorgUtils.hasElementsNotOfType(javaElements,
5131: IJavaElement.COMPILATION_UNIT))
5132: return NO;
5133: if (ReorgUtils.hasElementsNotOfType(resources,
5134: IResource.FILE | IResource.FOLDER))
5135: return NO;
5136: if (copy)
5137: return new CopyFilesFoldersAndCusPolicy(ReorgUtils
5138: .getFiles(resources), ReorgUtils
5139: .getFolders(resources), ArrayTypeConverter
5140: .toCuArray(javaElements));
5141: else
5142: return new MoveFilesFoldersAndCusPolicy(ReorgUtils
5143: .getFiles(resources), ReorgUtils
5144: .getFolders(resources), ArrayTypeConverter
5145: .toCuArray(javaElements));
5146: }
5147:
5148: if (hasOnlyMembers(javaElements)) {
5149: if (hasAnonymousClassDeclarations(javaElements))
5150: return NO;
5151:
5152: if (copy) {
5153: return new CopySubCuElementsPolicy(javaElements);
5154: } else {
5155: List members = Arrays.asList(javaElements);
5156: return new MoveMembersPolicy((IMember[]) members
5157: .toArray(new IMember[members.size()]));
5158: }
5159: }
5160:
5161: if (hasOnlyImportDeclarations(javaElements)) {
5162: if (copy) {
5163: return new CopySubCuElementsPolicy(javaElements);
5164: } else {
5165: List declarations = ReorgUtils.getElementsOfType(
5166: javaElements, IJavaElement.IMPORT_DECLARATION);
5167: return new MoveImportDeclarationsPolicy(
5168: (IImportDeclaration[]) declarations
5169: .toArray(new IImportDeclaration[declarations
5170: .size()]));
5171: }
5172: }
5173:
5174: if (copy && hasElementsSmallerThanCuOrClassFile(javaElements)) {
5175: if (ReorgUtils.hasElementsOfType(javaElements,
5176: IJavaElement.PACKAGE_DECLARATION))
5177: return NO;
5178:
5179: if (hasAnonymousClassDeclarations(javaElements))
5180: return NO;
5181:
5182: Assert.isTrue(resources.length == 0);
5183: return new CopySubCuElementsPolicy(javaElements);
5184: }
5185:
5186: return NO;
5187: }
5188:
5189: private static boolean hasAnonymousClassDeclarations(
5190: IJavaElement[] javaElements) throws JavaModelException {
5191: for (int i = 0; i < javaElements.length; i++) {
5192: if (javaElements[i] instanceof IType) {
5193: IType type = (IType) javaElements[i];
5194: if (type.isAnonymous())
5195: return true;
5196: }
5197: }
5198: return false;
5199: }
5200:
5201: private static boolean hasElementsSmallerThanCuOrClassFile(
5202: IJavaElement[] javaElements) {
5203: for (int i = 0; i < javaElements.length; i++) {
5204: if (ReorgUtils.isInsideCompilationUnit(javaElements[i]))
5205: return true;
5206: if (ReorgUtils.isInsideClassFile(javaElements[i]))
5207: return true;
5208: }
5209: return false;
5210: }
5211:
5212: private static boolean hasOnlyImportDeclarations(
5213: IJavaElement[] javaElements) {
5214: for (int i = 0; i < javaElements.length; i++) {
5215: if (javaElements[i].getElementType() != IJavaElement.IMPORT_DECLARATION)
5216: return false;
5217: }
5218: return true;
5219: }
5220:
5221: private static boolean hasOnlyMembers(IJavaElement[] javaElements) {
5222: for (int i = 0; i < javaElements.length; i++) {
5223: if (!(javaElements[i] instanceof IMember))
5224: return false;
5225: }
5226: return true;
5227: }
5228:
5229: public static CreateTargetExecutionLog loadCreateTargetExecutionLog(
5230: JavaRefactoringArguments arguments) {
5231: CreateTargetExecutionLog log = new CreateTargetExecutionLog();
5232: final String value = arguments.getAttribute(ATTRIBUTE_LOG);
5233: if (value != null) {
5234: final StringTokenizer tokenizer = new StringTokenizer(
5235: value, DELIMITER_RECORD, false);
5236: while (tokenizer.hasMoreTokens()) {
5237: final String token = tokenizer.nextToken();
5238: processCreateTargetExecutionRecord(log, arguments,
5239: token);
5240: }
5241: }
5242: return log;
5243: }
5244:
5245: public static ReorgExecutionLog loadReorgExecutionLog(
5246: JavaRefactoringArguments arguments) {
5247: ReorgExecutionLog log = new ReorgExecutionLog();
5248: final String value = arguments.getAttribute(ATTRIBUTE_LOG);
5249: if (value != null) {
5250: final StringTokenizer tokenizer = new StringTokenizer(
5251: value, DELIMITER_RECORD, false);
5252: while (tokenizer.hasMoreTokens()) {
5253: final String token = tokenizer.nextToken();
5254: processReorgExecutionRecord(log, arguments, token);
5255: }
5256: }
5257: return log;
5258: }
5259:
5260: private static void processCreateTargetExecutionRecord(
5261: CreateTargetExecutionLog log,
5262: JavaRefactoringArguments arguments, String token) {
5263: final StringTokenizer tokenizer = new StringTokenizer(token,
5264: DELIMITER_ELEMENT, false);
5265: String value = null;
5266: if (tokenizer.hasMoreTokens()) {
5267: value = tokenizer.nextToken();
5268: Object selection = JavaRefactoringDescriptorUtil
5269: .handleToElement(arguments.getProject(), value,
5270: false);
5271: if (selection == null)
5272: selection = JavaRefactoringDescriptorUtil
5273: .handleToResource(arguments.getProject(), value);
5274: if (selection != null && tokenizer.hasMoreTokens()) {
5275: value = tokenizer.nextToken();
5276: Object created = JavaRefactoringDescriptorUtil
5277: .handleToElement(arguments.getProject(), value,
5278: false);
5279: if (created == null)
5280: created = JavaRefactoringDescriptorUtil
5281: .handleToResource(arguments.getProject(),
5282: value);
5283: if (created != null)
5284: log.markAsCreated(selection, created);
5285: }
5286: }
5287: }
5288:
5289: private static void processReorgExecutionRecord(
5290: ReorgExecutionLog log, JavaRefactoringArguments arguments,
5291: String token) {
5292: final StringTokenizer tokenizer = new StringTokenizer(token,
5293: DELIMITER_ELEMENT, false);
5294: String value = null;
5295: if (tokenizer.hasMoreTokens()) {
5296: value = tokenizer.nextToken();
5297: Object element = JavaRefactoringDescriptorUtil
5298: .handleToElement(arguments.getProject(), value);
5299: if (element == null)
5300: element = JavaRefactoringDescriptorUtil
5301: .handleToResource(arguments.getProject(), value);
5302: if (tokenizer.hasMoreTokens()) {
5303: final boolean processed = Boolean.valueOf(
5304: tokenizer.nextToken()).booleanValue();
5305: if (processed) {
5306: log.markAsProcessed(element);
5307: if (element instanceof IJavaElement)
5308: log.markAsProcessed(JavaElementResourceMapping
5309: .create((IJavaElement) element));
5310: }
5311: if (tokenizer.hasMoreTokens()) {
5312: final boolean renamed = Boolean.valueOf(
5313: tokenizer.nextToken()).booleanValue();
5314: if (renamed && tokenizer.hasMoreTokens()) {
5315: final String name = tokenizer.nextToken();
5316: log.setNewName(element, name);
5317: if (element instanceof IJavaElement)
5318: log.setNewName(JavaElementResourceMapping
5319: .create((IJavaElement) element),
5320: name);
5321: }
5322: }
5323: }
5324: }
5325: }
5326:
5327: public static void storeCreateTargetExecutionLog(String project,
5328: Map arguments, CreateTargetExecutionLog log) {
5329: if (log != null) {
5330: final StringBuffer buffer = new StringBuffer(64);
5331: final Object[] selections = log.getSelectedElements();
5332: for (int index = 0; index < selections.length; index++) {
5333: final Object selection = selections[index];
5334: if (selection != null) {
5335: final Object created = log
5336: .getCreatedElement(selection);
5337: if (created != null) {
5338: storeLogElement(buffer, project, selection);
5339: buffer.append(DELIMITER_ELEMENT);
5340: storeLogElement(buffer, project, created);
5341: buffer.append(DELIMITER_RECORD);
5342: }
5343:
5344: }
5345: }
5346: final String value = new String(buffer.toString().trim());
5347: if (!"".equals(value)) //$NON-NLS-1$
5348: arguments.put(ATTRIBUTE_LOG, value);
5349: }
5350: }
5351:
5352: private static boolean storeLogElement(StringBuffer buffer,
5353: String project, Object object) {
5354: if (object instanceof IJavaElement) {
5355: final IJavaElement element = (IJavaElement) object;
5356: buffer.append(JavaRefactoringDescriptorUtil
5357: .elementToHandle(project, element));
5358: return true;
5359: } else if (object instanceof IResource) {
5360: final IResource resource = (IResource) object;
5361: buffer.append(JavaRefactoringDescriptorUtil
5362: .resourceToHandle(project, resource));
5363: return true;
5364: }
5365: return false;
5366: }
5367:
5368: public static void storeReorgExecutionLog(String project,
5369: Map arguments, ReorgExecutionLog log) {
5370: if (log != null) {
5371: final Set set = new HashSet();
5372: set.addAll(Arrays.asList(log.getProcessedElements()));
5373: set.addAll(Arrays.asList(log.getRenamedElements()));
5374: final StringBuffer buffer = new StringBuffer(64);
5375: for (final Iterator iterator = set.iterator(); iterator
5376: .hasNext();) {
5377: final Object object = iterator.next();
5378: if (storeLogElement(buffer, project, object)) {
5379: buffer.append(DELIMITER_ELEMENT);
5380: buffer.append(log.isProcessed(object));
5381: buffer.append(DELIMITER_ELEMENT);
5382: final boolean renamed = log.isRenamed(object);
5383: buffer.append(renamed);
5384: if (renamed) {
5385: buffer.append(DELIMITER_ELEMENT);
5386: buffer.append(log.getNewName(object));
5387: }
5388: buffer.append(DELIMITER_RECORD);
5389: }
5390: }
5391: final String value = new String(buffer.toString().trim());
5392: if (!"".equals(value)) //$NON-NLS-1$
5393: arguments.put(ATTRIBUTE_LOG, value);
5394: }
5395: }
5396:
5397: private ReorgPolicyFactory() {
5398: // private
5399: }
5400: }
|