Java Code Examples for org.eclipse.jdt.core.search.SearchEngine#search()

The following examples show how to use org.eclipse.jdt.core.search.SearchEngine#search() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JavaReferenceCodeMining.java    From jdt-codemining with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Return the number of references for the given java element.
 * 
 * @param element the java element.
 * @param monitor the monitor
 * @return he number of references for the given java element.
 * @throws JavaModelException throws when java error.
 * @throws CoreException      throws when java error.
 */
private static long countReferences(IJavaElement element, IProgressMonitor monitor)
		throws JavaModelException, CoreException {
	if (element == null) {
		return 0;
	}
	final AtomicLong count = new AtomicLong(0);
	SearchPattern pattern = SearchPattern.createPattern(element, IJavaSearchConstants.REFERENCES);
	SearchEngine engine = new SearchEngine();
	engine.search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() },
			createSearchScope(), new SearchRequestor() {

				@Override
				public void acceptSearchMatch(SearchMatch match) throws CoreException {
					Object o = match.getElement();
					if (o instanceof IJavaElement
							&& ((IJavaElement) o).getAncestor(IJavaElement.COMPILATION_UNIT) != null) {
						count.incrementAndGet();
					}
				}
			}, monitor);

	return count.get();
}
 
Example 2
Source File: RippleMethodFinder.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private void findAllDeclarations(IProgressMonitor monitor, WorkingCopyOwner owner) throws CoreException {
	fDeclarations = new ArrayList<>();

	class MethodRequestor extends SearchRequestor {
		@Override
		public void acceptSearchMatch(SearchMatch match) throws CoreException {
			IMethod method = (IMethod) match.getElement();
			boolean isBinary = method.isBinary();
			if (!isBinary) {
				fDeclarations.add(method);
			}
		}
	}

	int limitTo = IJavaSearchConstants.DECLARATIONS | IJavaSearchConstants.IGNORE_DECLARING_TYPE | IJavaSearchConstants.IGNORE_RETURN_TYPE;
	int matchRule = SearchPattern.R_ERASURE_MATCH | SearchPattern.R_CASE_SENSITIVE;
	SearchPattern pattern = SearchPattern.createPattern(fMethod, limitTo, matchRule);
	MethodRequestor requestor = new MethodRequestor();
	SearchEngine searchEngine = owner != null ? new SearchEngine(owner) : new SearchEngine();

	searchEngine.search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, createSearchScope(), requestor, monitor);
}
 
Example 3
Source File: WebXmlValidator.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
/**
 * Searches for a class that matches a pattern.
 */
@VisibleForTesting
static boolean performSearch(SearchPattern pattern, IJavaSearchScope scope,
    IProgressMonitor monitor) {
  try {
    SearchEngine searchEngine = new SearchEngine();
    TypeSearchRequestor requestor = new TypeSearchRequestor();
    searchEngine.search(pattern,
        new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() },
        scope, requestor, monitor);
    return requestor.foundMatch();
  } catch (CoreException ex) {
    logger.log(Level.SEVERE, ex.getMessage());
    return false;
  }
}
 
Example 4
Source File: RefactoringSearchEngine.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static SearchResultGroup[] internalSearch(SearchEngine searchEngine, SearchPattern pattern, IJavaSearchScope scope,
		CollectingSearchRequestor requestor, IProgressMonitor monitor, RefactoringStatus status) throws JavaModelException {
	try {
		searchEngine.search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor, monitor);
	} catch (CoreException e) {
		throw new JavaModelException(e);
	}
	return groupByCu(requestor.getResults(), status);
}
 
