/** * search the bundle that contains the Main class. The search is done in the * workspace scope (ie. if it is defined in the current workspace it will * find it * * @return the name of the bundle containing the Main class or null if not * found */ private IType getITypeMainByWorkspaceScope(String className) { SearchPattern pattern = SearchPattern.createPattern(className, IJavaSearchConstants.CLASS, IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH); IJavaSearchScope scope = SearchEngine.createWorkspaceScope(); final List<IType> binaryType = new ArrayList<IType>(); SearchRequestor requestor = new SearchRequestor() { @Override public void acceptSearchMatch(SearchMatch match) throws CoreException { binaryType.add((IType) match.getElement()); } }; SearchEngine engine = new SearchEngine(); try { engine.search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, scope, requestor, null); } catch (CoreException e1) { throw new RuntimeException("Error while searching the bundle: " + e1.getMessage()); // return new Status(IStatus.ERROR, Activator.PLUGIN_ID, ); } return binaryType.isEmpty() ? null : binaryType.get(0); }
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); }
private List<IType> searchType(String classFQN, IProgressMonitor monitor) { classFQN = classFQN.replace('$', '.'); final List<IType> types = new ArrayList<IType>(); IJavaSearchScope scope = SearchEngine.createWorkspaceScope(); SearchEngine engine = new SearchEngine(); SearchPattern pattern = SearchPattern.createPattern(classFQN, IJavaSearchConstants.TYPE, IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH); SearchRequestor requestor = new SearchRequestor() { public void acceptSearchMatch(final SearchMatch match) throws CoreException { TypeDeclarationMatch typeMatch = (TypeDeclarationMatch) match; IType type = (IType) typeMatch.getElement(); types.add(type); } }; try { engine.search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, scope, requestor, monitor); } catch (final CoreException e) { return types; } return types; }
private static List<Controller> search(IJavaProject project, SearchPattern namePattern) throws JavaModelException, CoreException { List<Controller> controllers = new ArrayList<Controller>(); IJavaSearchScope scope = SearchEngine.createJavaSearchScope(project.getPackageFragments()); SearchRequestor requestor = new SearchRequestor() { @Override public void acceptSearchMatch(SearchMatch match) { if (match.getElement() instanceof IJavaElement) { IJavaElement element = (IJavaElement) match.getElement(); controllers.add(new Controller((IType) element)); } } }; SearchEngine searchEngine = new SearchEngine(); searchEngine.search(namePattern, new SearchParticipant[] {SearchEngine .getDefaultSearchParticipant()}, scope, requestor, null); return controllers; }
private IType[] searchForOuterTypesOfReferences(IMethod[] newNameMethods, IProgressMonitor pm) throws CoreException { final Set<IType> outerTypesOfReferences = new HashSet<IType>(); SearchPattern pattern = RefactoringSearchEngine.createOrPattern(newNameMethods, IJavaSearchConstants.REFERENCES); IJavaSearchScope scope = createRefactoringScope(getMethod()); SearchRequestor requestor = new SearchRequestor() { @Override public void acceptSearchMatch(SearchMatch match) throws CoreException { Object element = match.getElement(); if (!(element instanceof IMember)) return; // e.g. an IImportDeclaration for a static method import IMember member = (IMember) element; IType declaring = member.getDeclaringType(); if (declaring == null) return; IType outer = declaring.getDeclaringType(); if (outer != null) outerTypesOfReferences.add(declaring); } }; new SearchEngine() .search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor, pm); return outerTypesOfReferences.toArray(new IType[outerTypesOfReferences.size()]); }
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 (method instanceof IMethod) // check for bug 90138: [refactoring] [rename] Renaming method throws // internal exception results.add((IMethod) method); else JavaPlugin.logErrorMessage( "Unexpected element in search match: " + match.toString()); // $NON-NLS-1$ } }; new SearchEngine() .search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor, pm); return results.toArray(new IMethod[results.size()]); }
private IType[] searchForOuterTypesOfReferences(IMethod[] newNameMethods, IProgressMonitor pm) throws CoreException { final Set<IType> outerTypesOfReferences= new HashSet<IType>(); SearchPattern pattern= RefactoringSearchEngine.createOrPattern(newNameMethods, IJavaSearchConstants.REFERENCES); IJavaSearchScope scope= createRefactoringScope(getMethod()); SearchRequestor requestor= new SearchRequestor() { @Override public void acceptSearchMatch(SearchMatch match) throws CoreException { Object element= match.getElement(); if (!(element instanceof IMember)) return; // e.g. an IImportDeclaration for a static method import IMember member= (IMember) element; IType declaring= member.getDeclaringType(); if (declaring == null) return; IType outer= declaring.getDeclaringType(); if (outer != null) outerTypesOfReferences.add(declaring); } }; new SearchEngine().search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor, pm); return outerTypesOfReferences.toArray(new IType[outerTypesOfReferences.size()]); }
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 (method instanceof IMethod) // check for bug 90138: [refactoring] [rename] Renaming method throws internal exception results.add((IMethod) method); else JavaPlugin.logErrorMessage("Unexpected element in search match: " + match.toString()); //$NON-NLS-1$ } }; new SearchEngine().search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor, pm); return results.toArray(new IMethod[results.size()]); }
/** * @param scope search scope * @param pm mrogress monitor * @return all package fragments in <code>scope</code> with same name as <code>fPackage</code>, excluding fPackage * @throws CoreException if search failed */ private IPackageFragment[] getNamesakePackages(IJavaSearchScope scope, IProgressMonitor pm) throws CoreException { SearchPattern pattern= SearchPattern.createPattern(fPackage.getElementName(), IJavaSearchConstants.PACKAGE, IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE); final HashSet<IPackageFragment> packageFragments= new HashSet<IPackageFragment>(); SearchRequestor requestor= new SearchRequestor() { @Override public void acceptSearchMatch(SearchMatch match) throws CoreException { IJavaElement enclosingElement= SearchUtils.getEnclosingJavaElement(match); if (enclosingElement instanceof IPackageFragment) { IPackageFragment pack= (IPackageFragment) enclosingElement; if (! fPackage.equals(pack)) packageFragments.add(pack); } } }; new SearchEngine().search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor, pm); return packageFragments.toArray(new IPackageFragment[packageFragments.size()]); }
public SearchRequestor createSearchRequestor() { SearchRequestor requestor = new SearchRequestor() { @Override public void acceptSearchMatch(SearchMatch match) throws CoreException { IJavaElement type = null; if(match.getElement() instanceof ResolvedSourceMethod) { type = ((ResolvedSourceMethod )match.getElement()).getParent(); } else if(match.getElement() instanceof ResolvedSourceType) { type = ((ResolvedSourceType )match.getElement()).getParent(); } else if(match.getElement() instanceof ResolvedSourceField) { type = ((ResolvedSourceField)match.getElement()).getParent(); } if(null != type && inChangedFiles(type.getElementName())) { addMatched(match); } } }; return requestor; }
/** * Find all java files that match the class name * * @param cls * The class name * @return List of java files */ public static List<IJavaElement> search(String cls) { final List<IJavaElement> javaElements = new ArrayList<IJavaElement>(); IJavaSearchScope scope = SearchEngine.createWorkspaceScope(); SearchEngine engine = new SearchEngine(); SearchPattern pattern = SearchPattern.createPattern(cls.split("\\.")[0], IJavaSearchConstants.TYPE, IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH); SearchRequestor requestor = new SearchRequestor() { public void acceptSearchMatch(final SearchMatch match) throws CoreException { TypeDeclarationMatch typeMatch = (TypeDeclarationMatch) match; IJavaElement type = (IJavaElement) typeMatch.getElement(); javaElements.add(type); } }; try { engine.search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, scope, requestor, new NullProgressMonitor()); } catch (final CoreException e) { e.printStackTrace(); } return javaElements; }
protected void search(String patternString, int searchFor, int limitTo, int matchRule, IJavaSearchScope scope, SearchRequestor requestor) throws CoreException { if (patternString.indexOf('*') != -1 || patternString.indexOf('?') != -1) matchRule |= SearchPattern.R_PATTERN_MATCH; SearchPattern pattern = SearchPattern.createPattern( patternString, searchFor, limitTo, matchRule); assertNotNull("Pattern should not be null", pattern); new SearchEngine().search( pattern, new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()}, scope, requestor, null); }
/** * Get java project from type. * * @param fullyQualifiedTypeName * fully qualified name of type * @return java project * @throws CoreException * CoreException */ private static List<IJavaProject> getJavaProjectFromType(String fullyQualifiedTypeName) throws CoreException { 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; 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 IJavaElement) { IJavaProject project = ((IJavaElement) element).getJavaProject(); if (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()); }
public void renameOccurrences(WorkspaceEdit edit, String newName, IProgressMonitor monitor) throws CoreException { if (fElement == null || !canRename()) { return; } IJavaElement[] elementsToSearch = null; if (fElement instanceof IMethod) { elementsToSearch = RippleMethodFinder.getRelatedMethods((IMethod) fElement, monitor, null); } else { elementsToSearch = new IJavaElement[] { fElement }; } SearchPattern pattern = createOccurrenceSearchPattern(elementsToSearch); if (pattern == null) { return; } 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 element = (IJavaElement) o; ICompilationUnit compilationUnit = (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT); if (compilationUnit == null) { return; } TextEdit replaceEdit = collectMatch(match, element, compilationUnit, newName); if (replaceEdit != null) { convert(edit, compilationUnit, replaceEdit); } } } }, monitor); }
private Set<SearchMatch> findReferences(Set<? extends IJavaElement> elements) throws CoreException { Set<SearchMatch> ret = new HashSet<>(); for (IJavaElement elem : elements) new SearchEngine().search( SearchPattern.createPattern(elem, IJavaSearchConstants.REFERENCES, SearchPattern.R_EXACT_MATCH), new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, SearchEngine.createWorkspaceScope(), new SearchRequestor() { @Override public void acceptSearchMatch(SearchMatch match) throws CoreException { ret.add(match); } }, new NullProgressMonitor()); return ret; }
void commenceSearch(SearchEngine engine, SearchPattern pattern, IJavaSearchScope scope, final SearchMatchPurpose purpose, IProgressMonitor monitor) throws CoreException { engine.search(pattern, new SearchParticipant[] { SearchEngine .getDefaultSearchParticipant() }, scope, new SearchRequestor() { public void acceptSearchMatch(SearchMatch match) throws CoreException { if (match.getAccuracy() == SearchMatch.A_ACCURATE && !match.isInsideDocComment()) matchToPurposeMap.put(match, purpose); } }, new SubProgressMonitor(monitor, 1, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)); }
private void findParameters(final int paramNumber, SearchPattern pattern) throws CoreException { final SearchRequestor requestor = new SearchRequestor() { public void acceptSearchMatch(SearchMatch match) throws CoreException { if (match.getAccuracy() == SearchMatch.A_ACCURATE && !match.isInsideDocComment()) { IJavaElement elem = (IJavaElement) match.getElement(); ASTNode node = Util.getASTNode(elem, ASTNodeProcessor.this.monitor); ParameterProcessingVisitor visitor = new ParameterProcessingVisitor( paramNumber, match.getOffset()); node.accept(visitor); ASTNodeProcessor.this.found.addAll(visitor.getElements()); for (Iterator it = visitor.getExpressions().iterator(); it .hasNext();) { Expression exp = (Expression) it.next(); ASTNodeProcessor.this.processExpression(exp); } } } }; final SearchEngine searchEngine = new SearchEngine(); searchEngine.search(pattern, new SearchParticipant[] { SearchEngine .getDefaultSearchParticipant() }, this.scope, requestor, null); }
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); }
/** * @param scope search scope * @param pm mrogress monitor * @return all package fragments in <code>scope</code> with same name as <code>fPackage</code>, * excluding fPackage * @throws CoreException if search failed */ private IPackageFragment[] getNamesakePackages(IJavaSearchScope scope, IProgressMonitor pm) throws CoreException { SearchPattern pattern = SearchPattern.createPattern( fPackage.getElementName(), IJavaSearchConstants.PACKAGE, IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE); final HashSet<IPackageFragment> packageFragments = new HashSet<IPackageFragment>(); SearchRequestor requestor = new SearchRequestor() { @Override public void acceptSearchMatch(SearchMatch match) throws CoreException { IJavaElement enclosingElement = SearchUtils.getEnclosingJavaElement(match); if (enclosingElement instanceof IPackageFragment) { IPackageFragment pack = (IPackageFragment) enclosingElement; if (!fPackage.equals(pack)) packageFragments.add(pack); } } }; new SearchEngine() .search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor, pm); return packageFragments.toArray(new IPackageFragment[packageFragments.size()]); }
private List<String> getExistingCategories() { if(existingCategories==null) { final Set<String> categories = new TreeSet<String>(); if(selectedJavaProject!=null) { SearchRequestor requestor = new SearchRequestor() { @Override public void acceptSearchMatch(SearchMatch match) throws CoreException { if(match.getElement() instanceof IType) { String fqn = ((IType) match.getElement()).getFullyQualifiedName(); if(!fqn.startsWith("net.sf.jasperreports.functions.standard")) { // avoid to propose standard functions categories categories.add(fqn); } } } }; IJavaElement[] elements= new IJavaElement[] { selectedJavaProject }; IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements); int matchRule= SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE; SearchPattern fullAnnotationPattern= SearchPattern.createPattern( "net.sf.jasperreports.functions.annotations.FunctionCategory", IJavaSearchConstants.ANNOTATION_TYPE, IJavaSearchConstants.ANNOTATION_TYPE_REFERENCE, matchRule); SearchPattern simpleNamePattern= SearchPattern.createPattern( "FunctionCategory", IJavaSearchConstants.ANNOTATION_TYPE, IJavaSearchConstants.ANNOTATION_TYPE_REFERENCE, matchRule); SearchPattern annotationsPattern= SearchPattern.createOrPattern(fullAnnotationPattern, simpleNamePattern); SearchParticipant[] searchParticipants= new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }; try { new SearchEngine().search(annotationsPattern, searchParticipants, scope, requestor,new NullProgressMonitor()); } catch (CoreException e) { } } existingCategories = new ArrayList<String>(categories); ((NewFunctionsLibraryWizard)getWizard()).setAvailableCategories(existingCategories); } return existingCategories; }
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); }
/** * Searches for all main methods in the given scope. * Valid styles are IJavaElementSearchConstants.CONSIDER_BINARIES and * IJavaElementSearchConstants.CONSIDER_EXTERNAL_JARS * @param pm progress monitor * @param scope the search scope * @param style search style constants (see {@link IJavaElementSearchConstants}) * @return the types found * @throws CoreException */ public IType[] searchMainMethods(IProgressMonitor pm, IJavaSearchScope scope, int style) throws CoreException { List<IType> typesFound= new ArrayList<IType>(200); SearchPattern pattern= SearchPattern.createPattern("main(String[]) void", //$NON-NLS-1$ IJavaSearchConstants.METHOD, IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE); SearchRequestor requestor= new MethodCollector(typesFound, style); new SearchEngine().search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor, pm); return typesFound.toArray(new IType[typesFound.size()]); }
private void proposePackage(final ContentAssistRequest contentAssistRequest, IJavaProject project, String matchString, final int start, final int length) throws CoreException { final List<ICompletionProposal> results = new ArrayList<ICompletionProposal>(); final Set<String> foundPkgs = new HashSet<String>(); int includeMask = IJavaSearchScope.SOURCES | IJavaSearchScope.REFERENCED_PROJECTS; // Include application libraries only when package is specified (for better performance). boolean pkgSpecified = matchString != null && matchString.indexOf('.') > 0; if (pkgSpecified) includeMask |= IJavaSearchScope.APPLICATION_LIBRARIES | IJavaSearchScope.SYSTEM_LIBRARIES; IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaProject[]{ project }, includeMask); SearchRequestor requestor = new SearchRequestor() { @Override public void acceptSearchMatch(SearchMatch match) throws CoreException { PackageFragment element = (PackageFragment)match.getElement(); String pkg = element.getElementName(); if (pkg != null && pkg.length() > 0 && !foundPkgs.contains(pkg)) { foundPkgs.add(pkg); results.add(new CompletionProposal(pkg, start, length, pkg.length(), Activator.getIcon(), pkg, null, null)); } } }; searchPackage(matchString, scope, requestor); addProposals(contentAssistRequest, results); }
private void searchPackage(String matchString, IJavaSearchScope scope, SearchRequestor requestor) throws CoreException { SearchPattern pattern = SearchPattern.createPattern(matchString + "*", IJavaSearchConstants.PACKAGE, IJavaSearchConstants.DECLARATIONS, SearchPattern.R_PREFIX_MATCH); SearchEngine searchEngine = new SearchEngine(); searchEngine.search(pattern, new SearchParticipant[]{ SearchEngine.getDefaultSearchParticipant() }, scope, requestor, null); }
private List<IMember> findElementReferences(IMember iMember, IProgressMonitor pm) { final List<IMember> references = new ArrayList<IMember>(); SearchRequestor requestor = new SearchRequestor() { @Override public void acceptSearchMatch(SearchMatch match) throws CoreException { if (match.getAccuracy() == SearchMatch.A_ACCURATE) references.add((IMember) match.getElement()); } }; SearchEngine engine = new SearchEngine(); IJavaSearchScope workspaceScope = SearchEngine.createWorkspaceScope(); SearchPattern pattern = SearchPattern.createPattern(iMember, IJavaSearchConstants.ALL_OCCURRENCES, SearchPattern.R_EXACT_MATCH); SearchParticipant[] participant = new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }; try { engine.search(pattern, participant, workspaceScope, requestor, pm); } catch (CoreException e) { e.printStackTrace(); } return references; }
private static List<SearchMatch> searchJava(IProject project, SearchPattern pattern) { IJavaSearchScope scope = SearchEngine.createJavaSearchScope( new IJavaElement[] { JavaCore.create(project) }, true); final List<SearchMatch> matches = new ArrayList<SearchMatch>(); SearchRequestor requestor = new SearchRequestor() { @Override public void acceptSearchMatch(SearchMatch match) throws CoreException { matches.add(match); } }; SearchEngine searchEngine = new SearchEngine(); try { searchEngine.search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, scope, requestor, null); } catch (CoreException e) { Activator.getDefault().logWarning("Error performing search", e);; } return matches; }
protected void search(IJavaElement element, int limitTo, int matchRule, IJavaSearchScope scope, SearchRequestor requestor) throws CoreException { SearchPattern pattern = SearchPattern.createPattern(element, limitTo, matchRule); assertNotNull("Pattern should not be null", pattern); new SearchEngine().search( pattern, new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()}, scope, requestor, null ); }
public static IJavaElement[] findElementsAtSelection(ITypeRoot unit, int line, int column) throws JavaModelException, BadLocationException { if (unit == null) { return null; } int offset = toDocument(unit.getBuffer()).getLineOffset(line) + column; if (offset > -1) { return unit.codeSelect(offset, 0); } if (unit instanceof IClassFile) { IClassFile classFile = (IClassFile) unit; String contents = disassemble(classFile); 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()); 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; }
public static IJavaElement[] findElementsAtSelection(ITypeRoot unit, int line, int column, PreferenceManager preferenceManager, IProgressMonitor monitor) throws JavaModelException { if (unit == null) { 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()); 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; }
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; } 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{ 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; }
public static ICompilationUnit[] findAffectedCompilationUnits( SearchPattern pattern, IJavaSearchScope scope, final IProgressMonitor pm, RefactoringStatus status, final boolean tolerateInAccurateMatches) throws JavaModelException { boolean hasNonCuMatches = false; class ResourceSearchRequestor extends SearchRequestor { boolean hasPotentialMatches = false; Set<IResource> resources = new HashSet<IResource>(5); private IResource fLastResource; @Override public void acceptSearchMatch(SearchMatch match) { if (!tolerateInAccurateMatches && match.getAccuracy() == SearchMatch.A_INACCURATE) { hasPotentialMatches = true; } if (fLastResource != match.getResource()) { fLastResource = match.getResource(); resources.add(fLastResource); } } } ResourceSearchRequestor requestor = new ResourceSearchRequestor(); try { new SearchEngine() .search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor, pm); } catch (CoreException e) { throw new JavaModelException(e); } List<IJavaElement> result = new ArrayList<IJavaElement>(requestor.resources.size()); for (Iterator<IResource> iter = requestor.resources.iterator(); iter.hasNext(); ) { IResource resource = iter.next(); IJavaElement element = JavaCore.create(resource); if (element instanceof ICompilationUnit) { result.add(element); } else { hasNonCuMatches = true; } } addStatusErrors(status, requestor.hasPotentialMatches, hasNonCuMatches); return result.toArray(new ICompilationUnit[result.size()]); }
private List<String> findClassesInContainer( IJavaElement container, String testMethodAnnotation, String testClassAnnotation) { List<String> result = new LinkedList<>(); IRegion region = getRegion(container); try { ITypeHierarchy hierarchy = JavaCore.newTypeHierarchy(region, null, null); IType[] allClasses = hierarchy.getAllClasses(); // search for all types with references to RunWith and Test and all subclasses HashSet<IType> candidates = new HashSet<>(allClasses.length); SearchRequestor requestor = new AnnotationSearchRequestor(hierarchy, candidates); IJavaSearchScope scope = SearchEngine.createJavaSearchScope(allClasses, IJavaSearchScope.SOURCES); int matchRule = SearchPattern.R_CASE_SENSITIVE; SearchPattern testPattern = SearchPattern.createPattern( testMethodAnnotation, IJavaSearchConstants.ANNOTATION_TYPE, IJavaSearchConstants.ANNOTATION_TYPE_REFERENCE, matchRule); SearchPattern runWithPattern = isNullOrEmpty(testClassAnnotation) ? testPattern : SearchPattern.createPattern( testClassAnnotation, IJavaSearchConstants.ANNOTATION_TYPE, IJavaSearchConstants.ANNOTATION_TYPE_REFERENCE, matchRule); SearchPattern annotationsPattern = SearchPattern.createOrPattern(runWithPattern, testPattern); SearchParticipant[] searchParticipants = new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()}; new SearchEngine().search(annotationsPattern, searchParticipants, scope, requestor, null); // find all classes in the region for (IType candidate : candidates) { if (isAccessibleClass(candidate) && !Flags.isAbstract(candidate.getFlags()) && region.contains(candidate)) { result.add(candidate.getFullyQualifiedName()); } } } catch (CoreException e) { LOG.info("Can't build project hierarchy.", e); } return result; }
public static ICompilationUnit[] findAffectedCompilationUnits(SearchPattern pattern, IJavaSearchScope scope, final IProgressMonitor pm, RefactoringStatus status, final boolean tolerateInAccurateMatches) throws JavaModelException { boolean hasNonCuMatches= false; class ResourceSearchRequestor extends SearchRequestor{ boolean hasPotentialMatches= false ; Set<IResource> resources= new HashSet<IResource>(5); private IResource fLastResource; @Override public void acceptSearchMatch(SearchMatch match) { if (!tolerateInAccurateMatches && match.getAccuracy() == SearchMatch.A_INACCURATE) { hasPotentialMatches= true; } if (fLastResource != match.getResource()) { fLastResource= match.getResource(); resources.add(fLastResource); } } } ResourceSearchRequestor requestor = new ResourceSearchRequestor(); try { new SearchEngine().search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor, pm); } catch (CoreException e) { throw new JavaModelException(e); } List<IJavaElement> result= new ArrayList<IJavaElement>(requestor.resources.size()); for (Iterator<IResource> iter= requestor.resources.iterator(); iter.hasNext(); ) { IResource resource= iter.next(); IJavaElement element= JavaCore.create(resource); if (element instanceof ICompilationUnit) { result.add(element); } else { hasNonCuMatches= true; } } addStatusErrors(status, requestor.hasPotentialMatches, hasNonCuMatches); return result.toArray(new ICompilationUnit[result.size()]); }
public void searchImpactSet() { for (final StereotypeIdentifier identifier : identifiers) { SearchRequestor findMethod = new SearchRequestor() { @SuppressWarnings("unused") @Override public void acceptSearchMatch(SearchMatch match) throws CoreException { IJavaElement type = null; if(match.getElement() instanceof SourceType) { addMatched(identifier, match); } else if(match.getElement() instanceof ResolvedSourceType) { type = ((ResolvedSourceType )match.getElement()).getParent(); addMatched(identifier, match); } else if(match.getElement() instanceof ResolvedSourceField) { type = ((ResolvedSourceField)match.getElement()).getParent(); addMatched(identifier, match); } else if(match.getElement() instanceof ResolvedSourceMethod) { type = ((ResolvedSourceMethod)match.getElement()).getParent(); addMatched(identifier, match); } } }; SearchEngine engine = new SearchEngine(); IJavaSearchScope workspaceScope = null; if(getProject() != null) { workspaceScope = SearchEngine.createJavaSearchScope(createSearchScope()); } else { workspaceScope = SearchEngine.createWorkspaceScope(); } String typeName = Constants.EMPTY_STRING; if(null != identifier.getCompilationUnit() && identifier.getCompilationUnit().findPrimaryType() != null) { typeName = identifier.getCompilationUnit().findPrimaryType().getElementName(); } else { if(null != identifier.getCompilationUnit()) { typeName = identifier.getCompilationUnit().getElementName(); if(typeName.endsWith(Constants.JAVA_EXTENSION)) { typeName = typeName.replace(Constants.JAVA_EXTENSION, Constants.EMPTY_STRING); } } } SearchPattern pattern = SearchPattern .createPattern( typeName, IJavaSearchConstants.TYPE, IJavaSearchConstants.REFERENCES, SearchPattern.R_EXACT_MATCH); SearchParticipant[] participant = new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }; try { engine.search(pattern, participant, workspaceScope, findMethod, new NullProgressMonitor()); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }