Example usage for org.eclipse.jdt.core.search IJavaSearchConstants METHOD

List of usage examples for org.eclipse.jdt.core.search IJavaSearchConstants METHOD

Introduction

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

Prototype

int METHOD

To view the source code for org.eclipse.jdt.core.search IJavaSearchConstants METHOD.

Click Source Link

Document

The searched element is a method.

Usage

From source file:org.eclim.plugin.jdt.command.launching.JavaCommand.java

License:Open Source License

private String findMainClass(IJavaProject javaProject) throws Exception {
    ArrayList<IJavaElement> srcs = new ArrayList<IJavaElement>();
    for (IClasspathEntry entry : javaProject.getResolvedClasspath(true)) {
        if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
            for (IPackageFragmentRoot root : javaProject.findPackageFragmentRoots(entry)) {
                srcs.add(root);// w  w  w  .jav a2 s  .  c om
            }
        }
    }

    final ArrayList<IMethod> methods = new ArrayList<IMethod>();
    int context = IJavaSearchConstants.DECLARATIONS;
    int type = IJavaSearchConstants.METHOD;
    int matchType = SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE;
    IJavaSearchScope scope = SearchEngine.createJavaSearchScope(srcs.toArray(new IJavaElement[srcs.size()]));
    SearchPattern pattern = SearchPattern.createPattern("main(String[])", type, context, matchType);
    SearchRequestor requestor = new SearchRequestor() {
        public void acceptSearchMatch(SearchMatch match) {
            if (match.getAccuracy() != SearchMatch.A_ACCURATE) {
                return;
            }

            try {
                IMethod method = (IMethod) match.getElement();
                String[] params = method.getParameterTypes();
                if (params.length != 1) {
                    return;
                }

                if (!Signature.SIG_VOID.equals(method.getReturnType())) {
                    return;
                }

                int flags = method.getFlags();
                if (!Flags.isPublic(flags) || !Flags.isStatic(flags)) {
                    return;
                }

                methods.add(method);
            } catch (JavaModelException e) {
                // ignore
            }
        }
    };

    SearchEngine engine = new SearchEngine();
    SearchParticipant[] participants = new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() };
    engine.search(pattern, participants, scope, requestor, null);

    // if we found only 1 result, we can use it.
    if (methods.size() == 1) {
        IMethod method = methods.get(0);
        ICompilationUnit cu = method.getCompilationUnit();
        IPackageDeclaration[] packages = cu.getPackageDeclarations();
        if (packages != null && packages.length > 0) {
            return packages[0].getElementName() + "." + cu.getElementName();
        }
        return cu.getElementName();
    }
    return null;
}

From source file:org.eclim.plugin.jdt.command.search.SearchCommand.java

License:Open Source License

/**
 * Executes the search./*from w w  w.j  a  v  a 2  s .  co  m*/
 *
 * @param commandLine The command line for the search.
 * @return The search results.
 */
