Example #1
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);
      }
    }
  }
 /**
  * @param change
  * @param oldMatches
  * @return Map &lt;Integer updatedOffset, SearchMatch oldMatch&gt;
  */
 private static Map<Integer, SearchMatch> getUpdatedChangeOffsets(
     TextChange change, SearchMatch[] oldMatches) {
   Map<Integer, SearchMatch> updatedOffsets = new HashMap<>();
   Map<Integer, Integer> oldToUpdatedOffsets = getEditChangeOffsetUpdates(change);
   for (int i = 0; i < oldMatches.length; i++) {
     SearchMatch oldMatch = oldMatches[i];
     Integer updatedOffset = oldToUpdatedOffsets.get(new Integer(oldMatch.getOffset()));
     if (updatedOffset == null) updatedOffset = new Integer(-1); // match not updated
     updatedOffsets.put(updatedOffset, oldMatch);
   }
   return updatedOffsets;
 }
  private static void addShadowsError(
      ICompilationUnit cu, SearchMatch oldMatch, RefactoringStatus result) {
    // Old match not found in new matches -> reference has been shadowed

    // TODO: should not have to filter declarations:
    if (oldMatch instanceof MethodDeclarationMatch || oldMatch instanceof FieldDeclarationMatch)
      return;
    ISourceRange range = new SourceRange(oldMatch.getOffset(), oldMatch.getLength());
    RefactoringStatusContext context = JavaStatusContext.create(cu, range);
    String message =
        Messages.format(
            RefactoringCoreMessages.RenameAnalyzeUtil_shadows, BasicElementLabels.getFileName(cu));
    result.addError(message, context);
  }
 @Override
 public void acceptSearchMatch(SearchMatch match) throws CoreException {
   if (match.getResource() instanceof IFile && !mFoundFirstMatch) {
     mFoundFirstMatch = true;
     IFile matched_file = (IFile) match.getResource();
     IMarker marker = createMarkerFromSearchMatch(matched_file, match);
     // There should only be one exact match,
     // so we go immediately to that one.
     if (marker != null) {
       switchPerspective();
       openFile(matched_file, marker);
     }
   }
 }
  /*
   * @see org.eclipse.jdt.core.search.SearchRequestor#acceptSearchMatch(org.eclipse.jdt.core.search.SearchMatch)
   */
  @Override
  public void acceptSearchMatch(SearchMatch match) throws CoreException {
    if (match.getAccuracy() == SearchMatch.A_INACCURATE) return;

    int offset = match.getOffset();
    int length = match.getLength();
    if (offset == -1 || length == -1) return;

    if (!(match.getElement() instanceof IJavaElement)) return;
    IJavaElement javaElement = (IJavaElement) match.getElement();

    // ignore matches in import declarations:
    if (javaElement.getElementType() == IJavaElement.IMPORT_DECLARATION) return;
    if (javaElement.getElementType() == IJavaElement.CLASS_FILE)
      return; // matches in import statements of class files
    if (javaElement.getElementType() == IJavaElement.TYPE)
      return; // classes extending the accessor class and workaround for bug 61286

    // heuristic: ignore matches in resource bundle name field:
    if (javaElement.getElementType() == IJavaElement.FIELD) {
      IField field = (IField) javaElement;
      String source = field.getSource();
      if (source != null && fgGetClassNameMatcher.match(source)) return;
    }

    if (javaElement instanceof ISourceReference) {
      String source = ((ISourceReference) javaElement).getSource();
      if (source != null) {
        if (source.indexOf("NLS.initializeMessages") != -1) // $NON-NLS-1$
        return;
      }
    }

    // found reference to NLS Wrapper - now check if the key is there:
    Position mutableKeyPosition = new Position(offset, length);
    // TODO: What to do if argument string not found? Currently adds a match with type name.
    String key = findKey(mutableKeyPosition, javaElement);
    if (key == null || isKeyDefined(key)) return;

    ICompilationUnit[] allCompilationUnits =
        JavaModelUtil.getAllCompilationUnits(new IJavaElement[] {javaElement});
    Object element = javaElement;
    if (allCompilationUnits != null && allCompilationUnits.length == 1)
      element = allCompilationUnits[0];

    fResult.addMatch(
        new Match(element, mutableKeyPosition.getOffset(), mutableKeyPosition.getLength()));
  }
