Ejemplo 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);
     }
   }
 }
Ejemplo n.º 2
0
  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);
    }
  }
  /*
   * Ensures that searching takes the owner's working copies into account.
   */
  public void testSearch2() throws CoreException {
    ICompilationUnit cu = getCompilationUnit("P/X.java");
    TestWorkingCopyOwner owner = new TestWorkingCopyOwner();
    this.workingCopy = cu.getWorkingCopy(owner, null);

    // remove type X
    this.workingCopy.getBuffer().setContents("");
    this.workingCopy.makeConsistent(null);

    SearchPattern pattern =
        SearchPattern.createPattern(
            "X",
            IJavaSearchConstants.TYPE,
            IJavaSearchConstants.DECLARATIONS,
            SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE);
    JavaSearchTests.JavaSearchResultCollector resultCollector =
        new JavaSearchTests.JavaSearchResultCollector();
    new SearchEngine(owner)
        .search(
            pattern,
            new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()},
            SearchEngine.createWorkspaceScope(),
            resultCollector,
            null);
    assertEquals(
        "", // should not find any in the owner's context
        resultCollector.toString());
  }
Ejemplo n.º 4
0
  private SearchResultGroup[] getNewReferences(
      IProgressMonitor pm,
      RefactoringStatus status,
      WorkingCopyOwner owner,
      ICompilationUnit[] newWorkingCopies)
      throws CoreException {
    pm.beginTask("", 2); // $NON-NLS-1$
    ICompilationUnit declaringCuWorkingCopy =
        RenameAnalyzeUtil.findWorkingCopyForCu(newWorkingCopies, fField.getCompilationUnit());
    if (declaringCuWorkingCopy == null) return new SearchResultGroup[0];

    IField field = getFieldInWorkingCopy(declaringCuWorkingCopy, getNewElementName());
    if (field == null || !field.exists()) return new SearchResultGroup[0];

    CollectingSearchRequestor requestor = null;
    if (fDelegateUpdating
        && RefactoringAvailabilityTester.isDelegateCreationAvailable(getField())) {
      // There will be two new matches inside the delegate (the invocation
      // and the javadoc) which are OK and must not be reported.
      final IField oldField =
          getFieldInWorkingCopy(declaringCuWorkingCopy, getCurrentElementName());
      requestor =
          new CollectingSearchRequestor() {
            public void acceptSearchMatch(SearchMatch match) throws CoreException {
              if (!oldField.equals(match.getElement())) super.acceptSearchMatch(match);
            }
          };
    } else requestor = new CollectingSearchRequestor();

    SearchPattern newPattern = SearchPattern.createPattern(field, IJavaSearchConstants.REFERENCES);
    IJavaSearchScope scope = RefactoringScopeFactory.create(fField, true, true);
    return RefactoringSearchEngine.search(
        newPattern, owner, scope, requestor, new SubProgressMonitor(pm, 1), status);
  }
Ejemplo n.º 5
0
  private void addAccessorOccurrences(
      IProgressMonitor pm,
      IMethod accessor,
      String editName,
      String newAccessorName,
      RefactoringStatus status)
      throws CoreException {
    Assert.isTrue(accessor.exists());

    IJavaSearchScope scope = RefactoringScopeFactory.create(accessor);
    SearchPattern pattern =
        SearchPattern.createPattern(
            accessor,
            IJavaSearchConstants.ALL_OCCURRENCES,
            SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
    SearchResultGroup[] groupedResults =
        RefactoringSearchEngine.search(
            pattern, scope, new MethodOccurenceCollector(accessor.getElementName()), pm, status);

    for (int i = 0; i < groupedResults.length; i++) {
      ICompilationUnit cu = groupedResults[i].getCompilationUnit();
      if (cu == null) continue;
      SearchMatch[] results = groupedResults[i].getSearchResults();
      for (int j = 0; j < results.length; j++) {
        SearchMatch searchResult = results[j];
        TextEdit edit =
            new ReplaceEdit(searchResult.getOffset(), searchResult.getLength(), newAccessorName);
        addTextEdit(fChangeManager.get(cu), editName, edit);
      }
    }
  }
Ejemplo n.º 6
0
 private RefactoringStatus checkAccessorDeclarations(IProgressMonitor pm, IMethod existingAccessor)
     throws CoreException {
   RefactoringStatus result = new RefactoringStatus();
   SearchPattern pattern =
       SearchPattern.createPattern(
           existingAccessor,
           IJavaSearchConstants.DECLARATIONS,
           SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
   IJavaSearchScope scope = SearchEngine.createHierarchyScope(fField.getDeclaringType());
   SearchResultGroup[] groupDeclarations =
       RefactoringSearchEngine.search(pattern, scope, pm, result);
   Assert.isTrue(groupDeclarations.length > 0);
   if (groupDeclarations.length != 1) {
     String message =
         Messages.format(
             RefactoringCoreMessages.RenameFieldRefactoring_overridden,
             JavaElementUtil.createMethodSignature(existingAccessor));
     result.addError(message);
   } else {
     SearchResultGroup group = groupDeclarations[0];
     Assert.isTrue(group.getSearchResults().length > 0);
     if (group.getSearchResults().length != 1) {
       String message =
           Messages.format(
               RefactoringCoreMessages.RenameFieldRefactoring_overridden_or_overrides,
               JavaElementUtil.createMethodSignature(existingAccessor));
       result.addError(message);
     }
   }
   return result;
 }
Ejemplo n.º 7
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();
   }
 }