public List<SearchMatch> executeSearch(CommandLine commandLine) throws Exception {
    int context = -1;
    if (commandLine.hasOption(Options.CONTEXT_OPTION)) {
        context = getContext(commandLine.getValue(Options.CONTEXT_OPTION));
    }
    String project = commandLine.getValue(Options.NAME_OPTION);
    String scope = commandLine.getValue(Options.SCOPE_OPTION);
    String file = commandLine.getValue(Options.FILE_OPTION);
    String offset = commandLine.getValue(Options.OFFSET_OPTION);
    String length = commandLine.getValue(Options.LENGTH_OPTION);
    String pat = commandLine.getValue(Options.PATTERN_OPTION);

    SearchPattern pattern = null;
    IJavaProject javaProject = project != null ? JavaUtils.getJavaProject(project) : null;

    SearchRequestor requestor = new SearchRequestor();

    // element search
    if (file != null && offset != null && length != null) {
        int charOffset = getOffset(commandLine);
        IJavaElement element = getElement(javaProject, file, charOffset, Integer.parseInt(length));
        if (element != null) {
            // user requested a contextual search.
            if (context == -1) {
                context = getElementContextualContext(element);

                // jdt search doesn't support implementors for method searches, so
                // switch to declarations.
            } else if (context == IJavaSearchConstants.IMPLEMENTORS
                    && element.getElementType() == IJavaElement.METHOD) {
                context = IJavaSearchConstants.DECLARATIONS;
                requestor = new ImplementorsSearchRequestor();
            }
            pattern = SearchPattern.createPattern(element, context);
        }

        // pattern search
    } else if (pat != null) {
        if (context == -1) {
            context = IJavaSearchConstants.DECLARATIONS;
        }

        int matchType = SearchPattern.R_EXACT_MATCH;

        // wild card character supplied, use pattern matching.
        if (pat.indexOf('*') != -1 || pat.indexOf('?') != -1) {
            matchType = SearchPattern.R_PATTERN_MATCH;

            // all upper case, add camel case support.
        } else if (pat.equals(pat.toUpperCase())) {
            matchType |= SearchPattern.R_CAMELCASE_MATCH;
        }

        boolean caseSensitive = !commandLine.hasOption(Options.CASE_INSENSITIVE_OPTION);
        if (caseSensitive) {
            matchType |= SearchPattern.R_CASE_SENSITIVE;
        }

        int type = getType(commandLine.getValue(Options.TYPE_OPTION));

        // jdt search doesn't support implementors for method searches, so switch
        // to declarations.
        if (type == IJavaSearchConstants.METHOD && context == IJavaSearchConstants.IMPLEMENTORS) {
            context = IJavaSearchConstants.DECLARATIONS;
            requestor = new ImplementorsSearchRequestor();
        }

        // hack for inner classes
        Matcher matcher = INNER_CLASS.matcher(pat);
        if (matcher.matches()) {
            // pattern search doesn't support org.test.Type$Inner or
            // org.test.Type.Inner, so convert it to org.test.*Inner, then filter
            // the results.
            pattern = SearchPattern.createPattern(matcher.replaceFirst("$1*$3"), type, context, matchType);
            Pattern toMatch = Pattern.compile(pat.replace(".", "\\.").replace("$", "\\$").replace("(", "\\(")
                    .replace(")", "\\)").replace("*", ".*").replace("?", "."));
            List<SearchMatch> matches = search(pattern, getScope(scope, javaProject));
            Iterator<SearchMatch> iterator = matches.iterator();
            while (iterator.hasNext()) {
                SearchMatch match = iterator.next();
                String name = JavaUtils.getFullyQualifiedName((IJavaElement) match.getElement()).replace("#",
                        ".");
                if (!toMatch.matcher(name).matches()) {
                    iterator.remove();
                }
            }
            return matches;
        }

        pattern = SearchPattern.createPattern(pat, type, context, matchType);

        // bad search request
    } else {
        throw new IllegalArgumentException(Services.getMessage("java_search.indeterminate"));
    }

    List<SearchMatch> matches = search(pattern, getScope(scope, javaProject), requestor);
    return matches;
}

From source file:org.eclim.plugin.jdt.command.search.SearchCommand.java

License:Open Source License

/**
 * Translates the string type to the int equivalent.
 *
 * @param type The String type.//from   w ww.  j  a  v  a 2  s.co m
 * @return The int type.
 */
protected int getType(String type) {
    if (TYPE_ANNOTATION.equals(type)) {
        return IJavaSearchConstants.ANNOTATION_TYPE;
    } else if (TYPE_CLASS.equals(type)) {
        return IJavaSearchConstants.CLASS;
    } else if (TYPE_CLASS_OR_ENUM.equals(type)) {
        return IJavaSearchConstants.CLASS_AND_ENUM;
    } else if (TYPE_CLASS_OR_INTERFACE.equals(type)) {
        return IJavaSearchConstants.CLASS_AND_INTERFACE;
    } else if (TYPE_CONSTRUCTOR.equals(type)) {
        return IJavaSearchConstants.CONSTRUCTOR;
    } else if (TYPE_ENUM.equals(type)) {
        return IJavaSearchConstants.ENUM;
    } else if (TYPE_FIELD.equals(type)) {
        return IJavaSearchConstants.FIELD;
    } else if (TYPE_INTERFACE.equals(type)) {
        return IJavaSearchConstants.INTERFACE;
    } else if (TYPE_METHOD.equals(type)) {
        return IJavaSearchConstants.METHOD;
    } else if (TYPE_PACKAGE.equals(type)) {
        return IJavaSearchConstants.PACKAGE;
    }
    return IJavaSearchConstants.TYPE;
}

