Example usage for org.eclipse.jdt.core.search SearchPattern createPattern

List of usage examples for org.eclipse.jdt.core.search SearchPattern createPattern

Introduction

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

Prototype

public static SearchPattern createPattern(String stringPattern, int searchFor, int limitTo, int matchRule) 

Source Link

Document

Returns a search pattern based on a given string pattern.

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);/*from  w w  w.j a v a 2 s  .  c  om*/
        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   www.j a  va  2 s.  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:ca.mcgill.cs.swevo.jayfx.FastConverter.java

License:Open Source License

/**
 * Returns a Java element associated with pElement. This method cannot track
 * local or anonymous types or any of their members, primitive types, or
 * array types. It also cannot find initializers, default constructors that
 * are not explicitly declared, or non-top-level types outside the project
 * analyzed. If such types are passed as argument, a ConversionException is
 * thrown./*ww  w .  j  a  va 2s  . co  m*/
 * 
 * @param pElement
 *            The element to convert. Never null.
 * @return Never null.
 * @throws ConversionException
 *             If the element cannot be
 */
public IJavaElement getJavaElement(final IElement pElement) throws ConversionException {
    // assert( pElement!= null );
    IJavaElement lReturn = null;
    if (pElement.getCategory() == Category.CLASS) {
        lReturn = this.aTypeMap.get(pElement.getId());
        if (lReturn == null)
            // TODO Make this smarter in the case of multiple projects
            if (this.aTypeMap.size() > 0)
                try {
                    lReturn = this.aTypeMap.values().iterator().next().getJavaProject()
                            .findType(pElement.getId());
                } catch (final JavaModelException pException) {
                    // noting
                }
        if (lReturn == null)
            throw new ConversionException("Cannot find type " + pElement);
    } else if (pElement.getCategory() == Category.PACKAGE) {
        String id = pElement.getId();
        final SearchPattern pattern = SearchPattern.createPattern(id, IJavaSearchConstants.PACKAGE,
                IJavaSearchConstants.DECLARATIONS,
                SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE);
        Collection<SearchMatch> matches = SearchEngineUtil.search(pattern, null);
        if (matches.isEmpty())
            throw new ConversionException("Cannot find type " + pElement);
        else
            lReturn = (IJavaElement) matches.iterator().next().getElement();
    } else {
        final IJavaElement lDeclaringClass = this.getJavaElement(pElement.getDeclaringClass());
        if (pElement.getCategory() == Category.FIELD) {
            lReturn = ((IType) lDeclaringClass).getField(((FieldElement) pElement).getSimpleName());
            if (lReturn == null)
                throw new ConversionException("Cannot find field " + pElement);
        } else if (pElement.getCategory() == Category.METHOD)
            try {
                final IMethod[] lMethods = ((IType) lDeclaringClass).getMethods();
                lReturn = this.findMethod((MethodElement) pElement, lMethods);

                // if( lReturn == null &&
                // isDefaultConstructor((MethodElement)pElement)) {
                //
                // }

                if (lReturn == null)
                    throw new ConversionException("Cannot find method " + pElement);
            } catch (final JavaModelException pException) {
                throw new ConversionException("Cannot convert method " + pElement);
            }
        else
            throw new ConversionException("Unsupported element type " + pElement.getClass().getName());
    }
    // assert( lReturn != null );
    return lReturn;
}

From source file:ca.uvic.chisel.javasketch.internal.JavaSearchUtils.java

License:Open Source License

public static SearchPattern createMethodDeclarationPattern(ITraceClassMethod method) {
    if (method == null) {
        return null;
    }//from ww  w. j a  v a 2 s  . co m
    ITraceClass callingClass = method.getTraceClass();
    if (callingClass == null) {
        return null;
    }
    String className = callingClass.getName();
    className = Signature.toString(className);
    boolean isConstructor = false;
    String methodName = method.getName();
    isConstructor = methodName.startsWith("<init");
    if (isConstructor) {
        int lastDotIndex = className.lastIndexOf('.');
        if (lastDotIndex >= 0) {
            methodName = className.substring(lastDotIndex + 1);
        }
    }

    String methodString = Signature.toString(method.getSignature(), methodName, null, false, true);
    String returnType = "";
    if (!isConstructor) {
        int returnIndex = methodString.indexOf(' ');
        if (returnIndex > 0) {
            returnType = " " + methodString.substring(0, returnIndex);
            methodString = methodString.substring(returnIndex + 1, methodString.length());
        }
    }
    return SearchPattern.createPattern(className + '.' + methodString + returnType, IJavaSearchConstants.METHOD,
            IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH);
}

