Example usage for org.eclipse.jdt.core.search SearchMatch getResource

List of usage examples for org.eclipse.jdt.core.search SearchMatch getResource

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.search SearchMatch getResource.

Prototype

public final IResource getResource() 

Source Link

Document

Returns the resource containing this search match.

Usage

From source file:bndtools.internal.pkgselection.SearchUtils.java

License:Open Source License

/**
 * @param match/*from  w ww . jav a 2s .  c om*/
 * @return the enclosing {@link ICompilationUnit} of the given match, or null iff none
 */
public static ICompilationUnit getCompilationUnit(SearchMatch match) {
    IJavaElement enclosingElement = getEnclosingJavaElement(match);
    if (enclosingElement != null) {
        if (enclosingElement instanceof ICompilationUnit)
            return (ICompilationUnit) enclosingElement;
        ICompilationUnit cu = (ICompilationUnit) enclosingElement.getAncestor(IJavaElement.COMPILATION_UNIT);
        if (cu != null)
            return cu;
    }

    IJavaElement jElement = JavaCore.create(match.getResource());
    if (jElement != null && jElement.exists() && jElement.getElementType() == IJavaElement.COMPILATION_UNIT)
        return (ICompilationUnit) jElement;
    return null;
}

From source file:com.android.ide.eclipse.adt.internal.editors.layout.gle2.CustomViewFinder.java

License:Open Source License

private Pair<List<String>, List<String>> findViews(final boolean layoutsOnly) {
    final Set<String> customViews = new HashSet<String>();
    final Set<String> thirdPartyViews = new HashSet<String>();

    ProjectState state = Sdk.getProjectState(mProject);
    final List<IProject> libraries = state != null ? state.getFullLibraryProjects()
            : Collections.<IProject>emptyList();

    SearchRequestor requestor = new SearchRequestor() {
        @Override//www  .  j  ava  2 s .  co m
        public void acceptSearchMatch(SearchMatch match) throws CoreException {
            // Ignore matches in comments
            if (match.isInsideDocComment()) {
                return;
            }

            Object element = match.getElement();
            if (element instanceof ResolvedBinaryType) {
                // Third party view
                ResolvedBinaryType type = (ResolvedBinaryType) element;
                IPackageFragment fragment = type.getPackageFragment();
                IPath path = fragment.getPath();
                String last = path.lastSegment();
                // Filter out android.jar stuff
                if (last.equals(FN_FRAMEWORK_LIBRARY)) {
                    return;
                }
                if (!isValidView(type, layoutsOnly)) {
                    return;
                }

                IProject matchProject = match.getResource().getProject();
                if (mProject == matchProject || libraries.contains(matchProject)) {
                    String fqn = type.getFullyQualifiedName();
                    thirdPartyViews.add(fqn);
                }
            } else if (element instanceof ResolvedSourceType) {
                // User custom view
                IProject matchProject = match.getResource().getProject();
                if (mProject == matchProject || libraries.contains(matchProject)) {
                    ResolvedSourceType type = (ResolvedSourceType) element;
                    if (!isValidView(type, layoutsOnly)) {
                        return;
                    }
                    String fqn = type.getFullyQualifiedName();
                    fqn = fqn.replace('$', '.');
                    customViews.add(fqn);
                }
            }
        }
    };
    try {
        IJavaProject javaProject = BaseProjectHelper.getJavaProject(mProject);
        if (javaProject != null) {
            String className = layoutsOnly ? CLASS_VIEWGROUP : CLASS_VIEW;
            IType viewType = javaProject.findType(className);
            if (viewType != null) {
                IJavaSearchScope scope = SearchEngine.createHierarchyScope(viewType);
                SearchParticipant[] participants = new SearchParticipant[] {
                        SearchEngine.getDefaultSearchParticipant() };
                int matchRule = SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CASE_SENSITIVE;

                SearchPattern pattern = SearchPattern.createPattern("*", IJavaSearchConstants.CLASS,
                        IJavaSearchConstants.IMPLEMENTORS, matchRule);
                SearchEngine engine = new SearchEngine();
                engine.search(pattern, participants, scope, requestor, new NullProgressMonitor());
            }
        }
    } catch (CoreException e) {
        AdtPlugin.log(e, null);
    }

    List<String> custom = new ArrayList<String>(customViews);
    List<String> thirdParty = new ArrayList<String>(thirdPartyViews);

    if (!layoutsOnly) {
        // Update our cached answers (unless we were filtered on only layouts)
        mCustomViews = custom;
        mThirdPartyViews = thirdParty;
    }

    return Pair.of(custom, thirdParty);
}

