Java Code Examples for org.eclipse.jdt.core.search.SearchMatch#getElement()

The following examples show how to use org.eclipse.jdt.core.search.SearchMatch#getElement() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MethodReferencesSearchRequestor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@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 2
Source File: RenameMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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()]);
}
 
Example 3
Source File: RippleMethodFinder.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
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);
}
 
Example 4
Source File: RenameMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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()]);
}
 
Example 5
Source File: RenameMethodProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private IMethod[] searchForDeclarationsOfClashingMethods(IProgressMonitor pm) throws CoreException {
	final List<IMethod> results= new ArrayList<>();
	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) {
				results.add((IMethod) method);
			}
			else {
				JavaLanguageServerPlugin.logError("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()]);
}
 
Example 6
Source File: ReferencesInBinaryStatusContextViewer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public void setInput(RefactoringStatusContext input) {
	ContentProvider contentProvider= new ContentProvider();

	ReferencesInBinaryContext binariesContext= (ReferencesInBinaryContext) input;
	List<SearchMatch> matches= binariesContext.getMatches();
	for (Iterator<SearchMatch> iter= matches.iterator(); iter.hasNext();) {
		SearchMatch match= iter.next();
		Object element= match.getElement();
		if (element != null)
			contentProvider.add(element);
	}
	fTreeViewer.setContentProvider(contentProvider);
	fTreeViewer.setInput(contentProvider);

	fLabel.setText(binariesContext.getDescription());

	fInput= binariesContext;
	fButton.setEnabled(!matches.isEmpty());
}
 
Example 7
Source File: TypeSearchRequestor.java    From JDeodorant with MIT License 5 votes vote down vote up
public void acceptSearchMatch(SearchMatch match) throws CoreException {
	Object element = match.getElement();
	if (match.getElement() instanceof IType) {
		IType iType = (IType)element;
		if(!iType.isAnonymous()) {
			subTypes.add(iType);
		}
	}
}
 
Example 8
Source File: NewSearchResultCollector.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void acceptSearchMatch(SearchMatch match) throws CoreException {
	IJavaElement enclosingElement= (IJavaElement) match.getElement();
	if (enclosingElement != null) {
		if (fIgnorePotentials && (match.getAccuracy() == SearchMatch.A_INACCURATE))
			return;
		boolean isWriteAccess= false;
		boolean isReadAccess= false;
		if (match instanceof FieldReferenceMatch) {
			FieldReferenceMatch fieldRef= ((FieldReferenceMatch) match);
			isWriteAccess= fieldRef.isWriteAccess();
			isReadAccess= fieldRef.isReadAccess();
		} else if (match instanceof FieldDeclarationMatch) {
			isWriteAccess= true;
		} else if (match instanceof LocalVariableReferenceMatch) {
			LocalVariableReferenceMatch localVarRef= ((LocalVariableReferenceMatch) match);
			isWriteAccess= localVarRef.isWriteAccess();
			isReadAccess= localVarRef.isReadAccess();
		} else if (match instanceof LocalVariableDeclarationMatch) {
			isWriteAccess= true;
		}
		boolean isSuperInvocation= false;
		if (match instanceof MethodReferenceMatch) {
			MethodReferenceMatch methodRef= (MethodReferenceMatch) match;
			isSuperInvocation= methodRef.isSuperInvocation();
		}
		fSearch.addMatch(new JavaElementMatch(enclosingElement, match.getRule(), match.getOffset(), match.getLength(), match.getAccuracy(), isReadAccess, isWriteAccess, match.isInsideDocComment(), isSuperInvocation));
	}
}
 
Example 9
Source File: RippleMethodFinder2.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void findAllDeclarations(IProgressMonitor monitor, WorkingCopyOwner owner) throws CoreException {
	fDeclarations= new ArrayList<IMethod>();

	class MethodRequestor extends SearchRequestor {
		@Override
		public void acceptSearchMatch(SearchMatch match) throws CoreException {
			IMethod method= (IMethod) match.getElement();
			boolean isBinary= method.isBinary();
			if (fBinaryRefs != null || ! (fExcludeBinaries && isBinary)) {
				fDeclarations.add(method);
			}
			if (isBinary && fBinaryRefs != null) {
				fDeclarationToMatch.put(method, match);
			}
		}
	}

	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);
	SearchParticipant[] participants= SearchUtils.getDefaultSearchParticipants();
	IJavaSearchScope scope= RefactoringScopeFactory.createRelatedProjectsScope(fMethod.getJavaProject(), IJavaSearchScope.SOURCES | IJavaSearchScope.APPLICATION_LIBRARIES | IJavaSearchScope.SYSTEM_LIBRARIES);
	MethodRequestor requestor= new MethodRequestor();
	SearchEngine searchEngine= owner != null ? new SearchEngine(owner) : new SearchEngine();

	searchEngine.search(pattern, participants, scope, requestor, monitor);
}
 
