Esempio n. 1
0
 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);
     }
   }
 }
  void goToErrorLine(String choice) {
    try {
      String msg = mLogPanel.getSelectedErrorLineMessage();
      if (msg != null) {
        String error_line_matcher_string = "\\s*at\\ (.*)\\((.*)\\.java\\:(\\d+)\\)";
        Matcher error_line_matcher = Pattern.compile(error_line_matcher_string).matcher(msg);

        if (error_line_matcher.find()) {
          String class_name_method = error_line_matcher.group(1);

          // TODO: Search currently only matches the class declaration (using
          // IJavaSearchConstants.DECLARATIONS). We may want to jump to the
          // "reference" of the class instead (IJavaSearchConstants.REFERENCES)
          // using the filename and line number to disambiguate the search results.
          String class_name_line = error_line_matcher.group(2);
          int line_number = Integer.parseInt(error_line_matcher.group(3));

          SearchEngine se = new SearchEngine();
          if (CHOICE_ERROR_LINE.equals(choice)) {
            se.search(
                SearchPattern.createPattern(
                    class_name_line,
                    IJavaSearchConstants.CLASS,
                    IJavaSearchConstants.DECLARATIONS,
                    SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE),
                new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()},
                SearchEngine.createWorkspaceScope(),
                new LogCatViewSearchRequestor(CHOICE_ERROR_LINE, line_number),
                new NullProgressMonitor());
          } else if (CHOICE_METHOD_DECLARATION.equals(choice)) {
            se.search(
                SearchPattern.createPattern(
                    class_name_method,
                    IJavaSearchConstants.METHOD,
                    IJavaSearchConstants.DECLARATIONS,
                    SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE),
                new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()},
                SearchEngine.createWorkspaceScope(),
                new LogCatViewSearchRequestor(CHOICE_METHOD_DECLARATION, 0),
                new NullProgressMonitor());
          }
        }
      }
    } catch (Exception e) {
      Status s = new Status(Status.ERROR, DdmsPlugin.PLUGIN_ID, e.getMessage(), e);
      DdmsPlugin.getDefault().getLog().log(s);
    }
  }
Esempio n. 3
0
  /**
   * Performs a search using the given pattern, scope and handler. The search will abort if it takes
   * longer than {@link #SEARCH_TIMEOUT_MS} milliseconds.
   */
  private static void search(
      SearchRequestor requestor, IJavaProject javaProject, SearchPattern pattern)
      throws CoreException {
    // Find the package fragment specified in the manifest; the activities should
    // live there.
    IJavaSearchScope scope = createPackageScope(javaProject);

    SearchParticipant[] participants =
        new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()};
    SearchEngine engine = new SearchEngine();

    final long searchStart = System.currentTimeMillis();
    NullProgressMonitor monitor =
        new NullProgressMonitor() {
          private boolean mCancelled;

          @Override
          public void internalWorked(double work) {
            long searchEnd = System.currentTimeMillis();
            if (searchEnd - searchStart > SEARCH_TIMEOUT_MS) {
              mCancelled = true;
            }
          }

          @Override
          public boolean isCanceled() {
            return mCancelled;
          }
        };
    engine.search(pattern, participants, scope, requestor, monitor);
  }
  /** This method is extremely expensive. */
  @OnEclipseVersionUpgrade("Replace monitor.newChild(1) by monitor.split(1)")
  private boolean isMethodUsedInItsPackage(IMethodBinding methodBinding, MethodDeclaration node) {
    final IPackageBinding methodPackage = methodBinding.getDeclaringClass().getPackage();

    final AtomicBoolean methodIsUsedInPackage = new AtomicBoolean(false);
    final SearchRequestor requestor =
        new SearchRequestor() {
          @Override
          public void acceptSearchMatch(SearchMatch match) {
            methodIsUsedInPackage.set(true);
          }
        };

    final SubMonitor subMonitor = SubMonitor.convert(ctx.getProgressMonitor(), 1);
    final SubMonitor childMonitor = subMonitor.newChild(1);
    try {
      final SearchEngine searchEngine = new SearchEngine();
      searchEngine.search(
          createPattern(methodBinding.getJavaElement(), REFERENCES, R_EXACT_MATCH),
          new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()},
          SearchEngine.createJavaSearchScope(new IJavaElement[] {methodPackage.getJavaElement()}),
          requestor,
          childMonitor);
      return methodIsUsedInPackage.get();
    } catch (CoreException e) {
      throw new UnhandledException(node, e);
    } finally {
      childMonitor.done();
    }
  }
