Java 类org.eclipse.jdt.core.search.SearchMatch 实例源码

项目:gemoc-studio-modeldebugging    文件:PlainK3ExecutionEngine.java   
/**
 * search the bundle that contains the Main class. The search is done in the
 * workspace scope (ie. if it is defined in the current workspace it will
 * find it
 * 
 * @return the name of the bundle containing the Main class or null if not
 *         found
 */
private IType getITypeMainByWorkspaceScope(String className) {
    SearchPattern pattern = SearchPattern.createPattern(className, IJavaSearchConstants.CLASS,
            IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH);
    IJavaSearchScope scope = SearchEngine.createWorkspaceScope();

    final List<IType> binaryType = new ArrayList<IType>();

    SearchRequestor requestor = new SearchRequestor() {
        @Override
        public void acceptSearchMatch(SearchMatch match) throws CoreException {
            binaryType.add((IType) match.getElement());
        }
    };
    SearchEngine engine = new SearchEngine();

    try {
        engine.search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, scope,
                requestor, null);
    } catch (CoreException e1) {
        throw new RuntimeException("Error while searching the bundle: " + e1.getMessage());
        // return new Status(IStatus.ERROR, Activator.PLUGIN_ID, );
    }

    return binaryType.isEmpty() ? null : binaryType.get(0);
}
项目:eclipse.jdt.ls    文件:RippleMethodFinder.java   
private void findAllDeclarations(IProgressMonitor monitor, WorkingCopyOwner owner) throws CoreException {
    fDeclarations = new ArrayList<>();

    class MethodRequestor extends SearchRequestor {
        @Override
        public void acceptSearchMatch(SearchMatch match) throws CoreException {
            IMethod method = (IMethod) match.getElement();
            boolean isBinary = method.isBinary();
            if (!isBinary) {
                fDeclarations.add(method);
            }
        }
    }

    int limitTo = IJavaSearchConstants.DECLARATIONS | IJavaSearchConstants.IGNORE_DECLARING_TYPE | IJavaSearchConstants.IGNORE_RETURN_TYPE;
    int matchRule = SearchPattern.R_ERASURE_MATCH | SearchPattern.R_CASE_SENSITIVE;
    SearchPattern pattern = SearchPattern.createPattern(fMethod, limitTo, matchRule);
    MethodRequestor requestor = new MethodRequestor();
    SearchEngine searchEngine = owner != null ? new SearchEngine(owner) : new SearchEngine();

    searchEngine.search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, createSearchScope(), requestor, monitor);
}
项目:mesfavoris    文件:JavaTypeMemberBookmarkLocationProvider.java   
private List<IType> searchType(String classFQN, IProgressMonitor monitor) {
    classFQN = classFQN.replace('$', '.');
    final List<IType> types = new ArrayList<IType>();

    IJavaSearchScope scope = SearchEngine.createWorkspaceScope();
    SearchEngine engine = new SearchEngine();
    SearchPattern pattern = SearchPattern.createPattern(classFQN, IJavaSearchConstants.TYPE,
            IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH);

    SearchRequestor requestor = new SearchRequestor() {
        public void acceptSearchMatch(final SearchMatch match) throws CoreException {
            TypeDeclarationMatch typeMatch = (TypeDeclarationMatch) match;
            IType type = (IType) typeMatch.getElement();
            types.add(type);
        }
    };
    try {
        engine.search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, scope,
                requestor, monitor);
    } catch (final CoreException e) {
        return types;
    }

    return types;
}
项目:Constants-to-Enum-Eclipse-Plugin    文件:ConvertConstantsToEnumRefactoring.java   
protected void rewriteCompilationUnit(ICompilationUnit unit,
        Collection matches, CompilationUnit node, RefactoringStatus status,
        IProgressMonitor monitor) throws CoreException {
    final ASTRewrite astRewrite = ASTRewrite.create(node.getAST());
    final ImportRewrite importRewrite = ImportRewrite.create(node, true);

    for (final Iterator it = matches.iterator(); it.hasNext();) {
        final SearchMatch match = (SearchMatch) it.next();
        if (match.getAccuracy() == SearchMatch.A_ACCURATE
                && !match.isInsideDocComment())
            if (this.matchToPurposeMap.get(match) == SearchMatchPurpose.ALTER_TYPE_DECLARATION
                    || this.matchToPurposeMap.get(match) == SearchMatchPurpose.ALTER_NAMESPACE_PREFIX)
                this.rewriteDeclarationsAndNamespaces(node, match, status,
                        astRewrite, importRewrite);
            else if (this.matchToPurposeMap.get(match) == SearchMatchPurpose.ALTER_INFIX_EXPRESSION)
                this.rewriteExpressions(node, match, status, astRewrite,
                        importRewrite);
    }

    this.rewriteAST(unit, astRewrite, importRewrite);
}
项目:VRaptorEclipsePlugin    文件:SearchHelper.java   
private static List<Controller> search(IJavaProject project, SearchPattern namePattern) throws JavaModelException, CoreException {
    List<Controller> controllers = new ArrayList<Controller>();

    IJavaSearchScope scope = SearchEngine.createJavaSearchScope(project.getPackageFragments());

    SearchRequestor requestor = new SearchRequestor() {

        @Override
        public void acceptSearchMatch(SearchMatch match) {
            if (match.getElement() instanceof IJavaElement) {
                IJavaElement element = (IJavaElement) match.getElement();
                controllers.add(new Controller((IType) element));
            }
        }

    };

    SearchEngine searchEngine = new SearchEngine();
    searchEngine.search(namePattern, new SearchParticipant[] {SearchEngine
                    .getDefaultSearchParticipant()}, scope, requestor,
                    null);

    return controllers;
}
项目:che    文件:SearchUtils.java   
/**
 * @param match the search match
 * @return the enclosing {@link ICompilationUnit} of the given match, or null iff none
 */