From source file:org.eclim.plugin.jdt.command.src.JavaCommand.java

License:Open Source License

private String findMainClass(IJavaProject javaProject) throws Exception {
    final String projectPath = ProjectUtils.getPath(javaProject.getProject());
    final ArrayList<IMethod> methods = new ArrayList<IMethod>();
    int context = IJavaSearchConstants.DECLARATIONS;
    int type = IJavaSearchConstants.METHOD;
    int matchType = SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE;
    IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaElement[] { javaProject });
    SearchPattern pattern = SearchPattern.createPattern("main(String[])", type, context, matchType);
    SearchRequestor requestor = new SearchRequestor() {
        public void acceptSearchMatch(SearchMatch match) {
            if (match.getAccuracy() != SearchMatch.A_ACCURATE) {
                return;
            }//  w ww.j a  v a 2s .  com

            IPath location = match.getResource().getRawLocation();
            if (location == null) {
                return;
            }

            String path = location.toOSString().replace('\\', '/');
            if (!path.toLowerCase().startsWith(projectPath.toLowerCase())) {
                return;
            }

            IJavaElement element = (IJavaElement) match.getElement();
            if (element.getElementType() != IJavaElement.METHOD) {
                return;
            }

            IMethod method = (IMethod) element;
            String[] params = method.getParameterTypes();
            if (params.length != 1) {
                return;
            }
            methods.add(method);
        }
    };

    if (pattern != null) {
        SearchEngine engine = new SearchEngine();
        SearchParticipant[] participants = new SearchParticipant[] {
                SearchEngine.getDefaultSearchParticipant() };
        engine.search(pattern, participants, scope, requestor, null);

        // if we found only 1 result, we can use it.
        if (methods.size() == 1) {
            IMethod method = methods.get(0);
            ICompilationUnit cu = method.getCompilationUnit();
            IPackageDeclaration[] packages = cu.getPackageDeclarations();
            if (packages != null && packages.length > 0) {
                return packages[0].getElementName() + "." + cu.getElementName();
            }
            return cu.getElementName();
        }
    }
    return null;
}

From source file:org.eclipse.acceleo.internal.ide.ui.launching.AcceleoMainMethodSearchEngine.java

License:Open Source 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  av a 2s  .  c  om*/
 * @param pm
 *            progress monitor
 * @param scope
 *            search scope
 * @param includeSubtypes
 *            whether to consider types that inherit a main method
 * @return main methods types
 */
public IType[] searchMainMethods(IProgressMonitor pm, IJavaSearchScope scope, boolean includeSubtypes) {
    final int v100 = 100;
    final int v25 = 25;
    final int v75 = 75;
    pm.beginTask(AcceleoUIMessages.getString("AcceleoMainMethodSearchEngine.SearchingForMainTypes"), 100); //$NON-NLS-1$
    int searchTicks = v100;
    if (includeSubtypes) {
        searchTicks = v25;
    }

    SearchPattern pattern = SearchPattern.createPattern("main(String[]) void", IJavaSearchConstants.METHOD, //$NON-NLS-1$
            IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE);
    SearchParticipant[] participants = new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant(), };
    MethodCollector collector = new MethodCollector();
    IProgressMonitor searchMonitor = new SubProgressMonitor(pm, searchTicks);
    try {
        new SearchEngine().search(pattern, participants, scope, collector, searchMonitor);
    } catch (CoreException e) {
        AcceleoUIActivator.getDefault().getLog().log(e.getStatus());
    }

    List<IType> result = collector.getResult();
    if (includeSubtypes) {
        IProgressMonitor subtypesMonitor = new SubProgressMonitor(pm, v75);
        subtypesMonitor.beginTask(
                AcceleoUIMessages.getString("AcceleoMainMethodSearchEngine.SearchingForMainTypes"), //$NON-NLS-1$
                result.size());
        Set<IType> set = addSubtypes(result, subtypesMonitor, scope);
        return set.toArray(new IType[set.size()]);
    }
    return result.toArray(new IType[result.size()]);
}

