List of usage examples for org.eclipse.jdt.core.search IJavaSearchConstants DECLARATIONS
int DECLARATIONS
To view the source code for org.eclipse.jdt.core.search IJavaSearchConstants DECLARATIONS.
Click Source Link
From source file:org.eclipse.andmore.internal.editors.Hyperlinks.java
License:Open Source License
/** * Opens a Java method referenced by the given on click attribute method name * * @param project the project containing the click handler * @param method the method name of the on click handler * @return true if the method was opened, false otherwise *//*from w ww. j a v a2s . co m*/ public static boolean openOnClickMethod(IProject project, String method) { // Search for the method in the Java index, filtering by the required click handler // method signature (public and has a single View parameter), and narrowing the scope // first to Activity classes, then to the whole workspace. final AtomicBoolean success = new AtomicBoolean(false); SearchRequestor requestor = new SearchRequestor() { @Override public void acceptSearchMatch(SearchMatch match) throws CoreException { Object element = match.getElement(); if (element instanceof IMethod) { IMethod methodElement = (IMethod) element; String[] parameterTypes = methodElement.getParameterTypes(); if (parameterTypes != null && parameterTypes.length == 1 && ("Qandroid.view.View;".equals(parameterTypes[0]) //$NON-NLS-1$ || "QView;".equals(parameterTypes[0]))) { //$NON-NLS-1$ // Check that it's public if (Flags.isPublic(methodElement.getFlags())) { JavaUI.openInEditor(methodElement); success.getAndSet(true); } } } } }; try { IJavaSearchScope scope = null; IType activityType = null; IJavaProject javaProject = BaseProjectHelper.getJavaProject(project); if (javaProject != null) { activityType = javaProject.findType(CLASS_ACTIVITY); if (activityType != null) { scope = SearchEngine.createHierarchyScope(activityType); } } if (scope == null) { scope = SearchEngine.createWorkspaceScope(); } SearchParticipant[] participants = new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }; int matchRule = SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CASE_SENSITIVE; SearchPattern pattern = SearchPattern.createPattern("*." + method, IJavaSearchConstants.METHOD, IJavaSearchConstants.DECLARATIONS, matchRule); SearchEngine engine = new SearchEngine(); engine.search(pattern, participants, scope, requestor, new NullProgressMonitor()); boolean ok = success.get(); if (!ok && activityType != null) { // TODO: Create a project+dependencies scope and search only that scope // Try searching again with a complete workspace scope this time scope = SearchEngine.createWorkspaceScope(); engine.search(pattern, participants, scope, requestor, new NullProgressMonitor()); // TODO: There could be more than one match; add code to consider them all // and pick the most likely candidate and open only that one. ok = success.get(); } return ok; } catch (CoreException e) { AndmoreAndroidPlugin.log(e, null); } return false; }
From source file:org.eclipse.andmore.SourceRevealer.java
License:Open Source License
private List<SearchMatch> searchForPattern(String pattern, int searchFor, Predicate<SearchMatch> filterPredicate) { SearchEngine se = new SearchEngine(); SearchPattern searchPattern = SearchPattern.createPattern(pattern, searchFor, IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE); SearchResultAccumulator requestor = new SearchResultAccumulator(filterPredicate); try {//from w ww .jav a 2s .c o m se.search(searchPattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, SearchEngine.createWorkspaceScope(), requestor, new NullProgressMonitor()); } catch (CoreException e) { AndmoreAndroidPlugin.printErrorToConsole(e.getMessage()); return Collections.emptyList(); } return requestor.getMatches(); }
From source file:org.eclipse.buildship.ui.view.execution.OpenTestSourceFileJob.java
License:Open Source License
private void searchForTestSource(String className, String methodName, IProgressMonitor monitor) { monitor.setTaskName(String.format("Open test source file for class %s.", className)); try {/*from ww w .j ava2s. co m*/ // search for Java file SearchEngine searchEngine = new SearchEngine(); SearchPattern pattern = SearchPattern.createPattern(className, IJavaSearchConstants.TYPE, IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH); ShowTestSourceFileSearchRequester requester = new ShowTestSourceFileSearchRequester(methodName); searchEngine.search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, SearchEngine.createWorkspaceScope(), requester, monitor); // if no Java file has been found, search for Groovy file if (!requester.isFoundJavaTestSourceFile()) { IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); workspaceRoot.accept( new ShowTestSourceFileResourceVisitor(methodName, className, ImmutableList.of("groovy"))); //$NON-NLS-1$ } } catch (CoreException e) { UiPlugin.logger().error(e.getMessage(), e); } finally { monitor.done(); } }
From source file:org.eclipse.emf.mwe.internal.ui.eclipse.launch.MWELaunchShortcut.java
License:Open Source License
@SuppressWarnings("unused") private boolean checkClasspathEntries(final IResource resource, String classNameToFind) throws CoreException { // TODO: ER: put required oAW packages always to the classpath final IJavaProject project = JavaCore.create(resource.getProject()); final SearchPattern pattern = SearchPattern.createPattern(classNameToFind, IJavaSearchConstants.TYPE, IJavaSearchConstants.DECLARATIONS, SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CASE_SENSITIVE); final IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaElement[] { project }, true); final TypeDeclarationSearchRequestor requestor = new TypeDeclarationSearchRequestor(); final SearchEngine searchEngine = new SearchEngine(); searchEngine.search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, scope, requestor, null);// ww w. jav a 2s . com return requestor.match(); }
From source file:org.eclipse.mylyn.internal.sandbox.ui.hyperlinks.JavaResourceHyperlink.java
License:Open Source License
/** * Starts a search for the type with the given name. Reports back to 'searchCompleted(...)'. * /*w w w. ja va2 s .c om*/ * @param typeName * the type to search for */ protected void startSourceSearch(final String typeName) { Job search = new Job("Searching...") { @Override protected IStatus run(IProgressMonitor monitor) { try { // search for the type in the workspace final List<IType> results = new ArrayList<IType>(); SearchRequestor collector = new SearchRequestor() { @Override public void acceptSearchMatch(SearchMatch match) throws CoreException { Object element = match.getElement(); if (element instanceof IType) { results.add((IType) element); } } }; // do a case-sensitive search for the class name see bug 244352 SearchEngine engine = new SearchEngine(); SearchPattern pattern = SearchPattern.createPattern(typeName, IJavaSearchConstants.TYPE, IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE); engine.search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, SearchEngine.createWorkspaceScope(), collector, monitor); searchCompleted(results, typeName, null); } catch (CoreException e) { searchCompleted(null, typeName, e.getStatus()); } return Status.OK_STATUS; } }; search.schedule(); }
From source file:org.eclipse.pde.internal.ui.correction.java.FindClassResolutionsOperation.java
License:Open Source License
/** * Finds all exported packages containing the simple type aTypeName. The packages * will be filtered from the given packages which are already imported, and all * system packages./*w ww .java2 s . c o m*/ * * If no exported package is left, packagesToExport will be filled with those * packages that would have been returned, if they were exported. * @param aTypeName the simple type to search for * @param importPkgs the packages which are already imported * @param packagesToExport return parameter that will be filled with packages to export * if no valid package to import was found * @param monitor * @return the set of packages to import */ private Collection<ExportPackageDescription> findValidPackagesContainingSimpleType(String aTypeName, ImportPackageSpecification[] importPkgs, Set<IPackageFragment> packagesToExport, IProgressMonitor monitor) { SubMonitor subMonitor = SubMonitor.convert(monitor); IPluginModelBase[] activeModels = PluginRegistry.getActiveModels(); Set<IJavaProject> javaProjects = new HashSet<IJavaProject>(activeModels.length * 2); for (int i = 0; i < activeModels.length; i++) { IResource resource = activeModels[i].getUnderlyingResource(); if (resource != null && resource.isAccessible()) { IJavaProject javaProject = JavaCore.create(resource.getProject()); if (javaProject.exists()) { javaProjects.add(javaProject); } } } final IJavaProject currentJavaProject = JavaCore.create(fProject); javaProjects.remove(currentJavaProject); // no need to search in current project itself try { IJavaSearchScope searchScope = SearchEngine .createJavaSearchScope(javaProjects.toArray(new IJavaElement[javaProjects.size()])); final Map<String, IPackageFragment> packages = new HashMap<String, IPackageFragment>(); SearchRequestor requestor = new SearchRequestor() { public void acceptSearchMatch(SearchMatch aMatch) throws CoreException { Object element = aMatch.getElement(); if (element instanceof IType) { IType type = (IType) element; // Only try to import types we can access (Bug 406232) if (Flags.isPublic(type.getFlags())) { if (!currentJavaProject.equals(type.getJavaProject())) { IPackageFragment packageFragment = type.getPackageFragment(); if (packageFragment.exists()) { packages.put(packageFragment.getElementName(), packageFragment); } } } } } }; SearchPattern typePattern = SearchPattern.createPattern(aTypeName, IJavaSearchConstants.TYPE, IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE); new SearchEngine().search(typePattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, searchScope, requestor, subMonitor.newChild(1)); if (!packages.isEmpty()) { // transform to ExportPackageDescriptions Map<String, ExportPackageDescription> exportDescriptions = new HashMap<String, ExportPackageDescription>( packages.size()); // remove system packages if they happen to be included. Adding a system package won't resolve anything, since package package already comes from JRE ExportPackageDescription[] systemPackages = PDECore.getDefault().getModelManager().getState() .getState().getSystemPackages(); for (int i = 0; i < systemPackages.length; i++) { packages.remove(systemPackages[i].getName()); } // also remove packages that are already imported for (int i = 0; i < importPkgs.length; i++) { packages.remove(importPkgs[i].getName()); } // finally create the list of ExportPackageDescriptions ExportPackageDescription[] knownPackages = PDECore.getDefault().getModelManager().getState() .getState().getExportedPackages(); for (int i = 0; i < knownPackages.length; i++) { if (packages.containsKey(knownPackages[i].getName())) { exportDescriptions.put(knownPackages[i].getName(), knownPackages[i]); } } if (exportDescriptions.isEmpty()) { // no packages to import found, maybe there are packages to export packagesToExport.addAll(packages.values()); } return exportDescriptions.values(); } return Collections.emptySet(); } catch (CoreException ex) { // ignore, return an empty set return Collections.emptySet(); } }
From source file:org.eclipse.rap.ui.internal.launch.rwt.shortcut.EntryPointSearchEngine.java
License:Open Source License
private void search(IProgressMonitor monitor) throws CoreException { monitor.beginTask("Searching for entry points...", 100); try {/*from w ww. jav a 2s .c om*/ int matchRule = SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE; SearchParticipant[] participants = getSearchParticipants(); IProgressMonitor searchMonitor = new SubProgressMonitor(monitor, 100); SearchEngine searchEngine = new SearchEngine(); SearchPattern pattern1 = SearchPattern.createPattern("createUI() int", //$NON-NLS-1$ IJavaSearchConstants.METHOD, IJavaSearchConstants.DECLARATIONS, matchRule); SearchPattern pattern2 = SearchPattern.createPattern("createContents( Composite ) void", //$NON-NLS-1$ IJavaSearchConstants.METHOD, IJavaSearchConstants.DECLARATIONS, matchRule); SearchPattern pattern = SearchPattern.createOrPattern(pattern1, pattern2); searchEngine.search(pattern, participants, searchScope, entryPointCollector, searchMonitor); } finally { monitor.done(); } }
From source file:org.eclipse.recommenders.rcp.JavaElementResolver.java
License:Open Source License
private Optional<IType> resolveType(final ITypeName recType) { // TODO woah, what a hack just to find a nested/anonymous type... this // definitely needs refactoring! ensureIsNotNull(recType);/* w w w .ja v a 2s . c o m*/ if (recType.isArrayType()) { // TODO see https://bugs.eclipse.org/bugs/show_bug.cgi?id=339806 // should throw an exception? or return an Array type? log(ERROR_ARRAY_TYPE_IN_JAVA_ELEMENT_RESOLVER, recType); return absent(); } if (recType.isNestedType()) { final ITypeName declaringType = recType.getDeclaringType(); final String simpleName = StringUtils.substringAfterLast(recType.getIdentifier(), "$"); //$NON-NLS-1$ final IType parent = resolveType(declaringType).orNull(); if (parent != null) { try { for (final IType nested : parent.getTypes()) { final String key = nested.getKey(); if (key.equals(recType.getIdentifier() + ';')) { return fromNullable(nested); } } for (final IMethod m : parent.getMethods()) { for (final IJavaElement children : m.getChildren()) { if (children instanceof IType) { final IType nested = (IType) children; if (nested.getKey().endsWith(simpleName + ';')) { return of(nested); } final String key = nested.getKey(); if (key.equals(recType.getIdentifier() + ';')) { return fromNullable(nested); } } } } } catch (final Exception x) { return absent(); } } return absent(); } final IType[] res = new IType[1]; final IJavaSearchScope scope = SearchEngine.createWorkspaceScope(); final SearchEngine search = new SearchEngine(); final String srcTypeName = Names.vm2srcTypeName(recType.getIdentifier()); final SearchPattern pattern = SearchPattern.createPattern(srcTypeName, IJavaSearchConstants.TYPE, IJavaSearchConstants.DECLARATIONS, SearchPattern.R_FULL_MATCH); try { search.search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, new SearchRequestor() { @Override public void acceptSearchMatch(final SearchMatch match) throws CoreException { IType element = (IType) match.getElement(); // with the current settings the engine matches 'Lnull' with 'Ljava/lang/ref/ReferenceQueue$Null' if (toRecType(element).equals(recType)) { res[0] = element; } } }, null); } catch (final CoreException e) { throwUnhandledException(e); } return fromNullable(res[0]); }
From source file:org.eclipse.recommenders.utils.rcp.JavaElementResolver.java
License:Open Source License
private Optional<IType> resolveType(final ITypeName recType) { // TODO woah, what a hack just to find a nested/anonymous type... this // definitely needs refactoring! ensureIsNotNull(recType);/*from w ww .j a va2s. c o m*/ if (recType.isArrayType()) { // TODO see https://bugs.eclipse.org/bugs/show_bug.cgi?id=339806 // should throw an exception? or return an Array type? System.err.println("array type in JavaElementResolver. Decision bug 339806 pending...?"); return absent(); } if (recType.isNestedType()) { final ITypeName declaringType = recType.getDeclaringType(); final String simpleName = StringUtils.substringAfterLast(recType.getIdentifier(), "$"); final IType parent = resolveType(declaringType).orNull(); if (parent != null) { try { for (final IType nested : parent.getTypes()) { final String key = nested.getKey(); if (key.equals(recType.getIdentifier() + ";")) { return fromNullable(nested); } } // int count = 0; for (final IMethod m : parent.getMethods()) { for (final IJavaElement children : m.getChildren()) { if (children instanceof IType) { final IType nested = (IType) children; // count++; if (nested.getKey().endsWith(simpleName + ";")) { return of(nested); } // if (String.valueOf(count).equals(simpleName)) { // return of(nested); // } final String key = nested.getKey(); if (key.equals(recType.getIdentifier() + ";")) { return fromNullable(nested); } } } } } catch (final Exception x) { // final IType type = // parent.getType(recType.getClassName()); return absent(); } } return absent(); } final IType[] res = new IType[1]; final IJavaSearchScope scope = SearchEngine.createWorkspaceScope(); final SearchEngine search = new SearchEngine(); final String srcTypeName = Names.vm2srcTypeName(recType.getIdentifier()); final SearchPattern pattern = SearchPattern.createPattern(srcTypeName, IJavaSearchConstants.TYPE, IJavaSearchConstants.DECLARATIONS, SearchPattern.R_FULL_MATCH); try { search.search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, new SearchRequestor() { @Override public void acceptSearchMatch(final SearchMatch match) throws CoreException { IType element = (IType) match.getElement(); // with the current settings the engine matches 'Lnull' with 'Ljava/lang/ref/ReferenceQueue$Null' if (toRecType(element).equals(recType)) { res[0] = element; } } }, null); } catch (final CoreException e) { throwUnhandledException(e); } return fromNullable(res[0]); }
From source file:org.eclipse.xtext.xbase.ui.navigation.JvmImplementationOpener.java
License:Open Source License
/** * Main parts of the logic is taken from {@link org.eclipse.jdt.internal.ui.javaeditor.JavaElementImplementationHyperlink} * * @param element - Element to show implementations for * @param textviewer - Viewer to show hierarchy view on * @param region - Region where to show hierarchy view *//*from w w w . j a va2 s . c om*/ public void openImplementations(final IJavaElement element, ITextViewer textviewer, IRegion region) { if (element instanceof IMethod) { ITypeRoot typeRoot = ((IMethod) element).getTypeRoot(); CompilationUnit ast = SharedASTProvider.getAST(typeRoot, SharedASTProvider.WAIT_YES, null); if (ast == null) { openQuickHierarchy(textviewer, element, region); return; } try { ISourceRange nameRange = ((IMethod) element).getNameRange(); ASTNode node = NodeFinder.perform(ast, nameRange); 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 openEditor(element); return; } else if (parent instanceof MethodDeclaration) { parentTypeBinding = Bindings.getBindingOfParentType(node); } } final IType type = parentTypeBinding != null ? (IType) parentTypeBinding.getJavaElement() : null; if (type == null) { openQuickHierarchy(textviewer, element, region); return; } final String earlyExitIndicator = "EarlyExitIndicator"; final ArrayList<IJavaElement> links = Lists.newArrayList(); IRunnableWithProgress runnable = new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { if (monitor == null) { monitor = new NullProgressMonitor(); } try { String methodLabel = JavaElementLabels.getElementLabel(element, JavaElementLabels.DEFAULT_QUALIFIED); monitor.beginTask( Messages.format("Searching for implementors of ''{0}''", methodLabel), 100); SearchRequestor requestor = new SearchRequestor() { @Override public void acceptSearchMatch(SearchMatch match) throws CoreException { if (match.getAccuracy() == SearchMatch.A_ACCURATE) { IJavaElement element = (IJavaElement) match.getElement(); if (element instanceof IMethod && !JdtFlags.isAbstract((IMethod) element)) { links.add(element); if (links.size() > 1) { throw new OperationCanceledException(earlyExitIndicator); } } } } }; int limitTo = IJavaSearchConstants.DECLARATIONS | IJavaSearchConstants.IGNORE_DECLARING_TYPE | IJavaSearchConstants.IGNORE_RETURN_TYPE; SearchPattern pattern = SearchPattern.createPattern(element, limitTo); Assert.isNotNull(pattern); SearchParticipant[] participants = new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }; SearchEngine engine = new SearchEngine(); engine.search(pattern, participants, SearchEngine.createHierarchyScope(type), requestor, new SubProgressMonitor(monitor, 100)); if (monitor.isCanceled()) { throw new InterruptedException(); } } catch (OperationCanceledException e) { throw new InterruptedException(e.getMessage()); } catch (CoreException e) { throw new InvocationTargetException(e); } finally { monitor.done(); } } }; try { PlatformUI.getWorkbench().getProgressService().busyCursorWhile(runnable); } catch (InvocationTargetException e) { IStatus status = new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.OK, Messages.format( "An error occurred while searching for implementations of method ''{0}''. See error log for details.", element.getElementName()), e.getCause()); JavaPlugin.log(status); ErrorDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Open Implementation", "Problems finding implementations.", status); } catch (InterruptedException e) { if (e.getMessage() != earlyExitIndicator) { return; } } if (links.size() == 1) { openEditor(links.get(0)); } else { openQuickHierarchy(textviewer, element, region); } } catch (JavaModelException e) { log.error("An error occurred while searching for implementations", e.getCause()); } catch (PartInitException e) { log.error("An error occurred while searching for implementations", e.getCause()); } } }