Example usage for org.eclipse.jdt.core.search SearchRequestor SearchRequestor

List of usage examples for org.eclipse.jdt.core.search SearchRequestor SearchRequestor

Introduction

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

Prototype

SearchRequestor

Source Link

Usage

From source file:bndtools.editor.pkgpatterns.PkgPatternsProposalProvider.java

License:Open Source License

@Override
protected Collection<? extends IContentProposal> doGenerateProposals(String contents, int position) {
    String prefix = contents.substring(0, position);

    final int replaceFromPos;
    if (prefix.startsWith("!")) { //$NON-NLS-1$
        prefix = prefix.substring(1);// w ww .  jav a2  s  .  c o m
        replaceFromPos = 1;
    } else {
        replaceFromPos = 0;
    }

    Comparator<PkgPatternProposal> comparator = new Comparator<PkgPatternProposal>() {
        @Override
        public int compare(PkgPatternProposal o1, PkgPatternProposal o2) {
            int result = o1.getPackageFragment().getElementName()
                    .compareTo(o2.getPackageFragment().getElementName());
            if (result == 0) {
                result = Boolean.valueOf(o1.isWildcard()).compareTo(Boolean.valueOf(o2.isWildcard()));
            }
            return result;
        }
    };
    final TreeSet<PkgPatternProposal> result = new TreeSet<PkgPatternProposal>(comparator);

    final IJavaSearchScope scope = SearchEngine
            .createJavaSearchScope(new IJavaElement[] { searchContext.getJavaProject() });
    final SearchPattern pattern = SearchPattern.createPattern("*" + prefix + "*", IJavaSearchConstants.PACKAGE,
            IJavaSearchConstants.DECLARATIONS, SearchPattern.R_PATTERN_MATCH);
    final SearchRequestor requestor = new SearchRequestor() {
        @Override
        public void acceptSearchMatch(SearchMatch match) throws CoreException {
            IPackageFragment pkg = (IPackageFragment) match.getElement();
            // Reject the default package and any package starting with
            // "java." since these cannot be imported
            if (pkg.isDefaultPackage() || pkg.getElementName().startsWith("java."))
                return;

            result.add(new PkgPatternProposal(pkg, false, replaceFromPos));
            result.add(new PkgPatternProposal(pkg, true, replaceFromPos));
        }
    };
    IRunnableWithProgress runnable = new IRunnableWithProgress() {
        @Override
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            try {
                new SearchEngine().search(pattern,
                        new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, scope,
                        requestor, monitor);
            } catch (CoreException e) {
                throw new InvocationTargetException(e);
            }
        }
    };

    try {
        IRunnableContext runContext = searchContext.getRunContext();
        if (runContext != null) {
            runContext.run(false, false, runnable);
        } else {
            runnable.run(new NullProgressMonitor());
        }
        return result;
    } catch (InvocationTargetException e) {
        logger.logError("Error searching for packages.", e);
        return Collections.emptyList();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        return Collections.emptyList();
    }
}

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

License:Open Source License