Example 5
Source File: RippleMethodFinder2.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void findAllDeclarations(IProgressMonitor monitor, WorkingCopyOwner owner) throws CoreException {
	fDeclarations= new ArrayList<IMethod>();

	class MethodRequestor extends SearchRequestor {
		@Override
		public void acceptSearchMatch(SearchMatch match) throws CoreException {
			IMethod method= (IMethod) match.getElement();
			boolean isBinary= method.isBinary();
			if (fBinaryRefs != null || ! (fExcludeBinaries && isBinary)) {
				fDeclarations.add(method);
			}
			if (isBinary && fBinaryRefs != null) {
				fDeclarationToMatch.put(method, match);
			}
		}
	}

	int limitTo = IJavaSearchConstants.DECLARATIONS | IJavaSearchConstants.IGNORE_DECLARING_TYPE | IJavaSearchConstants.IGNORE_RETURN_TYPE;
	int matchRule= SearchPattern.R_ERASURE_MATCH | SearchPattern.R_CASE_SENSITIVE;
	SearchPattern pattern= SearchPattern.createPattern(fMethod, limitTo, matchRule);
	SearchParticipant[] participants= SearchUtils.getDefaultSearchParticipants();
	IJavaSearchScope scope= RefactoringScopeFactory.createRelatedProjectsScope(fMethod.getJavaProject(), IJavaSearchScope.SOURCES | IJavaSearchScope.APPLICATION_LIBRARIES | IJavaSearchScope.SYSTEM_LIBRARIES);
	MethodRequestor requestor= new MethodRequestor();
	SearchEngine searchEngine= owner != null ? new SearchEngine(owner) : new SearchEngine();

	searchEngine.search(pattern, participants, scope, requestor, monitor);
}
 
Example 6
Source File: RefactoringSearchEngine.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static SearchResultGroup[] internalSearch(SearchEngine searchEngine, SearchPattern pattern, IJavaSearchScope scope, CollectingSearchRequestor requestor, IProgressMonitor monitor, RefactoringStatus status)
		throws JavaModelException {
	try {
		searchEngine.search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor, monitor);
	} catch (CoreException e) {
		throw new JavaModelException(e);
	}
	return groupByCu(requestor.getResults(), status);
}
 
Example 7
Source File: RippleMethodFinder2.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private void findAllDeclarations(IProgressMonitor monitor, WorkingCopyOwner owner) throws CoreException {
	fDeclarations= new ArrayList<>();

	class MethodRequestor extends SearchRequestor {
		@Override
		public void acceptSearchMatch(SearchMatch match) throws CoreException {
			IMethod method= (IMethod) match.getElement();
			boolean isBinary= method.isBinary();
			if (fBinaryRefs != null || ! (fExcludeBinaries && isBinary)) {
				fDeclarations.add(method);
			}
			if (isBinary && fBinaryRefs != null) {
				fDeclarationToMatch.put(method, match);
			}
		}
	}

	int limitTo = IJavaSearchConstants.DECLARATIONS | IJavaSearchConstants.IGNORE_DECLARING_TYPE | IJavaSearchConstants.IGNORE_RETURN_TYPE;
	int matchRule= SearchPattern.R_ERASURE_MATCH | SearchPattern.R_CASE_SENSITIVE;
	SearchPattern pattern= SearchPattern.createPattern(fMethod, limitTo, matchRule);
	SearchParticipant[] participants= SearchUtils.getDefaultSearchParticipants();
	IJavaSearchScope scope= RefactoringScopeFactory.createRelatedProjectsScope(fMethod.getJavaProject(), IJavaSearchScope.SOURCES | IJavaSearchScope.APPLICATION_LIBRARIES | IJavaSearchScope.SYSTEM_LIBRARIES);
	MethodRequestor requestor= new MethodRequestor();
	SearchEngine searchEngine= owner != null ? new SearchEngine(owner) : new SearchEngine();

	searchEngine.search(pattern, participants, scope, requestor, monitor);
}
 
Example 8
Source File: Utils.java    From CogniCrypt with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * This method searches the passed project for the class that contains the main method.
 *
 * @param project Project that is searched
 * @param requestor Object that handles the search results
 */
public static void findMainMethodInCurrentProject(final IJavaProject project, final SearchRequestor requestor) {
	final SearchPattern sp = SearchPattern.createPattern("main", IJavaSearchConstants.METHOD, IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH);

	final SearchEngine se = new SearchEngine();
	final SearchParticipant[] searchParticipants = new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()};
	final IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaElement[] {project});

	try {
		se.search(sp, searchParticipants, scope, requestor, null);
	}
	catch (final CoreException e) {
		Activator.getDefault().logError(e);
	}
}
 
Example 9
Source File: CallerFinder.java    From lapse-plus with GNU General Public License v3.0 5 votes vote down vote up
public static Collection/*<MethodUnitPair>*/ findDeclarations(IProgressMonitor progressMonitor, String methodName, IJavaProject project, boolean isConstructor) {
    try {
        SearchRequestor searchRequestor = new MethodSearchRequestor.MethodDeclarationsSearchRequestor(); 
        SearchEngine searchEngine = new SearchEngine();

        IProgressMonitor monitor = new SubProgressMonitor(
                progressMonitor, 5, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
        monitor.beginTask("Searching for calls to " + 
                methodName + (project != null ? " in " + project.getProject().getName() : ""), 100);            
        IJavaSearchScope searchScope = getSearchScope(project);
        // This is kind of hacky: we need to make up a string name for the search to work right
        log("Looking for " + methodName);
        int matchType = !isConstructor ? IJavaSearchConstants.METHOD : IJavaSearchConstants.CONSTRUCTOR;
        SearchPattern pattern = SearchPattern.createPattern(
                methodName, 
                matchType,
                IJavaSearchConstants.DECLARATIONS,
                SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE );
        
        searchEngine.search(
                pattern, 
                new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() },
                searchScope, 
                searchRequestor, 
                monitor
                );

        if(searchRequestor instanceof MethodSearchRequestor.MethodDeclarationsSearchRequestor){                
            return ((MethodSearchRequestor.MethodDeclarationsSearchRequestor)searchRequestor).getMethodUnitPairs();
        }else{
            return ((MethodSearchRequestor.MethodReferencesSearchRequestor)searchRequestor).getMethodUnitPairs();
        }
    } catch (CoreException e) {
        JavaPlugin.log(e);

        return new LinkedList();
    }
}
 
Example 10
Source File: CallerFinder.java    From lapse-plus with GNU General Public License v3.0 5 votes vote down vote up
public static Collection/*<MethodDeclarationUnitPair>*/ 
		findCallees(IProgressMonitor progressMonitor, String methodName, IJavaProject project, boolean isConstructor) 
{
	try {
           MethodSearchRequestor.MethodDeclarationsSearchRequestor searchRequestor = 
           	new MethodSearchRequestor.MethodDeclarationsSearchRequestor();
           SearchEngine searchEngine = new SearchEngine();

           IProgressMonitor monitor = new SubProgressMonitor(
           		progressMonitor, 5, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL);
           monitor.beginTask("Searching for declaration of " + methodName +
           		(project != null ? " in " + project.getProject().getName() : ""), 100);
           IJavaSearchScope searchScope = getSearchScope(project);
           int matchType = !isConstructor ? IJavaSearchConstants.METHOD : IJavaSearchConstants.CONSTRUCTOR;
           SearchPattern pattern = SearchPattern.createPattern(
           		methodName, 
				matchType,
				IJavaSearchConstants.DECLARATIONS, 
				SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE );
           
           searchEngine.search(
           		pattern, 
				new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() },
                   searchScope, 
				searchRequestor, 
				monitor
				);
           monitor.done();

           return searchRequestor.getMethodUnitPairs();
       } catch (CoreException e) {
           JavaPlugin.log(e);

           return new LinkedList();
       }
}
 
Example 11
Source File: ResolveClasspathsHandler.java    From java-debug with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Try to find the associated java element with the main class from the test folders.
 *
 * @param project the java project containing the main class
 * @param mainClass the main class name
 * @return the associated java element
 */
private static IJavaElement findMainClassInTestFolders(IJavaProject project, String mainClass) {
    if (project == null || StringUtils.isBlank(mainClass)) {
        return null;
    }

    // get a list of test folders and check whether main class is here
    int constraints = IJavaSearchScope.SOURCES;
    IJavaElement[] testFolders = JdtUtils.getTestPackageFragmentRoots(project);
    if (testFolders.length > 0) {
        try {

            List<IJavaElement> mainClassesInTestFolder = new ArrayList<>();
            SearchPattern pattern = SearchPattern.createPattern(mainClass, IJavaSearchConstants.CLASS,
                    IJavaSearchConstants.DECLARATIONS,
                    SearchPattern.R_CASE_SENSITIVE | SearchPattern.R_EXACT_MATCH);
            SearchEngine searchEngine = new SearchEngine();
            IJavaSearchScope scope = SearchEngine.createJavaSearchScope(testFolders, constraints);
            SearchRequestor requestor = new SearchRequestor() {
                @Override
                public void acceptSearchMatch(SearchMatch match) {
                    Object element = match.getElement();
                    if (element instanceof IJavaElement) {
                        mainClassesInTestFolder.add((IJavaElement) element);
                    }
                }
            };

            searchEngine.search(pattern, new SearchParticipant[] {
                        SearchEngine.getDefaultSearchParticipant()
                }, scope, requestor, null /* progress monitor */);

            if (!mainClassesInTestFolder.isEmpty()) {
                return mainClassesInTestFolder.get(0);
            }
        } catch (Exception e) {
            logger.log(Level.SEVERE, String.format("Searching the main class failure: %s", e.toString()), e);
        }
    }

    return null;
}
 