Esempio n. 5
0
 /**
  * @param packageNames
  * @return
  */
 private List getPackageFragments(List packageNames) {
   monitor.subTask("Finding Packages in tangle");
   SearchEngine searchEngine = new SearchEngine();
   IJavaSearchScope scope = SearchEngine.createWorkspaceScope();
   SearchPattern pattern =
       SearchPattern.createPattern(
           "*",
           IJavaSearchConstants.PACKAGE,
           IJavaSearchConstants.DECLARATIONS,
           SearchPattern.R_PATTERN_MATCH);
   PackageCollector c = new PackageCollector(packageNames);
   try {
     searchEngine.search(
         pattern,
         new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()},
         scope,
         c,
         monitor);
     monitor.worked(100);
     return c.getResult();
   } catch (CoreException e) {
     e.printStackTrace();
     return new ArrayList();
   }
 }
 private void searchPackage(String matchString, IJavaSearchScope scope, SearchRequestor requestor)
     throws CoreException {
   SearchPattern pattern =
       SearchPattern.createPattern(
           matchString + "*",
           IJavaSearchConstants.PACKAGE,
           IJavaSearchConstants.DECLARATIONS,
           SearchPattern.R_PREFIX_MATCH);
   SearchEngine searchEngine = new SearchEngine();
   searchEngine.search(
       pattern,
       new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()},
       scope,
       requestor,
       null);
 }
Esempio n. 7
0
  public static IJavaElement searchForClass(IJavaProject javaProject, String className)
      throws JavaModelException {
    // Get the search pattern
    SearchPattern pattern =
        SearchPattern.createPattern(
            className,
            IJavaSearchConstants.TYPE,
            IJavaSearchConstants.DECLARATIONS,
            SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE);
    // Get the search scope
    IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaElement[] {javaProject});

    final List<SearchMatch> matches = new ArrayList<SearchMatch>(INITIAL_CAPACITY);
    // Get the search requestor
    SearchRequestor requestor =
        new SearchRequestor() {
          public void acceptSearchMatch(SearchMatch match) throws CoreException {
            matches.add(match);
          }
        };

    // Search
    SearchEngine searchEngine = new SearchEngine();
    try {
      searchEngine.search(
          pattern,
          new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()},
          scope,
          requestor,
          null);
    } catch (CoreException ex) {
      JspEditorPlugin.getPluginLog().logError(ex);
    }
    for (SearchMatch match : matches) {
      IJavaElement element = (IJavaElement) match.getElement();
      if (element instanceof IType
          && className.equals(((IType) element).getFullyQualifiedName('.'))) {
        return element;
      }
    }
    return javaProject.findType(className, new NullProgressMonitor());
  }
