Search in sources :

Example 6 with SearchResultGroup

use of org.eclipse.jdt.internal.corext.refactoring.SearchResultGroup in project che by eclipse.

the class IntroduceFactoryRefactoring method createChange.

/* (non-Javadoc)
	 * @see org.eclipse.ltk.core.refactoring.Refactoring#createChange(org.eclipse.core.runtime.IProgressMonitor)
	 */
@Override
public Change createChange(IProgressMonitor pm) throws CoreException {
    try {
        pm.beginTask(RefactoringCoreMessages.IntroduceFactory_createChanges, fAllCallsTo.length);
        final ITypeBinding binding = fFactoryOwningClass.resolveBinding();
        final Map<String, String> arguments = new HashMap<String, String>();
        String project = null;
        IJavaProject javaProject = fCUHandle.getJavaProject();
        if (javaProject != null)
            project = javaProject.getElementName();
        int flags = JavaRefactoringDescriptor.JAR_MIGRATION | JavaRefactoringDescriptor.JAR_REFACTORING | RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE;
        if (binding.isNested() && !binding.isMember())
            flags |= JavaRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
        final String description = Messages.format(RefactoringCoreMessages.IntroduceFactoryRefactoring_descriptor_description_short, BasicElementLabels.getJavaElementName(fCtorOwningClass.getName().getIdentifier()));
        final String header = Messages.format(RefactoringCoreMessages.IntroduceFactory_descriptor_description, new String[] { BasicElementLabels.getJavaElementName(fNewMethodName), BindingLabelProvider.getBindingLabel(binding, JavaElementLabels.ALL_FULLY_QUALIFIED), BindingLabelProvider.getBindingLabel(fCtorBinding, JavaElementLabels.ALL_FULLY_QUALIFIED) });
        final JDTRefactoringDescriptorComment comment = new JDTRefactoringDescriptorComment(project, this, header);
        comment.addSetting(Messages.format(RefactoringCoreMessages.IntroduceFactoryRefactoring_original_pattern, BindingLabelProvider.getBindingLabel(fCtorBinding, JavaElementLabels.ALL_FULLY_QUALIFIED)));
        comment.addSetting(Messages.format(RefactoringCoreMessages.IntroduceFactoryRefactoring_factory_pattern, BasicElementLabels.getJavaElementName(fNewMethodName)));
        comment.addSetting(Messages.format(RefactoringCoreMessages.IntroduceFactoryRefactoring_owner_pattern, BindingLabelProvider.getBindingLabel(binding, JavaElementLabels.ALL_FULLY_QUALIFIED)));
        if (fProtectConstructor)
            comment.addSetting(RefactoringCoreMessages.IntroduceFactoryRefactoring_declare_private);
        final IntroduceFactoryDescriptor descriptor = RefactoringSignatureDescriptorFactory.createIntroduceFactoryDescriptor(project, description, comment.asString(), arguments, flags);
        arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT, JavaRefactoringDescriptorUtil.elementToHandle(project, fCUHandle));
        arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME, fNewMethodName);
        arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_ELEMENT + 1, JavaRefactoringDescriptorUtil.elementToHandle(project, binding.getJavaElement()));
        //$NON-NLS-1$
        arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION, new Integer(fSelectionStart).toString() + " " + new Integer(fSelectionLength).toString());
        arguments.put(ATTRIBUTE_PROTECT, Boolean.valueOf(fProtectConstructor).toString());
        final DynamicValidationStateChange result = new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.IntroduceFactory_name);
        boolean hitInFactoryClass = false;
        boolean hitInCtorClass = false;
        for (int i = 0; i < fAllCallsTo.length; i++) {
            SearchResultGroup rg = fAllCallsTo[i];
            ICompilationUnit unitHandle = rg.getCompilationUnit();
            CompilationUnitChange cuChange = new CompilationUnitChange(getName(), unitHandle);
            if (addAllChangesFor(rg, unitHandle, cuChange))
                result.add(cuChange);
            if (unitHandle.equals(fFactoryUnitHandle))
                hitInFactoryClass = true;
            if (unitHandle.equals(ASTCreator.getCu(fCtorOwningClass)))
                hitInCtorClass = true;
            pm.worked(1);
            if (pm.isCanceled())
                throw new OperationCanceledException();
        }
        if (!hitInFactoryClass) {
            // Handle factory class if no search hits there
            CompilationUnitChange cuChange = new CompilationUnitChange(getName(), fFactoryUnitHandle);
            addAllChangesFor(null, fFactoryUnitHandle, cuChange);
            result.add(cuChange);
        }
        if (!hitInCtorClass && !fFactoryUnitHandle.equals(ASTCreator.getCu(fCtorOwningClass))) {
            // Handle constructor-owning class if no search hits there
            CompilationUnitChange cuChange = new CompilationUnitChange(getName(), ASTCreator.getCu(fCtorOwningClass));
            addAllChangesFor(null, ASTCreator.getCu(fCtorOwningClass), cuChange);
            result.add(cuChange);
        }
        return result;
    } finally {
        pm.done();
    }
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) HashMap(java.util.HashMap) DynamicValidationRefactoringChange(org.eclipse.jdt.internal.corext.refactoring.changes.DynamicValidationRefactoringChange) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) SearchResultGroup(org.eclipse.jdt.internal.corext.refactoring.SearchResultGroup) DynamicValidationStateChange(org.eclipse.jdt.internal.corext.refactoring.changes.DynamicValidationStateChange) JDTRefactoringDescriptorComment(org.eclipse.jdt.internal.corext.refactoring.JDTRefactoringDescriptorComment) IntroduceFactoryDescriptor(org.eclipse.jdt.core.refactoring.descriptors.IntroduceFactoryDescriptor) IJavaProject(org.eclipse.jdt.core.IJavaProject) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) CompilationUnitChange(org.eclipse.jdt.core.refactoring.CompilationUnitChange)