Ejemplo n.º 8
0
  /**
   * 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.
   *
   * @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;
  }
Ejemplo n.º 9
0
  public void findIndexMatches(
      Index index,
      IndexQueryRequestor requestor,
      SearchParticipant participant,
      IJavaSearchScope scope,
      IProgressMonitor progressMonitor)
      throws IOException {
    if (progressMonitor != null && progressMonitor.isCanceled())
      throw new OperationCanceledException();

    resetQuery();
    SimpleSet intersectedNames = null;
    try {
      index.startQuery();
      do {
        SearchPattern pattern = currentPattern();
        EntryResult[] entries = pattern.queryIn(index);
        if (entries == null) return;

        SearchPattern decodedResult = pattern.getBlankPattern();
        SimpleSet newIntersectedNames = new SimpleSet(3);
        for (int i = 0, l = entries.length; i < l; i++) {
          if (progressMonitor != null && progressMonitor.isCanceled())
            throw new OperationCanceledException();

          EntryResult entry = entries[i];
          decodedResult.decodeIndexKey(entry.getWord());
          if (pattern.matchesDecodedKey(decodedResult)) {
            String[] names = entry.getDocumentNames(index);
            if (intersectedNames != null) {
              for (int j = 0, n = names.length; j < n; j++)
                if (intersectedNames.includes(names[j])) newIntersectedNames.add(names[j]);
            } else {
              for (int j = 0, n = names.length; j < n; j++) newIntersectedNames.add(names[j]);
            }
          }
        }

        if (newIntersectedNames.elementSize == 0) return;
        intersectedNames = newIntersectedNames;
      } while (hasNextQuery());
    } finally {
      index.stopQuery();
    }

    String containerPath = index.containerPath;
    char separator = index.separator;
    Object[] names = intersectedNames.values;
    for (int i = 0, l = names.length; i < l; i++)
      if (names[i] != null)
        acceptMatch(
            (String) names[i],
            containerPath,
            separator,
            null /*no pattern*/,
            requestor,
            participant,
            scope); // AndPatterns cannot provide the decoded result
  }
  private SearchPattern createNewMethodPattern() {
    StringBuffer stringPattern = new StringBuffer(getNewElementName()).append('(');
    int paramCount = getMethod().getNumberOfParameters();
    for (int i = 0; i < paramCount; i++) {
      if (i > 0) stringPattern.append(',');
      stringPattern.append('*');
    }
    stringPattern.append(')');

    return SearchPattern.createPattern(
        stringPattern.toString(),
        IJavaSearchConstants.METHOD,
        IJavaSearchConstants.DECLARATIONS,
        SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
  }
 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);
 }
