org.eclipse.jdt.core.search.IJavaSearchScope Java Examples

The following examples show how to use org.eclipse.jdt.core.search.IJavaSearchScope. 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: ProblemSeveritiesConfigurationBlock.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void doBrowseTypes(StringButtonDialogField dialogField) {
	IRunnableContext context= new BusyIndicatorRunnableContext();
	IJavaSearchScope scope= SearchEngine.createWorkspaceScope();
	int style= IJavaElementSearchConstants.CONSIDER_ANNOTATION_TYPES;
	try {
		SelectionDialog dialog= JavaUI.createTypeDialog(getShell(), context, scope, style, false, dialogField.getText());
		dialog.setTitle(PreferencesMessages.NullAnnotationsConfigurationDialog_browse_title);
		dialog.setMessage(PreferencesMessages.NullAnnotationsConfigurationDialog_choose_annotation);
		if (dialog.open() == Window.OK) {
			IType res= (IType) dialog.getResult()[0];
			dialogField.setText(res.getFullyQualifiedName('.'));
		}
	} catch (JavaModelException e) {
		ExceptionHandler.handle(e, getShell(), PreferencesMessages.NullAnnotationsConfigurationDialog_error_title, PreferencesMessages.NullAnnotationsConfigurationDialog_error_message);
	}
}
 
Example #2
Source File: MultiMainTypeSelectionDialog.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Constructor.
 */
public MultiMainTypeSelectionDialog(Shell shell, IRunnableContext context,
	IJavaSearchScope scope, int style)
{
	super(shell, new JavaElementLabelProvider(
		JavaElementLabelProvider.SHOW_PARAMETERS | JavaElementLabelProvider.SHOW_POST_QUALIFIED | JavaElementLabelProvider.SHOW_ROOT));

	setMultipleSelection(true);

	Assert.isNotNull(context);
	Assert.isNotNull(scope);

	fRunnableContext= context;
	fScope= scope;
	fStyle= style;
}
 
Example #3
Source File: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Searches for references to the original method.
 *
 * @param monitor
 *            the progress monitor to use
 * @param status
 *            the refactoring status to use
 * @return the array of search result groups
 * @throws CoreException
 *             if an error occurred during search
 */
protected SearchResultGroup[] computeMethodReferences(final IProgressMonitor monitor, final RefactoringStatus status) throws CoreException {
	Assert.isNotNull(monitor);
	Assert.isNotNull(status);
	try {
		monitor.beginTask("", 1); //$NON-NLS-1$
		monitor.setTaskName(RefactoringCoreMessages.MoveInstanceMethodProcessor_checking);
		SearchPattern pattern= SearchPattern.createPattern(fMethod, IJavaSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
		IJavaSearchScope scope= RefactoringScopeFactory.create(fMethod, true, false);

		String binaryRefsDescription= Messages.format(RefactoringCoreMessages.ReferencesInBinaryContext_ref_in_binaries_description , BasicElementLabels.getJavaElementName(fMethod.getElementName()));
		ReferencesInBinaryContext binaryRefs= new ReferencesInBinaryContext(binaryRefsDescription);
		CollectingSearchRequestor requestor= new CollectingSearchRequestor(binaryRefs);
		SearchResultGroup[] result= RefactoringSearchEngine.search(pattern, scope, requestor, new SubProgressMonitor(monitor, 1), status);
		binaryRefs.addErrorIfNecessary(status);

		return result;
	} finally {
		monitor.done();
	}
}
 
Example #4
Source File: TypeInfoFilter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public TypeInfoFilter(String text, IJavaSearchScope scope, int elementKind, ITypeInfoFilterExtension extension) {
	fText= text;
	fSearchScope= scope;
	fIsWorkspaceScope= fSearchScope.equals(SearchEngine.createWorkspaceScope());
	fElementKind= elementKind;
	fFilterExtension= extension;

	int index= text.lastIndexOf("."); //$NON-NLS-1$
	if (index == -1) {
		fNameMatcher= new PatternMatcher(text);
		fPackageMatcher= null;
	} else {
		fPackageMatcher= new PatternMatcher(evaluatePackagePattern(text.substring(0, index)));
		String name= text.substring(index + 1);
		if (name.length() == 0)
			name= "*"; //$NON-NLS-1$
		fNameMatcher= new PatternMatcher(name);
	}
}
 
Example #5
Source File: RenamePackageProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private List<SearchResultGroup> getReferencesToTypesInPackage(IProgressMonitor pm, ReferencesInBinaryContext binaryRefs, RefactoringStatus status) throws CoreException {
	pm.beginTask("", 2); //$NON-NLS-1$
	IJavaSearchScope referencedFromNamesakesScope= RefactoringScopeFactory.create(fPackage, true, false);
	IPackageFragment[] namesakePackages= getNamesakePackages(referencedFromNamesakesScope, new SubProgressMonitor(pm, 1));
	if (namesakePackages.length == 0) {
		pm.done();
		return new ArrayList<SearchResultGroup>(0);
	}

	IJavaSearchScope scope= SearchEngine.createJavaSearchScope(namesakePackages);
	IType[] typesToSearch= getTypesInPackage(fPackage);
	if (typesToSearch.length == 0) {
		pm.done();
		return new ArrayList<SearchResultGroup>(0);
	}
	SearchPattern pattern= RefactoringSearchEngine.createOrPattern(typesToSearch, IJavaSearchConstants.REFERENCES);
	CollectingSearchRequestor requestor= new CuCollectingSearchRequestor(binaryRefs);
	SearchResultGroup[] results= RefactoringSearchEngine.search(pattern, scope, requestor, new SubProgressMonitor(pm, 1), status);
	pm.done();
	return new ArrayList<SearchResultGroup>(Arrays.asList(results));
}
 
Example #6
Source File: InteractiveUnresolvedTypeResolver.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected void findCandidateTypes(final JvmDeclaredType contextType, final String typeSimpleName,
		IJavaSearchScope searchScope, final IAcceptor<JvmDeclaredType> acceptor) throws JavaModelException {
	BasicSearchEngine searchEngine = new BasicSearchEngine();
	final IVisibilityHelper contextualVisibilityHelper = new ContextualVisibilityHelper(visibilityHelper, contextType);
	searchEngine.searchAllTypeNames(null, SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE, typeSimpleName.toCharArray(),
			SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE, IJavaSearchConstants.TYPE, searchScope,
			new IRestrictedAccessTypeRequestor() {
				@Override
				public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName,
						char[][] enclosingTypeNames, String path, AccessRestriction access) {
					final String qualifiedTypeName = getQualifiedTypeName(packageName, enclosingTypeNames,
							simpleTypeName);
					if ((access == null
							|| (access.getProblemId() != IProblem.ForbiddenReference && !access.ignoreIfBetter()))
						&& !TypeFilter.isFiltered(packageName, simpleTypeName)) {
						JvmType importType = typeRefs.findDeclaredType(qualifiedTypeName, contextType.eResource());
						if (importType instanceof JvmDeclaredType
								&& contextualVisibilityHelper.isVisible((JvmDeclaredType) importType)) {
							acceptor.accept((JvmDeclaredType) importType);
						}
					}
				}
			}, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, new NullProgressMonitor());
}
 
Example #7
Source File: WebXmlValidator.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
/**
 * Searches for a class that matches a pattern.
 */
@VisibleForTesting
static boolean performSearch(SearchPattern pattern, IJavaSearchScope scope,
    IProgressMonitor monitor) {
  try {
    SearchEngine searchEngine = new SearchEngine();
    TypeSearchRequestor requestor = new TypeSearchRequestor();
    searchEngine.search(pattern,
        new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() },
        scope, requestor, monitor);
    return requestor.foundMatch();
  } catch (CoreException ex) {
    logger.log(Level.SEVERE, ex.getMessage());
    return false;
  }
}
 