From source file:org.eclipse.andmore.internal.editors.Hyperlinks.java

License:Open Source License

/**
 * Opens a Java method referenced by the given on click attribute method name
 *
 * @param project the project containing the click handler
 * @param method the method name of the on click handler
 * @return true if the method was opened, false otherwise
 *///from ww w . j a  va  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) {
        AndmoreAndroidPlugin.log(e, null);
    }
    return false;
}

From source file:org.eclipse.che.jdt.search.SearchTestHelper.java

License:Open Source License

static JavaSearchQuery runMethodRefQuery(String methodName) {
    JavaSearchQuery query = new JavaSearchQuery(new PatternQuerySpecification(methodName,
            IJavaSearchConstants.METHOD, true, IJavaSearchConstants.REFERENCES,
            JavaSearchScopeFactory.getInstance().createWorkspaceScope(true), "workspace scope"));
    NewSearchUI.runQueryInForeground(null, query);
    return query;
}

From source file:org.eclipse.dltk.mod.javascript.jdt.integration.JdtReferenceResolver.java

License:Open Source License

public Set getChilds(final IResolvableReference ref) {
    if (ref instanceof AbstractCallResultReference) {
        final AbstractCallResultReference cm = (AbstractCallResultReference) ref;
        if (cm instanceof NewReference) {
            String preId = cm.getId();
            final HashSet result = new HashSet();
            if (preId.startsWith(PACKAGES))
                preId = preId.substring(PACKAGES.length());
            IJavaSearchScope createJavaSearchScope = SearchEngine
                    .createJavaSearchScope(new IJavaElement[] { create });
            SearchPattern createPattern = SearchPattern.createPattern("jsFunction*",
                    IJavaSearchConstants.METHOD, 100, SearchPattern.R_PATTERN_MATCH);
            try {

                engine.search(createPattern,
                        new org.eclipse.jdt.core.search.SearchParticipant[] {
                                engine.getDefaultSearchParticipant() },
                        createJavaSearchScope, new SearchRequestor() {

                            public void acceptSearchMatch(SearchMatch match) throws CoreException {
                                Object element = match.getElement();

                                if (element instanceof IMethod) {
                                    IMethod m = (IMethod) element;
                                    IType declaringType = m.getDeclaringType();
                                    if (!declaringType.getElementName().equals(cm.getId()))
                                        return;
                                    IMethod[] ts = declaringType.getMethods();
                                    for (int a = 0; a < ts.length; a++) {
                                        String string = "jsFunction_";
                                        String stringget = "jsGet_";
                                        String stringset = "jsSet_";
                                        IMethod method = ts[a];
                                        if (method.getElementName().startsWith(string)) {
                                            UnknownReference r = new UnknownReference(
                                                    method.getElementName().substring(string.length()), true);

                                            result.add(r);
                                            r.setFunctionRef();
                                        } else if (method.getElementName().startsWith(stringget)) {
                                            IReference r = new UnknownReference(
                                                    method.getElementName().substring(stringget.length()),
                                                    true);
                                            result.add(r);
                                        } else if (method.getElementName().startsWith(stringset)) {
                                            IReference r = new UnknownReference(
                                                    method.getElementName().substring(stringset.length()),
                                                    true);
                                            result.add(r);
                                        }
                                    }//  ww  w.  ja  va2 s.  c  o  m
                                }
                            }

                        }, null);
            } catch (CoreException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            final String cmid = preId;
            if (!result.isEmpty())
                return result;
            String string = cmid + " z=new " + cmid + ";z.";
            try {

                context.codeComplete(string, string.length(), new CompletionRequestor() {
                    public void accept(CompletionProposal proposal) {
                        IReference r = new JavaProposalReference(context, proposal, owner, create, cmid);
                        result.add(r);

                    }
                });
                return result;
            } catch (JavaModelException e) {
                return null;
            }
        }
        if (cm instanceof CallResultReference) {
            CallResultReference call = (CallResultReference) cm;
            IReference rm = call.getRoot();
            if (rm != null) {
                int lastIndexOf = call.getId().lastIndexOf('.');
                String substring = call.getId().substring(lastIndexOf + 1);
                IReference child = rm.getChild(substring, true);
                if (child == null)
                    return null;
                return child.getChilds(true);
            }
        }
    }
    return null;
}

From source file:org.eclipse.dltk.mod.javascript.jdt.integration.JdtReferenceResolver.java

License:Open Source License

public Set resolveGlobals(String id) {

    final HashSet result = new HashSet();
    if (id.startsWith(PACKAGES))
        id = id.substring(PACKAGES.length());
    final String id2 = id;

    String sm = id;//from  www.  jav a2  s  .  co  m

    int indexOf = id.indexOf('.');

    if (indexOf == -1) {
        sm = "import " + sm;
        IJavaSearchScope createJavaSearchScope = SearchEngine
                .createJavaSearchScope(new IJavaElement[] { create });
        SearchPattern createPattern = SearchPattern.createPattern("jsFunction*", IJavaSearchConstants.METHOD,
                100, SearchPattern.R_PATTERN_MATCH);
        try {
            engine.search(createPattern,
                    new org.eclipse.jdt.core.search.SearchParticipant[] {
                            engine.getDefaultSearchParticipant() },
                    createJavaSearchScope, new SearchRequestor() {

                        public void acceptSearchMatch(SearchMatch match) throws CoreException {
                            Object element = match.getElement();

                            if (element instanceof IMethod) {
                                IMethod m = (IMethod) element;
                                String elementName = m.getDeclaringType().getElementName();
                                IReference r = new ClassRef(elementName, true);
                                result.add(r);
                            }
                        }

                    }, null);
        } catch (CoreException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        if (result.size() > 0)
            return result;
        try {
            context.codeComplete(sm, sm.length(), new CompletionRequestor() {

                public void accept(CompletionProposal proposal) {
                    if (proposal.getName() != null) {
                        IReference r = new JavaProposalReference(context, proposal, owner, create, "");
                        result.add(r);
                    } else {
                        char[] completion = proposal.getCompletion();
                        String sm = new String(completion);
                        IReference r = new JavaProposalReference(context, sm, proposal, owner, create, "");
                        result.add(r);
                    }
                }

            });
        } catch (JavaModelException e) {

        }
    } else {
        try {
            context.codeComplete(sm, sm.length(), new CompletionRequestor() {

                public void accept(CompletionProposal proposal) {
                    if (proposal.getName() != null) {
                        IReference r = new JavaProposalReference(context, proposal, owner, create, "");
                        result.add(r);
                    } else {

                        char[] completion = proposal.getCompletion();
                        String sm = new String(completion);
                        String pName = sm;
                        if (proposal.getKind() == CompletionProposal.PACKAGE_REF) {
                            sm = sm.substring(id2.length());
                        } else {
                            if (sm.startsWith(id2) && sm.length() != id2.length())
                                sm = sm.substring(id2.length()).trim();

                        }
                        IReference r = new JavaProposalReference(context, sm, proposal, owner, create, pName);
                        result.add(r);
                    }
                }

            });
        } catch (JavaModelException e) {

        }
    }
    return result;
}

From source file:org.eclipse.rap.ui.internal.launch.rwt.shortcut.EntryPointSearchEngine.java

License:Open Source License

private void search(IProgressMonitor monitor) throws CoreException {
    monitor.beginTask("Searching for entry points...", 100);
    try {/*  w  w  w . j  a  v  a2  s  . co m*/
        int matchRule = SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE;
        SearchParticipant[] participants = getSearchParticipants();
        IProgressMonitor searchMonitor = new SubProgressMonitor(monitor, 100);
        SearchEngine searchEngine = new SearchEngine();
        SearchPattern pattern1 = SearchPattern.createPattern("createUI() int", //$NON-NLS-1$
                IJavaSearchConstants.METHOD, IJavaSearchConstants.DECLARATIONS, matchRule);
        SearchPattern pattern2 = SearchPattern.createPattern("createContents( Composite ) void", //$NON-NLS-1$
                IJavaSearchConstants.METHOD, IJavaSearchConstants.DECLARATIONS, matchRule);
        SearchPattern pattern = SearchPattern.createOrPattern(pattern1, pattern2);
        searchEngine.search(pattern, participants, searchScope, entryPointCollector, searchMonitor);
    } finally {
        monitor.done();
    }
}