From source file:com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo.java

License:Open Source License

/**
 * Returns the activity associated with the given layout file.
 * <p>//www .  ja v  a  2s .  c  o m
 * This is an alternative to {@link #guessActivity(IFile, String)}. Whereas
 * guessActivity simply looks for references to "R.layout.foo", this method searches
 * for all usages of Activity#setContentView(int), and for each match it looks up the
 * corresponding call text (such as "setContentView(R.layout.foo)"). From this it uses
 * a regexp to pull out "foo" from this, and stores the association that layout "foo"
 * is associated with the activity class that contained the setContentView call.
 * <p>
 * This has two potential advantages:
 * <ol>
 * <li>It can be faster. We do the reference search -once-, and we've built a map of
 * all the layout-to-activity mappings which we can then immediately look up other
 * layouts for, which is particularly useful at startup when we have to compute the
 * layout activity associations to populate the theme choosers.
 * <li>It can be more accurate. Just because an activity references an "R.layout.foo"
 * field doesn't mean it's setting it as a content view.
 * </ol>
 * However, this second advantage is also its chief problem. There are some common
 * code constructs which means that the associated layout is not explicitly referenced
 * in a direct setContentView call; on a couple of sample projects I tested I found
 * patterns like for example "setContentView(v)" where "v" had been computed earlier.
 * Therefore, for now we're going to stick with the more general approach of just
 * looking up each field when needed. We're keeping the code around, though statically
 * compiled out with the "if (false)" construct below in case we revisit this.
 *
 * @param layoutFile the layout whose activity we want to look up
 * @return the activity name
 */
@SuppressWarnings("all")
@Nullable
public String guessActivityBySetContentView(String layoutName) {
    if (false) {
        // These should be fields
        final Pattern LAYOUT_FIELD_PATTERN = Pattern.compile("R\\.layout\\.([a-z0-9_]+)"); //$NON-NLS-1$
        Map<String, String> mUsages = null;

        sync();
        if (mUsages == null) {
            final Map<String, String> usages = new HashMap<String, String>();
            mUsages = usages;
            SearchRequestor requestor = new SearchRequestor() {
                @Override
                public void acceptSearchMatch(SearchMatch match) throws CoreException {
                    Object element = match.getElement();
                    if (element instanceof IMethod) {
                        IMethod method = (IMethod) element;
                        IType declaringType = method.getDeclaringType();
                        String fqcn = declaringType.getFullyQualifiedName();
                        IDocumentProvider provider = new TextFileDocumentProvider();
                        IResource resource = match.getResource();
                        try {
                            provider.connect(resource);
                            IDocument document = provider.getDocument(resource);
                            if (document != null) {
                                String matchText = document.get(match.getOffset(), match.getLength());
                                Matcher matcher = LAYOUT_FIELD_PATTERN.matcher(matchText);
                                if (matcher.find()) {
                                    usages.put(matcher.group(1), fqcn);
                                }
                            }
                        } catch (Exception e) {
                            AdtPlugin.log(e, "Can't find range information for %1$s", resource.getName());
                        } finally {
                            provider.disconnect(resource);
                        }
                    }
                }
            };
            try {
                IJavaProject javaProject = BaseProjectHelper.getJavaProject(mProject);
                if (javaProject == null) {
                    return null;
                }

                // Search for which java classes call setContentView(R.layout.layoutname);
                String typeFqcn = "R.layout"; //$NON-NLS-1$
                if (mPackage != null) {
                    typeFqcn = mPackage + '.' + typeFqcn;
                }

                IType activityType = javaProject.findType(CLASS_ACTIVITY);
                if (activityType != null) {
                    IMethod method = activityType.getMethod("setContentView", new String[] { "I" }); //$NON-NLS-1$ //$NON-NLS-2$
                    if (method.exists()) {
                        SearchPattern pattern = SearchPattern.createPattern(method, REFERENCES);
                        search(requestor, javaProject, pattern);
                    }
                }
            } catch (CoreException e) {
                AdtPlugin.log(e, null);
            }
        }

        return mUsages.get(layoutName);
    }

    return null;
}

From source file:com.android.ide.eclipse.adt.SourceRevealer.java

License:Open Source License