Example #8
Source File: AddImportsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private TypeNameMatch[] findAllTypes(String simpleTypeName, IJavaSearchScope searchScope, SimpleName nameNode, IProgressMonitor monitor) throws JavaModelException {
	boolean is50OrHigher= JavaModelUtil.is50OrHigher(fCompilationUnit.getJavaProject());

	int typeKinds= SimilarElementsRequestor.ALL_TYPES;
	if (nameNode != null) {
		typeKinds= ASTResolving.getPossibleTypeKinds(nameNode, is50OrHigher);
	}

	ArrayList<TypeNameMatch> typeInfos= new ArrayList<TypeNameMatch>();
	TypeNameMatchCollector requestor= new TypeNameMatchCollector(typeInfos);
	int matchMode= SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE;
	new SearchEngine().searchAllTypeNames(null, matchMode, simpleTypeName.toCharArray(), matchMode, getSearchForConstant(typeKinds), searchScope, requestor, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, monitor);

	ArrayList<TypeNameMatch> typeRefsFound= new ArrayList<TypeNameMatch>(typeInfos.size());
	for (int i= 0, len= typeInfos.size(); i < len; i++) {
		TypeNameMatch curr= typeInfos.get(i);
		if (curr.getPackageName().length() > 0) { // do not suggest imports from the default package
			if (isOfKind(curr, typeKinds, is50OrHigher) && isVisible(curr)) {
				typeRefsFound.add(curr);
			}
		}
	}
	return typeRefsFound.toArray(new TypeNameMatch[typeRefsFound.size()]);
}
 
Example #9
Source File: MultiPageEditor.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the search scope for descriptor type.
 *
 * @return the search scope for descriptor type
 */
public IJavaSearchScope getSearchScopeForDescriptorType() {
  try {
    switch (descriptorType) {
      case DESCRIPTOR_AE:
        CombinedHierarchyScope scope = new CombinedHierarchyScope();
        scope.addScope(SearchEngine.createHierarchyScope(getAnalysisComponentIType()));
        scope.addScope(SearchEngine.createHierarchyScope(getBaseAnnotatorIType()));
        scope.addScope(SearchEngine.createHierarchyScope(getCollectionReaderIType()));
        scope.addScope(SearchEngine.createHierarchyScope(getCasConsumerIType()));
        return scope;
      case DESCRIPTOR_CASCONSUMER:
        return SearchEngine.createHierarchyScope(getCasConsumerIType());
      case DESCRIPTOR_CASINITIALIZER:
        return SearchEngine.createHierarchyScope(getCasInitializerIType());
      case DESCRIPTOR_COLLECTIONREADER:
        return SearchEngine.createHierarchyScope(getCollectionReaderIType());
      case DESCRIPTOR_FLOWCONTROLLER:
        return SearchEngine.createHierarchyScope(getFlowControllerIType());
    }
  } catch (JavaModelException e) {
    throw new InternalErrorCDE("unexpected exception", e);
  }
  return null;
}
 
Example #10
Source File: TypeFilterPreferencePage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private String[] choosePackage() {
	IJavaSearchScope scope= SearchEngine.createWorkspaceScope();
	BusyIndicatorRunnableContext context= new BusyIndicatorRunnableContext();
	int flags= PackageSelectionDialog.F_SHOW_PARENTS | PackageSelectionDialog.F_HIDE_DEFAULT_PACKAGE | PackageSelectionDialog.F_REMOVE_DUPLICATES;
	PackageSelectionDialog dialog = new PackageSelectionDialog(getShell(), context, flags , scope);
	dialog.setTitle(PreferencesMessages.TypeFilterPreferencePage_choosepackage_label);
	dialog.setMessage(PreferencesMessages.TypeFilterPreferencePage_choosepackage_description);
	dialog.setMultipleSelection(true);
	if (dialog.open() == IDialogConstants.OK_ID) {
		Object[] fragments= dialog.getResult();
		String[] res= new String[fragments.length];
		for (int i= 0; i < res.length; i++) {
			res[i]= ((IPackageFragment) fragments[i]).getElementName() + ".*"; //$NON-NLS-1$
		}
		return res;
	}
	return null;
}
 
