Search in sources :

Example 1 with SearchPattern

use of org.eclipse.jdt.core.search.SearchPattern in project che by eclipse.

the class RenameMethodProcessor method batchFindNewOccurrences.

//Lower memory footprint than batchFindNewOccurrences. Not used because it is too slow.
//Final solution is maybe to do searches in chunks of ~ 50 CUs.
//	private SearchResultGroup[] findNewOccurrences(IMethod[] newMethods, ICompilationUnit[] newDeclarationWCs, IProgressMonitor pm) throws CoreException {
//		pm.beginTask("", fOccurrences.length * 2); //$NON-NLS-1$
//
//		SearchPattern refsPattern= RefactoringSearchEngine.createOrPattern(newMethods, IJavaSearchConstants.REFERENCES);
//		SearchParticipant[] searchParticipants= SearchUtils.getDefaultSearchParticipants();
//		IJavaSearchScope scope= RefactoringScopeFactory.create(newMethods);
//		MethodOccurenceCollector requestor= new MethodOccurenceCollector(getNewElementName());
//		SearchEngine searchEngine= new SearchEngine(fWorkingCopyOwner);
//
//		//TODO: should process only references
//		for (int j= 0; j < fOccurrences.length; j++) { //should be getReferences()
//			//cut memory peak by holding only one reference CU at a time in memory
//			ICompilationUnit originalCu= fOccurrences[j].getCompilationUnit();
//			ICompilationUnit newWc= null;
//			try {
//				ICompilationUnit wc= RenameAnalyzeUtil.findWorkingCopyForCu(newDeclarationWCs, originalCu);
//				if (wc == null) {
//					newWc= RenameAnalyzeUtil.createNewWorkingCopy(originalCu, fChangeManager, fWorkingCopyOwner,
//							new SubProgressMonitor(pm, 1));
//				}
//				searchEngine.search(refsPattern, searchParticipants, scope,	requestor, new SubProgressMonitor(pm, 1));
//			} finally {
//				if (newWc != null)
//					newWc.discardWorkingCopy();
//			}
//		}
//		SearchResultGroup[] newResults= RefactoringSearchEngine.groupByResource(requestor.getResults());
//		pm.done();
//		return newResults;
//	}
private SearchResultGroup[] batchFindNewOccurrences(IMethod[] wcNewMethods, final IMethod[] wcOldMethods, ICompilationUnit[] newDeclarationWCs, IProgressMonitor pm, RefactoringStatus status) throws CoreException {
    //$NON-NLS-1$
    pm.beginTask("", 2);
    SearchPattern refsPattern = RefactoringSearchEngine.createOrPattern(wcNewMethods, IJavaSearchConstants.REFERENCES);
    SearchParticipant[] searchParticipants = SearchUtils.getDefaultSearchParticipants();
    IJavaSearchScope scope = RefactoringScopeFactory.create(wcNewMethods);
    MethodOccurenceCollector requestor;
    if (getDelegateUpdating()) {
        // There will be two new matches inside the delegate(s) (the invocation
        // and the javadoc) which are OK and must not be reported.
        // Note that except these ocurrences, the delegate bodies are empty
        // (as they were created this way).
        requestor = new MethodOccurenceCollector(getNewElementName()) {

            @Override
            public void acceptSearchMatch(ICompilationUnit unit, SearchMatch match) throws CoreException {
                for (int i = 0; i < wcOldMethods.length; i++) if (wcOldMethods[i].equals(match.getElement()))
                    return;
                super.acceptSearchMatch(unit, match);
            }
        };
    } else
        requestor = new MethodOccurenceCollector(getNewElementName());
    SearchEngine searchEngine = new SearchEngine(fWorkingCopyOwner);
    ArrayList<ICompilationUnit> needWCs = new ArrayList<ICompilationUnit>();
    HashSet<ICompilationUnit> declaringCUs = new HashSet<ICompilationUnit>(newDeclarationWCs.length);
    for (int i = 0; i < newDeclarationWCs.length; i++) declaringCUs.add(newDeclarationWCs[i].getPrimary());
    for (int i = 0; i < fOccurrences.length; i++) {
        ICompilationUnit cu = fOccurrences[i].getCompilationUnit();
        if (!declaringCUs.contains(cu))
            needWCs.add(cu);
    }
    ICompilationUnit[] otherWCs = null;
    try {
        otherWCs = RenameAnalyzeUtil.createNewWorkingCopies(needWCs.toArray(new ICompilationUnit[needWCs.size()]), fChangeManager, fWorkingCopyOwner, new SubProgressMonitor(pm, 1));
        searchEngine.search(refsPattern, searchParticipants, scope, requestor, new SubProgressMonitor(pm, 1));
    } finally {
        pm.done();
        if (otherWCs != null) {
            for (int i = 0; i < otherWCs.length; i++) {
                otherWCs[i].discardWorkingCopy();
            }
        }
    }
    SearchResultGroup[] newResults = RefactoringSearchEngine.groupByCu(requestor.getResults(), status);
    return newResults;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) SearchMatch(org.eclipse.jdt.core.search.SearchMatch) ArrayList(java.util.ArrayList) SearchResultGroup(org.eclipse.jdt.internal.corext.refactoring.SearchResultGroup) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) SearchParticipant(org.eclipse.jdt.core.search.SearchParticipant) SearchEngine(org.eclipse.jdt.core.search.SearchEngine) RefactoringSearchEngine(org.eclipse.jdt.internal.corext.refactoring.RefactoringSearchEngine) CoreException(org.eclipse.core.runtime.CoreException) IJavaSearchScope(org.eclipse.jdt.core.search.IJavaSearchScope) SearchPattern(org.eclipse.jdt.core.search.SearchPattern) HashSet(java.util.HashSet)