private boolean revealLineMatch(List<SearchMatch> matches, String fileName, int lineNumber,
        String perspective) {//from  www.  j ava  2 s  .com
    SearchMatch match = getMatchToDisplay(matches, String.format("%s:%d", fileName, lineNumber));
    if (match == null) {
        return false;
    }

    if (perspective != null) {
        SourceRevealer.switchToPerspective(perspective);
    }

    return displayFile((IFile) match.getResource(), lineNumber);
}

From source file:com.android.ide.eclipse.adt.SourceRevealer.java

License:Open Source License

private List<SearchMatch> filterMatchByFileName(List<SearchMatch> matches, String fileName) {
    if (fileName == null) {
        return matches;
    }/*  w ww  . j a  va 2s. co  m*/

    // Use a map to collapse multiple matches in a single file into just one match since
    // we know the line number in the file.
    Map<IResource, SearchMatch> matchesPerFile = new HashMap<IResource, SearchMatch>(matches.size());

    for (SearchMatch m : matches) {
        if (m.getResource() instanceof IFile && m.getResource().getName().startsWith(fileName)) {
            matchesPerFile.put(m.getResource(), m);
        }
    }

    List<SearchMatch> filteredMatches = new ArrayList<SearchMatch>(matchesPerFile.values());

    // sort results, first by project name, then by file name
    Collections.sort(filteredMatches, new Comparator<SearchMatch>() {
        @Override
        public int compare(SearchMatch m1, SearchMatch m2) {
            String p1 = m1.getResource().getProject().getName();
            String p2 = m2.getResource().getProject().getName();

            if (!p1.equals(p2)) {
                return p1.compareTo(p2);
            }

            String r1 = m1.getResource().getName();
            String r2 = m2.getResource().getName();
            return r1.compareTo(r2);
        }
    });
    return filteredMatches;
}

From source file:com.android.ide.eclipse.adt.SourceRevealer.java

License:Open Source License

private List<SearchMatch> filterMatchByResource(List<SearchMatch> matches, IResource resource) {
    List<SearchMatch> filteredMatches = new ArrayList<SearchMatch>(matches.size());

    for (SearchMatch m : matches) {
        if (m.getResource().equals(resource)) {
            filteredMatches.add(m);//from  www.  ja va 2 s.  com
        }
    }

    return filteredMatches;
}

From source file:com.android.ide.eclipse.adt.SourceRevealer.java

License:Open Source License

private SearchMatch getMatchToDisplay(List<SearchMatch> matches, String searchTerm) {
    // no matches for given search
    if (matches.size() == 0) {
        return null;
    }/*w ww. j av  a  2s. c om*/

    // there is only 1 match, so we return that
    if (matches.size() == 1) {
        return matches.get(0);
    }

    // multiple matches, prompt the user to select
    IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
    if (window == null) {
        return null;
    }

    ListDialog dlg = new ListDialog(window.getShell());
    dlg.setMessage("Multiple files match search: " + searchTerm);
    dlg.setTitle("Select file to open");
    dlg.setInput(matches);
    dlg.setContentProvider(new IStructuredContentProvider() {
        @Override
        public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
        }

        @Override
        public void dispose() {
        }

        @Override
        public Object[] getElements(Object inputElement) {
            return ((List<?>) inputElement).toArray();
        }
    });
    dlg.setLabelProvider(new LabelProvider() {
        @Override
        public String getText(Object element) {
            SearchMatch m = (SearchMatch) element;
            return String.format("/%s/%s", //$NON-NLS-1$
                    m.getResource().getProject().getName(),
                    m.getResource().getProjectRelativePath().toString());
        }
    });
    dlg.setInitialSelections(new Object[] { matches.get(0) });
    dlg.setHelpAvailable(false);

    if (dlg.open() == Window.OK) {
        Object[] selectedMatches = dlg.getResult();
        if (selectedMatches.length > 0) {
            return (SearchMatch) selectedMatches[0];
        }
    }

    return null;
}

From source file:com.android.ide.eclipse.auidt.internal.editors.layout.gle2.CustomViewFinder.java

License:Open Source License