Example #11
Source File: FindReadReferencesInProjectAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
QuerySpecification createQuery(IJavaElement element) throws JavaModelException {
	JavaSearchScopeFactory factory= JavaSearchScopeFactory.getInstance();
	JavaEditor editor= getEditor();

	IJavaSearchScope scope;
	String description;
	boolean isInsideJRE= factory.isInsideJRE(element);
	if (editor != null) {
		scope= factory.createJavaProjectSearchScope(editor.getEditorInput(), isInsideJRE);
		description= factory.getProjectScopeDescription(editor.getEditorInput(), isInsideJRE);
	} else {
		scope= factory.createJavaProjectSearchScope(element.getJavaProject(), isInsideJRE);
		description=  factory.getProjectScopeDescription(element.getJavaProject(), isInsideJRE);
	}
	return new ElementQuerySpecification(element, getLimitTo(), scope, description);
}
 
Example #12
Source File: CallerFinder.java    From lapse-plus with GNU General Public License v3.0 6 votes vote down vote up
public static IJavaSearchScope getSearchScope(IJavaProject project) {
    	if (fSearchScope == null) {
            fSearchScope = SearchEngine.createWorkspaceScope();
        	//fSearchScope = SearchEngine.createJavaSearchScope(new IResource[] {method.getResource()});
        }
//    	return fSearchScope;

    	if(project == null) {	        
	        return fSearchScope;
    	} else {
    		JavaSearchScope js = new JavaSearchScope();
    		try {
    			int includeMask = 
    				JavaSearchScope.SOURCES | 
					JavaSearchScope.APPLICATION_LIBRARIES | 
					JavaSearchScope.SYSTEM_LIBRARIES ;
				js.add((JavaProject) project, includeMask, new HashSet());
			} catch (JavaModelException e) {
				log(e.getMessage(), e);
				return fSearchScope;
			}
    		return js;
    	} 
    }
 
Example #13
Source File: ImportOrganizeInputDialog.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void doBrowseTypes() {
	IRunnableContext context= new BusyIndicatorRunnableContext();
	IJavaSearchScope scope= SearchEngine.createWorkspaceScope();
	int style= IJavaElementSearchConstants.CONSIDER_ALL_TYPES;
	try {
		SelectionDialog dialog= JavaUI.createTypeDialog(getShell(), context, scope, style, false, fNameDialogField.getText());
		dialog.setTitle(PreferencesMessages.ImportOrganizeInputDialog_ChooseTypeDialog_title);
		dialog.setMessage(PreferencesMessages.ImportOrganizeInputDialog_ChooseTypeDialog_description);
		if (dialog.open() == Window.OK) {
			IType res= (IType) dialog.getResult()[0];
			fNameDialogField.setText(res.getFullyQualifiedName('.'));
		}
	} catch (JavaModelException e) {
		ExceptionHandler.handle(e, getShell(), PreferencesMessages.ImportOrganizeInputDialog_ChooseTypeDialog_title, PreferencesMessages.ImportOrganizeInputDialog_ChooseTypeDialog_error_message);
	}
}
 
Example #14
Source File: MoveMembersWizard.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void openTypeSelectionDialog(){
	int elementKinds= IJavaSearchConstants.TYPE;
	final IJavaSearchScope scope= createWorkspaceSourceScope();
	FilteredTypesSelectionDialog dialog= new FilteredTypesSelectionDialog(getShell(), false,
		getWizard().getContainer(), scope, elementKinds);
	dialog.setTitle(RefactoringMessages.MoveMembersInputPage_choose_Type);
	dialog.setMessage(RefactoringMessages.MoveMembersInputPage_dialogMessage);
	dialog.setValidator(new ISelectionStatusValidator(){
		public IStatus validate(Object[] selection) {
			Assert.isTrue(selection.length <= 1);
			if (selection.length == 0)
				return new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.OK, RefactoringMessages.MoveMembersInputPage_Invalid_selection, null);
			Object element= selection[0];
			if (! (element instanceof IType))
				return new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.OK, RefactoringMessages.MoveMembersInputPage_Invalid_selection, null);
			IType type= (IType)element;
			return validateDestinationType(type, type.getElementName());
		}
	});
	dialog.setInitialPattern(createInitialFilter());
	if (dialog.open() == Window.CANCEL)
		return;
	IType firstResult= (IType)dialog.getFirstResult();
	fDestinationField.setText(firstResult.getFullyQualifiedName('.'));
}
 
Example #15
Source File: ExpandWithConstructorsConfigurationBlock.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates the type hierarchy for type selection.
 */
private void doBrowseTypes() {
	IRunnableContext context= new BusyIndicatorRunnableContext();
	IJavaSearchScope scope= SearchEngine.createWorkspaceScope();
	int style= IJavaElementSearchConstants.CONSIDER_ALL_TYPES;
	try {
		SelectionDialog dialog= JavaUI.createTypeDialog(getShell(), context, scope, style, false, fNameDialogField.getText());
		dialog.setTitle(CallHierarchyMessages.CallHierarchyTypesOrMembersDialog_ChooseTypeDialog_title);
		dialog.setMessage(CallHierarchyMessages.CallHierarchyTypesOrMembersDialog_ChooseTypeDialog_description);
		if (dialog.open() == Window.OK) {
			IType res= (IType)dialog.getResult()[0];
			fNameDialogField.setText(res.getFullyQualifiedName('.'));
		}
	} catch (JavaModelException e) {
		ExceptionHandler.handle(e, getShell(), CallHierarchyMessages.CallHierarchyTypesOrMembersDialog_ChooseTypeDialog_title,
				CallHierarchyMessages.CallHierarchyTypesOrMembersDialog_ChooseTypeDialog_error_message);
	}
}
 
Example #16
Source File: RenamePackageProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private List<SearchResultGroup> getReferencesToTypesInPackage(IProgressMonitor pm, ReferencesInBinaryContext binaryRefs, RefactoringStatus status) throws CoreException {
	pm.beginTask("", 2); //$NON-NLS-1$
	IJavaSearchScope referencedFromNamesakesScope= RefactoringScopeFactory.create(fPackage, true, false);
	IPackageFragment[] namesakePackages= getNamesakePackages(referencedFromNamesakesScope, new SubProgressMonitor(pm, 1));
	if (namesakePackages.length == 0) {
		pm.done();
		return new ArrayList<>(0);
	}

	IJavaSearchScope scope= SearchEngine.createJavaSearchScope(namesakePackages);
	IType[] typesToSearch= getTypesInPackage(fPackage);
	if (typesToSearch.length == 0) {
		pm.done();
		return new ArrayList<>(0);
	}
	SearchPattern pattern= RefactoringSearchEngine.createOrPattern(typesToSearch, IJavaSearchConstants.REFERENCES);
	CollectingSearchRequestor requestor= new CuCollectingSearchRequestor(binaryRefs);
	SearchResultGroup[] results= RefactoringSearchEngine.search(pattern, scope, requestor, new SubProgressMonitor(pm, 1), status);
	pm.done();
	return new ArrayList<>(Arrays.asList(results));
}
 
Example #17
Source File: IntersectingJavaSearchScope.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean encloses(String resourcePath) {
	boolean result = false;
	for (int i = 0; i < scopes.length; i++) {
		if (!dontAsk[i]) {
			IJavaSearchScope scope = scopes[i];
			try {
				if (!scope.encloses(resourcePath))
					return false;
				result = true;
			} catch(Exception e) {
				dontAsk[i] = true;
				log.info("Exception in JDT code", e);
			}
		}
	}
	return result;
}
 
Example #18
Source File: TextMatchUpdater.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private TextMatchUpdater(TextChangeManager manager, IJavaSearchScope scope, String currentName, String currentQualifier, String newName, SearchResultGroup[] references, boolean onlyQualified){
	Assert.isNotNull(manager);
	Assert.isNotNull(scope);
	Assert.isNotNull(references);
	fManager= manager;
	fScope= scope;
	fReferences= references;
	fOnlyQualified= onlyQualified;

	fNewName= newName;
	fCurrentNameLength= currentName.length();
	fScanner= new RefactoringScanner(currentName, currentQualifier);
}
 
Example #19
Source File: RenameFieldProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
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() {
			@Override
			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);
}
 