Example 7 with SearchResultGroup

use of org.eclipse.jdt.internal.corext.refactoring.SearchResultGroup in project che by eclipse.

the class InlineConstantRefactoring method checkFinalConditions.

@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
    RefactoringStatus result = new RefactoringStatus();
    //$NON-NLS-1$
    pm.beginTask("", 3);
    try {
        fSelectionCuRewrite.clearASTAndImportRewrites();
        fDeclarationCuRewrite.clearASTAndImportRewrites();
        List<CompilationUnitChange> changes = new ArrayList<CompilationUnitChange>();
        HashSet<SimpleName> staticImportsInInitializer = new HashSet<SimpleName>();
        ImportReferencesCollector.collect(getInitializer(), fField.getJavaProject(), null, new ArrayList<SimpleName>(), staticImportsInInitializer);
        if (getReplaceAllReferences()) {
            SearchResultGroup[] searchResultGroups = findReferences(pm, result);
            for (int i = 0; i < searchResultGroups.length; i++) {
                if (pm.isCanceled())
                    throw new OperationCanceledException();
                SearchResultGroup group = searchResultGroups[i];
                ICompilationUnit cu = group.getCompilationUnit();
                CompilationUnitRewrite cuRewrite = getCuRewrite(cu);
                Name[] references = extractReferenceNodes(group.getSearchResults(), cuRewrite.getRoot());
                InlineTargetCompilationUnit targetCompilationUnit = new InlineTargetCompilationUnit(cuRewrite, references, this, staticImportsInInitializer);
                CompilationUnitChange change = targetCompilationUnit.getChange();
                if (change != null)
                    changes.add(change);
            }
        } else {
            Assert.isTrue(!isDeclarationSelected());
            InlineTargetCompilationUnit targetForOnlySelectedReference = new InlineTargetCompilationUnit(fSelectionCuRewrite, new Name[] { fSelectedConstantName }, this, staticImportsInInitializer);
            CompilationUnitChange change = targetForOnlySelectedReference.getChange();
            if (change != null)
                changes.add(change);
        }
        if (result.hasFatalError())
            return result;
        if (getRemoveDeclaration() && getReplaceAllReferences()) {
            boolean declarationRemoved = false;
            for (Iterator<CompilationUnitChange> iter = changes.iterator(); iter.hasNext(); ) {
                CompilationUnitChange change = iter.next();
                if (change.getCompilationUnit().equals(fDeclarationCuRewrite.getCu())) {
                    declarationRemoved = true;
                    break;
                }
            }
            if (!declarationRemoved) {
                InlineTargetCompilationUnit targetForDeclaration = new InlineTargetCompilationUnit(fDeclarationCuRewrite, new Name[0], this, staticImportsInInitializer);
                CompilationUnitChange change = targetForDeclaration.getChange();
                if (change != null)
                    changes.add(change);
            }
        }
        ICompilationUnit[] cus = new ICompilationUnit[changes.size()];
        for (int i = 0; i < changes.size(); i++) {
            CompilationUnitChange change = changes.get(i);
            cus[i] = change.getCompilationUnit();
        }
        result.merge(Checks.validateModifiesFiles(ResourceUtil.getFiles(cus), getValidationContext()));
        pm.worked(1);
        fChanges = changes.toArray(new CompilationUnitChange[changes.size()]);
        return result;
    } finally {
        pm.done();
    }
}
Also used : CompilationUnitRewrite(org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) SimpleName(org.eclipse.jdt.core.dom.SimpleName) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) ArrayList(java.util.ArrayList) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) SearchResultGroup(org.eclipse.jdt.internal.corext.refactoring.SearchResultGroup) SimpleName(org.eclipse.jdt.core.dom.SimpleName) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) Name(org.eclipse.jdt.core.dom.Name) CompilationUnitChange(org.eclipse.jdt.core.refactoring.CompilationUnitChange) HashSet(java.util.HashSet)