Example 12
Source File: ResolveClasspathsHandler.java    From java-debug with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Get java project from type.
 *
 * @param fullyQualifiedTypeName
 *            fully qualified name of type
 * @return java project
 * @throws CoreException
 *             CoreException
 */
public static List<IJavaProject> getJavaProjectFromType(String fullyQualifiedTypeName) throws CoreException {
    // If only one Java project exists in the whole workspace, return the project directly.
    List<IJavaProject> javaProjects = JdtUtils.listJavaProjects(ResourcesPlugin.getWorkspace().getRoot());
    if (javaProjects.size() <= 1) {
        return javaProjects;
    }

    String[] splitItems = fullyQualifiedTypeName.split("/");
    // If the main class name contains the module name, should trim the module info.
    if (splitItems.length == 2) {
        fullyQualifiedTypeName = splitItems[1];
    }
    final String moduleName = splitItems.length == 2 ? splitItems[0] : null;
    final String className = fullyQualifiedTypeName;
    SearchPattern pattern = SearchPattern.createPattern(
            fullyQualifiedTypeName,
            IJavaSearchConstants.TYPE,
            IJavaSearchConstants.DECLARATIONS,
            SearchPattern.R_EXACT_MATCH);
    IJavaSearchScope scope = SearchEngine.createWorkspaceScope();
    ArrayList<IJavaProject> projects = new ArrayList<>();
    SearchRequestor requestor = new SearchRequestor() {
        @Override
        public void acceptSearchMatch(SearchMatch match) {
            Object element = match.getElement();
            if (element instanceof IType) {
                IType type = (IType) element;
                IJavaProject project = type.getJavaProject();
                if (className.equals(type.getFullyQualifiedName())
                        && (moduleName == null || moduleName.equals(JdtUtils.getModuleName(project)))) {
                    projects.add(project);
                }
            }
        }
    };
    SearchEngine searchEngine = new SearchEngine();
    searchEngine.search(pattern, new SearchParticipant[] {
        SearchEngine.getDefaultSearchParticipant() }, scope,
        requestor, null /* progress monitor */);

    return projects.stream().distinct().collect(Collectors.toList());
}
 
Example 13
Source File: JDTUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public static IJavaElement[] findElementsAtSelection(ITypeRoot unit, int line, int column, PreferenceManager preferenceManager, IProgressMonitor monitor) throws JavaModelException {
	if (unit == null || monitor.isCanceled()) {
		return null;
	}
	int offset = JsonRpcHelpers.toOffset(unit.getBuffer(), line, column);
	if (offset > -1) {
		return unit.codeSelect(offset, 0);
	}
	if (unit instanceof IClassFile) {
		IClassFile classFile = (IClassFile) unit;
		ContentProviderManager contentProvider = JavaLanguageServerPlugin.getContentProviderManager();
		String contents = contentProvider.getSource(classFile, monitor);
		if (contents != null) {
			IDocument document = new Document(contents);
			try {
				offset = document.getLineOffset(line) + column;
				if (offset > -1) {
					String name = parse(contents, offset);
					if (name == null) {
						return null;
					}
					SearchPattern pattern = SearchPattern.createPattern(name, IJavaSearchConstants.TYPE,
							IJavaSearchConstants.DECLARATIONS, SearchPattern.R_FULL_MATCH);

					IJavaSearchScope scope = createSearchScope(unit.getJavaProject(), preferenceManager);

					List<IJavaElement> elements = new ArrayList<>();
					SearchRequestor requestor = new SearchRequestor() {
						@Override
						public void acceptSearchMatch(SearchMatch match) {
							if (match.getElement() instanceof IJavaElement) {
								elements.add((IJavaElement) match.getElement());
							}
						}
					};
					SearchEngine searchEngine = new SearchEngine();
					searchEngine.search(pattern,
							new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, scope,
							requestor, null);
					return elements.toArray(new IJavaElement[0]);
				}
			} catch (BadLocationException | CoreException e) {
				JavaLanguageServerPlugin.logException(e.getMessage(), e);
			}
		}
	}
	return null;
}
 
