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

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

Introduction

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

Prototype

int ALL_OCCURRENCES

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

Click Source Link

Document

The search result is a declaration, a reference, or an implementer of an interface.

Usage

From source file:ca.ecliptical.pde.ds.search.DescriptorQueryParticipant.java

License:Open Source License

public void search(ISearchRequestor requestor, QuerySpecification query, IProgressMonitor monitor)
        throws CoreException {
    if (debug.isDebugging())
        debug.trace(String.format("Query: %s", query)); //$NON-NLS-1$

    // we only look for straight references
    switch (query.getLimitTo()) {
    case IJavaSearchConstants.REFERENCES:
    case IJavaSearchConstants.ALL_OCCURRENCES:
        break;/*w w w .ja va 2 s  .co  m*/
    default:
        return;
    }

    // we only look for types and methods
    if (query instanceof ElementQuerySpecification) {
        searchElement = ((ElementQuerySpecification) query).getElement();
        switch (searchElement.getElementType()) {
        case IJavaElement.TYPE:
        case IJavaElement.METHOD:
            break;
        default:
            return;
        }
    } else {
        String pattern = ((PatternQuerySpecification) query).getPattern();
        boolean ignoreMethodParams = false;
        searchFor = ((PatternQuerySpecification) query).getSearchFor();
        switch (searchFor) {
        case IJavaSearchConstants.UNKNOWN:
        case IJavaSearchConstants.METHOD:
            int leftParen = pattern.lastIndexOf('(');
            int rightParen = pattern.indexOf(')');
            ignoreMethodParams = leftParen == -1 || rightParen == -1 || leftParen >= rightParen;
            // no break
        case IJavaSearchConstants.TYPE:
        case IJavaSearchConstants.CLASS:
        case IJavaSearchConstants.CLASS_AND_INTERFACE:
        case IJavaSearchConstants.CLASS_AND_ENUM:
        case IJavaSearchConstants.INTERFACE:
        case IJavaSearchConstants.INTERFACE_AND_ANNOTATION:
            break;
        default:
            return;
        }

        // searchPattern = PatternConstructor.createPattern(pattern, ((PatternQuerySpecification) query).isCaseSensitive());
        int matchMode = getMatchMode(pattern) | SearchPattern.R_ERASURE_MATCH;
        if (((PatternQuerySpecification) query).isCaseSensitive())
            matchMode |= SearchPattern.R_CASE_SENSITIVE;

        searchPattern = new SearchPatternDescriptor(pattern, matchMode, ignoreMethodParams);
    }

    HashSet<IPath> scope = new HashSet<IPath>();
    for (IPath path : query.getScope().enclosingProjectsAndJars()) {
        scope.add(path);
    }

    if (scope.isEmpty())
        return;

    this.requestor = requestor;

    // look through all active bundles
    IPluginModelBase[] wsModels = PluginRegistry.getWorkspaceModels();
    IPluginModelBase[] exModels = PluginRegistry.getExternalModels();
    monitor.beginTask(Messages.DescriptorQueryParticipant_taskName, wsModels.length + exModels.length);
    try {
        // workspace models
        for (IPluginModelBase model : wsModels) {
            if (monitor.isCanceled())
                throw new OperationCanceledException();

            if (!model.isEnabled() || !(model instanceof IBundlePluginModelBase)) {
                monitor.worked(1);
                if (debug.isDebugging())
                    debug.trace(String.format("Non-bundle model: %s", model)); //$NON-NLS-1$

                continue;
            }

            IProject project = model.getUnderlyingResource().getProject();
            if (!scope.contains(project.getFullPath())) {
                monitor.worked(1);
                if (debug.isDebugging())
                    debug.trace(String.format("Project out of scope: %s", project.getName())); //$NON-NLS-1$

                continue;
            }

            // we can only search in Java bundle projects (for now)
            if (!project.hasNature(JavaCore.NATURE_ID)) {
                monitor.worked(1);
                if (debug.isDebugging())
                    debug.trace(String.format("Non-Java project: %s", project.getName())); //$NON-NLS-1$

                continue;
            }

            PDEModelUtility.modifyModel(new ModelModification(project) {
                @Override
                protected void modifyModel(IBaseModel model, IProgressMonitor monitor) throws CoreException {
                    if (model instanceof IBundlePluginModelBase)
                        searchBundle((IBundlePluginModelBase) model, monitor);
                }
            }, new SubProgressMonitor(monitor, 1));
        }

        // external models
        SearchablePluginsManager spm = PDECore.getDefault().getSearchablePluginsManager();
        IJavaProject javaProject = spm.getProxyProject();
        if (javaProject == null || !javaProject.exists() || !javaProject.isOpen()) {
            monitor.worked(exModels.length);
            if (debug.isDebugging())
                debug.trace("External Plug-in Search project inaccessible!"); //$NON-NLS-1$

            return;
        }

        for (IPluginModelBase model : exModels) {
            if (monitor.isCanceled())
                throw new OperationCanceledException();

            BundleDescription bd;
            if (!model.isEnabled() || (bd = model.getBundleDescription()) == null) {
                monitor.worked(1);
                if (debug.isDebugging())
                    debug.trace(String.format("Non-bundle model: %s", model)); //$NON-NLS-1$

                continue;
            }

            // check scope
            ArrayList<IClasspathEntry> cpEntries = new ArrayList<IClasspathEntry>();
            ClasspathUtilCore.addLibraries(model, cpEntries);
            ArrayList<IPath> cpEntryPaths = new ArrayList<IPath>(cpEntries.size());
            for (IClasspathEntry cpEntry : cpEntries) {
                cpEntryPaths.add(cpEntry.getPath());
            }

            cpEntryPaths.retainAll(scope);
            if (cpEntryPaths.isEmpty()) {
                monitor.worked(1);
                if (debug.isDebugging())
                    debug.trace(String.format("External bundle out of scope: %s", model.getInstallLocation())); //$NON-NLS-1$

                continue;
            }

            if (!spm.isInJavaSearch(bd.getSymbolicName())) {
                monitor.worked(1);
                if (debug.isDebugging())
                    debug.trace(String.format("Non-searchable external model: %s", bd.getSymbolicName())); //$NON-NLS-1$

                continue;
            }

            searchBundle(model, javaProject, new SubProgressMonitor(monitor, 1));
        }
    } finally {
        monitor.done();
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.VariablePattern.java

License:Open Source License

public VariablePattern(int patternKind, char[] name, int limitTo, int matchRule) {
    super(patternKind, matchRule);

    this.fineGrain = limitTo & FINE_GRAIN_MASK;
    if (this.fineGrain == 0) {
        switch (limitTo & 0xF) {
        case IJavaSearchConstants.DECLARATIONS:
            this.findDeclarations = true;
            break;
        case IJavaSearchConstants.REFERENCES:
            this.readAccess = true;
            this.writeAccess = true;
            break;
        case IJavaSearchConstants.READ_ACCESSES:
            this.readAccess = true;
            break;
        case IJavaSearchConstants.WRITE_ACCESSES:
            this.writeAccess = true;
            break;
        case IJavaSearchConstants.ALL_OCCURRENCES:
            this.findDeclarations = true;
            this.readAccess = true;
            this.writeAccess = true;
            break;
        }/*from   w ww .ja va 2s  .c  o  m*/
        this.findReferences = this.readAccess || this.writeAccess;
    }

    this.name = (this.isCaseSensitive || this.isCamelCase) ? name : CharOperation.toLowerCase(name);
}

From source file:com.google.gwt.eclipse.core.search.JavaQueryParticipant.java

License:Open Source License

public void search(ISearchRequestor requestor, QuerySpecification query, IProgressMonitor monitor)
        throws CoreException {
    try {/* w  ww . j  a  va  2s .co  m*/
        monitor.subTask("Locating GWT matches...");

        // Make sure we're searching for Java references
        switch (query.getLimitTo()) {
        case IJavaSearchConstants.REFERENCES:
        case IJavaSearchConstants.ALL_OCCURRENCES:
            // These we handle as expected
            break;
        case IJavaSearchConstants.READ_ACCESSES:
        case IJavaSearchConstants.WRITE_ACCESSES:
            // We don't actually check field references to see if they're read or
            // write accesses; we just treat this as a generic references search
            break;
        default:
            // Anything else (e.g., Declarations), we don't support
            return;
        }

        Set<IIndexedJavaRef> matchingJavaRefs = null;

        // Find all matching Java references in the index. The search algorithm
        // differs depending on whether we're doing an element query
        // (Ctrl-Shift-G) or a pattern query (Java Search dialog box)
        if (query instanceof ElementQuerySpecification) {
            ElementQuerySpecification elementQuery = (ElementQuerySpecification) query;
            matchingJavaRefs = findMatches(elementQuery, true);
        } else {
            assert (query instanceof PatternQuerySpecification);
            PatternQuerySpecification patternQuery = (PatternQuerySpecification) query;
            matchingJavaRefs = findMatches(patternQuery);
        }

        for (IIndexedJavaRef javaRef : matchingJavaRefs) {
            Match match = createMatch(javaRef, query);
            if (match != null) {
                // Report the match location to the Java Search engine
                requestor.reportMatch(match);
            }
        }
    } catch (Exception e) {
        // If we allow any exceptions to escape, the JDT will disable us
        GWTPluginLog.logError("Error finding Java Search matches", e);
    }
}

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  ww .  j  a  v  a  2s . com*/

    // 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: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)//from www.j  a  v  a 2  s  .  co  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();//from   w  w  w .ja  v a  2 s . com

    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:edu.brown.cs.bubbles.bedrock.BedrockRenamer.java

License:Open Source License

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

void rename(String proj, String bid, String file, int start, int end, String name, String handle,
        String newname, boolean keeporig, boolean getters, boolean setters, boolean dohier, boolean qual,
        boolean refs, boolean dosimilar, boolean textocc, boolean doedit, String filespat, IvyXmlWriter xw)
        throws BedrockException {
    ICompilationUnit icu = our_plugin.getCompilationUnit(proj, file);

    IJavaElement[] elts;// w w  w. j ava 2s  .c o m
    try {
        elts = icu.codeSelect(start, end - start);
    } catch (JavaModelException e) {
        throw new BedrockException("Bad location: " + e, e);
    }

    IJavaElement relt = null;
    for (IJavaElement ije : elts) {
        if (handle != null && !handle.equals(ije.getHandleIdentifier()))
            continue;
        if (name != null && !name.equals(ije.getElementName()))
            continue;
        relt = ije;
        break;
    }
    if (relt == null)
        throw new BedrockException("Item to rename not found");

    BedrockPlugin.logD("RENAME CHECK " + relt.getElementType() + " " + relt.getParent().getElementType());

    switch (relt.getElementType()) {
    case IJavaElement.COMPILATION_UNIT:
        throw new BedrockException("Compilation unit renaming not supported yet");
    case IJavaElement.PACKAGE_FRAGMENT_ROOT:
    case IJavaElement.PACKAGE_FRAGMENT:
        throw new BedrockException("Package renaming not supported yet");
    case IJavaElement.FIELD:
    case IJavaElement.LOCAL_VARIABLE:
    case IJavaElement.TYPE_PARAMETER:
        break;
    case IJavaElement.METHOD:
        IMethod mthd = (IMethod) relt;
        try {
            if (mthd.isConstructor())
                throw new BedrockException("Constructor renaming not supported yet");
        } catch (JavaModelException e) {
        }
        break;
    case IJavaElement.TYPE:
        IJavaElement pelt = relt.getParent();
        if (pelt.getElementType() == IJavaElement.COMPILATION_UNIT) {
            ITypeRoot xcu = (ITypeRoot) pelt;
            if (relt == xcu.findPrimaryType()) {
                throw new BedrockException("Compilation unit renaming based on type not supported yet");
            }
        }
        break;
    default:
        throw new BedrockException("Invalid element type to rename");
    }

    SearchPattern sp = SearchPattern.createPattern(relt, IJavaSearchConstants.ALL_OCCURRENCES,
            SearchPattern.R_EXACT_MATCH);

    List<ICompilationUnit> worku = new ArrayList<ICompilationUnit>();
    for (IJavaElement je : BedrockJava.getAllProjects()) {
        our_plugin.getWorkingElements(je, worku);
    }
    ICompilationUnit[] work = new ICompilationUnit[worku.size()];
    work = worku.toArray(work);

    int fg = IJavaSearchScope.SOURCES | IJavaSearchScope.REFERENCED_PROJECTS;
    IJavaSearchScope scp = SearchEngine.createJavaSearchScope(work, fg);

    SearchEngine se = new SearchEngine(work);
    SearchParticipant[] parts = new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() };
    FindHandler fh = new FindHandler(xw, null);

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

    BedrockPlugin.logD("RENAME RESULT = " + xw.toString());
}

From source file:info.cukes.editor.annotation.ScenarioAnnotationSearch.java

License:Open Source License

/**
 * Parse the current row, looking for a keyword ("Given", "And", etc.). If found, search all java code for that
 * annotation and return all potential matches.
 *//*from  w  ww.  j  a v  a2 s .c o m*/
public List<IAnnotation> search(ITextViewer viewer, int line) {
    IDocument doc = viewer.getDocument();
    try {
        IRegion lineRegion = doc.getLineInformation(line);

        final int offs = lineRegion.getOffset();
        final int len = lineRegion.getLength();

        String currentLine = viewer.getDocument().get(offs, len);

        String potentialAnnotationName = annotationInString(currentLine);

        if (potentialAnnotationName == null) {
            return Collections.emptyList();
        }

        /*
         * Found that the row begins with a supported annotation. Try to find a match in code.
         */
        if (supportedAnnotations.containsKey(potentialAnnotationName)) {
            SearchPattern pattern = SearchPattern.createPattern(potentialAnnotationName,
                    IJavaSearchConstants.ANNOTATION_TYPE, IJavaSearchConstants.ALL_OCCURRENCES,
                    SearchPattern.R_EXACT_MATCH);

            /*
             * Keep cached list of matches, unless a resource change has occurred.
             */
            if (matches.get(potentialAnnotationName) != null) {
                return matches.get(potentialAnnotationName);
            }

            try {
                final List<IAnnotation> matchesForAnnotation = new ArrayList<IAnnotation>();
                SearchRequestor requestor = new SearchRequestor() {
                    @Override
                    public void acceptSearchMatch(SearchMatch match) throws CoreException {
                        if (match.getElement() instanceof IMethod) {
                            IAnnotation[] annotations = ((IMethod) match.getElement()).getAnnotations();
                            for (IAnnotation annotation : annotations) {
                                if (supportedAnnotations.containsKey(annotation.getElementName())) {
                                    matchesForAnnotation.add(annotation);
                                }
                            }
                        }
                    }
                };

                if (scopeHasChanged) {
                    updateSearchScope();
                }

                SearchEngine engine = new SearchEngine();

                Activator.getLogservice().log(LogService.LOG_ERROR, "Searching for " + potentialAnnotationName);
                engine.search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() },
                        scope, requestor, null);
                matches.put(potentialAnnotationName, matchesForAnnotation);

                return matchesForAnnotation;

            } catch (CoreException e) {
                Activator.getLogservice().log(LogService.LOG_ERROR, e.getMessage());
            }
        }

    } catch (BadLocationException e) {

    }
    return Collections.emptyList();
}

From source file:org.codehaus.groovy.eclipse.core.search.SyntheticAccessorSearchRequestor.java

License:Apache License

private SearchPattern createPattern(IJavaElement element) throws JavaModelException {
    List<IJavaElement> toSearch = new ArrayList<IJavaElement>(4);
    toSearch.add(findSyntheticMember(element, "is"));
    toSearch.add(findSyntheticMember(element, "get"));
    toSearch.add(findSyntheticMember(element, "set"));
    toSearch.add(findSyntheticProperty(element));
    SearchPattern pattern = null;/*from  www.j  a  va2 s  .  c  om*/
    for (IJavaElement searchElt : toSearch) {
        if (searchElt != null) {
            SearchPattern newPattern = SearchPattern.createPattern(searchElt,
                    IJavaSearchConstants.ALL_OCCURRENCES | IJavaSearchConstants.IGNORE_RETURN_TYPE);
            if (pattern == null) {
                pattern = newPattern;
            } else {
                pattern = SearchPattern.createOrPattern(pattern, newPattern);
            }
        }
    }
    return pattern;
}

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

License:Open Source License

/**
 * Translates the string context to the int equivalent.
 *
 * @param context The String context.//from   ww  w. jav  a2  s .  c om
 * @return The int context
 */
protected int getContext(String context) {
    if (CONTEXT_ALL.equals(context)) {
        return IJavaSearchConstants.ALL_OCCURRENCES;
    } else if (CONTEXT_IMPLEMENTORS.equals(context)) {
        return IJavaSearchConstants.IMPLEMENTORS;
    } else if (CONTEXT_REFERENCES.equals(context)) {
        return IJavaSearchConstants.REFERENCES;
    }
    return IJavaSearchConstants.DECLARATIONS;
}