Example 2 with SearchPattern

use of org.eclipse.jdt.core.search.SearchPattern in project che by eclipse.

the class RenameMethodProcessor method searchForDeclarationsOfClashingMethods.

private IMethod[] searchForDeclarationsOfClashingMethods(IProgressMonitor pm) throws CoreException {
    final List<IMethod> results = new ArrayList<IMethod>();
    SearchPattern pattern = createNewMethodPattern();
    IJavaSearchScope scope = RefactoringScopeFactory.create(getMethod().getJavaProject());
    SearchRequestor requestor = new SearchRequestor() {

        @Override
        public void acceptSearchMatch(SearchMatch match) throws CoreException {
            Object method = match.getElement();
            if (// check for bug 90138: [refactoring] [rename] Renaming method throws internal exception
            method instanceof IMethod)
                results.add((IMethod) method);
            else
                //$NON-NLS-1$
                JavaPlugin.logErrorMessage("Unexpected element in search match: " + match.toString());
        }
    };
    new SearchEngine().search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor, pm);
    return results.toArray(new IMethod[results.size()]);
}
Also used : SearchRequestor(org.eclipse.jdt.core.search.SearchRequestor) SearchMatch(org.eclipse.jdt.core.search.SearchMatch) SearchEngine(org.eclipse.jdt.core.search.SearchEngine) RefactoringSearchEngine(org.eclipse.jdt.internal.corext.refactoring.RefactoringSearchEngine) IJavaSearchScope(org.eclipse.jdt.core.search.IJavaSearchScope) ArrayList(java.util.ArrayList) SearchPattern(org.eclipse.jdt.core.search.SearchPattern) IMethod(org.eclipse.jdt.core.IMethod)

Example 3 with SearchPattern

use of org.eclipse.jdt.core.search.SearchPattern in project che by eclipse.

the class RenameTypeProcessor method initializeReferences.