@Override
public String[] getPackages(boolean includeNonSource, IPackageFilter filter) throws PackageListException {
    final List<IJavaElement> packageList = new LinkedList<IJavaElement>();
    final SearchRequestor requestor = new SearchRequestor() {
        @Override/*from   w w w .j ava  2s . com*/
        public void acceptSearchMatch(SearchMatch match) throws CoreException {
            IJavaElement enclosingElement = (IJavaElement) match.getElement();
            String name = enclosingElement.getElementName();
            if (name.length() > 0) { // Do not include default pkg
                packageList.add(enclosingElement);
            }
        }
    };
    final SearchPattern pattern = SearchPattern.createPattern("*", IJavaSearchConstants.PACKAGE,
            IJavaSearchConstants.DECLARATIONS, SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CASE_SENSITIVE);

    IRunnableWithProgress operation = new IRunnableWithProgress() {
        @Override
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            try {
                new SearchEngine().search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor,
                        monitor);
            } catch (CoreException e) {
                throw new InvocationTargetException(e);
            }
        }
    };

    try {
        runContext.run(true, true, operation);
    } catch (InvocationTargetException e) {
        throw new PackageListException(e.getCause());
    } catch (InterruptedException e) {
        throw new PackageListException("Operation interrupted");
    }

    // Remove non-source and excludes
    Set<String> packageNames = new LinkedHashSet<String>();
    for (Iterator<IJavaElement> iter = packageList.iterator(); iter.hasNext();) {
        boolean omit = false;
        IJavaElement element = iter.next();
        if (!includeNonSource) {
            IPackageFragment pkgFragment = (IPackageFragment) element;
            try {
                if (pkgFragment.getCompilationUnits().length == 0) {
                    omit = true;
                }
            } catch (JavaModelException e) {
                throw new PackageListException(e);
            }
        }

        if (filter != null && !filter.select(element.getElementName())) {
            omit = true;
        }
        if (!omit) {
            packageNames.add(element.getElementName());
        }
    }

    return packageNames.toArray(new String[0]);
}

From source file:ccw.editors.clojure.ClojureProposalProcessor.java

License:Open Source License

private List<ICompletionProposal> computeAndAddJavaInstanceMethodCompletionProposal(
        final PrefixInfo prefixInfo) {
    final List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();

    if (!checkJavaPrefixLength(prefixInfo)) {
        return Collections.emptyList();
    }/*from   w  ww.  j  a v a2s  .c  o  m*/

    final String methodPrefix = prefixInfo.prefix.substring(1);
    System.out.println("method prefix:" + methodPrefix);
    boolean isPattern = (methodPrefix.contains("*") || methodPrefix.contains("?"));
    boolean autoAddEndWildcard = isPattern && !methodPrefix.endsWith("*");
    SearchPattern pattern = SearchPattern.createPattern(autoAddEndWildcard ? methodPrefix + "*" : methodPrefix,
            IJavaSearchConstants.METHOD, // | IJavaSearchConstants.FIELD,
            //         IJavaSearchConstants.TYPE,
            IJavaSearchConstants.DECLARATIONS,
            isPattern ? SearchPattern.R_PATTERN_MATCH : SearchPattern.R_PREFIX_MATCH);
    if (pattern != null) {
        IJavaProject editedFileProject = editor.getAssociatedProject();
        if (editedFileProject != null) {
            IJavaSearchScope scope = SearchEngine
                    .createJavaSearchScope(new IJavaElement[] { editedFileProject });
            SearchRequestor requestor = new SearchRequestor() {
                private int counter;

                @Override
                public void beginReporting() {
                    super.beginReporting();
                    System.out.println("begin reporting");
                    counter = 0;
                }

                @Override
                public void acceptSearchMatch(SearchMatch match) throws CoreException {
                    counter++;
                    if (counter >= MAX_JAVA_SEARCH_RESULT_NUMBER) {
                        System.out.println("too much results (>" + MAX_JAVA_SEARCH_RESULT_NUMBER
                                + "), throwing exception");
                        throw new CoreException(Status.OK_STATUS);
                    }
                    proposals.add(new MethodLazyCompletionProposal((IMethod) match.getElement(), methodPrefix,
                            prefixInfo.prefixOffset + 1, null, editor));
                }

                @Override
                public void endReporting() {
                    super.endReporting();
                    System.out.println("end reporting : count=" + counter);
                }

            };
            SearchEngine searchEngine = new SearchEngine();
            try {
                searchEngine.search(pattern,
                        new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, scope,
                        requestor, null /* no progress monitor */);
                assistant.setStatusMessage(MESSAGE_JAVA_COMPLETION);
            } catch (CoreException e) {
                if (e.getStatus() != Status.OK_STATUS) {
                    CCWPlugin.logWarning("java code proposal search error in clojure dev", e);
                } else {
                    errorMessage = ERROR_MESSAGE_TOO_MANY_COMPLETIONS;
                    assistant.setStatusMessage(ERROR_MESSAGE_TOO_MANY_COMPLETIONS);
                }
            }
        }
    }
    return proposals;
}