private Pair<List<String>, List<String>> findViews(final boolean layoutsOnly) {
    final Set<String> customViews = new HashSet<String>();
    final Set<String> thirdPartyViews = new HashSet<String>();

    ProjectState state = Sdk.getProjectState(mProject);
    final List<IProject> libraries = state != null ? state.getFullLibraryProjects()
            : Collections.<IProject>emptyList();

    SearchRequestor requestor = new SearchRequestor() {
        @Override// w  ww  .j  av  a2 s.  co m
        public void acceptSearchMatch(SearchMatch match) throws CoreException {
            // Ignore matches in comments
            if (match.isInsideDocComment()) {
                return;
            }

            Object element = match.getElement();
            if (element instanceof ResolvedBinaryType) {
                // Third party view
                ResolvedBinaryType type = (ResolvedBinaryType) element;
                IPackageFragment fragment = type.getPackageFragment();
                IPath path = fragment.getPath();
                String last = path.lastSegment();
                // Filter out android.jar stuff
                /*  if (last.equals(FN_FRAMEWORK_LIBRARY)) {
                return;
                  }*/
                if (last.equals(FN_FRAMEWORK_LIBRARY)) {
                    return;
                }

                if (!isValidView(type, layoutsOnly)) {
                    return;
                }

                IProject matchProject = match.getResource().getProject();
                if (mProject == matchProject || libraries.contains(matchProject)) {
                    String fqn = type.getFullyQualifiedName();
                    thirdPartyViews.add(fqn);
                }
            } else if (element instanceof ResolvedSourceType) {
                // User custom view
                IProject matchProject = match.getResource().getProject();
                if (mProject == matchProject || libraries.contains(matchProject)) {
                    ResolvedSourceType type = (ResolvedSourceType) element;
                    if (!isValidView(type, layoutsOnly)) {
                        return;
                    }
                    String fqn = type.getFullyQualifiedName();
                    fqn = fqn.replace('$', '.');
                    customViews.add(fqn);
                }
            }
        }
    };
    try {
        IJavaProject javaProject = BaseProjectHelper.getJavaProject(mProject);
        if (javaProject != null) {
            String className = layoutsOnly ? CLASS_VIEWGROUP : CLASS_VIEW;
            IType viewType = javaProject.findType(className);
            if (viewType != null) {
                IJavaSearchScope scope = SearchEngine.createHierarchyScope(viewType);
                SearchParticipant[] participants = new SearchParticipant[] {
                        SearchEngine.getDefaultSearchParticipant() };
                int matchRule = SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CASE_SENSITIVE;

                SearchPattern pattern = SearchPattern.createPattern("*", IJavaSearchConstants.CLASS,
                        IJavaSearchConstants.IMPLEMENTORS, matchRule);
                SearchEngine engine = new SearchEngine();
                engine.search(pattern, participants, scope, requestor, new NullProgressMonitor());
            }
        }
    } catch (CoreException e) {
        AdtPlugin.log(e, null);
    }

    List<String> custom = new ArrayList<String>(customViews);
    List<String> thirdParty = new ArrayList<String>(thirdPartyViews);

    if (!layoutsOnly) {
        // Update our cached answers (unless we were filtered on only layouts)
        mCustomViews = custom;
        mThirdPartyViews = thirdParty;
    }

    return Pair.of(custom, thirdParty);
}

From source file:com.android.ide.eclipse.auidt.internal.editors.manifest.ManifestInfo.java

License:Open Source License