/**
	 * Initializes the references to the type and the similarly named elements. This
	 * method creates both the fReferences and the fPreloadedElementToName
	 * fields.
	 *
	 * May be called from the UI.
	 * @param monitor progress monitor
	 * @return initialization status
	 * @throws JavaModelException some fundamental error with the underlying model
	 * @throws OperationCanceledException if user canceled the task
	 *
	 */
public RefactoringStatus initializeReferences(IProgressMonitor monitor) throws JavaModelException, OperationCanceledException {
    Assert.isNotNull(fType);
    Assert.isNotNull(getNewElementName());
    if (fReferences != null && (getNewElementName().equals(fCachedNewName)) && (fCachedRenameSimilarElements == getUpdateSimilarDeclarations()) && (fCachedRenamingStrategy == fRenamingStrategy))
        return fCachedRefactoringStatus;
    fCachedNewName = getNewElementName();
    fCachedRenameSimilarElements = fUpdateSimilarElements;
    fCachedRenamingStrategy = fRenamingStrategy;
    fCachedRefactoringStatus = new RefactoringStatus();
    try {
        SearchPattern pattern = SearchPattern.createPattern(fType, IJavaSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
        String binaryRefsDescription = Messages.format(RefactoringCoreMessages.ReferencesInBinaryContext_ref_in_binaries_description, BasicElementLabels.getJavaElementName(fType.getElementName()));
        ReferencesInBinaryContext binaryRefs = new ReferencesInBinaryContext(binaryRefsDescription);
        fReferences = RefactoringSearchEngine.search(pattern, RefactoringScopeFactory.create(fType, true, false), new TypeOccurrenceCollector(fType, binaryRefs), monitor, fCachedRefactoringStatus);
        binaryRefs.addErrorIfNecessary(fCachedRefactoringStatus);
        fReferences = Checks.excludeCompilationUnits(fReferences, fCachedRefactoringStatus);
        fPreloadedElementToName = new LinkedHashMap<IJavaElement, String>();
        fPreloadedElementToSelection = new HashMap<IJavaElement, Boolean>();
        final String unQualifiedTypeName = fType.getElementName();
        //$NON-NLS-1$
        monitor.beginTask("", fReferences.length);
        if (getUpdateSimilarDeclarations()) {
            RenamingNameSuggestor sugg = new RenamingNameSuggestor(fRenamingStrategy);
            for (int i = 0; i < fReferences.length; i++) {
                final ICompilationUnit cu = fReferences[i].getCompilationUnit();
                if (cu == null)
                    continue;
                final SearchMatch[] results = fReferences[i].getSearchResults();
                for (int j = 0; j < results.length; j++) {
                    if (!(results[j] instanceof TypeReferenceMatch))
                        continue;
                    final TypeReferenceMatch match = (TypeReferenceMatch) results[j];
                    final List<IJavaElement> matches = new ArrayList<IJavaElement>();
                    if (match.getLocalElement() != null) {
                        if (match.getLocalElement() instanceof ILocalVariable) {
                            matches.add(match.getLocalElement());
                        }
                    // else don't update (e.g. match in type parameter, annotation, ...)
                    } else {
                        matches.add((IJavaElement) match.getElement());
                    }
                    final IJavaElement[] others = match.getOtherElements();
                    if (others != null)
                        matches.addAll(Arrays.asList(others));
                    for (Iterator<IJavaElement> iter = matches.iterator(); iter.hasNext(); ) {
                        final IJavaElement element = iter.next();
                        if (!(element instanceof IMethod) && !(element instanceof IField) && !(element instanceof ILocalVariable))
                            continue;
                        if (!isInDeclaredType(match.getOffset(), element))
                            continue;
                        if (element instanceof IField) {
                            final IField currentField = (IField) element;
                            final String newFieldName = sugg.suggestNewFieldName(currentField.getJavaProject(), currentField.getElementName(), Flags.isStatic(currentField.getFlags()), unQualifiedTypeName, getNewElementName());
                            if (newFieldName != null)
                                fPreloadedElementToName.put(currentField, newFieldName);
                        } else if (element instanceof IMethod) {
                            final IMethod currentMethod = (IMethod) element;
                            addMethodRename(unQualifiedTypeName, sugg, currentMethod);
                        } else if (element instanceof ILocalVariable) {
                            final ILocalVariable currentLocal = (ILocalVariable) element;
                            final boolean isParameter;
                            if (currentLocal.isParameter()) {
                                addMethodRename(unQualifiedTypeName, sugg, (IMethod) currentLocal.getParent());
                                isParameter = true;
                            } else
                                isParameter = false;
                            final String newLocalName = sugg.suggestNewLocalName(currentLocal.getJavaProject(), currentLocal.getElementName(), isParameter, unQualifiedTypeName, getNewElementName());
                            if (newLocalName != null)
                                fPreloadedElementToName.put(currentLocal, newLocalName);
                        }
                    }
                }
                if (monitor.isCanceled())
                    throw new OperationCanceledException();
            }
        }
        for (Iterator<IJavaElement> iter = fPreloadedElementToName.keySet().iterator(); iter.hasNext(); ) {
            IJavaElement element = iter.next();
            fPreloadedElementToSelection.put(element, Boolean.TRUE);
        }
        fPreloadedElementToNameDefault = new LinkedHashMap<IJavaElement, String>(fPreloadedElementToName);
    } catch (OperationCanceledException e) {
        fReferences = null;
        fPreloadedElementToName = null;
        throw new OperationCanceledException();
    }
    return fCachedRefactoringStatus;
}
Also used : IJavaElement(org.eclipse.jdt.core.IJavaElement) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) SearchMatch(org.eclipse.jdt.core.search.SearchMatch) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) ArrayList(java.util.ArrayList) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) IField(org.eclipse.jdt.core.IField) ILocalVariable(org.eclipse.jdt.core.ILocalVariable) ReferencesInBinaryContext(org.eclipse.jdt.internal.corext.refactoring.base.ReferencesInBinaryContext) SearchPattern(org.eclipse.jdt.core.search.SearchPattern) IMethod(org.eclipse.jdt.core.IMethod) TypeReferenceMatch(org.eclipse.jdt.core.search.TypeReferenceMatch)

Example 4 with SearchPattern

use of org.eclipse.jdt.core.search.SearchPattern in project che by eclipse.

the class RenameFieldProcessor method checkAccessorDeclarations.

private RefactoringStatus checkAccessorDeclarations(IProgressMonitor pm, IMethod existingAccessor) throws CoreException {
    RefactoringStatus result = new RefactoringStatus();
    SearchPattern pattern = SearchPattern.createPattern(existingAccessor, IJavaSearchConstants.DECLARATIONS, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
    IJavaSearchScope scope = SearchEngine.createHierarchyScope(fField.getDeclaringType());
    SearchResultGroup[] groupDeclarations = RefactoringSearchEngine.search(pattern, scope, pm, result);
    Assert.isTrue(groupDeclarations.length > 0);
    if (groupDeclarations.length != 1) {
        String message = Messages.format(RefactoringCoreMessages.RenameFieldRefactoring_overridden, JavaElementUtil.createMethodSignature(existingAccessor));
        result.addError(message);
    } else {
        SearchResultGroup group = groupDeclarations[0];
        Assert.isTrue(group.getSearchResults().length > 0);
        if (group.getSearchResults().length != 1) {
            String message = Messages.format(RefactoringCoreMessages.RenameFieldRefactoring_overridden_or_overrides, JavaElementUtil.createMethodSignature(existingAccessor));
            result.addError(message);
        }
    }
    return result;
}
Also used : IJavaSearchScope(org.eclipse.jdt.core.search.IJavaSearchScope) SearchPattern(org.eclipse.jdt.core.search.SearchPattern) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) SearchResultGroup(org.eclipse.jdt.internal.corext.refactoring.SearchResultGroup)