Example #6
0
 /* (non-Javadoc)
  * @see org.eclipse.jdt.core.search.SearchRequestor#acceptSearchMatch(org.eclipse.jdt.core.search.SearchMatch)
  */
 public void acceptSearchMatch(SearchMatch match) {
   IJavaElement enclosingElement = (IJavaElement) match.getElement();
   if ((enclosingElement != null)
       && (packageNames.contains(enclosingElement.getElementName()))) {
     packages.add(enclosingElement);
   }
 }
 IMarker createMarkerFromSearchMatch(IFile file, SearchMatch match) {
   IMarker marker = null;
   try {
     if (CHOICE_METHOD_DECLARATION.equals(mChoice)) {
       HashMap<String, Object> map = new HashMap<String, Object>();
       map.put(IMarker.CHAR_START, new Integer(match.getOffset()));
       map.put(IMarker.CHAR_END, new Integer(match.getOffset() + match.getLength()));
       marker = file.createMarker(IMarker.TEXT);
       marker.setAttributes(map);
     } else if (CHOICE_ERROR_LINE.equals(mChoice)) {
       marker = file.createMarker(IMarker.TEXT);
       marker.setAttribute(IMarker.LINE_NUMBER, mLineNumber);
     }
   } catch (CoreException e) {
     Status s = new Status(Status.ERROR, DdmsPlugin.PLUGIN_ID, e.getMessage(), e);
     DdmsPlugin.getDefault().getLog().log(s);
   }
   return marker;
 }
Example #8
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());
  }
 protected final ReplaceEdit createReplaceEdit(SearchMatch searchResult, ICompilationUnit cu) {
   if (searchResult.isImplicit()) { // handle Annotation Element references, see bug 94062
     StringBuffer sb = new StringBuffer(getNewElementName());
     if (JavaCore.INSERT.equals(
         cu.getJavaProject()
             .getOption(
                 DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_ASSIGNMENT_OPERATOR,
                 true))) sb.append(' ');
     sb.append('=');
     if (JavaCore.INSERT.equals(
         cu.getJavaProject()
             .getOption(
                 DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_ASSIGNMENT_OPERATOR,
                 true))) sb.append(' ');
     return new ReplaceEdit(searchResult.getOffset(), 0, sb.toString());
   } else {
     return new ReplaceEdit(
         searchResult.getOffset(), searchResult.getLength(), getNewElementName());
   }
 }