Esempio n. 8
0
 /**
  * @param packages
  * @return
  */
 private void getDependencies(List packages) {
   try {
     SearchEngine searchEngine = new SearchEngine();
     // fill in the packageName->{IType}* map by getting all type declarations in scope
     IJavaElement[] packs = (IJavaElement[]) packages.toArray(new IJavaElement[] {});
     IJavaSearchScope scope = SearchEngine.createJavaSearchScope(packs);
     SearchPattern pattern =
         SearchPattern.createPattern(
             "*",
             IJavaSearchConstants.TYPE,
             IJavaSearchConstants.DECLARATIONS,
             SearchPattern.R_PATTERN_MATCH);
     TypeCollector c = new TypeCollector(result);
     monitor.subTask("Collecting types in packages");
     searchEngine.search(
         pattern,
         new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()},
         scope,
         c,
         monitor);
     if (monitor.isCanceled()) return;
     // get all type references to these types.
     // Have to do multiple searches to get proper relationship :-(
     Set typesInScope = result.keySet();
     monitor.worked(400);
     monitor.subTask("Collecting type dependencies");
     int scale = 500 / typesInScope.size();
     for (Iterator i = typesInScope.iterator(); i.hasNext(); ) {
       if (monitor.isCanceled()) return;
       String handle = (String) i.next();
       IJavaElement type = JavaCore.create(handle);
       searchEngine.searchDeclarationsOfReferencedTypes(
           type, new RefCollector((Set) result.get(handle), typesInScope, type), monitor);
       monitor.worked(scale);
     }
   } catch (CoreException e) {
     e.printStackTrace();
   }
 }
Esempio n. 9
0
  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
          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);
  }
  private SearchResultGroup[] batchFindNewOccurrences(
      IMethod[] wcNewMethods,
      final IMethod[] wcOldMethods,
      ICompilationUnit[] newDeclarationWCs,
      IProgressMonitor pm,
      RefactoringStatus status)
      throws CoreException {
    pm.beginTask("", 2); // $NON-NLS-1$

    SearchPattern refsPattern =
        RefactoringSearchEngine.createOrPattern(wcNewMethods, IJavaSearchConstants.REFERENCES);
    SearchParticipant[] searchParticipants = SearchUtils.getDefaultSearchParticipants();
    IJavaSearchScope scope = RefactoringScopeFactory.create(wcNewMethods);

    MethodOccurenceCollector requestor;
    if (getDelegateUpdating()) {
      // There will be two new matches inside the delegate(s) (the invocation
      // and the javadoc) which are OK and must not be reported.
      // Note that except these ocurrences, the delegate bodies are empty
      // (as they were created this way).
      requestor =
          new MethodOccurenceCollector(getNewElementName()) {
            @Override
            public void acceptSearchMatch(ICompilationUnit unit, SearchMatch match)
                throws CoreException {
              for (int i = 0; i < wcOldMethods.length; i++)
                if (wcOldMethods[i].equals(match.getElement())) return;
              super.acceptSearchMatch(unit, match);
            }
          };
    } else requestor = new MethodOccurenceCollector(getNewElementName());

    SearchEngine searchEngine = new SearchEngine(fWorkingCopyOwner);

    ArrayList<ICompilationUnit> needWCs = new ArrayList<>();
    HashSet<ICompilationUnit> declaringCUs = new HashSet<>(newDeclarationWCs.length);
    for (int i = 0; i < newDeclarationWCs.length; i++)
      declaringCUs.add(newDeclarationWCs[i].getPrimary());
    for (int i = 0; i < fOccurrences.length; i++) {
      ICompilationUnit cu = fOccurrences[i].getCompilationUnit();
      if (!declaringCUs.contains(cu)) needWCs.add(cu);
    }
    ICompilationUnit[] otherWCs = null;
    try {
      otherWCs =
          RenameAnalyzeUtil.createNewWorkingCopies(
              needWCs.toArray(new ICompilationUnit[needWCs.size()]),
              fChangeManager,
              fWorkingCopyOwner,
              new SubProgressMonitor(pm, 1));
      searchEngine.search(
          refsPattern, searchParticipants, scope, requestor, new SubProgressMonitor(pm, 1));
    } finally {
      pm.done();
      if (otherWCs != null) {
        for (int i = 0; i < otherWCs.length; i++) {
          otherWCs[i].discardWorkingCopy();
        }
      }
    }
    SearchResultGroup[] newResults =
        RefactoringSearchEngine.groupByCu(requestor.getResults(), status);
    return newResults;
  }