Ejemplo n.º 12
0
  public static Set<IType> searchForJavaConfigs(IJavaSearchScope scope) {
    SearchPattern configurationPattern =
        SearchPattern.createPattern(
            "org.springframework.context.annotation.Configuration",
            IJavaSearchConstants.ANNOTATION_TYPE,
            IJavaSearchConstants.ANNOTATION_TYPE_REFERENCE,
            SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE);
    SearchPattern componentPattern =
        SearchPattern.createPattern(
            "org.springframework.stereotype.Component",
            IJavaSearchConstants.ANNOTATION_TYPE,
            IJavaSearchConstants.ANNOTATION_TYPE_REFERENCE,
            SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE);
    SearchPattern beanPattern =
        SearchPattern.createPattern(
            "org.springframework.context.annotation.Bean",
            IJavaSearchConstants.ANNOTATION_TYPE,
            IJavaSearchConstants.ANNOTATION_TYPE_REFERENCE,
            SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE);
    SearchPattern importPattern =
        SearchPattern.createPattern(
            "org.springframework.context.annotation.Import",
            IJavaSearchConstants.ANNOTATION_TYPE,
            IJavaSearchConstants.ANNOTATION_TYPE_REFERENCE,
            SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE);
    SearchPattern bootAutoConfigPattern =
        SearchPattern.createPattern(
            "org.springframework.boot.autoconfigure.EnableAutoConfiguration",
            IJavaSearchConstants.ANNOTATION_TYPE,
            IJavaSearchConstants.ANNOTATION_TYPE_REFERENCE,
            SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE);

    SearchPattern pattern = SearchPattern.createOrPattern(configurationPattern, componentPattern);
    pattern = SearchPattern.createOrPattern(pattern, beanPattern);
    pattern = SearchPattern.createOrPattern(pattern, importPattern);
    pattern = SearchPattern.createOrPattern(pattern, bootAutoConfigPattern);
    return searchForJavaConfigs(pattern, scope);
  }
  /*
   * Ensures that searching takes the primary owner's working copies and the given working copies into account.
   * (regression test for bug 43300 SearchEngine(IWorkingCopy[] workingCopies) not backward compatible)
   */
  public void testSearch4() throws CoreException {
    ICompilationUnit primaryWorkingCopy = null;
    try {
      createFolder("P/p");
      createFile("/P/p/Y.java", "");
      primaryWorkingCopy = getCompilationUnit("P/p/Y.java");
      primaryWorkingCopy.becomeWorkingCopy(null);

      // create type Y in working copy
      primaryWorkingCopy.getBuffer().setContents("package p;\n" + "public class Y {\n" + "}");
      primaryWorkingCopy.makeConsistent(null);

      // create new working copy on X.java and add type X
      this.workingCopy = getCompilationUnit("P/p/X.java").getWorkingCopy(null);
      this.workingCopy.getBuffer().setContents("package p;\n" + "public class X {\n" + "}");
      this.workingCopy.makeConsistent(null);

      JavaSearchTests.JavaSearchResultCollector resultCollector =
          new JavaSearchTests.JavaSearchResultCollector();
      IJavaSearchScope scope =
          SearchEngine.createJavaSearchScope(new IJavaElement[] {primaryWorkingCopy.getParent()});
      SearchPattern pattern =
          SearchPattern.createPattern(
              "*",
              IJavaSearchConstants.TYPE,
              IJavaSearchConstants.DECLARATIONS,
              SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CASE_SENSITIVE);
      new SearchEngine(new ICompilationUnit[] {this.workingCopy})
          .search(
              pattern,
              new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()},
              scope,
              resultCollector,
              null);
      assertEquals("p/X.java p.X [X]\n" + "p/Y.java p.Y [Y]", resultCollector.toString());

    } finally {
      if (primaryWorkingCopy != null) {
        primaryWorkingCopy.discardWorkingCopy();
      }
      deleteFile("/P/p/Y.java");
    }
  }
Ejemplo n.º 14
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());
  }
Ejemplo n.º 15
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();
   }
 }
  @Override
  public StyledString emphasizeMatch(
      IDocument document, int offset, BoldStylerProvider boldStylerProvider) {
    StyledString styledDisplayString = new StyledString();
    styledDisplayString.append(getStyledDisplayString());

    String pattern = getPatternToEmphasizeMatch(document, offset);
    if (pattern != null && pattern.length() > 0) {
      String displayString = styledDisplayString.getString().substring(1); // remove '{'
      boolean patternHasBrace = pattern.charAt(0) == '{';
      if (patternHasBrace) {
        pattern = pattern.substring(1);
      }
      if (displayString.charAt(0) == '@' && pattern.charAt(0) == '@') {
        displayString = displayString.substring(1);
        pattern = pattern.substring(1);
        int patternMatchRule = getPatternMatchRule(pattern, displayString);
        int[] matchingRegions =
            SearchPattern.getMatchingRegions(pattern, displayString, patternMatchRule);
        if (matchingRegions != null) {
          if (patternHasBrace) {
            Strings.markMatchingRegions(
                styledDisplayString, 0, new int[] {0, 1}, boldStylerProvider.getBoldStyler());
          }
          Strings.markMatchingRegions(
              styledDisplayString, 0, new int[] {1, 1}, boldStylerProvider.getBoldStyler());
          for (int i = 0; i < matchingRegions.length; i += 2) {
            matchingRegions[i] += 2;
          }
        }
        Strings.markMatchingRegions(
            styledDisplayString, 0, matchingRegions, boldStylerProvider.getBoldStyler());
      }
    }
    return styledDisplayString;
  }
  /*
   * Ensures that searching takes the owner's working copies into account.
   */
  public void testSearch1() throws CoreException {
    ICompilationUnit cu = getCompilationUnit("P/Y.java");
    TestWorkingCopyOwner owner = new TestWorkingCopyOwner();
    this.workingCopy = cu.getWorkingCopy(owner, null);
    this.workingCopy.getBuffer().setContents("public class Y {\n" + "  X field;\n" + "}");
    this.workingCopy.makeConsistent(null);

    SearchPattern pattern =
        SearchPattern.createPattern(
            "X",
            IJavaSearchConstants.TYPE,
            IJavaSearchConstants.REFERENCES,
            SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE);
    JavaSearchTests.JavaSearchResultCollector resultCollector =
        new JavaSearchTests.JavaSearchResultCollector();
    new SearchEngine(owner)
        .search(
            pattern,
            new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()},
            SearchEngine.createWorkspaceScope(),
            resultCollector,
            null);
    assertEquals("Y.java Y.field [X]", resultCollector.toString());
  }