Example 8 with SearchResultGroup

use of org.eclipse.jdt.internal.corext.refactoring.SearchResultGroup in project che by eclipse.

the class IntroduceIndirectionRefactoring method updateReferences.

private RefactoringStatus updateReferences(IProgressMonitor monitor) throws CoreException {
    RefactoringStatus result = new RefactoringStatus();
    //$NON-NLS-1$
    monitor.beginTask("", 90);
    if (monitor.isCanceled())
        throw new OperationCanceledException();
    IMethod[] ripple = RippleMethodFinder2.getRelatedMethods(fTargetMethod, false, new NoOverrideProgressMonitor(monitor, 10), null);
    if (monitor.isCanceled())
        throw new OperationCanceledException();
    SearchResultGroup[] references = Checks.excludeCompilationUnits(getReferences(ripple, new NoOverrideProgressMonitor(monitor, 10), result), result);
    if (result.hasFatalError())
        return result;
    result.merge(Checks.checkCompileErrorsInAffectedFiles(references));
    if (monitor.isCanceled())
        throw new OperationCanceledException();
    int ticksPerCU = references.length == 0 ? 0 : 70 / references.length;
    for (int i = 0; i < references.length; i++) {
        SearchResultGroup group = references[i];
        SearchMatch[] searchResults = group.getSearchResults();
        CompilationUnitRewrite currentCURewrite = getCachedCURewrite(group.getCompilationUnit());
        for (int j = 0; j < searchResults.length; j++) {
            SearchMatch match = searchResults[j];
            if (match.isInsideDocComment())
                continue;
            IMember enclosingMember = (IMember) match.getElement();
            ASTNode target = getSelectedNode(group.getCompilationUnit(), currentCURewrite.getRoot(), match.getOffset(), match.getLength());
            if (target instanceof SuperMethodInvocation) {
                // Cannot retarget calls to super - add a warning
                result.merge(createWarningAboutCall(enclosingMember, target, RefactoringCoreMessages.IntroduceIndirectionRefactoring_call_warning_super_keyword));
                continue;
            }
            //$NON-NLS-1$
            Assert.isTrue(target instanceof MethodInvocation, "Element of call should be a MethodInvocation.");
            MethodInvocation invocation = (MethodInvocation) target;
            ITypeBinding typeBinding = getExpressionType(invocation);
            if (fIntermediaryFirstParameterType == null) {
                // no highest type yet
                fIntermediaryFirstParameterType = typeBinding.getTypeDeclaration();
            } else {
                // check if current type is higher
                result.merge(findCommonParent(typeBinding.getTypeDeclaration()));
            }
            if (result.hasFatalError())
                return result;
            // create an edit for this particular call
            result.merge(updateMethodInvocation(invocation, enclosingMember, currentCURewrite));
            // does call see the intermediary method?
            // => increase visibility of the type of the intermediary method.
            result.merge(adjustVisibility(fIntermediaryType, enclosingMember.getDeclaringType(), new NoOverrideProgressMonitor(monitor, 0)));
            if (monitor.isCanceled())
                throw new OperationCanceledException();
        }
        if (!isRewriteKept(group.getCompilationUnit()))
            createChangeAndDiscardRewrite(group.getCompilationUnit());
        monitor.worked(ticksPerCU);
    }
    monitor.done();
    return result;
}
Also used : CompilationUnitRewrite(org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite) SearchMatch(org.eclipse.jdt.core.search.SearchMatch) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) SearchResultGroup(org.eclipse.jdt.internal.corext.refactoring.SearchResultGroup) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) IMember(org.eclipse.jdt.core.IMember) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) IMethod(org.eclipse.jdt.core.IMethod)

Example 9 with SearchResultGroup

use of org.eclipse.jdt.internal.corext.refactoring.SearchResultGroup in project che by eclipse.

the class CreateCopyOfCompilationUnitChange method createChangeManager.