From source file:ccw.editors.clojure.ClojureProposalProcessor.java

License:Open Source License

private List<ICompletionProposal> computeAndAddJavaStaticMethodCompletionProposal(final PrefixInfo prefixInfo,
        final JavaSearchType searchType) {
    final List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();

    if (!checkJavaPrefixLength(prefixInfo)) {
        return Collections.emptyList();
    }/*from   w ww  .j a  v a2  s .  c  om*/

    int nbPatterns = searchType.matchRule().length;
    List<SearchPattern> combinedPattern = new ArrayList<SearchPattern>();

    for (int i = 0; i < nbPatterns; i++) {
        if (prefixInfo.prefix.length() < searchType.prefixMinLength()[i]) {
            continue;
        }
        SearchPattern pattern = SearchPattern.createPattern(searchType.patternStr(prefixInfo)[i],
                searchType.searchFor()[i], IJavaSearchConstants.DECLARATIONS, searchType.matchRule()[i]);
        combinedPattern.add(pattern);
    }

    IJavaProject editedFileProject = editor.getAssociatedProject();
    if (editedFileProject != null) {
        IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaElement[] { editedFileProject });
        SearchRequestor requestor = new SearchRequestor() {
            @Override
            public void acceptSearchMatch(SearchMatch match) throws CoreException {
                proposals.add(searchType.lazyCompletionProposal(prefixInfo, editor, match));
            }
        };
        SearchEngine searchEngine = new SearchEngine();
        try {
            for (SearchPattern pattern : combinedPattern) {
                if (pattern != null) {
                    searchEngine.search(pattern,
                            new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, scope,
                            requestor, null /* no progress monitor */);
                    assistant.setStatusMessage(MESSAGE_JAVA_COMPLETION);
                }
            }
        } catch (CoreException e) {
            if (e.getStatus() != Status.OK_STATUS) {
                CCWPlugin.logWarning("java code proposal search error in clojure dev", e);
            } else {
                errorMessage = ERROR_MESSAGE_TOO_MANY_COMPLETIONS;
                assistant.setStatusMessage(ERROR_MESSAGE_TOO_MANY_COMPLETIONS);
            }
        }
    }
    return proposals;
}

From source file:com.android.ide.eclipse.adt.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
 *//* w  w w .j  a  v a  2 s .  c om*/
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) {
        AdtPlugin.log(e, null);
    }
    return false;
}

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 a va  2 s  .c o 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 activities associated with the given layout file. Makes an educated guess
 * by peeking at the usages of the R.layout.name field corresponding to the layout and
 * if it finds a usage./*from w w  w.j  a  va  2 s.c  o  m*/
 *
 * @param project the project containing the layout
 * @param layoutName the layout whose activity we want to look up
 * @param pkg the package containing activities
 * @return the activity name
 */
@NonNull
public static List<String> guessActivities(IProject project, String layoutName, String pkg) {
    final LinkedList<String> activities = new LinkedList<String>();
    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();

                if ((declaringType.getSuperclassName() != null
                        && declaringType.getSuperclassName().endsWith("Activity")) //$NON-NLS-1$
                        || method.getElementName().equals("onCreate")) { //$NON-NLS-1$
                    activities.addFirst(fqcn);
                } else {
                    activities.addLast(fqcn);
                }
            }
        }
    };
    try {
        IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
        if (javaProject == null) {
            return Collections.emptyList();
        }
        // TODO - look around a bit more and see if we can figure out whether the
        // call if from within a setContentView call!

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

        IType type = javaProject.findType(typeFqcn);
        if (type != null) {
            IField field = type.getField(layoutName);
            if (field.exists()) {
                SearchPattern pattern = SearchPattern.createPattern(field, REFERENCES);
                try {
                    search(requestor, javaProject, pattern);
                } catch (OperationCanceledException canceled) {
                    // pass
                }
            }
        }
    } catch (CoreException e) {
        AdtPlugin.log(e, null);
    }

    return activities;
}

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>//w w w  .ja  v a  2 s.co 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.internal.editors.xml.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   ww  w  .j a  v  a 2 s.com*/
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(SdkConstants.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) {
        AdtPlugin.log(e, null);
    }
    return false;
}