public static ICompilationUnit getCompilationUnit(SearchMatch match) {
  IJavaElement enclosingElement = getEnclosingJavaElement(match);
  if (enclosingElement != null) {
    if (enclosingElement instanceof ICompilationUnit) return (ICompilationUnit) enclosingElement;
    ICompilationUnit cu =
        (ICompilationUnit) enclosingElement.getAncestor(IJavaElement.COMPILATION_UNIT);
    if (cu != null) return cu;
  }

  IJavaElement jElement = JavaCore.create(match.getResource());
  if (jElement != null
      && jElement.exists()
      && jElement.getElementType() == IJavaElement.COMPILATION_UNIT)
    return (ICompilationUnit) jElement;
  return null;
}
项目:che    文件:RenameNonVirtualMethodProcessor.java   
private void addReferenceUpdates(TextChangeManager manager, IProgressMonitor pm) {
  SearchResultGroup[] grouped = getOccurrences();
  for (int i = 0; i < grouped.length; i++) {
    SearchResultGroup group = grouped[i];
    SearchMatch[] results = group.getSearchResults();
    ICompilationUnit cu = group.getCompilationUnit();
    TextChange change = manager.get(cu);
    for (int j = 0; j < results.length; j++) {
      SearchMatch match = results[j];
      if (!(match instanceof MethodDeclarationMatch)) {
        ReplaceEdit replaceEdit = createReplaceEdit(match, cu);
        String editName = RefactoringCoreMessages.RenamePrivateMethodRefactoring_update;
        addTextEdit(change, editName, replaceEdit);
      }
    }
  }
  pm.done();
}
项目:che    文件:RenameMethodProcessor.java   
private IType[] searchForOuterTypesOfReferences(IMethod[] newNameMethods, IProgressMonitor pm)
    throws CoreException {
  final Set<IType> outerTypesOfReferences = new HashSet<IType>();
  SearchPattern pattern =
      RefactoringSearchEngine.createOrPattern(newNameMethods, IJavaSearchConstants.REFERENCES);
  IJavaSearchScope scope = createRefactoringScope(getMethod());
  SearchRequestor requestor =
      new SearchRequestor() {
        @Override
        public void acceptSearchMatch(SearchMatch match) throws CoreException {
          Object element = match.getElement();
          if (!(element instanceof IMember))
            return; // e.g. an IImportDeclaration for a static method import
          IMember member = (IMember) element;
          IType declaring = member.getDeclaringType();
          if (declaring == null) return;
          IType outer = declaring.getDeclaringType();
          if (outer != null) outerTypesOfReferences.add(declaring);
        }
      };
  new SearchEngine()
      .search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor, pm);
  return outerTypesOfReferences.toArray(new IType[outerTypesOfReferences.size()]);
}
项目:che    文件:RenameMethodProcessor.java   
private IMethod[] searchForDeclarationsOfClashingMethods(IProgressMonitor pm)
    throws CoreException {
  final List<IMethod> results = new ArrayList<IMethod>();
  SearchPattern pattern = createNewMethodPattern();
  IJavaSearchScope scope = RefactoringScopeFactory.create(getMethod().getJavaProject());
  SearchRequestor requestor =
      new SearchRequestor() {
        @Override
        public void acceptSearchMatch(SearchMatch match) throws CoreException {
          Object method = match.getElement();
          if (method
              instanceof
              IMethod) // check for bug 90138: [refactoring] [rename] Renaming method throws
            // internal exception
            results.add((IMethod) method);
          else
            JavaPlugin.logErrorMessage(
                "Unexpected element in search match: " + match.toString()); // $NON-NLS-1$
        }
      };
  new SearchEngine()
      .search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor, pm);
  return results.toArray(new IMethod[results.size()]);
}
项目:che    文件:RenameMethodProcessor.java   
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());
  }
}
项目:che    文件:RenameTypeProcessor.java   
private void addReferenceUpdates(TextChangeManager manager, IProgressMonitor pm) {
  pm.beginTask("", fReferences.length); // $NON-NLS-1$
  for (int i = 0; i < fReferences.length; i++) {
    ICompilationUnit cu = fReferences[i].getCompilationUnit();
    if (cu == null) continue;

    String name = RefactoringCoreMessages.RenameTypeRefactoring_update_reference;
    SearchMatch[] results = fReferences[i].getSearchResults();

    for (int j = 0; j < results.length; j++) {
      SearchMatch match = results[j];
      ReplaceEdit replaceEdit =
          new ReplaceEdit(match.getOffset(), match.getLength(), getNewElementName());
      TextChangeCompatibility.addTextEdit(
          manager.get(cu), name, replaceEdit, CATEGORY_TYPE_RENAME);
    }
    pm.worked(1);
  }
}
项目:che    文件:RenameAnalyzeUtil.java   
static RefactoringStatus analyzeRenameChanges(
    TextChangeManager manager,
    SearchResultGroup[] oldOccurrences,
    SearchResultGroup[] newOccurrences) {
  RefactoringStatus result = new RefactoringStatus();
  for (int i = 0; i < oldOccurrences.length; i++) {
    SearchResultGroup oldGroup = oldOccurrences[i];
    SearchMatch[] oldSearchResults = oldGroup.getSearchResults();
    ICompilationUnit cunit = oldGroup.getCompilationUnit();
    if (cunit == null) continue;
    for (int j = 0; j < oldSearchResults.length; j++) {
      SearchMatch oldSearchResult = oldSearchResults[j];
      if (!RenameAnalyzeUtil.existsInNewOccurrences(oldSearchResult, newOccurrences, manager)) {
        addShadowsError(cunit, oldSearchResult, result);
      }
    }
  }
  return result;
}
项目:che    文件:RenameAnalyzeUtil.java   
private static void addReferenceShadowedError(
    ICompilationUnit cu, SearchMatch newMatch, String newElementName, RefactoringStatus result) {
  // Found a new match with no corresponding old match.
  // -> The new match is a reference which was pointing to another element,
  // but that other element has been shadowed

  // TODO: should not have to filter declarations:
  if (newMatch instanceof MethodDeclarationMatch || newMatch instanceof FieldDeclarationMatch)
    return;
  ISourceRange range = getOldSourceRange(newMatch);
  RefactoringStatusContext context = JavaStatusContext.create(cu, range);
  String message =
      Messages.format(
          RefactoringCoreMessages.RenameAnalyzeUtil_reference_shadowed,
          new String[] {
            BasicElementLabels.getFileName(cu),
            BasicElementLabels.getJavaElementName(newElementName)
          });
  result.addError(message, context);
}
项目:datahierarchy    文件:AbstractReferencesRequestor.java   
public List<V> getResults() {
    while (!isDone) {
        synchronized (this) {
            try {
                wait(50);
            } catch (InterruptedException e) {
                DataHierarchyPlugin.logError("getResults() interrupted...", e);
            }
        }
    }
    List<V> results = new ArrayList<V>();
    for (SearchMatch match : searchResults) {
        results.add((V) match.getElement());
    }
    return results;
}
项目:che    文件:RippleMethodFinder2.java   
private IMethod[] getAllRippleMethods(IProgressMonitor pm, WorkingCopyOwner owner)
    throws CoreException {
  IMethod[] rippleMethods = findAllRippleMethods(pm, owner);
  if (fDeclarationToMatch == null) return rippleMethods;

  List<IMethod> rippleMethodsList = new ArrayList<IMethod>(Arrays.asList(rippleMethods));
  for (Iterator<IMethod> iter = rippleMethodsList.iterator(); iter.hasNext(); ) {
    Object match = fDeclarationToMatch.get(iter.next());
    if (match != null) {
      iter.remove();
      fBinaryRefs.add((SearchMatch) match);
    }
  }
  fDeclarationToMatch = null;
  return rippleMethodsList.toArray(new IMethod[rippleMethodsList.size()]);
}
项目:che    文件:RenamePackageProcessor.java   
/**
 * Add new imports to types in <code>typeReferences</code> with package <code>fPackage</code>.
 *
 * @param typeReferences type references
 * @throws CoreException should not happen
 */
