org.eclipse.jdt.core.search.SearchParticipant Java Examples

The following examples show how to use org.eclipse.jdt.core.search.SearchParticipant. 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: 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 #5
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 #6
Source File: TypeParameterPattern.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public void findIndexMatches(Index index, IndexQueryRequestor requestor, SearchParticipant participant, IJavaSearchScope scope, IProgressMonitor progressMonitor) {
    IPackageFragmentRoot root = (IPackageFragmentRoot) this.typeParameter.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
	String documentPath;
	String relativePath;
    if (root.isArchive()) {
	    	IType type = (IType) this.typeParameter.getAncestor(IJavaElement.TYPE);
   	    relativePath = (type.getFullyQualifiedName('$')).replace('.', '/') + SuffixConstants.SUFFIX_STRING_class;
        documentPath = root.getPath() + IJavaSearchScope.JAR_FILE_ENTRY_SEPARATOR + relativePath;
    } else {
		IPath path = this.typeParameter.getPath();
        documentPath = path.toString();
		relativePath = Util.relativePath(path, 1/*remove project segment*/);
    }

	if (scope instanceof JavaSearchScope) {
		JavaSearchScope javaSearchScope = (JavaSearchScope) scope;
		// Get document path access restriction from java search scope
		// Note that requestor has to verify if needed whether the document violates the access restriction or not
		AccessRuleSet access = javaSearchScope.getAccessRuleSet(relativePath, index.containerPath);
		if (access != JavaSearchScope.NOT_ENCLOSED) { // scope encloses the path
			if (!requestor.acceptIndexMatch(documentPath, this, participant, access))
				throw new OperationCanceledException();
		}
	} else if (scope.encloses(documentPath)) {
		if (!requestor.acceptIndexMatch(documentPath, this, participant, null))
			throw new OperationCanceledException();
	}
}
 
Example #7
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 #8
Source File: DefaultJavaIndexer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public void generateIndexForJar(String pathToJar, String pathToIndexFile) throws IOException {
	File f = new File(pathToJar);
	if (!f.exists()) {
		throw new FileNotFoundException(pathToJar + " not found"); //$NON-NLS-1$
	}
	IndexLocation indexLocation = new FileIndexLocation(new File(pathToIndexFile));
	Index index = new Index(indexLocation, pathToJar, false /*reuse index file*/);
	SearchParticipant participant = SearchEngine.getDefaultSearchParticipant();
	index.separator = JAR_SEPARATOR;
	ZipFile zip = new ZipFile(pathToJar);
	try {
		for (Enumeration e = zip.entries(); e.hasMoreElements();) {
			// iterate each entry to index it
			ZipEntry ze = (ZipEntry) e.nextElement();
			String zipEntryName = ze.getName();
			if (Util.isClassFileName(zipEntryName)) {
				final byte[] classFileBytes = org.eclipse.jdt.internal.compiler.util.Util.getZipEntryByteContent(ze, zip);
				JavaSearchDocument entryDocument = new JavaSearchDocument(ze, new Path(pathToJar), classFileBytes, participant);
				entryDocument.setIndex(index);
				new BinaryIndexer(entryDocument).indexDocument();
			}
		}
		index.save();
	} finally {
		zip.close();
	}
	return;
}
 
Example #9
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 #10
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 #11
Source File: JavaSearchDocument.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public JavaSearchDocument(String documentPath, SearchParticipant participant) {
	super(documentPath, participant);
}
 
Example #12
Source File: PathCollector.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) {
	this.paths.add(documentPath);
	return true;
}
 
Example #13
Source File: NewSearchResultCollector.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void exitParticipant(SearchParticipant participant) {
}
 
Example #14
Source File: NewSearchResultCollector.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void enterParticipant(SearchParticipant participant) {
}
 
Example #15
Source File: JavaSearchDocument.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public JavaSearchDocument(java.util.zip.ZipEntry zipEntry, IPath zipFilePath, byte[] contents, SearchParticipant participant) {
	super(zipFilePath + IJavaSearchScope.JAR_FILE_ENTRY_SEPARATOR + zipEntry.getName(), participant);
	this.byteContents = contents;
}
 
Example #16
Source File: SearchUtils.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static SearchParticipant[] getDefaultSearchParticipants() {
	return new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() };
}
 