Example 5 with SearchPattern

use of org.eclipse.jdt.core.search.SearchPattern in project che by eclipse.

the class RenameFieldProcessor method getNewReferences.

private SearchResultGroup[] getNewReferences(IProgressMonitor pm, RefactoringStatus status, WorkingCopyOwner owner, ICompilationUnit[] newWorkingCopies) throws CoreException {
    //$NON-NLS-1$
    pm.beginTask("", 2);
    ICompilationUnit declaringCuWorkingCopy = RenameAnalyzeUtil.findWorkingCopyForCu(newWorkingCopies, fField.getCompilationUnit());
    if (declaringCuWorkingCopy == null)
        return new SearchResultGroup[0];
    IField field = getFieldInWorkingCopy(declaringCuWorkingCopy, getNewElementName());
    if (field == null || !field.exists())
        return new SearchResultGroup[0];
    CollectingSearchRequestor requestor = null;
    if (fDelegateUpdating && RefactoringAvailabilityTester.isDelegateCreationAvailable(getField())) {
        // There will be two new matches inside the delegate (the invocation
        // and the javadoc) which are OK and must not be reported.
        final IField oldField = getFieldInWorkingCopy(declaringCuWorkingCopy, getCurrentElementName());
        requestor = new CollectingSearchRequestor() {

            @Override
            public void acceptSearchMatch(SearchMatch match) throws CoreException {
                if (!oldField.equals(match.getElement()))
                    super.acceptSearchMatch(match);
            }
        };
    } else
        requestor = new CollectingSearchRequestor();
    SearchPattern newPattern = SearchPattern.createPattern(field, IJavaSearchConstants.REFERENCES);
    IJavaSearchScope scope = RefactoringScopeFactory.create(fField, true, true);
    return RefactoringSearchEngine.search(newPattern, owner, scope, requestor, new SubProgressMonitor(pm, 1), status);
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) SearchMatch(org.eclipse.jdt.core.search.SearchMatch) CoreException(org.eclipse.core.runtime.CoreException) IJavaSearchScope(org.eclipse.jdt.core.search.IJavaSearchScope) SearchPattern(org.eclipse.jdt.core.search.SearchPattern) CuCollectingSearchRequestor(org.eclipse.jdt.internal.corext.refactoring.CuCollectingSearchRequestor) CollectingSearchRequestor(org.eclipse.jdt.internal.corext.refactoring.CollectingSearchRequestor) IField(org.eclipse.jdt.core.IField) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor)

Aggregations

SearchPattern (org.eclipse.jdt.core.search.SearchPattern)21 SearchMatch (org.eclipse.jdt.core.search.SearchMatch)13 IJavaSearchScope (org.eclipse.jdt.core.search.IJavaSearchScope)12 SearchEngine (org.eclipse.jdt.core.search.SearchEngine)9 CoreException (org.eclipse.core.runtime.CoreException)7 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)7 SearchRequestor (org.eclipse.jdt.core.search.SearchRequestor)6 SearchResultGroup (org.eclipse.jdt.internal.corext.refactoring.SearchResultGroup)6 SubProgressMonitor (org.eclipse.core.runtime.SubProgressMonitor)5 IJavaElement (org.eclipse.jdt.core.IJavaElement)5 ArrayList (java.util.ArrayList)4 IMethod (org.eclipse.jdt.core.IMethod)4 IPackageFragment (org.eclipse.jdt.core.IPackageFragment)4 RefactoringSearchEngine (org.eclipse.jdt.internal.corext.refactoring.RefactoringSearchEngine)4 HashSet (java.util.HashSet)3 IProgressMonitor (org.eclipse.core.runtime.IProgressMonitor)3 IType (org.eclipse.jdt.core.IType)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)2 IField (org.eclipse.jdt.core.IField)2