private void addTypeImports(SearchResultGroup typeReferences) throws CoreException {
  SearchMatch[] searchResults = typeReferences.getSearchResults();
  for (int i = 0; i < searchResults.length; i++) {
    SearchMatch result = searchResults[i];
    IJavaElement enclosingElement = SearchUtils.getEnclosingJavaElement(result);
    if (!(enclosingElement instanceof IImportDeclaration)) {
      String reference = getNormalizedTypeReference(result);
      if (!reference.startsWith(fPackage.getElementName())) {
        // is unqualified
        reference = cutOffInnerTypes(reference);
        ImportChange importChange =
            fImportsManager.getImportChange(typeReferences.getCompilationUnit());
        importChange.addImport(fPackage.getElementName() + '.' + reference);
      }
    }
  }
}
项目:che    文件:RenamePackageProcessor.java   
/**
 * Add new imports to types in <code>typeReferences</code> with package <code>fNewElementName
 * </code> and remove old import with <code>fPackage</code>.
 *
 * @param typeReferences type references
 * @throws CoreException should not happen
 */
private void updateTypeImports(SearchResultGroup typeReferences) throws CoreException {
  SearchMatch[] searchResults = typeReferences.getSearchResults();
  for (int i = 0; i < searchResults.length; i++) {
    SearchMatch result = searchResults[i];
    IJavaElement enclosingElement = SearchUtils.getEnclosingJavaElement(result);
    if (enclosingElement instanceof IImportDeclaration) {
      IImportDeclaration importDeclaration = (IImportDeclaration) enclosingElement;
      updateImport(
          typeReferences.getCompilationUnit(),
          importDeclaration,
          getUpdatedImport(importDeclaration));
    } else {
      String reference = getNormalizedTypeReference(result);
      if (!reference.startsWith(fPackage.getElementName())) {
        reference = cutOffInnerTypes(reference);
        ImportChange importChange =
            fImportsManager.getImportChange(typeReferences.getCompilationUnit());
        importChange.removeImport(fPackage.getElementName() + '.' + reference);
        importChange.addImport(getNewPackageName() + '.' + reference);
      } // else: already found & updated with package reference search
    }
  }
}
项目:che    文件:RefactoringSearchEngine2.java   
@Override
public final void acceptSearchMatch(final SearchMatch match) throws CoreException {
  final SearchMatch accepted = fRequestor.acceptSearchMatch(match);
  if (accepted != null) {
    final IResource resource = accepted.getResource();
    if (!resource.equals(fLastResource)) {
      final IJavaElement element = JavaCore.create(resource);
      if (element instanceof ICompilationUnit) fCollectedUnits.add((ICompilationUnit) element);
    }
    if (fInaccurate
        && accepted.getAccuracy() == SearchMatch.A_INACCURATE
        && !fInaccurateMatches.contains(accepted)) {
      fStatus.addEntry(
          fSeverity,
          Messages.format(
              RefactoringCoreMessages.RefactoringSearchEngine_inaccurate_match,
              BasicElementLabels.getResourceName(accepted.getResource())),
          null,
          null,
          RefactoringStatusEntry.NO_CODE);
      fInaccurateMatches.add(accepted);
    }
  }
}
项目:che    文件:InlineConstantRefactoring.java   
private SearchResultGroup[] findReferences(IProgressMonitor pm, RefactoringStatus status)
    throws JavaModelException {
  final RefactoringSearchEngine2 engine =
      new RefactoringSearchEngine2(
          SearchPattern.createPattern(fField, IJavaSearchConstants.REFERENCES));
  engine.setFiltering(true, true);
  engine.setScope(RefactoringScopeFactory.create(fField));
  engine.setStatus(status);
  engine.setRequestor(
      new IRefactoringSearchRequestor() {
        public SearchMatch acceptSearchMatch(SearchMatch match) {
          return match.isInsideDocComment() ? null : match;
        }
      });
  engine.searchPattern(new SubProgressMonitor(pm, 1));
  return (SearchResultGroup[]) engine.getResults();
}
项目:che    文件:SearchResultGroup.java   
@Override
public String toString() {
  StringBuffer buf = new StringBuffer(fResouce.getFullPath().toString());
  buf.append('\n');
  for (int i = 0; i < fSearchMatches.size(); i++) {
    SearchMatch match = fSearchMatches.get(i);
    buf.append("  ")
        .append(match.getOffset())
        .append(", ")
        .append(match.getLength()); // $NON-NLS-1$//$NON-NLS-2$
    buf.append(
        match.getAccuracy() == SearchMatch.A_ACCURATE
            ? "; acc"
            : "; inacc"); // $NON-NLS-1$//$NON-NLS-2$
    if (match.isInsideDocComment()) buf.append("; inDoc"); // $NON-NLS-1$
    if (match.getElement() instanceof IJavaElement)
      buf.append("; in: ")
          .append(((IJavaElement) match.getElement()).getElementName()); // $NON-NLS-1$
    buf.append('\n');
  }
  return buf.toString();
}
项目:java-debug    文件:ResolveClasspathsHandler.java   
/**
 * Get java project from type.
 *
 * @param fullyQualifiedTypeName
 *            fully qualified name of type
 * @return java project
 * @throws CoreException
 *             CoreException
 */
