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

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

Introduction

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

Prototype

int IMPLEMENTORS

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

Click Source Link

Document

The search result is a type that implements an interface or extends a class.

Usage

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
 * //w  w w. j  av  a  2  s.  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.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//from   w w w .j  a v a 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.auidt.internal.editors.layout.gle2.CustomViewFinder.java

License:Open Source License

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

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

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

            Object element = match.getElement();
            if (element instanceof ResolvedBinaryType) {
                // Third party view
                ResolvedBinaryType type = (ResolvedBinaryType) element;
                IPackageFragment fragment = type.getPackageFragment();
                IPath path = fragment.getPath();
                String last = path.lastSegment();
                // Filter out android.jar stuff
                /*  if (last.equals(FN_FRAMEWORK_LIBRARY)) {
                return;
                  }*/
                if (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.google.gwt.eclipse.core.search.JavaQueryParticipantTest.java

License:Open Source License

public void testLimitTo() throws CoreException {
    IJavaElement element = getTestType1().getField("keith");
    QuerySpecification query;//from w w w  . j  ava2  s .c  o  m

    // Limit to: references
    query = new ElementQuerySpecification(element, IJavaSearchConstants.REFERENCES, WORKSPACE_SCOPE, "");
    assertSearchMatch(createWindowsTestMatch(990, 5), query);

    // Limit to: all occurrences (declaration and all references, although in
    // this case we're only using our search engine so we'll only have refs)
    query = new ElementQuerySpecification(element, IJavaSearchConstants.ALL_OCCURRENCES, WORKSPACE_SCOPE, "");
    assertSearchMatch(createWindowsTestMatch(990, 5), query);

    // Limit to: read accesses (we don't differentiate between read/write
    // accesses, so this returns all references)
    query = new ElementQuerySpecification(element, IJavaSearchConstants.READ_ACCESSES, WORKSPACE_SCOPE, "");
    assertSearchMatch(createWindowsTestMatch(990, 5), query);

    // Limit to: write accesses (we don't differentiate between read/write
    // accesses, so this returns all references)
    query = new ElementQuerySpecification(element, IJavaSearchConstants.WRITE_ACCESSES, WORKSPACE_SCOPE, "");
    assertSearchMatch(createWindowsTestMatch(990, 5), query);

    // Limit to: declarations (unsupported)
    query = new ElementQuerySpecification(element, IJavaSearchConstants.DECLARATIONS, WORKSPACE_SCOPE, "");
    assertSearchMatches(NO_MATCHES, query);

    // Limit to: implementors (unsupported)
    query = new ElementQuerySpecification(element, IJavaSearchConstants.IMPLEMENTORS, WORKSPACE_SCOPE, "");
    assertSearchMatches(NO_MATCHES, query);
}

From source file:com.windowtester.swt.codegen.dialogs.SearchScopeHelper.java

License:Open Source License

public IType[] inProject(IJavaProject project) throws CoreException {

    int includeMask = IJavaSearchScope.SOURCES | IJavaSearchScope.APPLICATION_LIBRARIES |
    // IJavaSearchScope.SYSTEM_LIBRARIES |
            IJavaSearchScope.REFERENCED_PROJECTS;

    IJavaSearchScope searchScope = SearchEngine.createJavaSearchScope(new IJavaElement[] { project },
            includeMask);/*from  w  w  w . j  a  v a  2  s  .co m*/

    // // DEBUG: what does our scope encompass?
    // for (IPath path : searchScope.enclosingProjectsAndJars())
    // System.out.println("will search " + path);
    // jar containing classes we want to match is seen,
    // but results within that jar are not being returned.

    SearchEngine se = new SearchEngine();
    SearchPattern pattern = SearchPattern.createPattern(type.getFullyQualifiedName(),
            IJavaSearchConstants.CLASS, IJavaSearchConstants.IMPLEMENTORS,
            SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE);

    SearchRequestor requestor = new SearchRequestor() {

        public void acceptSearchMatch(SearchMatch match) throws CoreException {
            //            System.err.println("found match "
            //                  + match.getElement().getClass() + ":"
            //                  + match.getElement());

            results.add((IType) match.getElement());
        }
    };

    //      long start = System.currentTimeMillis();
    se.search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, searchScope,
            requestor, monitor);

    //add "self" type
    results.add(type);

    //      System.err.println("done in " + (System.currentTimeMillis() - start)
    //            + " ms");
    //      for (Iterator iterator = results.iterator(); iterator.hasNext();) {
    //         IType type = (IType) iterator.next();
    //         System.out.println(type);
    //      }

    return (IType[]) results.toArray(new IType[] {});
}

From source file:de.instantouch.model.search.SnakeTypeSearch.java

License:Open Source License

public ISnakeList<SnakeClassInfo<T>> findSnakeTypes(Class<T> snakeClass)
        throws JavaModelException, SnakeModelException {

    final ISnakeList<SnakeClassInfo<T>> allTypes = new SnakeList<SnakeClassInfo<T>>();

    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    if (workspace == null) {
        throw new SnakeNotInitializedException("no workspace available");
    }// w  w w  .j  a  v a 2  s  .  c om

    JavaModelManager modelManager = JavaModelManager.getJavaModelManager();

    JavaWorkspaceScope workspaceScope = modelManager.getWorkspaceScope();

    SearchPattern snakePattern = SearchPattern.createPattern(snakeClass.getCanonicalName(),
            IJavaSearchConstants.CLASS, IJavaSearchConstants.IMPLEMENTORS, SearchPattern.R_EXACT_MATCH);

    SearchEngine searchEngine = new SearchEngine();

    SearchRequestor requestor = new SearchRequestor() {

        @Override
        public void acceptSearchMatch(SearchMatch match) throws CoreException {
            ;
            Object element = match.getElement();
            if (element instanceof BinaryType) {
                SnakeClassInfo<T> info = new SnakeClassInfo<T>();
                try {
                    info.createFrom((BinaryType) element);
                } catch (SnakeWrongTypeException e) {
                    SnakeLog.log(e);
                }
                allTypes.add(info);
            }

        }
    };

    SearchParticipant participants[] = { new JavaSearchParticipant() };

    try {
        searchEngine.search(snakePattern, participants, workspaceScope, requestor, null);
    } catch (CoreException e) {
        throw new SnakeModelException(e.getMessage());
    }

    return allTypes;

}

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

License:Open Source License

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

void handleFindAll(String proj, String file, int start, int end, boolean defs, boolean refs, boolean impls,
        boolean equiv, boolean exact, boolean system, boolean typeof, boolean ronly, boolean wonly,
        IvyXmlWriter xw) throws BedrockException {
    IJavaProject ijp = getJavaProject(proj);
    IPath fp = new Path(file);

    int limit = 0;
    if (defs && refs)
        limit = IJavaSearchConstants.ALL_OCCURRENCES;
    else if (defs)
        limit = IJavaSearchConstants.DECLARATIONS;
    else if (refs)
        limit = IJavaSearchConstants.REFERENCES;
    int flimit = limit;
    if (ronly)//w  w w .j a  v a 2 s .  c  o m
        flimit = IJavaSearchConstants.READ_ACCESSES;
    else if (wonly)
        flimit = IJavaSearchConstants.WRITE_ACCESSES;

    int mrule = -1;
    if (equiv)
        mrule = SearchPattern.R_EQUIVALENT_MATCH;
    else if (exact)
        mrule = SearchPattern.R_EXACT_MATCH;

    SearchPattern pat = null;
    IJavaSearchScope scp = null;

    ICompilationUnit icu = our_plugin.getProjectManager().getCompilationUnit(proj, file);
    if (icu == null)
        throw new BedrockException("Compilation unit not found for " + fp);
    icu = getCompilationElement(icu);

    ICompilationUnit[] working = null;
    FindFilter filter = null;

    IJavaElement cls = null;
    char[] packagename = null;
    char[] typename = null;

    try {
        BedrockPlugin.logD("Getting search scopes");
        IJavaElement[] pelt;
        if (ijp != null)
            pelt = new IJavaElement[] { ijp };
        else
            pelt = getAllProjects();
        working = getWorkingElements(pelt);
        int fg = IJavaSearchScope.SOURCES | IJavaSearchScope.REFERENCED_PROJECTS;
        if (system)
            fg |= IJavaSearchScope.SYSTEM_LIBRARIES | IJavaSearchScope.APPLICATION_LIBRARIES;
        scp = SearchEngine.createJavaSearchScope(pelt, fg);

        BedrockPlugin.logD("Locating item to search for");
        IJavaElement[] elts = icu.codeSelect(start, end - start);

        if (typeof) {
            Set<IJavaElement> nelt = new LinkedHashSet<IJavaElement>();
            for (int i = 0; i < elts.length; ++i) {
                IType typ = null;
                String tnm = null;
                switch (elts[i].getElementType()) {
                case IJavaElement.FIELD:
                    tnm = ((IField) elts[i]).getTypeSignature();
                    break;
                case IJavaElement.LOCAL_VARIABLE:
                    tnm = ((ILocalVariable) elts[i]).getTypeSignature();
                    break;
                case IJavaElement.METHOD:
                    typ = ((IMethod) elts[i]).getDeclaringType();
                    break;
                default:
                    nelt.add(elts[i]);
                    break;
                }
                if (typ != null)
                    nelt.add(typ);
                else if (tnm != null && ijp != null) {
                    IJavaElement elt = ijp.findElement(tnm, null);
                    if (elt != null) {
                        nelt.add(elt);
                        typ = null;
                    } else {
                        while (tnm.startsWith("[")) {
                            String xtnm = tnm.substring(1);
                            if (xtnm == null)
                                break;
                            tnm = xtnm;
                        }
                        int ln = tnm.length();
                        String xtnm = tnm;
                        if (tnm.startsWith("L") && tnm.endsWith(";")) {
                            xtnm = tnm.substring(1, ln - 1);
                        } else if (tnm.startsWith("Q") && tnm.endsWith(";")) {
                            xtnm = tnm.substring(1, ln - 1);
                        }
                        if (xtnm != null)
                            tnm = xtnm;
                        int idx1 = tnm.lastIndexOf(".");
                        if (idx1 > 0) {
                            String pkgnm = tnm.substring(0, idx1);
                            xtnm = tnm.substring(idx1 + 1);
                            if (xtnm != null)
                                tnm = xtnm;
                            pkgnm = pkgnm.replace('$', '.');
                            packagename = pkgnm.toCharArray();
                        }
                        tnm = tnm.replace('$', '.');
                        typename = tnm.toCharArray();
                    }

                    if (typename != null) {
                        BedrockPlugin.logD("Handling type names");
                        FindTypeHandler fth = new FindTypeHandler(ijp);
                        SearchEngine se = new SearchEngine(working);
                        se.searchAllTypeNames(packagename, SearchPattern.R_EXACT_MATCH, typename,
                                SearchPattern.R_EXACT_MATCH, IJavaSearchConstants.TYPE, scp, fth,
                                IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null);
                        nelt.addAll(fth.getFoundItems());
                    }
                }
            }
            IJavaElement[] nelts = new IJavaElement[nelt.size()];
            elts = nelt.toArray(nelts);
        }

        if (elts.length == 1 && !typeof) {
            xw.begin("SEARCHFOR");
            switch (elts[0].getElementType()) {
            case IJavaElement.FIELD:
                xw.field("TYPE", "Field");
                break;
            case IJavaElement.LOCAL_VARIABLE:
                xw.field("TYPE", "Local");
                break;
            case IJavaElement.METHOD:
                xw.field("TYPE", "Function");
                break;
            case IJavaElement.TYPE:
            case IJavaElement.TYPE_PARAMETER:
                xw.field("TYPE", "Class");
                cls = elts[0];
                break;
            }
            xw.text(elts[0].getElementName());
            xw.end("SEARCHFOR");
        }
        int etyp = -1;
        for (int i = 0; i < elts.length; ++i) {
            SearchPattern sp;
            int xlimit = limit;
            switch (elts[i].getElementType()) {
            case IJavaElement.FIELD:
            case IJavaElement.LOCAL_VARIABLE:
                xlimit = flimit;
                break;
            case IJavaElement.TYPE:
                if (impls)
                    xlimit = IJavaSearchConstants.IMPLEMENTORS;
                break;
            case IJavaElement.METHOD:
                if (impls)
                    xlimit |= IJavaSearchConstants.IGNORE_DECLARING_TYPE;
                break;
            }
            if (mrule < 0)
                sp = SearchPattern.createPattern(elts[i], xlimit);
            else
                sp = SearchPattern.createPattern(elts[i], xlimit, mrule);
            if (pat == null)
                pat = sp;
            else
                pat = SearchPattern.createOrPattern(pat, sp);
            if (etyp < 0)
                etyp = elts[i].getElementType();
        }

        if (etyp == IJavaElement.METHOD) {
            if (impls) {
                if (defs)
                    filter = new ImplementFilter(elts);
            } else if (defs && !refs)
                filter = new ClassFilter(elts);
        }

    } catch (JavaModelException e) {
        BedrockPlugin.logE("SEARCH PROBLEM: " + e);
        e.printStackTrace();
        throw new BedrockException("Can't find anything to search for", e);
    }

    if (pat == null) {
        BedrockPlugin.logW("Nothing to search for");
        return;
    }

    BedrockPlugin.logD("Setting up search");
    SearchEngine se = new SearchEngine(working);
    SearchParticipant[] parts = new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() };
    FindHandler fh = new FindHandler(xw, filter, false);

    BedrockPlugin.logD(
            "BEGIN SEARCH " + pat + " " + parts.length + " " + " " + scp + " :: COPIES: " + working.length);

    try {
        se.search(pat, parts, scp, fh, null);
    } catch (Throwable e) {
        throw new BedrockException("Problem doing find all search for " + pat + ": " + e, e);
    }

    if (cls != null && defs) { // need to add the actual class definition
        BedrockUtil.outputJavaElement(cls, false, xw);
    }
}

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