Example #20
Source File: MoveCuUpdateCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static SearchResultGroup[] getReferences(ICompilationUnit unit, IProgressMonitor pm, RefactoringStatus status) throws CoreException {
	final SearchPattern pattern= RefactoringSearchEngine.createOrPattern(unit.getTypes(), IJavaSearchConstants.REFERENCES);
	if (pattern != null) {
		String binaryRefsDescription= Messages.format(RefactoringCoreMessages.ReferencesInBinaryContext_ref_in_binaries_description , BasicElementLabels.getFileName(unit));
		ReferencesInBinaryContext binaryRefs= new ReferencesInBinaryContext(binaryRefsDescription);
		Collector requestor= new Collector(((IPackageFragment) unit.getParent()), binaryRefs);
		IJavaSearchScope scope= RefactoringScopeFactory.create(unit, true, false);

		SearchResultGroup[] result= RefactoringSearchEngine.search(pattern, scope, requestor, new SubProgressMonitor(pm, 1), status);
		binaryRefs.addErrorIfNecessary(status);
		return result;
	}
	return new SearchResultGroup[] {};
}
 
Example #21
Source File: CallerMethodWrapper.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private IJavaSearchScope getAccurateSearchScope(IJavaSearchScope defaultSearchScope, IMember member) throws JavaModelException {
	if (! JdtFlags.isPrivate(member))
		return defaultSearchScope;

	if (member.getCompilationUnit() != null) {
		return SearchEngine.createJavaSearchScope(new IJavaElement[] { member.getCompilationUnit() });
	} else if (member.getClassFile() != null) {
		// member could be called from an inner class-> search
		// package fragment (see also bug 109053):
		return SearchEngine.createJavaSearchScope(new IJavaElement[] { member.getAncestor(IJavaElement.PACKAGE_FRAGMENT) });
	} else {
		return defaultSearchScope;
	}
}
 
Example #22
Source File: CreateCopyOfCompilationUnitChange.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static SearchResultGroup getReferences(final ICompilationUnit copy, IProgressMonitor monitor) throws JavaModelException {
	final ICompilationUnit[] copies= new ICompilationUnit[] { copy};
	IJavaSearchScope scope= SearchEngine.createJavaSearchScope(copies);
	final IType type= copy.findPrimaryType();
	if (type == null) {
		return null;
	}
	SearchPattern pattern= createSearchPattern(type);
	final RefactoringSearchEngine2 engine= new RefactoringSearchEngine2(pattern);
	engine.setScope(scope);
	engine.setWorkingCopies(copies);
	engine.setRequestor(new IRefactoringSearchRequestor() {
		TypeOccurrenceCollector fTypeOccurrenceCollector= new TypeOccurrenceCollector(type);
		@Override
		public SearchMatch acceptSearchMatch(SearchMatch match) {
			try {
				return fTypeOccurrenceCollector.acceptSearchMatch2(copy, match);
			} catch (CoreException e) {
				JavaLanguageServerPlugin.log(e);
				return null;
			}
		}
	});

	engine.searchPattern(monitor);
	final Object[] results= engine.getResults();
	// Assert.isTrue(results.length <= 1);
	// just 1 file or none, but inaccurate matches can play bad here (see
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=106127)
	for (int index= 0; index < results.length; index++) {
		SearchResultGroup group= (SearchResultGroup) results[index];
		if (group.getCompilationUnit().equals(copy)) {
			return group;
		}
	}
	return null;
}
 
Example #23
Source File: JavaSearchScopeFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public IJavaSearchScope createWorkspaceScope(int includeMask) {
	if ((includeMask & NO_PROJ) != NO_PROJ) {
		try {
			IJavaProject[] projects= JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()).getJavaProjects();
			return SearchEngine.createJavaSearchScope(projects, getSearchFlags(includeMask));
		} catch (JavaModelException e) {
			// ignore, use workspace scope instead
		}
	}
	return SearchEngine.createWorkspaceScope();
}
 