Example 10
Source File: RenameAnalyzeUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
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;
}
 
Example 11
Source File: MemberVisibilityAdjustor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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);
		}
	}
}
 
Example 12
Source File: RenameMethodProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private IType[] searchForOuterTypesOfReferences(IMethod[] newNameMethods, IProgressMonitor pm) throws CoreException {
	final Set<IType> outerTypesOfReferences= new HashSet<>();
	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()]);
}
 
Example 13
Source File: SearchUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @param match
 *            the search match
 * @return the enclosing {@link IJavaElement}, or null iff none
 */
public static IJavaElement getEnclosingJavaElement(SearchMatch match) {
	Object element = match.getElement();
	if (element instanceof IJavaElement) {
		return (IJavaElement) element;
	} else {
		return null;
	}
}
 
Example 14
Source File: ImplementationCollector.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private List<T> findMethodImplementations(IProgressMonitor monitor) throws CoreException {
	IMethod method = (IMethod) javaElement;
	try {
		if (cannotBeOverriddenMethod(method)) {
			return null;
		}
	} catch (JavaModelException e) {
		JavaLanguageServerPlugin.logException("Find method implementations failure ", e);
		return null;
	}

	CompilationUnit ast = CoreASTProvider.getInstance().getAST(typeRoot, CoreASTProvider.WAIT_YES, monitor);
	if (ast == null) {
		return null;
	}

	ASTNode node = NodeFinder.perform(ast, region.getOffset(), region.getLength());
	ITypeBinding parentTypeBinding = null;
	if (node instanceof SimpleName) {
		ASTNode parent = node.getParent();
		if (parent instanceof MethodInvocation) {
			Expression expression = ((MethodInvocation) parent).getExpression();
			if (expression == null) {
				parentTypeBinding= Bindings.getBindingOfParentType(node);
			} else {
				parentTypeBinding = expression.resolveTypeBinding();
			}
		} else if (parent instanceof SuperMethodInvocation) {
			// Directly go to the super method definition
			return Collections.singletonList(mapper.convert(method, 0, 0));
		} else if (parent instanceof MethodDeclaration) {
			parentTypeBinding = Bindings.getBindingOfParentType(node);
		}
	}
	final IType receiverType = getType(parentTypeBinding);
	if (receiverType == null) {
		return null;
	}

	final List<T> results = new ArrayList<>();
	try {
		String methodLabel = JavaElementLabelsCore.getElementLabel(method, JavaElementLabelsCore.DEFAULT_QUALIFIED);
		monitor.beginTask(Messages.format(JavaElementImplementationHyperlink_search_method_implementors, methodLabel), 10);
		SearchRequestor requestor = new SearchRequestor() {
			@Override
			public void acceptSearchMatch(SearchMatch match) throws CoreException {
				if (match.getAccuracy() == SearchMatch.A_ACCURATE) {
					Object element = match.getElement();
					if (element instanceof IMethod) {
						IMethod methodFound = (IMethod) element;
						if (!JdtFlags.isAbstract(methodFound)) {
							T result = mapper.convert(methodFound, match.getOffset(), match.getLength());
							if (result != null) {
								results.add(result);
							}
						}
					}
				}
			}
		};

		IJavaSearchScope hierarchyScope;
		if (receiverType.isInterface()) {
			hierarchyScope = SearchEngine.createHierarchyScope(method.getDeclaringType());
		} else {
			if (isFullHierarchyNeeded(new SubProgressMonitor(monitor, 3), method, receiverType)) {
				hierarchyScope = SearchEngine.createHierarchyScope(receiverType);
			} else {
				boolean isMethodAbstract = JdtFlags.isAbstract(method);
				hierarchyScope = SearchEngine.createStrictHierarchyScope(null, receiverType, true, isMethodAbstract, null);
			}
		}

		int limitTo = IJavaSearchConstants.DECLARATIONS | IJavaSearchConstants.IGNORE_DECLARING_TYPE | IJavaSearchConstants.IGNORE_RETURN_TYPE;
		SearchPattern pattern = SearchPattern.createPattern(method, limitTo);
		Assert.isNotNull(pattern);
		SearchParticipant[] participants = new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() };
		SearchEngine engine = new SearchEngine();
		engine.search(pattern, participants, hierarchyScope, requestor, new SubProgressMonitor(monitor, 7));
		if (monitor.isCanceled()) {
			throw new OperationCanceledException();
		}
	} finally {
		monitor.done();
	}
	return results;
}
 
