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

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

Introduction

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

Prototype

public static SearchPattern createPattern(IJavaElement element, int limitTo) 

Source Link

Document

Returns a search pattern based on a given Java element.

Usage

From source file:com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo.java

License:Open Source License

/**
 * Returns the activities associated with the given layout file. Makes an educated guess
 * by peeking at the usages of the R.layout.name field corresponding to the layout and
 * if it finds a usage.//from  w w w  . ja va2 s  .c  om
 *
 * @param project the project containing the layout
 * @param layoutName the layout whose activity we want to look up
 * @param pkg the package containing activities
 * @return the activity name
 */
@NonNull
public static List<String> guessActivities(IProject project, String layoutName, String pkg) {
    final LinkedList<String> activities = new LinkedList<String>();
    SearchRequestor requestor = new SearchRequestor() {
        @Override
        public void acceptSearchMatch(SearchMatch match) throws CoreException {
            Object element = match.getElement();
            if (element instanceof IMethod) {
                IMethod method = (IMethod) element;
                IType declaringType = method.getDeclaringType();
                String fqcn = declaringType.getFullyQualifiedName();

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

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

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

    return activities;
}

From source file:com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo.java

License:Open Source License

/**
 * Returns the activity associated with the given layout file.
 * <p>//from  ww w.j a v  a 2s  .c o m
 * This is an alternative to {@link #guessActivity(IFile, String)}. Whereas
 * guessActivity simply looks for references to "R.layout.foo", this method searches
 * for all usages of Activity#setContentView(int), and for each match it looks up the
 * corresponding call text (such as "setContentView(R.layout.foo)"). From this it uses
 * a regexp to pull out "foo" from this, and stores the association that layout "foo"
 * is associated with the activity class that contained the setContentView call.
 * <p>
 * This has two potential advantages:
 * <ol>
 * <li>It can be faster. We do the reference search -once-, and we've built a map of
 * all the layout-to-activity mappings which we can then immediately look up other
 * layouts for, which is particularly useful at startup when we have to compute the
 * layout activity associations to populate the theme choosers.
 * <li>It can be more accurate. Just because an activity references an "R.layout.foo"
 * field doesn't mean it's setting it as a content view.
 * </ol>
 * However, this second advantage is also its chief problem. There are some common
 * code constructs which means that the associated layout is not explicitly referenced
 * in a direct setContentView call; on a couple of sample projects I tested I found
 * patterns like for example "setContentView(v)" where "v" had been computed earlier.
 * Therefore, for now we're going to stick with the more general approach of just
 * looking up each field when needed. We're keeping the code around, though statically
 * compiled out with the "if (false)" construct below in case we revisit this.
 *
 * @param layoutFile the layout whose activity we want to look up
 * @return the activity name
 */
@SuppressWarnings("all")
@Nullable
public String guessActivityBySetContentView(String layoutName) {
    if (false) {
        // These should be fields
        final Pattern LAYOUT_FIELD_PATTERN = Pattern.compile("R\\.layout\\.([a-z0-9_]+)"); //$NON-NLS-1$
        Map<String, String> mUsages = null;

        sync();
        if (mUsages == null) {
            final Map<String, String> usages = new HashMap<String, String>();
            mUsages = usages;
            SearchRequestor requestor = new SearchRequestor() {
                @Override
                public void acceptSearchMatch(SearchMatch match) throws CoreException {
                    Object element = match.getElement();
                    if (element instanceof IMethod) {
                        IMethod method = (IMethod) element;
                        IType declaringType = method.getDeclaringType();
                        String fqcn = declaringType.getFullyQualifiedName();
                        IDocumentProvider provider = new TextFileDocumentProvider();
                        IResource resource = match.getResource();
                        try {
                            provider.connect(resource);
                            IDocument document = provider.getDocument(resource);
                            if (document != null) {
                                String matchText = document.get(match.getOffset(), match.getLength());
                                Matcher matcher = LAYOUT_FIELD_PATTERN.matcher(matchText);
                                if (matcher.find()) {
                                    usages.put(matcher.group(1), fqcn);
                                }
                            }
                        } catch (Exception e) {
                            AdtPlugin.log(e, "Can't find range information for %1$s", resource.getName());
                        } finally {
                            provider.disconnect(resource);
                        }
                    }
                }
            };
            try {
                IJavaProject javaProject = BaseProjectHelper.getJavaProject(mProject);
                if (javaProject == null) {
                    return null;
                }

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

                IType activityType = javaProject.findType(CLASS_ACTIVITY);
                if (activityType != null) {
                    IMethod method = activityType.getMethod("setContentView", new String[] { "I" }); //$NON-NLS-1$ //$NON-NLS-2$
                    if (method.exists()) {
                        SearchPattern pattern = SearchPattern.createPattern(method, REFERENCES);
                        search(requestor, javaProject, pattern);
                    }
                }
            } catch (CoreException e) {
                AdtPlugin.log(e, null);
            }
        }

        return mUsages.get(layoutName);
    }

    return null;
}

From source file:com.android.ide.eclipse.auidt.internal.editors.manifest.ManifestInfo.java

License:Open Source License

/**
 * Returns the activity associated with the given layout file.
 * <p>/*from w  w  w .jav  a  2  s  . c  om*/
 * This is an alternative to {@link #guessActivity(IFile, String)}. Whereas
 * guessActivity simply looks for references to "R.layout.foo", this method searches
 * for all usages of Activity#setContentView(int), and for each match it looks up the
 * corresponding call text (such as "setContentView(R.layout.foo)"). From this it uses
 * a regexp to pull out "foo" from this, and stores the association that layout "foo"
 * is associated with the activity class that contained the setContentView call.
 * <p>
 * This has two potential advantages:
 * <ol>
 * <li>It can be faster. We do the reference search -once-, and we've built a map of
 * all the layout-to-activity mappings which we can then immediately look up other
 * layouts for, which is particularly useful at startup when we have to compute the
 * layout activity associations to populate the theme choosers.
 * <li>It can be more accurate. Just because an activity references an "R.layout.foo"
 * field doesn't mean it's setting it as a content view.
 * </ol>
 * However, this second advantage is also its chief problem. There are some common
 * code constructs which means that the associated layout is not explicitly referenced
 * in a direct setContentView call; on a couple of sample projects I tested I found
 * patterns like for example "setContentView(v)" where "v" had been computed earlier.
 * Therefore, for now we're going to stick with the more general approach of just
 * looking up each field when needed. We're keeping the code around, though statically
 * compiled out with the "if (false)" construct below in case we revisit this.
 *
 * @param layoutFile the layout whose activity we want to look up
 * @return the activity name
 */
@SuppressWarnings("all")
@Nullable
public String guessActivityBySetContentView(String layoutName) {
    if (false) {
        // These should be fields
        final Pattern LAYOUT_FIELD_PATTERN = Pattern.compile("R\\.layout\\.([a-z0-9_]+)"); //$NON-NLS-1$
        Map<String, String> mUsages = null;

        sync();
        if (mUsages == null) {
            final Map<String, String> usages = new HashMap<String, String>();
            mUsages = usages;
            SearchRequestor requestor = new SearchRequestor() {
                @Override
                public void acceptSearchMatch(SearchMatch match) throws CoreException {
                    Object element = match.getElement();
                    if (element instanceof IMethod) {
                        IMethod method = (IMethod) element;
                        IType declaringType = method.getDeclaringType();
                        String fqcn = declaringType.getFullyQualifiedName();
                        IDocumentProvider provider = new TextFileDocumentProvider();
                        IResource resource = match.getResource();
                        try {
                            provider.connect(resource);
                            IDocument document = provider.getDocument(resource);
                            if (document != null) {
                                String matchText = document.get(match.getOffset(), match.getLength());
                                Matcher matcher = LAYOUT_FIELD_PATTERN.matcher(matchText);
                                if (matcher.find()) {
                                    usages.put(matcher.group(1), fqcn);
                                }
                            }
                        } catch (Exception e) {
                            AdtPlugin.log(e, "Can't find range information for %1$s", resource.getName());
                        } finally {
                            provider.disconnect(resource);
                        }
                    }
                }
            };
            try {
                IJavaProject javaProject = BaseProjectHelper.getJavaProject(mProject);
                if (javaProject == null) {
                    return null;
                }

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

                IType activityType = javaProject.findType(SdkConstants.CLASS_ACTIVITY);
                if (activityType != null) {
                    IMethod method = activityType.getMethod("setContentView", new String[] { "I" }); //$NON-NLS-1$ //$NON-NLS-2$
                    if (method.exists()) {
                        SearchPattern pattern = SearchPattern.createPattern(method, REFERENCES);
                        search(requestor, javaProject, pattern);
                    }
                }
            } catch (CoreException e) {
                AdtPlugin.log(e, null);
            }
        }

        return mUsages.get(layoutName);
    }

    return null;
}

From source file:com.siteview.mde.internal.ui.search.dependencies.DependencyExtentOperation.java

License:Open Source License

private void searchForTypesUsed(SearchEngine engine, IJavaElement parent, IType[] types, IJavaSearchScope scope)
        throws CoreException {
    for (int i = 0; i < types.length; i++) {
        if (types[i].isAnonymous())
            continue;
        TypeReferenceSearchRequestor requestor = new TypeReferenceSearchRequestor();
        engine.search(SearchPattern.createPattern(types[i], IJavaSearchConstants.REFERENCES),
                new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, scope, requestor, null);
        if (requestor.containMatches()) {
            TypeDeclarationSearchRequestor decRequestor = new TypeDeclarationSearchRequestor();
            engine.search(SearchPattern.createPattern(types[i], IJavaSearchConstants.DECLARATIONS),
                    new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() },
                    SearchEngine.createJavaSearchScope(new IJavaElement[] { parent }), decRequestor, null);
            Match match = decRequestor.getMatch();
            if (match != null)
                fSearchResult.addMatch(match);
        }//  w  ww  .ja v a  2  s .c o m
    }

}

From source file:com.siteview.mde.internal.ui.search.dependencies.GatherUnusedDependenciesOperation.java

License:Open Source License

private boolean provideJavaClasses(IMonitorModelBase[] models, IProgressMonitor monitor) {
    try {/*from  w  ww  . j ava2  s. c o m*/
        IProject project = fModel.getUnderlyingResource().getProject();
        if (!project.hasNature(JavaCore.NATURE_ID))
            return false;

        IJavaProject jProject = JavaCore.create(project);
        IPackageFragment[] packageFragments = PluginJavaSearchUtil.collectPackageFragments(models, jProject,
                true);
        SearchEngine engine = new SearchEngine();
        IJavaSearchScope searchScope = PluginJavaSearchUtil.createSeachScope(jProject);

        monitor.beginTask("", packageFragments.length * 2); //$NON-NLS-1$
        for (int i = 0; i < packageFragments.length; i++) {
            IPackageFragment pkgFragment = packageFragments[i];
            if (pkgFragment.hasChildren()) {
                Requestor requestor = new Requestor();
                engine.search(SearchPattern.createPattern(pkgFragment, IJavaSearchConstants.REFERENCES),
                        new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, searchScope,
                        requestor, new SubProgressMonitor(monitor, 1));
                if (requestor.foundMatches()) {
                    if (provideJavaClasses(packageFragments[i], engine, searchScope,
                            new SubProgressMonitor(monitor, 1))) {
                        return true;
                    }
                } else
                    monitor.worked(1);
            } else {
                monitor.worked(2);
            }
        }
    } catch (CoreException e) {
    } finally {
        monitor.done();
    }
    return false;
}

From source file:com.siteview.mde.internal.ui.search.dependencies.GatherUnusedDependenciesOperation.java

License:Open Source License

private boolean provideJavaClasses(IPackageFragment packageFragment, SearchEngine engine,
        IJavaSearchScope searchScope, IProgressMonitor monitor) throws JavaModelException, CoreException {
    Requestor requestor;//from   w w  w  .  jav a2  s  . com
    IJavaElement[] children = packageFragment.getChildren();
    monitor.beginTask("", children.length); //$NON-NLS-1$

    try {
        for (int j = 0; j < children.length; j++) {
            IType[] types = null;
            if (children[j] instanceof ICompilationUnit) {
                types = ((ICompilationUnit) children[j]).getAllTypes();
            } else if (children[j] instanceof IClassFile) {
                types = new IType[] { ((IClassFile) children[j]).getType() };
            }
            if (types != null) {
                for (int t = 0; t < types.length; t++) {
                    requestor = new Requestor();
                    engine.search(SearchPattern.createPattern(types[t], IJavaSearchConstants.REFERENCES),
                            new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, searchScope,
                            requestor, new SubProgressMonitor(monitor, 1));
                    if (requestor.foundMatches()) {
                        return true;
                    }
                }
            }
        }
    } finally {
        monitor.done();
    }
    return false;
}

From source file:de.devboost.eclipse.jdtutilities.ClassDependencyUtility.java

License:Open Source License

private Set<String> find(String path, int searchType) throws CoreException {
    Set<String> result = new LinkedHashSet<String>();
    // mark this element as visited
    List<IType> types = getTypes(path);
    if (types.isEmpty()) {
        return result;
    }//from www.j ava  2  s .co m

    SearchEngine engine = new SearchEngine();
    SearchParticipant[] participants = new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() };
    IJavaSearchScope scope = createScope();
    SearchRequestor requestor = new DependencySearchRequestor(result);
    IProgressMonitor monitor = new NullProgressMonitor();
    for (IType type : types) {
        SearchPattern pattern = SearchPattern.createPattern(type, searchType);
        engine.search(pattern, participants, scope, requestor, monitor);
    }
    return result;
}

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  . java 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:navclus.userinterface.classdiagram.java.analyzer.RelationAnalyzer.java

License:Open Source License

public boolean usedLocalMembers(final TypeNode node1, final TypeNode node2) throws JavaModelException {

    boolean bConnected = false;

    IType type1 = node1.getType();//  w  w  w .j  ava  2  s.  c om
    IType type2 = node2.getType();

    // type 2's fields/Methods which refer to type 1   
    final Set<IField> fieldsofType2 = new LinkedHashSet<IField>();
    final Set<IMethod> methodsofType2 = new LinkedHashSet<IMethod>();

    // Searching the connection from type 2 to type 1
    SearchPattern pattern = SearchPattern.createPattern(type1, IJavaSearchConstants.REFERENCES);
    IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaElement[] { type2 });
    SearchRequestor requestor = new SearchRequestor() {

        @Override
        public void acceptSearchMatch(SearchMatch match) throws CoreException {
            Object obj = match.getElement();
            if (obj == null)
                return;

            if (obj instanceof IMethod) {
                IMethod element = (IMethod) obj;
                methodsofType2.add(element);
            } else if (obj instanceof IField) {
                IField element = (IField) obj;
                fieldsofType2.add(element);
            }
        }
    };

    // Start to search...
    SearchEngine searchEngine = new SearchEngine();
    try {
        searchEngine.search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() },
                scope, requestor, null);
    } catch (CoreException e) {
        e.printStackTrace();
    }

    //      for (IMethod method: methodsofType2) {
    //         System.out.println(type1.getElementName() + "-- is used by -->" + type2.getElementName() +"." + method.getElementName());
    //      }      
    //      for (IField field: fieldsofType2) {
    //         System.out.println(type1.getElementName() + "-- is used by -->>" + type2.getElementName() +"." + field.getElementName());
    //      }

    if ((methodsofType2.size() == 0) && (fieldsofType2.size() == 0))
        return false;
    else
        return true;
    //      
    //      // Testing: Analyzing AST
    //      ASTParser parser = ASTParser.newParser(AST.JLS3);
    //      parser.setKind(ASTParser.K_COMPILATION_UNIT);
    //      parser.setResolveBindings(false);
    //      
    //      ITypeRoot unit = node2.getType().getTypeRoot();       
    //      if (unit.getSource() == null) return;
    //      
    //      parser.setSource(unit);
    //
    ////      CompilationUnit cu = JavaPlugin.getDefault().getASTProvider().getAST(unit, true, null);
    //      CompilationUnit cu = (CompilationUnit) parser.createAST(null);            
    //      cu.accept(
    //            new TypePartVisitorwithoutBinding(
    //                  node1, 
    //                  node2, 
    //                  methods2,
    //                  fields2));         
}

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

License:Open Source License

/**
 * <p>/*  w  w w  . j  a  v a 2s. c om*/
 * 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);
    }
}