From source file:ca.uvic.chisel.javasketch.internal.JavaSearchUtils.java

License:Open Source License

private static IJavaElement searchForType(String classSignature, IJavaSearchScope scope,
        IProgressMonitor monitor) throws CoreException, InterruptedException {
    try {/* w  w  w  . java  2 s.  co  m*/
        synchronized (cachedTypes) {
            IType found = cachedTypes.get(classSignature);
            if (found != null) {
                return found;
            }
            SearchEngine engine = new SearchEngine();
            SearchPattern pattern = null;
            SearchParticipant participant = SearchEngine.getDefaultSearchParticipant();
            LocalSearchRequestor requestor = new LocalSearchRequestor();
            pattern = SearchPattern.createPattern(classSignature.replace('$', '.'), IJavaSearchConstants.CLASS,
                    IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH);

            engine.search(pattern, new SearchParticipant[] { participant }, scope, requestor, monitor);
            if (requestor.matches.size() > 0) {
                found = (IType) requestor.matches.get(0).getElement();
                if (found.getFullyQualifiedName().equals(classSignature)) {
                    cachedTypes.put(classSignature, found);
                    return found;
                }

            }
            String[] className = classSignature.split("\\$");
            found = cachedTypes.get(className[0]);
            if (found == null) {

                //find the class
                pattern = SearchPattern.createPattern(className[0], IJavaSearchConstants.CLASS,
                        IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH);

                engine.search(pattern, new SearchParticipant[] { participant }, scope, requestor, monitor);
                if (monitor.isCanceled()) {
                    throw new InterruptedException();
                }
                if (requestor.matches.size() > 0) {
                    found = (IType) requestor.matches.get(0).getElement();
                    if (found.getFullyQualifiedName().equals(classSignature)) {
                        for (SearchMatch match : requestor.matches) {
                            IType temp = (IType) match.getElement();
                            if (temp.getTypeRoot() instanceof ICompilationUnit) {
                                //prefer source types.
                                found = temp;
                                break;
                            }
                        }
                        if (cachedTypes.size() > 100) {
                            cachedTypes.clear();
                        }
                        cachedTypes.put(className[0], found);
                    } else {
                        found = null;
                    }
                }
            }
            if (found == null)
                return null;
            StringBuilder childTypeName = new StringBuilder();
            childTypeName.append(className[0]);
            //check each of the indexes for the sub-types
            for (int i = 1; i < className.length; i++) {
                childTypeName.append('$');
                childTypeName.append(className[i]);
                IType parent = found;
                found = cachedTypes.get(childTypeName.toString());

                if (found == null) {
                    boolean isAnonymous = false;
                    Integer occurrenceCount = -1;
                    try {
                        occurrenceCount = Integer.parseInt(className[i]);
                        isAnonymous = true;
                    } catch (NumberFormatException e) {
                        isAnonymous = false;
                    }
                    if (isAnonymous) {
                        if (!parent.isBinary()) {
                            found = parent.getType("", occurrenceCount);
                            if (found != null) {
                                if (found.exists()) {
                                    cachedTypes.put(childTypeName.toString(), found);
                                    continue;
                                } else {
                                    found = null;
                                }
                            }
                        } else {
                            //if it is a binary type, there is no hope for 
                            //finding an anonymous inner class. Use the number
                            //as the type name, and cache the handle.
                            found = parent.getType(className[i]);
                            cachedTypes.put(childTypeName.toString(), found);
                            continue;
                        }
                    }
                    ArrayList<IType> childTypes = new ArrayList<IType>();
                    LinkedList<IJavaElement> children = new LinkedList<IJavaElement>();
                    children.addAll(Arrays.asList(parent.getChildren()));
                    while (children.size() > 0) {
                        IJavaElement child = children.removeFirst();
                        if (child instanceof IType) {
                            childTypes.add((IType) child);
                        } else if (child instanceof IMember) {
                            children.addAll(Arrays.asList(((IMember) child).getChildren()));
                        }
                    }
                    int numIndex = 0;
                    while (numIndex < className[i].length()
                            && Character.isDigit(className[i].charAt(numIndex))) {
                        numIndex++;
                    }
                    String name = className[i];
                    try {
                        //get a number at the beginning to find out if 
                        //there is an occurrence count
                        if (numIndex <= name.length()) {
                            occurrenceCount = parseInt(name.substring(0, numIndex));
                            if (occurrenceCount == null) {
                                occurrenceCount = 1;
                            }
                            if (numIndex < name.length() - 1) {
                                name = name.substring(numIndex);
                            } else {
                                name = "";
                            }
                        }
                        for (IType childType : childTypes) {
                            if ("".equals(name)) {
                                if (childType.getOccurrenceCount() == occurrenceCount) {
                                    found = childType;
                                    break;
                                }
                            } else {
                                if (name.equals(childType.getElementName())
                                        && childType.getOccurrenceCount() == occurrenceCount) {
                                    found = childType;
                                    break;
                                }
                            }
                        }
                        if (found == null) {
                            if ("".equals(name)) {
                                found = parent.getTypeRoot().getJavaProject().findType(classSignature);
                                //found = parent.getType("" + occurrenceCount);
                            } else {
                                found = parent.getType(name, occurrenceCount);
                            }
                        }
                        cachedTypes.put(childTypeName.toString(), found);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }
            return found;
        }
    } catch (Exception e) {
        SketchPlugin.getDefault().log(e);
        return null;
    }
}

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();
    }//  w  ww .j ava 2  s.  c  om

    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();
    }//  www.j  av  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.aliyun.odps.eclipse.launch.configuration.udf.UDFSearchEngine.java