private static TextChangeManager createChangeManager(IProgressMonitor monitor, ICompilationUnit copy, String newName) throws CoreException {
    TextChangeManager manager = new TextChangeManager();
    SearchResultGroup refs = getReferences(copy, monitor);
    if (refs == null)
        return manager;
    if (refs.getCompilationUnit() == null)
        return manager;
    String name = RefactoringCoreMessages.CopyRefactoring_update_ref;
    SearchMatch[] results = refs.getSearchResults();
    for (int j = 0; j < results.length; j++) {
        SearchMatch searchResult = results[j];
        if (searchResult.getAccuracy() == SearchMatch.A_INACCURATE)
            continue;
        int offset = searchResult.getOffset();
        int length = searchResult.getLength();
        TextChangeCompatibility.addTextEdit(manager.get(copy), name, new ReplaceEdit(offset, length, newName));
    }
    return manager;
}
Also used : SearchMatch(org.eclipse.jdt.core.search.SearchMatch) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit) SearchResultGroup(org.eclipse.jdt.internal.corext.refactoring.SearchResultGroup) TextChangeManager(org.eclipse.jdt.internal.corext.refactoring.util.TextChangeManager)

Example 10 with SearchResultGroup

use of org.eclipse.jdt.internal.corext.refactoring.SearchResultGroup in project che by eclipse.

the class CreateCopyOfCompilationUnitChange method getReferences.

private static SearchResultGroup getReferences(final ICompilationUnit copy, IProgressMonitor monitor) throws JavaModelException {
    final ICompilationUnit[] copies = new ICompilationUnit[] { copy };
    IJavaSearchScope scope = SearchEngine.createJavaSearchScope(copies);
    final IType type = copy.findPrimaryType();
    if (type == null)
        return null;
    SearchPattern pattern = createSearchPattern(type);
    final RefactoringSearchEngine2 engine = new RefactoringSearchEngine2(pattern);
    engine.setScope(scope);
    engine.setWorkingCopies(copies);
    engine.setRequestor(new IRefactoringSearchRequestor() {

        TypeOccurrenceCollector fTypeOccurrenceCollector = new TypeOccurrenceCollector(type);

        public SearchMatch acceptSearchMatch(SearchMatch match) {
            try {
                return fTypeOccurrenceCollector.acceptSearchMatch2(copy, match);
            } catch (CoreException e) {
                JavaPlugin.log(e);
                return null;
            }
        }
    });
    engine.searchPattern(monitor);
    final Object[] results = engine.getResults();
    // https://bugs.eclipse.org/bugs/show_bug.cgi?id=106127)
    for (int index = 0; index < results.length; index++) {
        SearchResultGroup group = (SearchResultGroup) results[index];
        if (group.getCompilationUnit().equals(copy))
            return group;
    }
    return null;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) SearchMatch(org.eclipse.jdt.core.search.SearchMatch) SearchResultGroup(org.eclipse.jdt.internal.corext.refactoring.SearchResultGroup) IType(org.eclipse.jdt.core.IType) IRefactoringSearchRequestor(org.eclipse.jdt.internal.corext.refactoring.IRefactoringSearchRequestor) CoreException(org.eclipse.core.runtime.CoreException) IJavaSearchScope(org.eclipse.jdt.core.search.IJavaSearchScope) SearchPattern(org.eclipse.jdt.core.search.SearchPattern) TypeOccurrenceCollector(org.eclipse.jdt.internal.corext.refactoring.rename.TypeOccurrenceCollector) RefactoringSearchEngine2(org.eclipse.jdt.internal.corext.refactoring.RefactoringSearchEngine2)

Aggregations

SearchResultGroup (org.eclipse.jdt.internal.corext.refactoring.SearchResultGroup)23 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)15 SearchMatch (org.eclipse.jdt.core.search.SearchMatch)12 SubProgressMonitor (org.eclipse.core.runtime.SubProgressMonitor)8 RefactoringStatus (org.eclipse.ltk.core.refactoring.RefactoringStatus)7 ArrayList (java.util.ArrayList)6 SearchPattern (org.eclipse.jdt.core.search.SearchPattern)6 IJavaSearchScope (org.eclipse.jdt.core.search.IJavaSearchScope)5 OperationCanceledException (org.eclipse.core.runtime.OperationCanceledException)4 IType (org.eclipse.jdt.core.IType)4 ReplaceEdit (org.eclipse.text.edits.ReplaceEdit)4 HashSet (java.util.HashSet)3 RefactoringSearchEngine2 (org.eclipse.jdt.internal.corext.refactoring.RefactoringSearchEngine2)3 TextChange (org.eclipse.ltk.core.refactoring.TextChange)3 HashMap (java.util.HashMap)2 CoreException (org.eclipse.core.runtime.CoreException)2 IMethod (org.eclipse.jdt.core.IMethod)2 ASTNode (org.eclipse.jdt.core.dom.ASTNode)2 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)2 CompilationUnitChange (org.eclipse.jdt.core.refactoring.CompilationUnitChange)2