Example #10
0
 /* (non-Javadoc)
  * @see org.eclipse.jdt.core.search.SearchRequestor#acceptSearchMatch(org.eclipse.jdt.core.search.SearchMatch)
  */
 public void acceptSearchMatch(SearchMatch match) throws CoreException {
   IJavaElement enclosingElement = (IJavaElement) match.getElement();
   if ((enclosingElement != null) && (enclosingElement.getElementType() == IJavaElement.TYPE)) {
     // found type declaration is of one of the types we want
     if (types.contains(enclosingElement.getHandleIdentifier())) {
       // it's in a different package than the from type
       // if (!fromPackage.equals(enclosingElement.getAncestor(IJavaElement.PACKAGE_FRAGMENT))) {
       store.add(enclosingElement.getHandleIdentifier());
       // }
     }
   }
 }
 private static void analyzeChanges(
     ICompilationUnit cu,
     TextChange change,
     SearchMatch[] oldMatches,
     SearchMatch[] newMatches,
     String newElementName,
     RefactoringStatus result) {
   Map<Integer, SearchMatch> updatedOldOffsets = getUpdatedChangeOffsets(change, oldMatches);
   for (int i = 0; i < newMatches.length; i++) {
     SearchMatch newMatch = newMatches[i];
     Integer offsetInNew = new Integer(newMatch.getOffset());
     SearchMatch oldMatch = updatedOldOffsets.remove(offsetInNew);
     if (oldMatch == null) {
       addReferenceShadowedError(cu, newMatch, newElementName, result);
     }
   }
   for (Iterator<SearchMatch> iter = updatedOldOffsets.values().iterator(); iter.hasNext(); ) {
     // remaining old matches are not found any more -> they have been shadowed
     SearchMatch oldMatch = iter.next();
     addShadowsError(cu, oldMatch, result);
   }
 }
 private static ISourceRange getOldSourceRange(SearchMatch newMatch) {
   // cannot transfom offset in preview to offset in original -> just show enclosing method
   IJavaElement newMatchElement = (IJavaElement) newMatch.getElement();
   IJavaElement primaryElement = newMatchElement.getPrimaryElement();
   ISourceRange range = null;
   if (primaryElement.exists() && primaryElement instanceof ISourceReference) {
     try {
       range = ((ISourceReference) primaryElement).getSourceRange();
     } catch (JavaModelException e) {
       // can live without source range
     }
   }
   return range;
 }
  private static boolean existsInNewOccurrences(
      SearchMatch searchResult, SearchResultGroup[] newOccurrences, TextChangeManager manager) {
    SearchResultGroup newGroup = findOccurrenceGroup(searchResult.getResource(), newOccurrences);
    if (newGroup == null) return false;

    IRegion oldEditRange = getCorrespondingEditChangeRange(searchResult, manager);
    if (oldEditRange == null) return false;

    SearchMatch[] newSearchResults = newGroup.getSearchResults();
    int oldRangeOffset = oldEditRange.getOffset();
    for (int i = 0; i < newSearchResults.length; i++) {
      if (newSearchResults[i].getOffset() == oldRangeOffset) return true;
    }
    return false;
  }
 private TextChange canonicalChange(
     CompositeChange composite, Map<IResource, TextChange> changes, SearchMatch match) {
   IResource resource = match.getResource();
   if (resource instanceof IFile) {
     TextChange change = changes.get(resource);
     if (change == null) {
       IFile file = (IFile) resource;
       change = new TextFileChange("Rename", file);
       change.setEdit(new MultiTextEdit());
       changes.put(resource, change);
       composite.add(change);
     }
     return change;
   } else {
     return null;
   }
 }
Example #15
0
 /* (non-Javadoc)
  * @see org.eclipse.jdt.core.search.SearchRequestor#acceptSearchMatch(org.eclipse.jdt.core.search.SearchMatch)
  */
 public void acceptSearchMatch(SearchMatch match) {
   IJavaElement enclosingElement = (IJavaElement) match.getElement();
   try {
     if ((enclosingElement != null)
         && (enclosingElement.getElementType() == IJavaElement.TYPE)) {
       String packName =
           enclosingElement.getAncestor(IJavaElement.PACKAGE_FRAGMENT).getElementName();
       Set deps = new HashSet();
       store.put(enclosingElement.getHandleIdentifier(), deps);
       Set typesInPackage = (Set) packages.get(packName);
       if (typesInPackage == null) {
         typesInPackage = new HashSet();
         packages.put(packName, typesInPackage);
       }
       typesInPackage.add(enclosingElement.getHandleIdentifier());
     }
   } catch (Throwable e) {
     e.printStackTrace();
   }
 }
  @Override
  public void acceptSearchMatch(SearchMatch match) {
    if (fRequireExactMatch && (match.getAccuracy() != SearchMatch.A_ACCURATE)) {
      return;
    }

    if (match.isInsideDocComment()) {
      return;
    }

    if (match.getElement() != null && match.getElement() instanceof IMember) {
      IMember member = (IMember) match.getElement();
      switch (member.getElementType()) {
        case IJavaElement.METHOD:
        case IJavaElement.TYPE:
        case IJavaElement.FIELD:
        case IJavaElement.INITIALIZER:
          fSearchResults.addMember(
              member, member, match.getOffset(), match.getOffset() + match.getLength());
          break;
      }
    }
  }