Example #24
Source File: TypeSelectionDialog2.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public TypeSelectionDialog2(Shell parent, boolean multi, IRunnableContext context, 
		IJavaSearchScope scope, int elementKinds, TypeSelectionExtension extension) {
	super(parent);
	setShellStyle(getShellStyle() | SWT.RESIZE);
	fMultipleSelection= multi;
	fRunnableContext= context;
	fScope= scope;
	fElementKind= elementKinds;
	fSelectionMode= NONE;
	fExtension= extension;
	if (fExtension != null) {
		fValidator= fExtension.getSelectionValidator();
	}
}
 
Example #25
Source File: TypeInfoViewer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public SearchEngineJob(int ticket, TypeInfoViewer viewer, TypeInfoFilter filter, OpenTypeHistory history, int numberOfVisibleItems, int mode,
		IJavaSearchScope scope, int elementKind) {
	super(ticket, viewer, filter, history, numberOfVisibleItems, mode);
	fScope= scope;
	fElementKind= elementKind;
	fReqestor= new SearchRequestor(filter);
}
 
Example #26
Source File: RippleMethodFinder2.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 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 (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 #27
Source File: ChangeExceptionsControl.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private IType chooseException() {
	IJavaElement[] elements= new IJavaElement[] { fProject.getJavaProject() };
	final IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements);

	FilteredTypesSelectionDialog dialog= new FilteredTypesSelectionDialog(getShell(), false,
			PlatformUI.getWorkbench().getProgressService(), scope, IJavaSearchConstants.CLASS);
	dialog.setTitle(RefactoringMessages.ChangeExceptionsControl_choose_title);
	dialog.setMessage(RefactoringMessages.ChangeExceptionsControl_choose_message);
	dialog.setInitialPattern("*Exception*"); //$NON-NLS-1$
	dialog.setValidator(new ISelectionStatusValidator() {
		public IStatus validate(Object[] selection) {
			if (selection.length == 0)
				return new StatusInfo(IStatus.ERROR, ""); //$NON-NLS-1$
			try {
				return checkException((IType)selection[0]);
			} catch (JavaModelException e) {
				JavaPlugin.log(e);
				return StatusInfo.OK_STATUS;
			}
		}
	});

	if (dialog.open() == Window.OK) {
		return (IType) dialog.getFirstResult();
	}
	return null;
}
 
Example #28
Source File: DataWizardPage.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("restriction")
protected void openClassSelectionDialog(final Text classText) {
    final IJavaSearchScope searchScope = SearchEngine
            .createJavaSearchScope(new IJavaElement[] { RepositoryManager.getInstance().getCurrentRepository()
                    .getJavaProject() });
    final OpenTypeSelectionDialog searchDialog = new OpenTypeSelectionDialog(getShell(), false, null, searchScope,
            IJavaSearchConstants.TYPE);
    if (searchDialog.open() == Dialog.OK) {
        classText.setText(((IType) searchDialog.getFirstResult()).getFullyQualifiedName());
    }
}
 
Example #29
Source File: JDTUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static IJavaSearchScope createSearchScope(IJavaProject project, PreferenceManager preferenceManager) {
	IJavaProject[] elements;
	if (project == null) {//workspace search
		elements = ProjectUtils.getJavaProjects();
	} else {
		elements = new IJavaProject[] { project };
	}
	int scope = IJavaSearchScope.SOURCES;
	if (preferenceManager != null && preferenceManager.isClientSupportsClassFileContent()) {
		scope |= IJavaSearchScope.APPLICATION_LIBRARIES | IJavaSearchScope.SYSTEM_LIBRARIES;
	}
	return SearchEngine.createJavaSearchScope(elements, scope);
}
 
Example #30
Source File: RefactoringScopeFactory.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates a new search scope with all projects possibly referenced from the
 * given <code>javaElements</code>.
 *
 * @param javaElements
 *            the java elements
 * @return the search scope
 */
public static IJavaSearchScope createReferencedScope(IJavaElement[] javaElements) {
	Set<IJavaProject> projects = new HashSet<>();
	for (int i = 0; i < javaElements.length; i++) {
		projects.add(javaElements[i].getJavaProject());
	}
	IJavaProject[] prj = projects.toArray(new IJavaProject[projects.size()]);
	return SearchEngine.createJavaSearchScope(prj, true);
}