Example 15
Source File: ResolveClasspathsHandler.java    From java-debug with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Get java project from type.
 *
 * @param fullyQualifiedTypeName
 *            fully qualified name of type
 * @return java project
 * @throws CoreException
 *             CoreException
 */
public static List<IJavaProject> getJavaProjectFromType(String fullyQualifiedTypeName) throws CoreException {
    // If only one Java project exists in the whole workspace, return the project directly.
    List<IJavaProject> javaProjects = JdtUtils.listJavaProjects(ResourcesPlugin.getWorkspace().getRoot());
    if (javaProjects.size() <= 1) {
        return javaProjects;
    }

    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;
    final String className = fullyQualifiedTypeName;
    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 IType) {
                IType type = (IType) element;
                IJavaProject project = type.getJavaProject();
                if (className.equals(type.getFullyQualifiedName())
                        && (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());
}
 
Example 16
Source File: MethodOccurenceCollector.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void acceptSearchMatch(ICompilationUnit unit, SearchMatch match) throws CoreException {
	if (match instanceof MethodReferenceMatch
			&& ((MethodReferenceMatch) match).isSuperInvocation()
			&& match.getAccuracy() == SearchMatch.A_INACCURATE) {
		return; // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=156491
	}

	if (match.isImplicit()) { // see bug 94062
		collectMatch(match);
		return;
	}

	int start= match.getOffset();
	int length= match.getLength();
	String matchText= unit.getBuffer().getText(start, length);

	//direct match:
	if (fName.equals(matchText)) {
		collectMatch(match);
		return;
	}

	// lambda expression
	if (match instanceof MethodDeclarationMatch
			&& match.getElement() instanceof IMethod
			&& ((IMethod) match.getElement()).isLambdaMethod()) {
		// don't touch the lambda
		return;
	}

	//Not a standard reference -- use scanner to find last identifier token before left parenthesis:
	IScanner scanner= getScanner(unit);
	scanner.setSource(matchText.toCharArray());
	int simpleNameStart= -1;
	int simpleNameEnd= -1;
	try {
		int token = scanner.getNextToken();
		while (token != ITerminalSymbols.TokenNameEOF && token != ITerminalSymbols.TokenNameLPAREN) { // reference in code includes arguments in parentheses
			if (token == ITerminalSymbols.TokenNameIdentifier) {
				simpleNameStart= scanner.getCurrentTokenStartPosition();
				simpleNameEnd= scanner.getCurrentTokenEndPosition();
			}
			token = scanner.getNextToken();
		}
	} catch (InvalidInputException e){
		//ignore
	}
	if (simpleNameStart != -1) {
		match.setOffset(start + simpleNameStart);
		match.setLength(simpleNameEnd + 1 - simpleNameStart);
	}
	collectMatch(match);
}
 
Example 17
Source File: MethodOccurenceCollector.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void acceptSearchMatch(ICompilationUnit unit, SearchMatch match) throws CoreException {
	if (match instanceof MethodReferenceMatch
			&& ((MethodReferenceMatch) match).isSuperInvocation()
			&& match.getAccuracy() == SearchMatch.A_INACCURATE) {
		return; // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=156491
	}

	if (match.isImplicit()) { // see bug 94062
		collectMatch(match);
		return;
	}

	int start= match.getOffset();
	int length= match.getLength();
	String matchText= unit.getBuffer().getText(start, length);

	//direct match:
	if (fName.equals(matchText)) {
		collectMatch(match);
		return;
	}

	// lambda expression
	if (match instanceof MethodDeclarationMatch
			&& match.getElement() instanceof IMethod
			&& ((IMethod) match.getElement()).isLambdaMethod()) {
		// don't touch the lambda
		return;
	}

	//Not a standard reference -- use scanner to find last identifier token before left parenthesis:
	IScanner scanner= getScanner(unit);
	scanner.setSource(matchText.toCharArray());
	int simpleNameStart= -1;
	int simpleNameEnd= -1;
	try {
		int token = scanner.getNextToken();
		while (token != ITerminalSymbols.TokenNameEOF && token != ITerminalSymbols.TokenNameLPAREN) { // reference in code includes arguments in parentheses
			if (token == InternalTokenNameIdentifier) {
				simpleNameStart= scanner.getCurrentTokenStartPosition();
				simpleNameEnd= scanner.getCurrentTokenEndPosition();
			}
			token = scanner.getNextToken();
		}
	} catch (InvalidInputException e){
		//ignore
	}
	if (simpleNameStart != -1) {
		match.setOffset(start + simpleNameStart);
		match.setLength(simpleNameEnd + 1 - simpleNameStart);
	}
	collectMatch(match);
}
 
Example 18
Source File: JDTUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public static IJavaElement[] findElementsAtSelection(ITypeRoot unit, int line, int column, PreferenceManager preferenceManager, IProgressMonitor monitor) throws JavaModelException {
	if (unit == null || monitor.isCanceled()) {
		return null;
	}
	int offset = JsonRpcHelpers.toOffset(unit.getBuffer(), line, column);
	if (offset > -1) {
		return unit.codeSelect(offset, 0);
	}
	if (unit instanceof IClassFile) {
		IClassFile classFile = (IClassFile) unit;
		ContentProviderManager contentProvider = JavaLanguageServerPlugin.getContentProviderManager();
		String contents = contentProvider.getSource(classFile, monitor);
		if (contents != null) {
			IDocument document = new Document(contents);
			try {
				offset = document.getLineOffset(line) + column;
				if (offset > -1) {
					String name = parse(contents, offset);
					if (name == null) {
						return null;
					}
					SearchPattern pattern = SearchPattern.createPattern(name, IJavaSearchConstants.TYPE,
							IJavaSearchConstants.DECLARATIONS, SearchPattern.R_FULL_MATCH);

					IJavaSearchScope scope = createSearchScope(unit.getJavaProject(), preferenceManager);

					List<IJavaElement> elements = new ArrayList<>();
					SearchRequestor requestor = new SearchRequestor() {
						@Override
						public void acceptSearchMatch(SearchMatch match) {
							if (match.getElement() instanceof IJavaElement) {
								elements.add((IJavaElement) match.getElement());
							}
						}
					};
					SearchEngine searchEngine = new SearchEngine();
					searchEngine.search(pattern,
							new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, scope,
							requestor, null);
					return elements.toArray(new IJavaElement[0]);
				}
			} catch (BadLocationException | CoreException e) {
				JavaLanguageServerPlugin.logException(e.getMessage(), e);
			}
		}
	}
	return null;
}
 
Example 19
Source File: IntroduceIndirectionRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private RefactoringStatus updateReferences(IProgressMonitor monitor) throws CoreException {

		RefactoringStatus result= new RefactoringStatus();

		monitor.beginTask("", 90); //$NON-NLS-1$

		if (monitor.isCanceled())
			throw new OperationCanceledException();

		IMethod[] ripple= RippleMethodFinder2.getRelatedMethods(fTargetMethod, false, new NoOverrideProgressMonitor(monitor, 10), null);

		if (monitor.isCanceled())
			throw new OperationCanceledException();

		SearchResultGroup[] references= Checks.excludeCompilationUnits(getReferences(ripple, new NoOverrideProgressMonitor(monitor, 10), result), result);

		if (result.hasFatalError())
			return result;

		result.merge(Checks.checkCompileErrorsInAffectedFiles(references));

		if (monitor.isCanceled())
			throw new OperationCanceledException();

		int ticksPerCU= references.length == 0 ? 0 : 70 / references.length;

		for (int i= 0; i < references.length; i++) {
			SearchResultGroup group= references[i];
			SearchMatch[] searchResults= group.getSearchResults();
			CompilationUnitRewrite currentCURewrite= getCachedCURewrite(group.getCompilationUnit());

			for (int j= 0; j < searchResults.length; j++) {

				SearchMatch match= searchResults[j];
				if (match.isInsideDocComment())
					continue;

				IMember enclosingMember= (IMember) match.getElement();
				ASTNode target= getSelectedNode(group.getCompilationUnit(), currentCURewrite.getRoot(), match.getOffset(), match.getLength());

				if (target instanceof SuperMethodInvocation) {
					// Cannot retarget calls to super - add a warning
					result.merge(createWarningAboutCall(enclosingMember, target, RefactoringCoreMessages.IntroduceIndirectionRefactoring_call_warning_super_keyword));
					continue;
				}

				Assert.isTrue(target instanceof MethodInvocation, "Element of call should be a MethodInvocation."); //$NON-NLS-1$

				MethodInvocation invocation= (MethodInvocation) target;
				ITypeBinding typeBinding= getExpressionType(invocation);

				if (fIntermediaryFirstParameterType == null) {
					// no highest type yet
					fIntermediaryFirstParameterType= typeBinding.getTypeDeclaration();
				} else {
					// check if current type is higher
					result.merge(findCommonParent(typeBinding.getTypeDeclaration()));
				}

				if (result.hasFatalError())
					return result;

				// create an edit for this particular call
				result.merge(updateMethodInvocation(invocation, enclosingMember, currentCURewrite));

				// does call see the intermediary method?
				// => increase visibility of the type of the intermediary method.
				result.merge(adjustVisibility(fIntermediaryType, enclosingMember.getDeclaringType(), new NoOverrideProgressMonitor(monitor, 0)));

				if (monitor.isCanceled())
					throw new OperationCanceledException();
			}

			if (!isRewriteKept(group.getCompilationUnit()))
				createChangeAndDiscardRewrite(group.getCompilationUnit());

			monitor.worked(ticksPerCU);
		}

		monitor.done();
		return result;
	}
 
Example 20
Source File: ResolveClasspathsHandler.java    From java-debug with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Try to find the associated java element with the main class from the test folders.
 *
 * @param project the java project containing the main class
 * @param mainClass the main class name
 * @return the associated java element
 */
private static IJavaElement findMainClassInTestFolders(IJavaProject project, String mainClass) {
    if (project == null || StringUtils.isBlank(mainClass)) {
        return null;
    }

    // get a list of test folders and check whether main class is here
    int constraints = IJavaSearchScope.SOURCES;
    IJavaElement[] testFolders = JdtUtils.getTestPackageFragmentRoots(project);
    if (testFolders.length > 0) {
        try {

            List<IJavaElement> mainClassesInTestFolder = new ArrayList<>();
            SearchPattern pattern = SearchPattern.createPattern(mainClass, IJavaSearchConstants.CLASS,
                    IJavaSearchConstants.DECLARATIONS,
                    SearchPattern.R_CASE_SENSITIVE | SearchPattern.R_EXACT_MATCH);
            SearchEngine searchEngine = new SearchEngine();
            IJavaSearchScope scope = SearchEngine.createJavaSearchScope(testFolders, constraints);
            SearchRequestor requestor = new SearchRequestor() {
                @Override
                public void acceptSearchMatch(SearchMatch match) {
                    Object element = match.getElement();
                    if (element instanceof IJavaElement) {
                        mainClassesInTestFolder.add((IJavaElement) element);
                    }
                }
            };

            searchEngine.search(pattern, new SearchParticipant[] {
                        SearchEngine.getDefaultSearchParticipant()
                }, scope, requestor, null /* progress monitor */);

            if (!mainClassesInTestFolder.isEmpty()) {
                return mainClassesInTestFolder.get(0);
            }
        } catch (Exception e) {
            logger.log(Level.SEVERE, String.format("Searching the main class failure: %s", e.toString()), e);
        }
    }

    return null;
}