Ejemplo n.º 18
0
  /**
   * Returns the activity associated with the given layout file.
   *
   * <p>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;
  }
Ejemplo n.º 19
0
 private SearchPattern createSearchPattern() {
   return SearchPattern.createPattern(fField, IJavaSearchConstants.REFERENCES);
 }
Ejemplo n.º 20
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);
  }
  @SuppressWarnings({"unchecked"})
  @Override
  public RefactoringStatus checkFinalConditions(IProgressMonitor pm)
      throws CoreException, OperationCanceledException {
    RefactoringStatus result = new RefactoringStatus();
    fChangeManager.clear();
    pm.beginTask("", 12);
    pm.setTaskName("Convert to AtomicInteger checking preconditions");
    pm.worked(1);
    if (result.hasFatalError()) return result;
    pm.setTaskName("ConvertToAtomicInteger searching for cunits");
    final SubProgressMonitor subPm = new SubProgressMonitor(pm, 5);
    ICompilationUnit[] affectedCUs =
        RefactoringSearchEngine.findAffectedCompilationUnits(
            SearchPattern.createPattern(targetClass, IJavaSearchConstants.ALL_OCCURRENCES),
            RefactoringScopeFactory.create(targetClass, true),
            subPm,
            result,
            true);

    if (result.hasFatalError()) return result;

    pm.setTaskName("Analyzing the field");
    IProgressMonitor sub = new SubProgressMonitor(pm, 5);
    sub.beginTask("", affectedCUs.length);

    List ownerDescriptions = new ArrayList();
    ICompilationUnit owner = targetClass.getCompilationUnit();

    for (int i = 0; i < affectedCUs.length; i++) {
      ICompilationUnit unit = affectedCUs[i];
      sub.subTask(unit.getElementName());
      CompilationUnit root = null;
      ASTRewrite rewriter = null;
      List descriptions;
      if (owner.equals(unit)) {
        root = fRoot;
        rewriter = fRewriter;
        descriptions = ownerDescriptions;
      } else {
        root = new RefactoringASTParser(AST.JLS3).parse(unit, true);
        rewriter = ASTRewrite.create(root.getAST());
        descriptions = new ArrayList();
      }
      checkCompileErrors(result, root, unit);

      // We will perform a different set of analysis and rewrites for the compilation unit
      // containing the
      // target class and other compilation units
      if (owner.equals(unit)) {

        // Analysis passes
        ClassMutatorAnalysis mutatorAnalysis = new ClassMutatorAnalysis(targetClass, pm);
        mutatorAnalysis.findMutators();

        ClassConstructorAnalysis constructorAnalysis =
            new ClassConstructorAnalysis(targetClassDeclaration);
        targetClassDeclaration.accept(constructorAnalysis);

        // Rewrite pass
        MakeClassImmutableRewriter immutableRewriter =
            new MakeClassImmutableRewriter(this, unit, rewriter);
        immutableRewriter.rewrite(targetClassDeclaration, mutatorAnalysis, constructorAnalysis);

        result.merge(immutableRewriter.getStatus());
        if (result.hasFatalError()) {
          fChangeManager.clear();
          return result;
        }
      } else {

        // descriptions.addAll(immutableRewriter.getGroupDescriptions());
        createEdits(unit, rewriter, descriptions);
      }

      sub.worked(1);
      if (pm.isCanceled()) throw new OperationCanceledException();
    }

    createEdits(owner, fRewriter, ownerDescriptions);

    sub.done();
    IFile[] filesToBeModified = ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits());
    result.merge(Checks.validateModifiesFiles(filesToBeModified, getValidationContext()));
    if (result.hasFatalError()) return result;
    ResourceChangeChecker.checkFilesToBeChanged(filesToBeModified, new SubProgressMonitor(pm, 1));
    return result;
  }