Example #17
0
 /* (non-Javadoc)
  * @see org.eclipse.jdt.core.search.SearchRequestor#acceptSearchMatch(org.eclipse.jdt.core.search.SearchMatch)
  */
 public void acceptSearchMatch(SearchMatch match) throws CoreException {
   if (match.getAccuracy() == SearchMatch.A_ACCURATE && !match.isInsideDocComment()) {
     fUsed = true;
   }
 }
  /**
   * Add occurrences
   *
   * @param manager the text change manager
   * @param pm the progress monitor
   * @param status the status
   * @throws CoreException if change creation failed
   */
  protected void addOccurrences(
      TextChangeManager manager, IProgressMonitor pm, RefactoringStatus status)
      throws CoreException /*thrown in subtype*/ {
    pm.beginTask("", fOccurrences.length); // $NON-NLS-1$
    for (int i = 0; i < fOccurrences.length; i++) {
      ICompilationUnit cu = fOccurrences[i].getCompilationUnit();
      if (cu == null) continue;

      SearchMatch[] results = fOccurrences[i].getSearchResults();

      // Split matches into declaration and non-declaration matches

      List<SearchMatch> declarationsInThisCu = new ArrayList<>();
      List<SearchMatch> referencesInThisCu = new ArrayList<>();

      for (int j = 0; j < results.length; j++) {
        if (results[j] instanceof MethodDeclarationMatch) declarationsInThisCu.add(results[j]);
        else referencesInThisCu.add(results[j]);
      }

      // First, handle the declarations
      if (declarationsInThisCu.size() > 0) {

        if (fDelegateUpdating) {
          // Update with delegates
          CompilationUnitRewrite rewrite = new CompilationUnitRewrite(cu);
          rewrite.setResolveBindings(true);

          for (Iterator<SearchMatch> iter = declarationsInThisCu.iterator(); iter.hasNext(); ) {
            SearchMatch element = iter.next();
            MethodDeclaration method =
                ASTNodeSearchUtil.getMethodDeclarationNode(
                    (IMethod) element.getElement(), rewrite.getRoot());
            DelegateCreator creator = new DelegateMethodCreator();
            creator.setDeclareDeprecated(fDelegateDeprecation);
            creator.setDeclaration(method);
            creator.setSourceRewrite(rewrite);
            creator.setNewElementName(getNewElementName());
            creator.prepareDelegate();
            creator.createEdit();
          }
          // Need to handle all delegates first as this
          // creates a completely new change object.
          TextChange changeForThisCu = rewrite.createChange(true);
          changeForThisCu.setKeepPreviewEdits(true);
          manager.manage(cu, changeForThisCu);
        }

        // Update the normal methods
        for (Iterator<SearchMatch> iter = declarationsInThisCu.iterator(); iter.hasNext(); ) {
          SearchMatch element = iter.next();
          simpleUpdate(element, cu, manager.get(cu));
        }
      }

      // Second, handle references
      if (fUpdateReferences) {
        for (Iterator<SearchMatch> iter = referencesInThisCu.iterator(); iter.hasNext(); ) {
          SearchMatch element = iter.next();
          simpleUpdate(element, cu, manager.get(cu));
        }
      }

      pm.worked(1);
      if (pm.isCanceled()) throw new OperationCanceledException();
    }
    pm.done();
  }
Example #19
0
 /* (non-Javadoc)
  * @see org.eclipse.jdt.core.search.SearchRequestor#acceptSearchMatch(org.eclipse.jdt.core.search.SearchMatch)
  */
 public void acceptSearchMatch(SearchMatch match) throws CoreException {
   if (!match.isInsideDocComment())
     fMatch =
         new Match(
             match.getElement(), Match.UNIT_CHARACTER, match.getOffset(), match.getLength());
 }
Example #20
0
 private TextEdit createTextChange(SearchMatch match) {
   return new ReplaceEdit(match.getOffset(), match.getLength(), getNewElementName());
 }
 private static IRegion createTextRange(SearchMatch searchResult) {
   return new Region(searchResult.getOffset(), searchResult.getLength());
 }