/**
 * Returns the activity associated with the given layout file.
 * <p>/*from   w w w. ja v a2s  .  c o m*/
 * This is an alternative to {@link #guessActivity(IFile, String)}. Whereas
 * guessActivity simply looks for references to "R.layout.foo", this method searches
 * for all usages of Activity#setContentView(int), and for each match it looks up the
 * corresponding call text (such as "setContentView(R.layout.foo)"). From this it uses
 * a regexp to pull out "foo" from this, and stores the association that layout "foo"
 * is associated with the activity class that contained the setContentView call.
 * <p>
 * This has two potential advantages:
 * <ol>
 * <li>It can be faster. We do the reference search -once-, and we've built a map of
 * all the layout-to-activity mappings which we can then immediately look up other
 * layouts for, which is particularly useful at startup when we have to compute the
 * layout activity associations to populate the theme choosers.
 * <li>It can be more accurate. Just because an activity references an "R.layout.foo"
 * field doesn't mean it's setting it as a content view.
 * </ol>
 * However, this second advantage is also its chief problem. There are some common
 * code constructs which means that the associated layout is not explicitly referenced
 * in a direct setContentView call; on a couple of sample projects I tested I found
 * patterns like for example "setContentView(v)" where "v" had been computed earlier.
 * Therefore, for now we're going to stick with the more general approach of just
 * looking up each field when needed. We're keeping the code around, though statically
 * compiled out with the "if (false)" construct below in case we revisit this.
 *
 * @param layoutFile the layout whose activity we want to look up
 * @return the activity name
 */
@SuppressWarnings("all")
@Nullable
public String guessActivityBySetContentView(String layoutName) {
    if (false) {
        // These should be fields
        final Pattern LAYOUT_FIELD_PATTERN = Pattern.compile("R\\.layout\\.([a-z0-9_]+)"); //$NON-NLS-1$
        Map<String, String> mUsages = null;

        sync();
        if (mUsages == null) {
            final Map<String, String> usages = new HashMap<String, String>();
            mUsages = usages;
            SearchRequestor requestor = new SearchRequestor() {
                @Override
                public void acceptSearchMatch(SearchMatch match) throws CoreException {
                    Object element = match.getElement();
                    if (element instanceof IMethod) {
                        IMethod method = (IMethod) element;
                        IType declaringType = method.getDeclaringType();
                        String fqcn = declaringType.getFullyQualifiedName();
                        IDocumentProvider provider = new TextFileDocumentProvider();
                        IResource resource = match.getResource();
                        try {
                            provider.connect(resource);
                            IDocument document = provider.getDocument(resource);
                            if (document != null) {
                                String matchText = document.get(match.getOffset(), match.getLength());
                                Matcher matcher = LAYOUT_FIELD_PATTERN.matcher(matchText);
                                if (matcher.find()) {
                                    usages.put(matcher.group(1), fqcn);
                                }
                            }
                        } catch (Exception e) {
                            AdtPlugin.log(e, "Can't find range information for %1$s", resource.getName());
                        } finally {
                            provider.disconnect(resource);
                        }
                    }
                }
            };
            try {
                IJavaProject javaProject = BaseProjectHelper.getJavaProject(mProject);
                if (javaProject == null) {
                    return null;
                }

                // Search for which java classes call setContentView(R.layout.layoutname);
                String typeFqcn = "R.layout"; //$NON-NLS-1$
                if (mPackage != null) {
                    typeFqcn = mPackage + '.' + typeFqcn;
                }

                IType activityType = javaProject.findType(SdkConstants.CLASS_ACTIVITY);
                if (activityType != null) {
                    IMethod method = activityType.getMethod("setContentView", new String[] { "I" }); //$NON-NLS-1$ //$NON-NLS-2$
                    if (method.exists()) {
                        SearchPattern pattern = SearchPattern.createPattern(method, REFERENCES);
                        search(requestor, javaProject, pattern);
                    }
                }
            } catch (CoreException e) {
                AdtPlugin.log(e, null);
            }
        }

        return mUsages.get(layoutName);
    }

    return null;
}

From source file:edu.brown.cs.bubbles.bedrock.BedrockUtil.java

License:Open Source License

/********************************************************************************/

static void outputSearchMatch(SearchMatch mat, IvyXmlWriter xw) {
    xw.begin("MATCH");
    xw.field("OFFSET", mat.getOffset());
    xw.field("LENGTH", mat.getLength());
    xw.field("STARTOFFSET", mat.getOffset());
    xw.field("ENDOFFSET", mat.getOffset() + mat.getLength());
    IResource irc = mat.getResource();
    if (irc != null) {
        File f = mat.getResource().getLocation().toFile();
        switch (irc.getType()) {
        case IResource.FILE:
            xw.field("FILE", f.toString());
            break;
        case IResource.PROJECT:
            xw.field("PROJECT", f.toString());
            break;
        case IResource.FOLDER:
            xw.field("FOLDER", f.toString());
            break;
        case IResource.ROOT:
            xw.field("ROOT", f.toString());
            break;
        }/*  www .  jav a2 s .  com*/
    }
    xw.field("ACCURACY", mat.getAccuracy());
    xw.field("EQUIV", mat.isEquivalent());
    xw.field("ERASURE", mat.isErasure());
    xw.field("EXACT", mat.isExact());
    xw.field("IMPLICIT", mat.isImplicit());
    xw.field("INDOCCMMT", mat.isInsideDocComment());
    xw.field("RAW", mat.isRaw());
    Object o = mat.getElement();
    BedrockPlugin.logD("MATCH ELEMENT " + o);
    if (o instanceof IJavaElement) {
        IJavaElement nelt = (IJavaElement) o;
        outputJavaElement(nelt, false, xw);
    }
    xw.end("MATCH");
}