Example #17
Source File: NLSSearchQuery.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public IStatus run(IProgressMonitor monitor) {
	monitor.beginTask("", 5 * fWrapperClass.length); //$NON-NLS-1$

	try {
		final AbstractTextSearchResult textResult= (AbstractTextSearchResult) getSearchResult();
		textResult.removeAll();

		for (int i= 0; i < fWrapperClass.length; i++) {
			IJavaElement wrapperClass= fWrapperClass[i];
			IFile propertieFile= fPropertiesFile[i];
			if (! wrapperClass.exists())
				return JavaUIStatus.createError(0, Messages.format(NLSSearchMessages.NLSSearchQuery_wrapperNotExists, JavaElementLabels.getElementLabel(wrapperClass, JavaElementLabels.ALL_DEFAULT)), null);
			if (! propertieFile.exists())
				return JavaUIStatus.createError(0, Messages.format(NLSSearchMessages.NLSSearchQuery_propertiesNotExists, BasicElementLabels.getResourceName(propertieFile)), null);

			SearchPattern pattern= SearchPattern.createPattern(wrapperClass, IJavaSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
			SearchParticipant[] participants= new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()};

			NLSSearchResultRequestor requestor= new NLSSearchResultRequestor(propertieFile, fResult);
			try {
				SearchEngine engine= new SearchEngine();
				engine.search(pattern, participants, fScope, requestor, new SubProgressMonitor(monitor, 4));
				requestor.reportUnusedPropertyNames(new SubProgressMonitor(monitor, 1));

				ICompilationUnit compilationUnit= ((IType)wrapperClass).getCompilationUnit();
				CompilationUnitEntry groupElement= new CompilationUnitEntry(NLSSearchMessages.NLSSearchResultCollector_unusedKeys, compilationUnit);

				boolean hasUnusedPropertie= false;
				IField[] fields= ((IType)wrapperClass).getFields();
				for (int j= 0; j < fields.length; j++) {
					IField field= fields[j];
					if (isNLSField(field)) {
						ISourceRange sourceRange= field.getSourceRange();
						if (sourceRange != null) {
							String fieldName= field.getElementName();
							if (!requestor.hasPropertyKey(fieldName)) {
								fResult.addMatch(new Match(compilationUnit, sourceRange.getOffset(), sourceRange.getLength()));
							}
							if (!requestor.isUsedPropertyKey(fieldName)) {
								hasUnusedPropertie= true;
								fResult.addMatch(new Match(groupElement, sourceRange.getOffset(), sourceRange.getLength()));
							}
						}
					}
				}
				if (hasUnusedPropertie)
					fResult.addCompilationUnitGroup(groupElement);

			} catch (CoreException e) {
				return new Status(e.getStatus().getSeverity(), JavaPlugin.getPluginId(), IStatus.OK, NLSSearchMessages.NLSSearchQuery_error, e);
			}
		}
	} finally {
		monitor.done();
	}
	return 	Status.OK_STATUS;
}
 
Example #18
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 #19
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 #20
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 #21
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 #22
Source File: SearchUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public static SearchParticipant[] getDefaultSearchParticipants() {
	return new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() };
}
 
Example #23
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 #24
Source File: ProjectAwareUniqueClassNameValidator.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
public boolean doCheckUniqueInProject(QualifiedName name, JvmDeclaredType type) throws JavaModelException {
	IJavaProject javaProject = javaProjectProvider.getJavaProject(type.eResource().getResourceSet());
	getContext().put(ProjectAwareUniqueClassNameValidator.OUTPUT_CONFIGS,
			outputConfigurationProvider.getOutputConfigurations(type.eResource()));

	String packageName = type.getPackageName();
	String typeName = type.getSimpleName();
	IndexManager indexManager = JavaModelManager.getIndexManager();
	List<IPackageFragmentRoot> sourceFolders = new ArrayList<>();
	for (IPackageFragmentRoot root : javaProject.getPackageFragmentRoots()) {
		if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
			sourceFolders.add(root);
		}
	}

	if (sourceFolders.isEmpty() || indexManager.awaitingJobsCount() > 0) {
		// still indexing - don't enter a busy wait loop but ask the source folders directly
		SourceTraversal sourceTraversal = doCheckUniqueInProjectSource(packageName != null ? packageName : "", typeName, type,
				sourceFolders);
		if (sourceTraversal == SourceTraversal.DUPLICATE) {
			return false;
		} else if (sourceTraversal == SourceTraversal.UNIQUE) {
			return true;
		}
	}

	Set<String> workingCopyPaths = new HashSet<>();
	ICompilationUnit[] copies = getWorkingCopies(type);
	if (copies != null) {
		for (ICompilationUnit workingCopy : copies) {
			IPath path = workingCopy.getPath();
			if (javaProject.getPath().isPrefixOf(path) && !isDerived(workingCopy.getResource())) {
				if (workingCopy.getPackageDeclaration(packageName).exists()) {
					IType result = workingCopy.getType(typeName);
					if (result.exists()) {
						addIssue(type, workingCopy.getElementName());
						return false;
					}
				}
				workingCopyPaths.add(workingCopy.getPath().toString());
			}
		}
	}

	// The code below is adapted from BasicSearchEnginge.searchAllSecondaryTypes
	// The Index is ready, query it for a secondary type 
	char[] pkg = packageName == null ? CharOperation.NO_CHAR : packageName.toCharArray();
	TypeDeclarationPattern pattern = new TypeDeclarationPattern(pkg, //
			CharOperation.NO_CHAR_CHAR, // top level type - no enclosing type names
			typeName.toCharArray(), //
			IIndexConstants.TYPE_SUFFIX, //
			SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE);

	IndexQueryRequestor searchRequestor = new IndexQueryRequestor() {

		@Override
		public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant,
				AccessRuleSet access) {
			if (workingCopyPaths.contains(documentPath)) {
				return true; // filter out working copies
			}
			IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(documentPath));
			if (!isDerived(file)) {
				addIssue(type, file.getName());
				return false;
			}
			return true;
		}
	};

	try {
		SearchParticipant searchParticipant = BasicSearchEngine.getDefaultSearchParticipant(); // Java search only
		IJavaSearchScope javaSearchScope = BasicSearchEngine.createJavaSearchScope(sourceFolders.toArray(new IJavaElement[0]));
		PatternSearchJob patternSearchJob = new PatternSearchJob(pattern, searchParticipant, javaSearchScope, searchRequestor);
		indexManager.performConcurrentJob(patternSearchJob, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null);
		return true;
	} catch (Throwable OperationCanceledException) {
		return false;
	}
}
 
Example #25
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 #26
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 #27
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 #28
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;
}
 
Example #29
Source File: IndexQueryRequestor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 votes vote down vote up
public abstract boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access);