Example 14
Source File: RenameMethodProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private SearchResultGroup[] batchFindNewOccurrences(IMethod[] wcNewMethods, final IMethod[] wcOldMethods, ICompilationUnit[] newDeclarationWCs, IProgressMonitor pm, RefactoringStatus status) throws CoreException {
	pm.beginTask("", 2); //$NON-NLS-1$

	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<>();
	HashSet<ICompilationUnit> declaringCUs= new HashSet<>(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;
}
 
Example 15
Source File: CallerFinder.java    From lapse-plus with GNU General Public License v3.0 4 votes vote down vote up
public static Collection/*<MethodUnitPair>*/ findCallers(IProgressMonitor progressMonitor, String methodName, IJavaProject project, boolean isConstructor) {
      
try {
	
	MethodSearchRequestor.initializeParserMap();
	
      	SearchRequestor searchRequestor =  (SearchRequestor)new MethodSearchRequestor.MethodReferencesSearchRequestor();
	
          SearchEngine searchEngine = new SearchEngine();

          IProgressMonitor monitor = new SubProgressMonitor(progressMonitor, 5, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
          
          monitor.beginTask("Searching for calls to " + methodName + (project != null ? " in " + project.getProject().getName() : ""), 100);
          
          IJavaSearchScope searchScope = getSearchScope(project);
          
          // This is kind of hacky: we need to make up a string name for the search to work right
          
          log("Looking for calls to " + methodName);
          
          int matchType = !isConstructor ? IJavaSearchConstants.METHOD : IJavaSearchConstants.CONSTRUCTOR;
          
          SearchPattern pattern = SearchPattern.createPattern(
          		methodName, 
			matchType,
			IJavaSearchConstants.REFERENCES,
			SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE);
          
          searchEngine.search(
          		pattern, 
			new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()},
                  searchScope, 
			searchRequestor, 
			monitor
	);

          if(searchRequestor instanceof MethodSearchRequestor.MethodDeclarationsSearchRequestor){                
              return ((MethodSearchRequestor.MethodDeclarationsSearchRequestor)searchRequestor).getMethodUnitPairs();
          }else{
              return ((MethodSearchRequestor.MethodReferencesSearchRequestor)searchRequestor).getMethodUnitPairs();
          }
          
      } catch (CoreException e) {
          JavaPlugin.log(e);

          return new LinkedList();
      }
  }
 
Example 16
Source File: ImplementationCollector.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private List<T> findMethodImplementations(IProgressMonitor monitor) throws CoreException {
	IMethod method = (IMethod) javaElement;
	try {
		if (cannotBeOverriddenMethod(method)) {
			return null;
		}
	} catch (JavaModelException e) {
		JavaLanguageServerPlugin.logException("Find method implementations failure ", e);
		return null;
	}

	CompilationUnit ast = CoreASTProvider.getInstance().getAST(typeRoot, CoreASTProvider.WAIT_YES, monitor);
	if (ast == null) {
		return null;
	}

	ASTNode node = NodeFinder.perform(ast, region.getOffset(), region.getLength());
	ITypeBinding parentTypeBinding = null;
	if (node instanceof SimpleName) {
		ASTNode parent = node.getParent();
		if (parent instanceof MethodInvocation) {
			Expression expression = ((MethodInvocation) parent).getExpression();
			if (expression == null) {
				parentTypeBinding= Bindings.getBindingOfParentType(node);
			} else {
				parentTypeBinding = expression.resolveTypeBinding();
			}
		} else if (parent instanceof SuperMethodInvocation) {
			// Directly go to the super method definition
			return Collections.singletonList(mapper.convert(method, 0, 0));
		} else if (parent instanceof MethodDeclaration) {
			parentTypeBinding = Bindings.getBindingOfParentType(node);
		}
	}
	final IType receiverType = getType(parentTypeBinding);
	if (receiverType == null) {
		return null;
	}

	final List<T> results = new ArrayList<>();
	try {
		String methodLabel = JavaElementLabelsCore.getElementLabel(method, JavaElementLabelsCore.DEFAULT_QUALIFIED);
		monitor.beginTask(Messages.format(JavaElementImplementationHyperlink_search_method_implementors, methodLabel), 10);
		SearchRequestor requestor = new SearchRequestor() {
			@Override
			public void acceptSearchMatch(SearchMatch match) throws CoreException {
				if (match.getAccuracy() == SearchMatch.A_ACCURATE) {
					Object element = match.getElement();
					if (element instanceof IMethod) {
						IMethod methodFound = (IMethod) element;
						if (!JdtFlags.isAbstract(methodFound)) {
							T result = mapper.convert(methodFound, match.getOffset(), match.getLength());
							if (result != null) {
								results.add(result);
							}
						}
					}
				}
			}
		};

		IJavaSearchScope hierarchyScope;
		if (receiverType.isInterface()) {
			hierarchyScope = SearchEngine.createHierarchyScope(method.getDeclaringType());
		} else {
			if (isFullHierarchyNeeded(new SubProgressMonitor(monitor, 3), method, receiverType)) {
				hierarchyScope = SearchEngine.createHierarchyScope(receiverType);
			} else {
				boolean isMethodAbstract = JdtFlags.isAbstract(method);
				hierarchyScope = SearchEngine.createStrictHierarchyScope(null, receiverType, true, isMethodAbstract, null);
			}
		}

		int limitTo = IJavaSearchConstants.DECLARATIONS | IJavaSearchConstants.IGNORE_DECLARING_TYPE | IJavaSearchConstants.IGNORE_RETURN_TYPE;
		SearchPattern pattern = SearchPattern.createPattern(method, limitTo);
		Assert.isNotNull(pattern);
		SearchParticipant[] participants = new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() };
		SearchEngine engine = new SearchEngine();
		engine.search(pattern, participants, hierarchyScope, requestor, new SubProgressMonitor(monitor, 7));
		if (monitor.isCanceled()) {
			throw new OperationCanceledException();
		}
	} finally {
		monitor.done();
	}
	return results;
}
 