From source file:com.android.ide.eclipse.adt.internal.refactoring.core.AndroidPackageRenameParticipant.java

License:Open Source License

@Override
protected boolean initialize(final Object element) {
    mIsPackage = false;/* ww  w .j  a  va 2 s . co m*/
    try {
        if (element instanceof IPackageFragment) {
            mPackageFragment = (IPackageFragment) element;
            if (!mPackageFragment.containsJavaResources())
                return false;
            IJavaProject javaProject = (IJavaProject) mPackageFragment.getAncestor(IJavaElement.JAVA_PROJECT);
            IProject project = javaProject.getProject();
            IResource manifestResource = project
                    .findMember(AdtConstants.WS_SEP + SdkConstants.FN_ANDROID_MANIFEST_XML);

            if (manifestResource == null || !manifestResource.exists()
                    || !(manifestResource instanceof IFile)) {
                RefactoringUtil.logInfo("Invalid or missing the " + SdkConstants.FN_ANDROID_MANIFEST_XML
                        + " in the " + project.getName() + " project.");
                return false;
            }
            mAndroidManifest = (IFile) manifestResource;
            String packageName = mPackageFragment.getElementName();
            ManifestData manifestData;
            manifestData = AndroidManifestHelper.parseForData(mAndroidManifest);
            if (manifestData == null) {
                return false;
            }
            mAppPackage = manifestData.getPackage();
            mOldName = packageName;
            mNewName = getArguments().getNewName();
            if (mOldName == null || mNewName == null) {
                return false;
            }

            if (RefactoringUtil.isRefactorAppPackage() && mAppPackage != null
                    && mAppPackage.equals(packageName)) {
                mIsPackage = true;
            }
            mAndroidElements = addAndroidElements();
            try {
                final IType type = javaProject.findType(SdkConstants.CLASS_VIEW);
                SearchPattern pattern = SearchPattern.createPattern("*", IJavaSearchConstants.TYPE,
                        IJavaSearchConstants.DECLARATIONS, SearchPattern.R_REGEXP_MATCH);
                IJavaSearchScope scope = SearchEngine
                        .createJavaSearchScope(new IJavaElement[] { mPackageFragment });
                final HashSet<IType> elements = new HashSet<IType>();
                SearchRequestor requestor = new SearchRequestor() {

                    @Override
                    public void acceptSearchMatch(SearchMatch match) throws CoreException {
                        Object elem = match.getElement();
                        if (elem instanceof IType) {
                            IType eType = (IType) elem;
                            IType[] superTypes = JavaModelUtil.getAllSuperTypes(eType,
                                    new NullProgressMonitor());
                            for (int i = 0; i < superTypes.length; i++) {
                                if (superTypes[i].equals(type)) {
                                    elements.add(eType);
                                    break;
                                }
                            }
                        }

                    }
                };
                SearchEngine searchEngine = new SearchEngine();
                searchEngine.search(pattern,
                        new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, scope,
                        requestor, null);
                List<String> views = new ArrayList<String>();
                for (IType elem : elements) {
                    views.add(elem.getFullyQualifiedName());
                }
                if (views.size() > 0) {
                    String[] classNames = views.toArray(new String[0]);
                    addLayoutChanges(project, classNames);
                }
            } catch (CoreException e) {
                RefactoringUtil.log(e);
            }

            return mIsPackage || mAndroidElements.size() > 0 || mFileChanges.size() > 0;
        }
    } catch (JavaModelException ignore) {
    }
    return false;
}