License:Open Source License

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

void handleJavaSearch(String proj, String bid, String patstr, String foritems, boolean defs, boolean refs,
        boolean impls, boolean equiv, boolean exact, boolean system, IvyXmlWriter xw) throws BedrockException {
    IJavaProject ijp = getJavaProject(proj);

    our_plugin.waitForEdits();//  www.java 2  s. c  o  m

    int forflags = 0;
    if (foritems == null)
        forflags = IJavaSearchConstants.TYPE;
    else if (foritems.equalsIgnoreCase("CLASS"))
        forflags = IJavaSearchConstants.CLASS;
    else if (foritems.equalsIgnoreCase("INTERFACE"))
        forflags = IJavaSearchConstants.INTERFACE;
    else if (foritems.equalsIgnoreCase("ENUM"))
        forflags = IJavaSearchConstants.ENUM;
    else if (foritems.equalsIgnoreCase("ANNOTATION"))
        forflags = IJavaSearchConstants.ANNOTATION_TYPE;
    else if (foritems.equalsIgnoreCase("CLASS&ENUM"))
        forflags = IJavaSearchConstants.CLASS_AND_ENUM;
    else if (foritems.equalsIgnoreCase("CLASS&INTERFACE"))
        forflags = IJavaSearchConstants.CLASS_AND_INTERFACE;
    else if (foritems.equalsIgnoreCase("TYPE"))
        forflags = IJavaSearchConstants.TYPE;
    else if (foritems.equalsIgnoreCase("FIELD"))
        forflags = IJavaSearchConstants.FIELD;
    else if (foritems.equalsIgnoreCase("METHOD"))
        forflags = IJavaSearchConstants.METHOD;
    else if (foritems.equalsIgnoreCase("CONSTRUCTOR"))
        forflags = IJavaSearchConstants.CONSTRUCTOR;
    else if (foritems.equalsIgnoreCase("PACKAGE"))
        forflags = IJavaSearchConstants.PACKAGE;
    else if (foritems.equalsIgnoreCase("FIELDWRITE"))
        forflags = IJavaSearchConstants.FIELD | IJavaSearchConstants.WRITE_ACCESSES;
    else if (foritems.equalsIgnoreCase("FIELDREAD"))
        forflags = IJavaSearchConstants.FIELD | IJavaSearchConstants.READ_ACCESSES;
    else
        forflags = IJavaSearchConstants.TYPE;

    int limit = 0;
    if (defs && refs)
        limit = IJavaSearchConstants.ALL_OCCURRENCES;
    else if (defs)
        limit = IJavaSearchConstants.DECLARATIONS;
    else if (refs)
        limit = IJavaSearchConstants.REFERENCES;
    else if (impls)
        limit = IJavaSearchConstants.IMPLEMENTORS;

    int mrule = SearchPattern.R_PATTERN_MATCH;
    if (equiv)
        mrule = SearchPattern.R_EQUIVALENT_MATCH;
    else if (exact)
        mrule = SearchPattern.R_EXACT_MATCH;

    SearchPattern pat = SearchPattern.createPattern(patstr, forflags, limit, mrule);
    if (pat == null) {
        throw new BedrockException(
                "Invalid java search pattern `" + patstr + "' " + forflags + " " + limit + " " + mrule);
    }

    FindFilter filter = null;
    if (forflags == IJavaSearchConstants.METHOD) {
        String p = patstr;
        int idx = p.indexOf("(");
        if (idx > 0)
            p = p.substring(0, idx);
        idx = p.lastIndexOf(".");
        if (idx > 0) {
            if (defs)
                filter = new ClassFilter(p.substring(0, idx));
        }
    }

    // TODO: create scope for only user's items
    IJavaElement[] pelt;
    if (ijp != null)
        pelt = new IJavaElement[] { ijp };
    else
        pelt = getAllProjects();

    ICompilationUnit[] working = getWorkingElements(pelt);
    for (ICompilationUnit xcu : working) {
        try {
            BedrockPlugin.logD("WORK WITH " + xcu.isWorkingCopy() + " " + xcu.getPath() + xcu.getSourceRange());
        } catch (JavaModelException e) {
            BedrockPlugin.logD("WORK WITH ERROR: " + e);
        }
    }

    IJavaSearchScope scp = null;
    int fg = IJavaSearchScope.SOURCES | IJavaSearchScope.REFERENCED_PROJECTS;
    if (system) {
        fg |= IJavaSearchScope.SYSTEM_LIBRARIES | IJavaSearchScope.APPLICATION_LIBRARIES;
        scp = SearchEngine.createWorkspaceScope();
    } else {
        scp = SearchEngine.createJavaSearchScope(pelt, fg);
    }

    SearchEngine se = new SearchEngine(working);
    SearchParticipant[] parts = new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() };
    FindHandler fh = new FindHandler(xw, filter, system);

    BedrockPlugin.logD("BEGIN SEARCH " + pat);
    BedrockPlugin.logD("SEARCH SCOPE " + system + " " + fg + " " + scp);

    try {
        se.search(pat, parts, scp, fh, null);
    } catch (Throwable e) {
        throw new BedrockException("Problem doing Java search: " + e, e);
    }
}