Example 17
Source File: ReferencesHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public List<Location> findReferences(ReferenceParams param, IProgressMonitor monitor) {

		final List<Location> locations = new ArrayList<>();
		try {
			IJavaElement elementToSearch = JDTUtils.findElementAtSelection(JDTUtils.resolveTypeRoot(param.getTextDocument().getUri()), param.getPosition().getLine(), param.getPosition().getCharacter(), this.preferenceManager, monitor);

			if (elementToSearch == null) {
				return locations;
			}

			boolean includeClassFiles = preferenceManager.isClientSupportsClassFileContent();
			SearchEngine engine = new SearchEngine();
			SearchPattern pattern = SearchPattern.createPattern(elementToSearch, IJavaSearchConstants.REFERENCES);

			engine.search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, createSearchScope(), new SearchRequestor() {

				@Override
				public void acceptSearchMatch(SearchMatch match) throws CoreException {
					Object o = match.getElement();
					if (o instanceof IJavaElement) {
						IJavaElement element = (IJavaElement) o;
						ICompilationUnit compilationUnit = (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT);
						Location location = null;
						if (compilationUnit != null) {
							location = JDTUtils.toLocation(compilationUnit, match.getOffset(), match.getLength());
						} else if (includeClassFiles) {
							IClassFile cf = (IClassFile) element.getAncestor(IJavaElement.CLASS_FILE);
							if (cf != null && cf.getSourceRange() != null) {
								location = JDTUtils.toLocation(cf, match.getOffset(), match.getLength());
							}
						}
						if (location != null) {
							locations.add(location);
						}
					}
				}
			}, monitor);

		} catch (CoreException e) {
			JavaLanguageServerPlugin.logException("Find references failure ", e);
		}
		return locations;
	}
 