private static List<IJavaProject> getJavaProjectFromType(String fullyQualifiedTypeName) throws CoreException {
    String[] splitItems = fullyQualifiedTypeName.split("/");
    // If the main class name contains the module name, should trim the module info.
    if (splitItems.length == 2) {
        fullyQualifiedTypeName = splitItems[1];
    }
    final String moduleName = splitItems.length == 2 ? splitItems[0] : null;

    SearchPattern pattern = SearchPattern.createPattern(
            fullyQualifiedTypeName,
            IJavaSearchConstants.TYPE,
            IJavaSearchConstants.DECLARATIONS,
            SearchPattern.R_EXACT_MATCH);
    IJavaSearchScope scope = SearchEngine.createWorkspaceScope();
    ArrayList<IJavaProject> projects = new ArrayList<>();
    SearchRequestor requestor = new SearchRequestor() {
        @Override
        public void acceptSearchMatch(SearchMatch match) {
            Object element = match.getElement();
            if (element instanceof IJavaElement) {
                IJavaProject project = ((IJavaElement) element).getJavaProject();
                if (moduleName == null || moduleName.equals(JdtUtils.getModuleName(project))) {
                    projects.add(project);
                }
            }
        }
    };
    SearchEngine searchEngine = new SearchEngine();
    searchEngine.search(pattern, new SearchParticipant[] {
        SearchEngine.getDefaultSearchParticipant() }, scope,
        requestor, null /* progress monitor */);

    return projects.stream().distinct().collect(Collectors.toList());
}
项目:ClassCleaner    文件:SearchReferenceCollector.java   
@Override
public void acceptSearchMatch(SearchMatch match) throws CoreException {
    if (match instanceof ReferenceMatch) {
        references.add(getJavaElement((ReferenceMatch) match));
    }

}
项目:eclipse.jdt.ls    文件:RenameProcessor.java   
public void renameOccurrences(WorkspaceEdit edit, String newName, IProgressMonitor monitor) throws CoreException {
    if (fElement == null || !canRename()) {
        return;
    }

    IJavaElement[] elementsToSearch = null;

    if (fElement instanceof IMethod) {
        elementsToSearch = RippleMethodFinder.getRelatedMethods((IMethod) fElement, monitor, null);
    } else {
        elementsToSearch = new IJavaElement[] { fElement };
    }

    SearchPattern pattern = createOccurrenceSearchPattern(elementsToSearch);
    if (pattern == null) {
        return;
    }
    SearchEngine engine = new SearchEngine();
    engine.search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, createSearchScope(), new SearchRequestor() {

        @Override
        public void acceptSearchMatch(SearchMatch match) throws CoreException {
            Object o = match.getElement();
            if (o instanceof IJavaElement) {
                IJavaElement element = (IJavaElement) o;
                ICompilationUnit compilationUnit = (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT);
                if (compilationUnit == null) {
                    return;
                }
                TextEdit replaceEdit = collectMatch(match, element, compilationUnit, newName);
                if (replaceEdit != null) {
                    convert(edit, compilationUnit, replaceEdit);
                }
            }
        }
    }, monitor);

}
项目:Migrate-Skeletal-Implementation-to-Interface-Refactoring    文件:EvaluateMigrateSkeletalImplementationToInterfaceRefactoringHandler.java   
private Set<SearchMatch> findReferences(Set<? extends IJavaElement> elements) throws CoreException {
    Set<SearchMatch> ret = new HashSet<>();
    for (IJavaElement elem : elements)
        new SearchEngine().search(
                SearchPattern.createPattern(elem, IJavaSearchConstants.REFERENCES, SearchPattern.R_EXACT_MATCH),
                new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() },
                SearchEngine.createWorkspaceScope(), new SearchRequestor() {

                    @Override
                    public void acceptSearchMatch(SearchMatch match) throws CoreException {
                        ret.add(match);
                    }
                }, new NullProgressMonitor());
    return ret;
}
项目:Constants-to-Enum-Eclipse-Plugin    文件:ConvertConstantsToEnumRefactoring.java   
void commenceSearch(SearchEngine engine, SearchPattern pattern,
        IJavaSearchScope scope, final SearchMatchPurpose purpose,
        IProgressMonitor monitor) throws CoreException {
    engine.search(pattern, new SearchParticipant[] { SearchEngine
            .getDefaultSearchParticipant() }, scope, new SearchRequestor() {

        public void acceptSearchMatch(SearchMatch match)
                throws CoreException {
            if (match.getAccuracy() == SearchMatch.A_ACCURATE
                    && !match.isInsideDocComment())
                matchToPurposeMap.put(match, purpose);
        }
    }, new SubProgressMonitor(monitor, 1,
            SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
}
项目:Constants-to-Enum-Eclipse-Plugin    文件:ConvertConstantsToEnumRefactoring.java   
private void rewriteExpressions(CompilationUnit node, SearchMatch match,
        RefactoringStatus status, ASTRewrite astRewrite,
        ImportRewrite importRewrite) {
    final ASTNode result = NodeFinder.perform(node, match.getOffset(),
            match.getLength());
    final InfixExpression ie = Util.getInfixExpression(result);
    if (ie == null) // there is none.
        return;
    else if (Util.inNeedOfTransformation(ie.getOperator())) {
        // Get the fully qualified type name.
        final String fqn = this.getFullyQualifiedName(((Name) result)
                .resolveBinding().getJavaElement());
        this.rewriteInfixExpression(astRewrite, importRewrite, ie, fqn);
    }
}
项目:Constants-to-Enum-Eclipse-Plugin    文件:Util.java   
public static ASTNode getExactASTNode(CompilationUnit root,
        final SearchMatch match) {
    final ArrayList ret = new ArrayList(1);
    final ASTVisitor visitor = new ASTVisitor() {
        public void preVisit(ASTNode node) {
            if (node.getStartPosition() == match.getOffset()) {
                ret.clear();
                ret.add(node);
            }
        }
    };
    root.accept(visitor);
    return (ASTNode) ret.get(0);
}
项目:Constants-to-Enum-Eclipse-Plugin    文件:Util.java   
public static ASTNode getExactASTNode(IJavaElement elem,
        final SearchMatch match, IProgressMonitor monitor) {
    final IMember mem = getIMember(elem);
    final CompilationUnit root = Util.getCompilationUnit(mem
            .getCompilationUnit(), monitor);
    return getExactASTNode(root, match);
}
项目:Constants-to-Enum-Eclipse-Plugin    文件:ASTNodeProcessor.java   
private void findParameters(final int paramNumber, SearchPattern pattern)
        throws CoreException {

    final SearchRequestor requestor = new SearchRequestor() {

        public void acceptSearchMatch(SearchMatch match)
                throws CoreException {
            if (match.getAccuracy() == SearchMatch.A_ACCURATE
                    && !match.isInsideDocComment()) {
                IJavaElement elem = (IJavaElement) match.getElement();
                ASTNode node = Util.getASTNode(elem,
                        ASTNodeProcessor.this.monitor);
                ParameterProcessingVisitor visitor = new ParameterProcessingVisitor(
                        paramNumber, match.getOffset());
                node.accept(visitor);
                ASTNodeProcessor.this.found.addAll(visitor.getElements());

                for (Iterator it = visitor.getExpressions().iterator(); it
                        .hasNext();) {
                    Expression exp = (Expression) it.next();
                    ASTNodeProcessor.this.processExpression(exp);
                }
            }
        }
    };

    final SearchEngine searchEngine = new SearchEngine();
    searchEngine.search(pattern, new SearchParticipant[] { SearchEngine
            .getDefaultSearchParticipant() }, this.scope, requestor, null);
}
项目:che    文件:MemberVisibilityAdjustor.java   
/**
 * Check whether anyone accesses the members of the moved type from the outside. Those may need to
 * have their visibility adjusted.
 *
 * @param member the member
 * @param monitor the progress monitor to use
 * @throws JavaModelException if an error occurs
 */
private void adjustMemberVisibility(final IMember member, final IProgressMonitor monitor)
    throws JavaModelException {

  if (member instanceof IType) {
    // recursively check accessibility of member type's members
    final IJavaElement[] typeMembers = ((IType) member).getChildren();
    for (int i = 0; i < typeMembers.length; i++) {
      if (!(typeMembers[i] instanceof IInitializer))
        adjustMemberVisibility((IMember) typeMembers[i], monitor);
    }
  }

  if (member.equals(fReferenced) || Modifier.isPublic(member.getFlags())) return;

  final SearchResultGroup[] references = findReferences(member, monitor);
  for (int i = 0; i < references.length; i++) {
    final SearchMatch[] searchResults = references[i].getSearchResults();
    for (int k = 0; k < searchResults.length; k++) {
      final IJavaElement referenceToMember = (IJavaElement) searchResults[k].getElement();
      if (fAdjustments.get(member) == null
          && referenceToMember instanceof IMember
          && !isInsideMovedMember(referenceToMember)) {
        // check whether the member is still visible from the
        // destination. As we are moving a type, the destination is
        // a package or another type.
        adjustIncomingVisibility(fReferencing, member, new SubProgressMonitor(monitor, 1));
      }
    }
  }
}
项目:che    文件:MemberVisibilityAdjustor.java   
/**
 * Adjusts the visibility of the member based on the incoming references represented by the
 * specified search result groups.
 *
 * <p>If there is at least one reference to the moved element from outside the moved element,
 * visibility must be increased such that the moved element (fReferenced) is still visible at the
 * target from all references. This effectively means that the old element (fReferenced) must be
 * visible from the new location (fReferencing).
 *
 * @param groups the search result groups representing the references
 * @param monitor the progress monitor to use
 * @throws JavaModelException if the java elements could not be accessed
 */
private void adjustIncomingVisibility(
    final SearchResultGroup[] groups, final IProgressMonitor monitor) throws JavaModelException {
  try {
    monitor.beginTask("", groups.length); // $NON-NLS-1$
    monitor.setTaskName(RefactoringCoreMessages.MemberVisibilityAdjustor_checking);
    SearchMatch[] matches = null;
    boolean adjusted = false;
    for (int index = 0; index < groups.length; index++) {
      matches = groups[index].getSearchResults();
      for (int offset = 0; offset < matches.length; offset++) {
        final Object element = matches[offset].getElement();
        if (element instanceof IMember && !isInsideMovedMember((IMember) element)) {
          // found one reference which is not inside the moved
          // element => adjust visibility of the moved element
          adjustIncomingVisibility(fReferencing, fReferenced, monitor);
          adjusted = true; // one adjustment is enough
          break;
        }
      }
      if (adjusted) break;
      monitor.worked(1);
    }
  } finally {
    monitor.done();
  }
}
项目:che    文件:MemberVisibilityAdjustor.java   
/**
 * Adjusts the visibilities of the referenced element from the search match found in a compilation
 * unit.
 *
 * @param match the search match representing the element declaration
 * @param monitor the progress monitor to use
 * @throws JavaModelException if the visibility could not be determined
 */
private void adjustOutgoingVisibility(final SearchMatch match, final IProgressMonitor monitor)
    throws JavaModelException {
  final Object element = match.getElement();
  if (element instanceof IMember) {
    final IMember member = (IMember) element;
    if (!member.isBinary() && !member.isReadOnly() && !isInsideMovedMember(member)) {
      adjustOutgoingVisibilityChain(member, monitor);
    }
  }
}
项目:che    文件:MemberVisibilityAdjustor.java   
/**
 * Adjusts the visibilities of the outgoing references from the member represented by the
 * specified search result groups.
 *
 * @param groups the search result groups representing the references
 * @param monitor the progress monitor to us
 * @throws JavaModelException if the visibility could not be determined
 */
private void adjustOutgoingVisibility(
    final SearchResultGroup[] groups, final IProgressMonitor monitor) throws JavaModelException {
  try {
    monitor.beginTask("", groups.length); // $NON-NLS-1$
    monitor.setTaskName(RefactoringCoreMessages.MemberVisibilityAdjustor_checking);
    IJavaElement element = null;
    SearchMatch[] matches = null;
    SearchResultGroup group = null;
    for (int index = 0; index < groups.length; index++) {
      group = groups[index];
      element = JavaCore.create(group.getResource());
      if (element instanceof ICompilationUnit) {
        matches = group.getSearchResults();
        for (int offset = 0; offset < matches.length; offset++)
          adjustOutgoingVisibility(matches[offset], new SubProgressMonitor(monitor, 1));
      } // else if (element != null)
      // fStatus.merge(RefactoringStatus.createStatus(fFailureSeverity,
      // RefactoringCoreMessages.getFormattedString
      // ("MemberVisibilityAdjustor.binary.outgoing.project", new String[] {
      // element.getJavaProject().getElementName(), getLabel
      // (fReferenced)}), null, null, RefactoringStatusEntry.NO_CODE, null)); //$NON-NLS-1$
      // else if (group.getResource() != null)
      // fStatus.merge(RefactoringStatus.createStatus(fFailureSeverity,
      // RefactoringCoreMessages.getFormattedString
      // ("MemberVisibilityAdjustor.binary.outgoing.resource", new String[] {
      // group.getResource().getName(), getLabel
      // (fReferenced)}), null, null, RefactoringStatusEntry.NO_CODE, null)); //$NON-NLS-1$

      // TW: enable when bug 78387 is fixed

      monitor.worked(1);
    }
  } finally {
    monitor.done();
  }
}
项目:che    文件:ReferenceFinderUtil.java   
public static IType[] getTypesReferencedIn(
    IJavaElement[] elements, WorkingCopyOwner owner, IProgressMonitor pm)
    throws JavaModelException {
  SearchMatch[] results = getTypeReferencesIn(elements, owner, pm);
  Set<IJavaElement> referencedTypes = extractElements(results, IJavaElement.TYPE);
  return referencedTypes.toArray(new IType[referencedTypes.size()]);
}
项目:che    文件:ReferenceFinderUtil.java   
private static SearchMatch[] getTypeReferencesIn(
    IJavaElement[] elements, WorkingCopyOwner owner, IProgressMonitor pm)
    throws JavaModelException {

  List<SearchMatch> referencedTypes = new ArrayList<SearchMatch>();
  pm.beginTask("", elements.length); // $NON-NLS-1$
  for (int i = 0; i < elements.length; i++) {
    referencedTypes.addAll(
        getTypeReferencesIn(elements[i], owner, new SubProgressMonitor(pm, 1)));
  }
  pm.done();
  return referencedTypes.toArray(new SearchMatch[referencedTypes.size()]);
}
项目:che    文件:ReferenceFinderUtil.java   
public static IField[] getFieldsReferencedIn(
    IJavaElement[] elements, WorkingCopyOwner owner, IProgressMonitor pm)
    throws JavaModelException {
  SearchMatch[] results = getFieldReferencesIn(elements, owner, pm);
  Set<IJavaElement> referencedFields = extractElements(results, IJavaElement.FIELD);
  return referencedFields.toArray(new IField[referencedFields.size()]);
}
项目:che    文件:ReferenceFinderUtil.java   
private static SearchMatch[] getFieldReferencesIn(
    IJavaElement[] elements, WorkingCopyOwner owner, IProgressMonitor pm)
    throws JavaModelException {
  List<SearchMatch> referencedFields = new ArrayList<SearchMatch>();
  pm.beginTask("", elements.length); // $NON-NLS-1$
  for (int i = 0; i < elements.length; i++) {
    referencedFields.addAll(
        getFieldReferencesIn(elements[i], owner, new SubProgressMonitor(pm, 1)));
  }
  pm.done();
  return referencedFields.toArray(new SearchMatch[referencedFields.size()]);
}
项目:che    文件:ReferenceFinderUtil.java   
private static List<SearchMatch> getFieldReferencesIn(
    IJavaElement element, WorkingCopyOwner owner, IProgressMonitor pm) throws JavaModelException {
  CollectingSearchRequestor requestor = new CollectingSearchRequestor();
  SearchEngine engine = owner != null ? new SearchEngine(owner) : new SearchEngine();
  engine.searchDeclarationsOfAccessedFields(element, requestor, pm);
  return requestor.getResults();
}
项目:che    文件:ReferenceFinderUtil.java   
public static IMethod[] getMethodsReferencedIn(
    IJavaElement[] elements, WorkingCopyOwner owner, IProgressMonitor pm)
    throws JavaModelException {
  SearchMatch[] results = getMethodReferencesIn(elements, owner, pm);
  Set<IJavaElement> referencedMethods = extractElements(results, IJavaElement.METHOD);
  return referencedMethods.toArray(new IMethod[referencedMethods.size()]);
}
项目:che    文件:ReferenceFinderUtil.java   
private static SearchMatch[] getMethodReferencesIn(
    IJavaElement[] elements, WorkingCopyOwner owner, IProgressMonitor pm)
    throws JavaModelException {
  List<SearchMatch> referencedMethods = new ArrayList<SearchMatch>();
  pm.beginTask("", elements.length); // $NON-NLS-1$
  for (int i = 0; i < elements.length; i++) {
    referencedMethods.addAll(
        getMethodReferencesIn(elements[i], owner, new SubProgressMonitor(pm, 1)));
  }
  pm.done();
  return referencedMethods.toArray(new SearchMatch[referencedMethods.size()]);
}