From source file:net.harawata.mybatipse.mybatis.TypeAliasCache.java

License:Open Source License

/**
 * <p>//from w  w w  .  ja v  a2  s .c  o  m
 * Trying to find calls registering type aliases.<br>
 * But only simple calls can be supported.
 * </p>
 */
private void scanJavaConfig(IJavaProject project, final TypeAliasMap aliasMap, final Set<String> packages,
        IReporter reporter) {
    try {
        IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaProject[] { project },
                IJavaSearchScope.SOURCES | IJavaSearchScope.REFERENCED_PROJECTS
                        | IJavaSearchScope.APPLICATION_LIBRARIES);
        SearchParticipant[] participants = new SearchParticipant[] {
                SearchEngine.getDefaultSearchParticipant() };
        SearchEngine searchEngine = new SearchEngine();

        final Set<ITypeRoot> typeRoots = new HashSet<ITypeRoot>();

        // Collect classes that contain mybatis-guice calls.
        IType mybatisModuleType = project.findType(GUICE_MODULE_FQN);
        if (mybatisModuleType == null || !mybatisModuleType.exists())
            return;

        IMethod addSimpleAliasMethod = mybatisModuleType.getMethod("addSimpleAlias",
                new String[] { "Ljava.lang.Class;" });
        SearchPattern pattern = SearchPattern.createPattern(addSimpleAliasMethod,
                IJavaSearchConstants.REFERENCES | IJavaSearchConstants.IGNORE_DECLARING_TYPE
                        | IJavaSearchConstants.IMPLEMENTORS);
        searchEngine.search(pattern, participants, scope, new MethodSearchRequestor(typeRoots), null);

        IMethod addSimpleAliasesMethodWithPackage = mybatisModuleType.getMethod("addSimpleAliases",
                new String[] { "Ljava.lang.String;" });
        pattern = SearchPattern.createPattern(addSimpleAliasesMethodWithPackage,
                IJavaSearchConstants.REFERENCES | IJavaSearchConstants.IGNORE_DECLARING_TYPE);
        searchEngine.search(pattern, participants, scope, new MethodSearchRequestor(typeRoots), null);

        // IMethod addSimpleAliasesMethodWithPackageAndTest = mybatisModuleType.getMethod(
        // "addSimpleAliases", new String[]{
        // "Ljava.util.Collection<Ljava.lang.Class<*>;>;"
        // });
        // pattern = SearchPattern.createPattern(addSimpleAliasesMethodWithPackageAndTest,
        // IJavaSearchConstants.REFERENCES | IJavaSearchConstants.IGNORE_DECLARING_TYPE);
        // searchEngine.search(pattern, participants, scope, new MethodSearchRequestor(typeRoots),
        // null);

        // Searches Spring java config if necessary.
        // if (typeRoots.isEmpty())
        // {
        // IType sqlSessionFactoryBeanType = project.findType(SPRING_BEAN_FQN);
        // if (sqlSessionFactoryBeanType == null || !sqlSessionFactoryBeanType.exists())
        // return;
        //
        // IMethod setTypeAliasesPackageMethod = sqlSessionFactoryBeanType.getMethod(
        // "setTypeAliasesPackage", new String[]{
        // "Ljava.lang.String;"
        // });
        // pattern = SearchPattern.createPattern(setTypeAliasesPackageMethod,
        // IJavaSearchConstants.REFERENCES | IJavaSearchConstants.IGNORE_DECLARING_TYPE
        // | IJavaSearchConstants.IMPLEMENTORS);
        // searchEngine.search(pattern, participants, scope, new MethodSearchRequestor(typeRoots),
        // null);
        // }

        for (ITypeRoot typeRoot : typeRoots) {
            ASTParser parser = ASTParser.newParser(AST.JLS4);
            parser.setSource(typeRoot);
            parser.setResolveBindings(true);
            CompilationUnit astUnit = (CompilationUnit) parser.createAST(null);
            astUnit.accept(new JavaConfigVisitor(aliasMap, packages));
        }
    } catch (JavaModelException e) {
        Activator.log(Status.ERROR, e.getMessage(), e);
    } catch (CoreException e) {
        Activator.log(Status.ERROR, e.getMessage(), e);
    }
}

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

License:Open Source License

/**
 * Executes the search./* w  w  w .j  a  v  a 2 s  .  c  o 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;
}