use of org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor in project che by eclipse.
the class RenameTypeProcessor method initializeSimilarElementsRenameProcessors.
// --------- Similar names
/**
* Creates and initializes the refactoring processors for similarly named elements
* @param progressMonitor progress monitor
* @param context context
* @return status
* @throws CoreException should not happen
*/
private RefactoringStatus initializeSimilarElementsRenameProcessors(IProgressMonitor progressMonitor, CheckConditionsContext context) throws CoreException {
Assert.isNotNull(fPreloadedElementToName);
Assert.isNotNull(fPreloadedElementToSelection);
final RefactoringStatus status = new RefactoringStatus();
final Set<IMethod> handledTopLevelMethods = new HashSet<IMethod>();
final Set<Warning> warnings = new HashSet<Warning>();
final List<RefactoringProcessor> processors = new ArrayList<RefactoringProcessor>();
fFinalSimilarElementToName = new HashMap<IJavaElement, String>();
CompilationUnit currentResolvedCU = null;
ICompilationUnit currentCU = null;
int current = 0;
final int max = fPreloadedElementToName.size();
//$NON-NLS-1$
progressMonitor.beginTask("", max * 3);
progressMonitor.setTaskName(RefactoringCoreMessages.RenameTypeProcessor_checking_similarly_named_declarations_refactoring_conditions);
for (Iterator<IJavaElement> iter = fPreloadedElementToName.keySet().iterator(); iter.hasNext(); ) {
final IJavaElement element = iter.next();
current++;
progressMonitor.worked(3);
// not selected? -> skip
if (!(fPreloadedElementToSelection.get(element)).booleanValue())
continue;
// already registered? (may happen with overridden methods) -> skip
if (fFinalSimilarElementToName.containsKey(element))
continue;
// CompilationUnit changed? (note: fPreloadedElementToName is sorted by CompilationUnit)
ICompilationUnit newCU = (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT);
if (!newCU.equals(currentCU)) {
checkCUCompleteConditions(status, currentResolvedCU, currentCU, processors);
if (status.hasFatalError())
return status;
// reset values
currentResolvedCU = null;
currentCU = newCU;
processors.clear();
}
final String newName = fPreloadedElementToName.get(element);
RefactoringProcessor processor = null;
if (element instanceof ILocalVariable) {
final ILocalVariable currentLocal = (ILocalVariable) element;
if (currentResolvedCU == null)
currentResolvedCU = new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(currentCU, true);
processor = createLocalRenameProcessor(currentLocal, newName, currentResolvedCU);
if (status.hasFatalError())
return status;
fFinalSimilarElementToName.put(currentLocal, newName);
}
if (element instanceof IField) {
final IField currentField = (IField) element;
processor = createFieldRenameProcessor(currentField, newName);
status.merge(checkForConflictingRename(currentField, newName));
if (status.hasFatalError())
return status;
fFinalSimilarElementToName.put(currentField, newName);
}
if (element instanceof IMethod) {
IMethod currentMethod = (IMethod) element;
if (MethodChecks.isVirtual(currentMethod)) {
final IType declaringType = currentMethod.getDeclaringType();
ITypeHierarchy hierarchy = null;
if (!declaringType.isInterface())
hierarchy = declaringType.newTypeHierarchy(new NullProgressMonitor());
final IMethod topmost = MethodChecks.getTopmostMethod(currentMethod, hierarchy, new NullProgressMonitor());
if (topmost != null)
currentMethod = topmost;
if (handledTopLevelMethods.contains(currentMethod))
continue;
handledTopLevelMethods.add(currentMethod);
final IMethod[] ripples = RippleMethodFinder2.getRelatedMethods(currentMethod, new NullProgressMonitor(), null);
if (checkForWarnings(warnings, newName, ripples))
continue;
status.merge(checkForConflictingRename(ripples, newName));
if (status.hasFatalError())
return status;
processor = createVirtualMethodRenameProcessor(currentMethod, newName, ripples, hierarchy);
fFinalSimilarElementToName.put(currentMethod, newName);
for (int i = 0; i < ripples.length; i++) {
fFinalSimilarElementToName.put(ripples[i], newName);
}
} else {
status.merge(checkForConflictingRename(new IMethod[] { currentMethod }, newName));
if (status.hasFatalError())
break;
fFinalSimilarElementToName.put(currentMethod, newName);
processor = createNonVirtualMethodRenameProcessor(currentMethod, newName);
}
}
progressMonitor.subTask(Messages.format(RefactoringCoreMessages.RenameTypeProcessor_progress_current_total, new Object[] { String.valueOf(current), String.valueOf(max) }));
status.merge(processor.checkInitialConditions(new NoOverrideProgressMonitor(progressMonitor, 1)));
if (status.hasFatalError())
return status;
status.merge(processor.checkFinalConditions(new NoOverrideProgressMonitor(progressMonitor, 1), context));
if (status.hasFatalError())
return status;
processors.add(processor);
progressMonitor.worked(1);
if (progressMonitor.isCanceled())
throw new OperationCanceledException();
}
// check last CU
checkCUCompleteConditions(status, currentResolvedCU, currentCU, processors);
status.merge(addWarnings(warnings));
progressMonitor.done();
return status;
}
use of org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor in project che by eclipse.
the class RenameTypeProcessor method checkCUCompleteConditions.
private void checkCUCompleteConditions(final RefactoringStatus status, CompilationUnit currentResolvedCU, ICompilationUnit currentCU, List<RefactoringProcessor> processors) throws CoreException {
// check local variable conditions
List<RefactoringProcessor> locals = getProcessorsOfType(processors, RenameLocalVariableProcessor.class);
if (!locals.isEmpty()) {
RenameAnalyzeUtil.LocalAnalyzePackage[] analyzePackages = new RenameAnalyzeUtil.LocalAnalyzePackage[locals.size()];
TextChangeManager manager = new TextChangeManager();
int current = 0;
TextChange textChange = manager.get(currentCU);
textChange.setKeepPreviewEdits(true);
for (Iterator<RefactoringProcessor> iterator = locals.iterator(); iterator.hasNext(); ) {
RenameLocalVariableProcessor localProcessor = (RenameLocalVariableProcessor) iterator.next();
RenameAnalyzeUtil.LocalAnalyzePackage analyzePackage = localProcessor.getLocalAnalyzePackage();
analyzePackages[current] = analyzePackage;
for (int i = 0; i < analyzePackage.fOccurenceEdits.length; i++) {
//$NON-NLS-1$
TextChangeCompatibility.addTextEdit(textChange, "", analyzePackage.fOccurenceEdits[i], GroupCategorySet.NONE);
}
current++;
}
status.merge(RenameAnalyzeUtil.analyzeLocalRenames(analyzePackages, textChange, currentResolvedCU, false));
}
/*
* There is room for performance improvement here: One could move
* shadowing analyzes out of the field and method processors and perform
* it here, thus saving on working copy creation. Drawback is increased
* heap consumption.
*/
}
use of org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor in project che by eclipse.
the class RenamePackageTest method testPackageRenameWithResource1.
@Test
public void testPackageRenameWithResource1() throws Exception {
IPackageFragment fragment = getRoot().createPackageFragment("org.test", true, null);
StringBuffer buf = new StringBuffer();
buf.append("package org.test;\n");
buf.append("public class MyClass {\n");
buf.append(" org.test.MyClass me;\n");
buf.append("}\n");
fragment.createCompilationUnit("MyClass.java", buf.toString(), true, null);
IFile file = ((IFolder) getRoot().getResource()).getFile("x.properties");
byte[] content = "This is about 'org.test' and more".getBytes();
file.create(new ByteArrayInputStream(content), true, null);
file.refreshLocal(IResource.DEPTH_ONE, null);
RenameJavaElementDescriptor descriptor = RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_PACKAGE);
descriptor.setJavaElement(fragment);
descriptor.setNewName("org.test2");
descriptor.setUpdateReferences(true);
descriptor.setUpdateQualifiedNames(true);
descriptor.setFileNamePatterns("*.properties");
Refactoring refactoring = createRefactoring(descriptor);
RefactoringStatus status = performRefactoring(refactoring);
if (status != null)
assertTrue(status.toString(), status.isOK());
RefactoringProcessor processor = ((RenameRefactoring) refactoring).getProcessor();
IResourceMapper rm = (IResourceMapper) processor.getAdapter(IResourceMapper.class);
IJavaElementMapper jm = (IJavaElementMapper) processor.getAdapter(IJavaElementMapper.class);
checkMappingUnchanged(jm, rm, new Object[] { getRoot().getJavaProject(), getRoot(), file });
IFile newFile = ((IContainer) getRoot().getResource()).getFile(new Path("x.properties"));
assertEquals("This is about 'org.test2' and more", getContents(newFile));
checkMappingChanged(jm, rm, new Object[][] { { fragment, getRoot().getPackageFragment("org.test2") } });
}
use of org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor in project che by eclipse.
the class RenamePackageTest method helper2.
private RenamePackageProcessor helper2(String[] packageNames, String[][] packageFileNames, String newPackageName) throws Exception {
ParticipantTesting.reset();
IPackageFragment[] packages = new IPackageFragment[packageNames.length];
ICompilationUnit[][] cus = new ICompilationUnit[packageFileNames.length][packageFileNames[0].length];
for (int i = 0; i < packageNames.length; i++) {
packages[i] = getRoot().createPackageFragment(packageNames[i], true, null);
for (int j = 0; j < packageFileNames[i].length; j++) {
cus[i][j] = createCUfromTestFile(packages[i], packageFileNames[i][j], packageNames[i].replace('.', '/') + "/");
}
}
IPackageFragment thisPackage = packages[0];
boolean hasSubpackages = thisPackage.hasSubpackages();
IPath path = thisPackage.getParent().getPath();
path = path.append(newPackageName.replace('.', '/'));
IFolder target = ResourcesPlugin.getWorkspace().getRoot().getFolder(path);
boolean targetExists = target.exists();
boolean isRename = !targetExists && !thisPackage.hasSubpackages() && thisPackage.getResource().getParent().equals(target.getParent());
String[] createHandles = null;
String[] moveHandles = null;
String[] deleteHandles = null;
boolean doDelete = true;
String[] renameHandles = null;
if (isRename) {
renameHandles = ParticipantTesting.createHandles(thisPackage, thisPackage.getResource());
} else {
renameHandles = ParticipantTesting.createHandles(thisPackage);
IContainer loop = target;
List handles = new ArrayList();
while (loop != null && !loop.exists()) {
handles.add(ParticipantTesting.createHandles(loop)[0]);
loop = loop.getParent();
}
createHandles = (String[]) handles.toArray(new String[handles.size()]);
IFolder source = (IFolder) thisPackage.getResource();
deleteHandles = ParticipantTesting.createHandles(source);
IResource[] members = source.members();
List movedObjects = new ArrayList();
for (int i = 0; i < members.length; i++) {
if (members[i] instanceof IFolder) {
doDelete = false;
} else {
movedObjects.add(members[i]);
}
}
moveHandles = ParticipantTesting.createHandles(movedObjects.toArray());
}
RenameJavaElementDescriptor descriptor = createRefactoringDescriptor(thisPackage, newPackageName);
descriptor.setUpdateReferences(fUpdateReferences);
descriptor.setUpdateTextualOccurrences(fUpdateTextualMatches);
setFilePatterns(descriptor);
Refactoring refactoring = createRefactoring(descriptor);
RefactoringStatus result = performRefactoring(refactoring);
TestCase.assertEquals("preconditions were supposed to pass", null, result);
if (isRename) {
ParticipantTesting.testRename(renameHandles, new RenameArguments[] { new RenameArguments(newPackageName, fUpdateReferences), new RenameArguments(target.getName(), fUpdateReferences) });
} else {
ParticipantTesting.testRename(renameHandles, new RenameArguments[] { new RenameArguments(newPackageName, fUpdateReferences) });
ParticipantTesting.testCreate(createHandles);
List args = new ArrayList();
for (int i = 0; i < packageFileNames[0].length; i++) {
args.add(new MoveArguments(target, fUpdateReferences));
}
ParticipantTesting.testMove(moveHandles, (MoveArguments[]) args.toArray(new MoveArguments[args.size()]));
if (doDelete) {
ParticipantTesting.testDelete(deleteHandles);
} else {
ParticipantTesting.testDelete(new String[0]);
}
}
if (hasSubpackages) {
assertTrue("old package does not exist anymore", getRoot().getPackageFragment(packageNames[0]).exists());
} else {
assertTrue("package not renamed", !getRoot().getPackageFragment(packageNames[0]).exists());
}
IPackageFragment newPackage = getRoot().getPackageFragment(newPackageName);
assertTrue("new package does not exist", newPackage.exists());
for (int i = 0; i < packageFileNames.length; i++) {
String packageName = (i == 0) ? newPackageName.replace('.', '/') + "/" : packageNames[i].replace('.', '/') + "/";
for (int j = 0; j < packageFileNames[i].length; j++) {
String s1 = getFileContents(getOutputTestFileName(packageFileNames[i][j], packageName));
ICompilationUnit cu = (i == 0) ? newPackage.getCompilationUnit(packageFileNames[i][j] + ".java") : cus[i][j];
//DebugUtils.dump("cu:" + cu.getElementName());
String s2 = cu.getSource();
//DebugUtils.dump("expected:" + s1);
//DebugUtils.dump("was:" + s2);
assertEqualLines("invalid update in file " + cu.getElementName(), s1, s2);
}
}
RefactoringProcessor processor = ((ProcessorBasedRefactoring) refactoring).getProcessor();
return (RenamePackageProcessor) processor;
}
use of org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor in project che by eclipse.
the class JDTRefactoringDescriptorComment method initializeInferredSettings.
/**
* Initializes the inferred settings.
*
* @param object
* the refactoring object
*/
private void initializeInferredSettings(final Object object) {
if (object instanceof INameUpdating) {
final INameUpdating updating = (INameUpdating) object;
fSettings.add(Messages.format(RefactoringCoreMessages.JavaRefactoringDescriptor_original_element_pattern, JavaElementLabels.getTextLabel(updating.getElements()[0], JavaElementLabels.ALL_FULLY_QUALIFIED)));
try {
final Object element = updating.getNewElement();
if (element != null)
fSettings.add(Messages.format(RefactoringCoreMessages.JavaRefactoringDescriptor_renamed_element_pattern, JavaElementLabels.getTextLabel(element, JavaElementLabels.ALL_FULLY_QUALIFIED)));
else {
final String newLabel = BasicElementLabels.getJavaElementName(updating.getCurrentElementName());
fSettings.add(Messages.format(RefactoringCoreMessages.JavaRefactoringDescriptor_renamed_element_pattern, newLabel));
}
} catch (CoreException exception) {
JavaPlugin.log(exception);
}
} else if (object instanceof RefactoringProcessor) {
final RefactoringProcessor processor = (RefactoringProcessor) object;
final Object[] elements = processor.getElements();
if (elements != null) {
if (elements.length == 1 && elements[0] != null)
fSettings.add(Messages.format(RefactoringCoreMessages.JavaRefactoringDescriptor_original_element_pattern, JavaElementLabels.getTextLabel(elements[0], JavaElementLabels.ALL_FULLY_QUALIFIED)));
else if (elements.length > 1) {
final StringBuffer buffer = new StringBuffer(128);
buffer.append(RefactoringCoreMessages.JavaRefactoringDescriptor_original_elements);
for (int index = 0; index < elements.length; index++) {
if (elements[index] != null) {
buffer.append(LINE_DELIMITER);
buffer.append(ELEMENT_DELIMITER);
buffer.append(JavaElementLabels.getTextLabel(elements[index], JavaElementLabels.ALL_FULLY_QUALIFIED));
} else {
buffer.append(LINE_DELIMITER);
buffer.append(ELEMENT_DELIMITER);
buffer.append(RefactoringCoreMessages.JavaRefactoringDescriptor_not_available);
}
}
fSettings.add(buffer.toString());
}
}
} else if (object instanceof IReorgPolicy) {
final IReorgPolicy policy = (IReorgPolicy) object;
Object destination = policy.getJavaElementDestination();
if (destination != null)
fSettings.add(Messages.format(RefactoringCoreMessages.JavaRefactoringDescriptorComment_destination_pattern, JavaElementLabels.getTextLabel(destination, JavaElementLabels.ALL_FULLY_QUALIFIED)));
else {
destination = policy.getResourceDestination();
if (destination != null)
fSettings.add(Messages.format(RefactoringCoreMessages.JavaRefactoringDescriptorComment_destination_pattern, JavaElementLabels.getTextLabel(destination, JavaElementLabels.ALL_FULLY_QUALIFIED)));
}
final List<IAdaptable> list = new ArrayList<IAdaptable>();
list.addAll(Arrays.asList(policy.getJavaElements()));
list.addAll(Arrays.asList(policy.getResources()));
final Object[] elements = list.toArray();
if (elements != null) {
if (elements.length == 1 && elements[0] != null)
fSettings.add(Messages.format(RefactoringCoreMessages.JavaRefactoringDescriptor_original_element_pattern, JavaElementLabels.getTextLabel(elements[0], JavaElementLabels.ALL_FULLY_QUALIFIED)));
else if (elements.length > 1) {
final StringBuffer buffer = new StringBuffer(128);
buffer.append(RefactoringCoreMessages.JavaRefactoringDescriptor_original_elements);
for (int index = 0; index < elements.length; index++) {
if (elements[index] != null) {
buffer.append(LINE_DELIMITER);
buffer.append(ELEMENT_DELIMITER);
buffer.append(JavaElementLabels.getTextLabel(elements[index], JavaElementLabels.ALL_FULLY_QUALIFIED));
} else {
buffer.append(LINE_DELIMITER);
buffer.append(ELEMENT_DELIMITER);
buffer.append(RefactoringCoreMessages.JavaRefactoringDescriptor_not_available);
}
}
fSettings.add(buffer.toString());
}
}
if (object instanceof IMovePolicy) {
final IMovePolicy extended = (IMovePolicy) object;
if (extended.isTextualMove())
fSettings.add(RefactoringCoreMessages.JavaRefactoringDescriptorComment_textual_move_only);
}
}
if (object instanceof IReferenceUpdating) {
final IReferenceUpdating updating = (IReferenceUpdating) object;
if (updating.getUpdateReferences())
fSettings.add(RefactoringCoreMessages.JavaRefactoringDescriptor_update_references);
}
if (object instanceof ISimilarDeclarationUpdating) {
final ISimilarDeclarationUpdating updating = (ISimilarDeclarationUpdating) object;
if (updating.canEnableSimilarDeclarationUpdating() && updating.getUpdateSimilarDeclarations()) {
final int strategy = updating.getMatchStrategy();
if (strategy == RenamingNameSuggestor.STRATEGY_EXACT)
fSettings.add(RefactoringCoreMessages.JavaRefactoringDescriptor_rename_similar);
else if (strategy == RenamingNameSuggestor.STRATEGY_EMBEDDED)
fSettings.add(RefactoringCoreMessages.JavaRefactoringDescriptor_rename_similar_embedded);
else if (strategy == RenamingNameSuggestor.STRATEGY_SUFFIX)
fSettings.add(RefactoringCoreMessages.JavaRefactoringDescriptor_rename_similar_suffix);
}
}
if (object instanceof IQualifiedNameUpdating) {
final IQualifiedNameUpdating updating = (IQualifiedNameUpdating) object;
if (updating.canEnableQualifiedNameUpdating() && updating.getUpdateQualifiedNames()) {
final String patterns = updating.getFilePatterns();
if (//$NON-NLS-1$
patterns != null && !"".equals(patterns))
fSettings.add(Messages.format(RefactoringCoreMessages.JavaRefactoringDescriptor_qualified_names_pattern, BasicElementLabels.getFilePattern(patterns.trim())));
else
fSettings.add(RefactoringCoreMessages.JavaRefactoringDescriptor_qualified_names);
}
}
if (object instanceof ITextUpdating) {
final ITextUpdating updating = (ITextUpdating) object;
if (updating.canEnableTextUpdating())
fSettings.add(RefactoringCoreMessages.JavaRefactoringDescriptor_textual_occurrences);
}
if (object instanceof IDelegateUpdating) {
final IDelegateUpdating updating = (IDelegateUpdating) object;
if (updating.canEnableDelegateUpdating() && updating.getDelegateUpdating()) {
if (updating.getDeprecateDelegates())
fSettings.add(RefactoringCoreMessages.JavaRefactoringDescriptor_keep_original_deprecated);
else
fSettings.add(RefactoringCoreMessages.JavaRefactoringDescriptor_keep_original);
}
}
}
Aggregations