License:Apache License

/**
 * Searches for all main methods in the given scope. Valid styles are
 * IJavaElementSearchConstants.CONSIDER_BINARIES and
 * IJavaElementSearchConstants.CONSIDER_EXTERNAL_JARS
 * //from ww w. j  a  v  a 2s . c o  m
 * @param pm progress monitor
 * @param scope search scope
 * @param includeSubtypes whether to consider types that inherit a main method
 */
public IType[] searchUDFClass(IProgressMonitor pm, IJavaSearchScope scope, boolean includeSubtypes) {
    int searchTicks = 100;
    if (includeSubtypes) {
        searchTicks = 25;
    }

    SearchPattern udfPattern = SearchPattern.createPattern("com.aliyun.odps.udf.UDF", //$NON-NLS-1$
            IJavaSearchConstants.CLASS, IJavaSearchConstants.IMPLEMENTORS, SearchPattern.R_PATTERN_MATCH);
    SearchPattern udtfpattern = SearchPattern.createPattern("com.aliyun.odps.udf.UDTF",
            IJavaSearchConstants.CLASS, IJavaSearchConstants.IMPLEMENTORS, SearchPattern.R_PATTERN_MATCH);
    SearchParticipant[] participants = new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() };
    UDFClassCollector collector = new UDFClassCollector();
    IProgressMonitor udfSearchMonitor = new SubProgressMonitor(pm, searchTicks);
    try {
        pm.beginTask("Searching for UDF class...", 100);
        new SearchEngine().search(udfPattern, participants, scope, collector, udfSearchMonitor);
        pm.beginTask("Searching for UDTF class...", 100);
        IProgressMonitor udtfSearchMonitor = new SubProgressMonitor(pm, searchTicks);
        new SearchEngine().search(udtfpattern, participants, scope, collector, udtfSearchMonitor);
        pm.beginTask("Searching for UDF class...", 100);
    } catch (CoreException ce) {
        JDIDebugUIPlugin.log(ce);
    }

    List result = collector.getResult();
    if (includeSubtypes) {
        IProgressMonitor subtypesMonitor = new SubProgressMonitor(pm, 75);
        subtypesMonitor.beginTask("Select UDF|UDTF class", result.size());
        Set set = addSubtypes(result, subtypesMonitor, scope);
        return (IType[]) set.toArray(new IType[set.size()]);
    }
    return (IType[]) result.toArray(new IType[result.size()]);
}

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
 *///from  ww w.j  a v a  2  s  .c o  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) {
        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/*  w ww  . j  ava 2 s. c  om*/
        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);
}