private void addAccessorOccurrences( IProgressMonitor pm, IMethod accessor, String editName, String newAccessorName, RefactoringStatus status) throws CoreException { Assert.isTrue(accessor.exists()); IJavaSearchScope scope = RefactoringScopeFactory.create(accessor); SearchPattern pattern = SearchPattern.createPattern( accessor, IJavaSearchConstants.ALL_OCCURRENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE); SearchResultGroup[] groupedResults = RefactoringSearchEngine.search( pattern, scope, new MethodOccurenceCollector(accessor.getElementName()), pm, status); for (int i = 0; i < groupedResults.length; i++) { ICompilationUnit cu = groupedResults[i].getCompilationUnit(); if (cu == null) continue; SearchMatch[] results = groupedResults[i].getSearchResults(); for (int j = 0; j < results.length; j++) { SearchMatch searchResult = results[j]; TextEdit edit = new ReplaceEdit(searchResult.getOffset(), searchResult.getLength(), newAccessorName); addTextEdit(fChangeManager.get(cu), editName, edit); } } }
private void addDeclarationUpdate() throws CoreException { ISourceRange nameRange = fField.getNameRange(); TextEdit textEdit = new ReplaceEdit(nameRange.getOffset(), nameRange.getLength(), getNewElementName()); ICompilationUnit cu = fField.getCompilationUnit(); String groupName = RefactoringCoreMessages.RenameFieldRefactoring_Update_field_declaration; addTextEdit(fChangeManager.get(cu), groupName, textEdit); }
static ICompilationUnit createNewWorkingCopy( ICompilationUnit cu, TextChangeManager manager, WorkingCopyOwner owner, SubProgressMonitor pm) throws CoreException { ICompilationUnit newWc = cu.getWorkingCopy(owner, null); String previewContent = manager.get(cu).getPreviewContent(new NullProgressMonitor()); newWc.getBuffer().setContents(previewContent); newWc.reconcile(ICompilationUnit.NO_AST, false, owner, pm); return newWc; }
@Override public Change createChange(IProgressMonitor monitor) throws CoreException { try { final TextChange[] changes = fChangeManager.getAllChanges(); final List<TextChange> list = new ArrayList<>(changes.length); list.addAll(Arrays.asList(changes)); String project = null; IJavaProject javaProject = fMethod.getJavaProject(); if (javaProject != null) project = javaProject.getElementName(); int flags = JavaRefactoringDescriptor.JAR_MIGRATION | JavaRefactoringDescriptor.JAR_REFACTORING | RefactoringDescriptor.STRUCTURAL_CHANGE; try { if (!Flags.isPrivate(fMethod.getFlags())) flags |= RefactoringDescriptor.MULTI_CHANGE; } catch (JavaModelException exception) { JavaPlugin.log(exception); } final IType declaring = fMethod.getDeclaringType(); try { if (declaring.isAnonymous() || declaring.isLocal()) flags |= JavaRefactoringDescriptor.JAR_SOURCE_ATTACHMENT; } catch (JavaModelException exception) { JavaPlugin.log(exception); } final String description = Messages.format( RefactoringCoreMessages.RenameMethodProcessor_descriptor_description_short, BasicElementLabels.getJavaElementName(fMethod.getElementName())); final String header = Messages.format( RefactoringCoreMessages.RenameMethodProcessor_descriptor_description, new String[] { JavaElementLabels.getTextLabel(fMethod, JavaElementLabels.ALL_FULLY_QUALIFIED), BasicElementLabels.getJavaElementName(getNewElementName()) }); final String comment = new JDTRefactoringDescriptorComment(project, this, header).asString(); final RenameJavaElementDescriptor descriptor = RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor( IJavaRefactorings.RENAME_METHOD); descriptor.setProject(project); descriptor.setDescription(description); descriptor.setComment(comment); descriptor.setFlags(flags); descriptor.setJavaElement(fMethod); descriptor.setNewName(getNewElementName()); descriptor.setUpdateReferences(fUpdateReferences); descriptor.setKeepOriginal(fDelegateUpdating); descriptor.setDeprecateDelegate(fDelegateDeprecation); return new DynamicValidationRefactoringChange( descriptor, RefactoringCoreMessages.RenameMethodProcessor_change_name, list.toArray(new Change[list.size()])); } finally { monitor.done(); } }
public Change createChange(IProgressMonitor monitor) throws CoreException { try { monitor.beginTask(RefactoringCoreMessages.RenameFieldRefactoring_checking, 1); TextChange[] changes = fChangeManager.getAllChanges(); RenameJavaElementDescriptor descriptor = createRefactoringDescriptor(); return new DynamicValidationRefactoringChange(descriptor, getProcessorName(), changes); } finally { monitor.done(); } }
private void createEdits( ICompilationUnit unit, ASTRewrite rewriter, List<TextEditGroup> descriptions) throws CoreException { TextChange change = fChangeManager.get(unit); MultiTextEdit root = new MultiTextEdit(); change.setEdit(root); for (TextEditGroup group : descriptions) change.addTextEditGroup(group); root.addChild(rewriter.rewriteAST()); }
private void addReferenceUpdates(IProgressMonitor pm) { pm.beginTask("", fReferences.length); // $NON-NLS-1$ String editName = RefactoringCoreMessages.RenameFieldRefactoring_Update_field_reference; for (int i = 0; i < fReferences.length; i++) { ICompilationUnit cu = fReferences[i].getCompilationUnit(); if (cu == null) continue; SearchMatch[] results = fReferences[i].getSearchResults(); for (int j = 0; j < results.length; j++) { addTextEdit(fChangeManager.get(cu), editName, createTextChange(results[j])); } pm.worked(1); } }
private RefactoringStatus addDelegates() throws JavaModelException, CoreException { RefactoringStatus status = new RefactoringStatus(); CompilationUnitRewrite rewrite = new CompilationUnitRewrite(fField.getCompilationUnit()); rewrite.setResolveBindings(true); // add delegate for the field if (RefactoringAvailabilityTester.isDelegateCreationAvailable(fField)) { FieldDeclaration fieldDeclaration = ASTNodeSearchUtil.getFieldDeclarationNode(fField, rewrite.getRoot()); if (fieldDeclaration.fragments().size() > 1) { status.addWarning( Messages.format( RefactoringCoreMessages .DelegateCreator_cannot_create_field_delegate_more_than_one_fragment, BasicElementLabels.getJavaElementName(fField.getElementName())), JavaStatusContext.create(fField)); } else if (((VariableDeclarationFragment) fieldDeclaration.fragments().get(0)) .getInitializer() == null) { status.addWarning( Messages.format( RefactoringCoreMessages.DelegateCreator_cannot_create_field_delegate_no_initializer, BasicElementLabels.getJavaElementName(fField.getElementName())), JavaStatusContext.create(fField)); } else { DelegateFieldCreator creator = new DelegateFieldCreator(); creator.setDeclareDeprecated(fDelegateDeprecation); creator.setDeclaration(fieldDeclaration); creator.setNewElementName(getNewElementName()); creator.setSourceRewrite(rewrite); creator.prepareDelegate(); creator.createEdit(); } } // add delegates for getter and setter methods // there may be getters even if the field is static final if (getGetter() != null && fRenameGetter) addMethodDelegate(getGetter(), getNewGetterName(), rewrite); if (getSetter() != null && fRenameSetter) addMethodDelegate(getSetter(), getNewSetterName(), rewrite); final CompilationUnitChange change = rewrite.createChange(true); if (change != null) { change.setKeepPreviewEdits(true); fChangeManager.manage(fField.getCompilationUnit(), change); } return status; }
private void addTextUpdates(ICompilationUnit cu, Set<TextMatch> matches) { for (Iterator<TextMatch> resultIter = matches.iterator(); resultIter.hasNext(); ) { TextMatch match = resultIter.next(); if (!match.isQualified() && fOnlyQualified) continue; int matchStart = match.getStartPosition(); ReplaceEdit edit = new ReplaceEdit(matchStart, fCurrentNameLength, fNewName); try { TextChangeCompatibility.addTextEdit( fManager.get(cu), TEXT_EDIT_LABEL, edit, TEXTUAL_MATCHES); } catch (MalformedTreeException e) { // conflicting update -> omit text match } } }
// ---------------- private RefactoringStatus analyzeRenameChanges(IProgressMonitor pm) throws CoreException { ICompilationUnit[] newWorkingCopies = null; WorkingCopyOwner newWCOwner = new WorkingCopyOwner() { /* must subclass */ }; try { pm.beginTask("", 2); // $NON-NLS-1$ RefactoringStatus result = new RefactoringStatus(); SearchResultGroup[] oldReferences = fReferences; List compilationUnitsToModify = new ArrayList(); if (fIsComposite) { // limited change set, no accessors. for (int i = 0; i < oldReferences.length; i++) compilationUnitsToModify.add(oldReferences[i].getCompilationUnit()); compilationUnitsToModify.add(fField.getCompilationUnit()); } else { // include all cus, including accessors compilationUnitsToModify.addAll(Arrays.asList(fChangeManager.getAllCompilationUnits())); } newWorkingCopies = RenameAnalyzeUtil.createNewWorkingCopies( (ICompilationUnit[]) compilationUnitsToModify.toArray( new ICompilationUnit[compilationUnitsToModify.size()]), fChangeManager, newWCOwner, new SubProgressMonitor(pm, 1)); SearchResultGroup[] newReferences = getNewReferences(new SubProgressMonitor(pm, 1), result, newWCOwner, newWorkingCopies); result.merge( RenameAnalyzeUtil.analyzeRenameChanges2( fChangeManager, oldReferences, newReferences, getNewElementName())); return result; } finally { pm.done(); if (newWorkingCopies != null) { for (int i = 0; i < newWorkingCopies.length; i++) { newWorkingCopies[i].discardWorkingCopy(); } } } }
// TODO: Currently filters out declarations (MethodDeclarationMatch, FieldDeclarationMatch). // Long term solution: only pass reference search results in. static RefactoringStatus analyzeRenameChanges2( TextChangeManager manager, SearchResultGroup[] oldReferences, SearchResultGroup[] newReferences, String newElementName) { RefactoringStatus result = new RefactoringStatus(); HashMap<ICompilationUnit, SearchMatch[]> cuToNewResults = new HashMap<>(newReferences.length); for (int i1 = 0; i1 < newReferences.length; i1++) { ICompilationUnit cu = newReferences[i1].getCompilationUnit(); if (cu != null) cuToNewResults.put(cu.getPrimary(), newReferences[i1].getSearchResults()); } for (int i = 0; i < oldReferences.length; i++) { SearchResultGroup oldGroup = oldReferences[i]; SearchMatch[] oldMatches = oldGroup.getSearchResults(); ICompilationUnit cu = oldGroup.getCompilationUnit(); if (cu == null) continue; SearchMatch[] newSearchMatches = cuToNewResults.remove(cu); if (newSearchMatches == null) { for (int j = 0; j < oldMatches.length; j++) { SearchMatch oldMatch = oldMatches[j]; addShadowsError(cu, oldMatch, result); } } else { analyzeChanges(cu, manager.get(cu), oldMatches, newSearchMatches, newElementName, result); } } for (Iterator<Entry<ICompilationUnit, SearchMatch[]>> iter = cuToNewResults.entrySet().iterator(); iter.hasNext(); ) { Entry<ICompilationUnit, SearchMatch[]> entry = iter.next(); ICompilationUnit cu = entry.getKey(); SearchMatch[] newSearchMatches = entry.getValue(); for (int i = 0; i < newSearchMatches.length; i++) { SearchMatch newMatch = newSearchMatches[i]; addReferenceShadowedError(cu, newMatch, newElementName, result); } } return result; }
@Override public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException { String project = null; IJavaProject javaProject = targetClass.getJavaProject(); if (javaProject != null) project = javaProject.getElementName(); int flags = JavaRefactoringDescriptor.JAR_MIGRATION | JavaRefactoringDescriptor.JAR_REFACTORING | RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE; try { if (targetClass.isAnonymous() || targetClass.isLocal()) flags |= JavaRefactoringDescriptor.JAR_SOURCE_ATTACHMENT; } catch (JavaModelException exception) { JavaPlugin.log(exception); } // TODO need to properly initialize the arguments so that this refactoring becomes recordable final Map arguments = new HashMap(); String description = "Convert Mutable into Immutable Class"; String comment = "Convert Mutable into Immutable Class"; final JavaRefactoringDescriptor descriptor = new JavaRefactoringDescriptor("fixme", project, description, comment, arguments, flags) {}; // JDTRefactoringDescriptor(IJavaRefactorings.ENCAPSULATE_FIELD, project, description, comment, // arguments, flags); final DynamicValidationRefactoringChange result = new DynamicValidationRefactoringChange(descriptor, getName()); TextChange[] changes = fChangeManager.getAllChanges(); pm.beginTask("ConvertToParallelArray create changes", changes.length); for (int i = 0; i < changes.length; i++) { result.add(changes[i]); pm.worked(1); } pm.done(); return result; }
private RefactoringStatus createChanges(IProgressMonitor pm) throws CoreException { pm.beginTask(RefactoringCoreMessages.RenameFieldRefactoring_checking, 10); RefactoringStatus result = new RefactoringStatus(); if (!fIsComposite) fChangeManager.clear(); // Delegate creation requires ASTRewrite which // creates a new change -> do this first. if (fDelegateUpdating) result.merge(addDelegates()); addDeclarationUpdate(); if (fUpdateReferences) { addReferenceUpdates(new SubProgressMonitor(pm, 1)); result.merge(analyzeRenameChanges(new SubProgressMonitor(pm, 2))); if (result.hasFatalError()) return result; } else { pm.worked(3); } if (getGetter() != null && fRenameGetter) { addGetterOccurrences(new SubProgressMonitor(pm, 1), result); } else { pm.worked(1); } if (getSetter() != null && fRenameSetter) { addSetterOccurrences(new SubProgressMonitor(pm, 1), result); } else { pm.worked(1); } if (fUpdateTextualMatches) { addTextMatches(new SubProgressMonitor(pm, 5)); } else { pm.worked(5); } pm.done(); return result; }
@SuppressWarnings({"unchecked"}) @Override public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException { RefactoringStatus result = new RefactoringStatus(); fChangeManager.clear(); pm.beginTask("", 12); pm.setTaskName("Convert to AtomicInteger checking preconditions"); pm.worked(1); if (result.hasFatalError()) return result; pm.setTaskName("ConvertToAtomicInteger searching for cunits"); final SubProgressMonitor subPm = new SubProgressMonitor(pm, 5); ICompilationUnit[] affectedCUs = RefactoringSearchEngine.findAffectedCompilationUnits( SearchPattern.createPattern(targetClass, IJavaSearchConstants.ALL_OCCURRENCES), RefactoringScopeFactory.create(targetClass, true), subPm, result, true); if (result.hasFatalError()) return result; pm.setTaskName("Analyzing the field"); IProgressMonitor sub = new SubProgressMonitor(pm, 5); sub.beginTask("", affectedCUs.length); List ownerDescriptions = new ArrayList(); ICompilationUnit owner = targetClass.getCompilationUnit(); for (int i = 0; i < affectedCUs.length; i++) { ICompilationUnit unit = affectedCUs[i]; sub.subTask(unit.getElementName()); CompilationUnit root = null; ASTRewrite rewriter = null; List descriptions; if (owner.equals(unit)) { root = fRoot; rewriter = fRewriter; descriptions = ownerDescriptions; } else { root = new RefactoringASTParser(AST.JLS3).parse(unit, true); rewriter = ASTRewrite.create(root.getAST()); descriptions = new ArrayList(); } checkCompileErrors(result, root, unit); // We will perform a different set of analysis and rewrites for the compilation unit // containing the // target class and other compilation units if (owner.equals(unit)) { // Analysis passes ClassMutatorAnalysis mutatorAnalysis = new ClassMutatorAnalysis(targetClass, pm); mutatorAnalysis.findMutators(); ClassConstructorAnalysis constructorAnalysis = new ClassConstructorAnalysis(targetClassDeclaration); targetClassDeclaration.accept(constructorAnalysis); // Rewrite pass MakeClassImmutableRewriter immutableRewriter = new MakeClassImmutableRewriter(this, unit, rewriter); immutableRewriter.rewrite(targetClassDeclaration, mutatorAnalysis, constructorAnalysis); result.merge(immutableRewriter.getStatus()); if (result.hasFatalError()) { fChangeManager.clear(); return result; } } else { // descriptions.addAll(immutableRewriter.getGroupDescriptions()); createEdits(unit, rewriter, descriptions); } sub.worked(1); if (pm.isCanceled()) throw new OperationCanceledException(); } createEdits(owner, fRewriter, ownerDescriptions); sub.done(); IFile[] filesToBeModified = ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits()); result.merge(Checks.validateModifiesFiles(filesToBeModified, getValidationContext())); if (result.hasFatalError()) return result; ResourceChangeChecker.checkFilesToBeChanged(filesToBeModified, new SubProgressMonitor(pm, 1)); return result; }
private TextChangeManager createChanges(IProgressMonitor pm, RefactoringStatus status) throws CoreException { if (!fIsComposite) fChangeManager.clear(); addOccurrences(fChangeManager, pm, status); return fChangeManager; }
private static TextChange getTextChange(SearchMatch searchResult, TextChangeManager manager) { ICompilationUnit cu = SearchUtils.getCompilationUnit(searchResult); if (cu == null) return null; return manager.get(cu); }
/** * Add occurrences * * @param manager the text change manager * @param pm the progress monitor * @param status the status * @throws CoreException if change creation failed */ protected void addOccurrences( TextChangeManager manager, IProgressMonitor pm, RefactoringStatus status) throws CoreException /*thrown in subtype*/ { pm.beginTask("", fOccurrences.length); // $NON-NLS-1$ for (int i = 0; i < fOccurrences.length; i++) { ICompilationUnit cu = fOccurrences[i].getCompilationUnit(); if (cu == null) continue; SearchMatch[] results = fOccurrences[i].getSearchResults(); // Split matches into declaration and non-declaration matches List<SearchMatch> declarationsInThisCu = new ArrayList<>(); List<SearchMatch> referencesInThisCu = new ArrayList<>(); for (int j = 0; j < results.length; j++) { if (results[j] instanceof MethodDeclarationMatch) declarationsInThisCu.add(results[j]); else referencesInThisCu.add(results[j]); } // First, handle the declarations if (declarationsInThisCu.size() > 0) { if (fDelegateUpdating) { // Update with delegates CompilationUnitRewrite rewrite = new CompilationUnitRewrite(cu); rewrite.setResolveBindings(true); for (Iterator<SearchMatch> iter = declarationsInThisCu.iterator(); iter.hasNext(); ) { SearchMatch element = iter.next(); MethodDeclaration method = ASTNodeSearchUtil.getMethodDeclarationNode( (IMethod) element.getElement(), rewrite.getRoot()); DelegateCreator creator = new DelegateMethodCreator(); creator.setDeclareDeprecated(fDelegateDeprecation); creator.setDeclaration(method); creator.setSourceRewrite(rewrite); creator.setNewElementName(getNewElementName()); creator.prepareDelegate(); creator.createEdit(); } // Need to handle all delegates first as this // creates a completely new change object. TextChange changeForThisCu = rewrite.createChange(true); changeForThisCu.setKeepPreviewEdits(true); manager.manage(cu, changeForThisCu); } // Update the normal methods for (Iterator<SearchMatch> iter = declarationsInThisCu.iterator(); iter.hasNext(); ) { SearchMatch element = iter.next(); simpleUpdate(element, cu, manager.get(cu)); } } // Second, handle references if (fUpdateReferences) { for (Iterator<SearchMatch> iter = referencesInThisCu.iterator(); iter.hasNext(); ) { SearchMatch element = iter.next(); simpleUpdate(element, cu, manager.get(cu)); } } pm.worked(1); if (pm.isCanceled()) throw new OperationCanceledException(); } pm.done(); }
protected IFile[] getChangedFiles() { return ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits()); }
@Override protected IFile[] getChangedFiles() throws CoreException { return ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits()); }