Example 18
Source File: ChangeSignatureProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private SearchResultGroup[] findOccurrences(IProgressMonitor pm, ReferencesInBinaryContext binaryRefs, RefactoringStatus status) throws JavaModelException{
		final boolean isConstructor= fMethod.isConstructor();
		CuCollectingSearchRequestor requestor= new CuCollectingSearchRequestor(binaryRefs) {
			@Override
			protected void acceptSearchMatch(ICompilationUnit unit, SearchMatch match) throws CoreException {
				// workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=27236 :
				if (isConstructor && match instanceof MethodReferenceMatch) {
					MethodReferenceMatch mrm= (MethodReferenceMatch) match;
					if (mrm.isSynthetic()) {
						return;
					}
				}
				collectMatch(match);
			}
		};

		SearchPattern pattern;
		if (isConstructor) {

//			// workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=226151 : don't find binary refs for constructors for now
//			return ConstructorReferenceFinder.getConstructorOccurrences(fMethod, pm, status);

//			SearchPattern occPattern= SearchPattern.createPattern(fMethod, IJavaSearchConstants.ALL_OCCURRENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
			SearchPattern declPattern= SearchPattern.createPattern(fMethod, IJavaSearchConstants.DECLARATIONS, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
			SearchPattern refPattern= SearchPattern.createPattern(fMethod, IJavaSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
//			pattern= SearchPattern.createOrPattern(declPattern, refPattern);
//			pattern= occPattern;

			// workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=226151 : do two searches
			try {
				SearchEngine engine= new SearchEngine();
				engine.search(declPattern, SearchUtils.getDefaultSearchParticipants(), createRefactoringScope(), requestor, new NullProgressMonitor());
				engine.search(refPattern, SearchUtils.getDefaultSearchParticipants(), createRefactoringScope(), requestor, pm);
			} catch (CoreException e) {
				throw new JavaModelException(e);
			}
			return RefactoringSearchEngine.groupByCu(requestor.getResults(), status);

		} else {
			pattern= RefactoringSearchEngine.createOrPattern(fRippleMethods, IJavaSearchConstants.ALL_OCCURRENCES);
		}
		return RefactoringSearchEngine.search(pattern, createRefactoringScope(), requestor, pm, status);
	}
 
Example 19
Source File: RenameMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private SearchResultGroup[] batchFindNewOccurrences(IMethod[] wcNewMethods, final IMethod[] wcOldMethods, ICompilationUnit[] newDeclarationWCs, IProgressMonitor pm, RefactoringStatus status) throws CoreException {
	pm.beginTask("", 2); //$NON-NLS-1$

	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;
}
 
Example 20
Source File: SourceView.java    From lapse-plus with GNU General Public License v3.0 4 votes vote down vote up
int addMethodsByName(String methodName, String type, String category, JavaProject project, IProgressMonitor monitor, boolean nonWeb) {
	int matches = 0;
	ViewContentProvider cp = ((ViewContentProvider)viewer.getContentProvider());
	try {
		MethodDeclarationsSearchRequestor requestor = new MethodDeclarationsSearchRequestor();
           SearchEngine searchEngine = new SearchEngine();

           IJavaSearchScope searchScope = CallerFinder.getSearchScope(project);
           SearchPattern pattern = SearchPattern.createPattern(
           		methodName, 
				IJavaSearchConstants.METHOD,
				IJavaSearchConstants.DECLARATIONS, 
				SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CASE_SENSITIVE
				);
    
		searchEngine.search(
				pattern, 
				new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() },
		        searchScope, 
		        requestor, 
				monitor
				);
		Collection pairs =  requestor.getMethodUnitPairs();
		for(Iterator iter = pairs.iterator(); iter.hasNext();) {
			Utils.MethodDeclarationUnitPair pair = (MethodDeclarationUnitPair) iter.next();
			ViewMatch match = new ViewMatch(
					pair.getMember().getDeclaringType().getElementName() + "." + pair.getMember().getElementName(),  
					pair.getMethod() != null ? pair.getMethod().getName() : null, 
					pair.getCompilationUnit(), 
					pair.getResource(), 
					type,
					category,
					pair.getMember(),
					false,
					nonWeb);
			cp.addMatch(match);
			monitor.subTask("Found " + matches + " matches");
			matches++;
		}
	} catch (CoreException e) {
		// TODO Auto-generated catch block
		log(e.getMessage(), e);
	}
	
	return matches;
}