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

The following examples show how to use org.eclipse.jdt.core.search.SearchEngine. 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: GotoTypeAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void run() {
	Shell shell= JavaPlugin.getActiveWorkbenchShell();
	SelectionDialog dialog= null;
	try {
		dialog= JavaUI.createTypeDialog(shell, new ProgressMonitorDialog(shell),
			SearchEngine.createWorkspaceScope(), IJavaElementSearchConstants.CONSIDER_ALL_TYPES, false);
	} catch (JavaModelException e) {
		String title= getDialogTitle();
		String message= PackagesMessages.GotoType_error_message;
		ExceptionHandler.handle(e, title, message);
		return;
	}

	dialog.setTitle(getDialogTitle());
	dialog.setMessage(PackagesMessages.GotoType_dialog_message);
	if (dialog.open() == IDialogConstants.CANCEL_ID) {
		return;
	}

	Object[] types= dialog.getResult();
	if (types != null && types.length > 0) {
		gotoType((IType) types[0]);
	}
}
 
Example #2
Source File: WorkspaceSymbolHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static IJavaSearchScope createSearchScope(String projectName, boolean sourceOnly) throws JavaModelException {
	IJavaProject[] targetProjects;
	IJavaProject project = ProjectUtils.getJavaProject(projectName);
	if (project != null) {
		targetProjects = new IJavaProject[] { project };
	} else {
		targetProjects = ProjectUtils.getJavaProjects();
	}

	int scope = IJavaSearchScope.REFERENCED_PROJECTS | IJavaSearchScope.SOURCES;
	PreferenceManager preferenceManager = JavaLanguageServerPlugin.getPreferencesManager();
	if (!sourceOnly && preferenceManager != null && preferenceManager.isClientSupportsClassFileContent()) {
		scope |= IJavaSearchScope.APPLICATION_LIBRARIES | IJavaSearchScope.SYSTEM_LIBRARIES;
	}

	return SearchEngine.createJavaSearchScope(targetProjects, scope);
}
 
Example #3
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 #4
Source File: PushDownRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static IJavaElement[] getReferencingElementsFromSameClass(IMember member, IProgressMonitor pm, RefactoringStatus status) throws JavaModelException {
	Assert.isNotNull(member);
	final RefactoringSearchEngine2 engine= new RefactoringSearchEngine2(SearchPattern.createPattern(member, IJavaSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE));
	engine.setFiltering(true, true);
	engine.setScope(SearchEngine.createJavaSearchScope(new IJavaElement[] { member.getDeclaringType() }));
	engine.setStatus(status);
	engine.searchPattern(new SubProgressMonitor(pm, 1));
	SearchResultGroup[] groups= (SearchResultGroup[]) engine.getResults();
	Set<IJavaElement> result= new HashSet<IJavaElement>(3);
	for (int i= 0; i < groups.length; i++) {
		SearchResultGroup group= groups[i];
		SearchMatch[] results= group.getSearchResults();
		for (int j= 0; j < results.length; j++) {
			SearchMatch searchResult= results[j];
			result.add(SearchUtils.getEnclosingJavaElement(searchResult));
		}
	}
	return result.toArray(new IJavaElement[result.size()]);
}
 
Example #5
Source File: FilteredTypesSelectionDialog.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void refreshSearchIndices(IProgressMonitor monitor) throws InvocationTargetException {
	try {
		new SearchEngine().searchAllTypeNames(
				null,
				0,
				// make sure we search a concrete name. This is faster according to Kent
				"_______________".toCharArray(), //$NON-NLS-1$
				SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE,
				IJavaSearchConstants.ENUM,
				SearchEngine.createWorkspaceScope(),
				new TypeNameRequestor() { /* dummy */},
				IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
				monitor);
	} catch (JavaModelException e) {
		throw new InvocationTargetException(e);
	}
}
 
Example #6
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 #7
Source File: CodeAssistFavoritesConfigurationBlock.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.FavoriteStaticMemberInputDialog_ChooseTypeDialog_title);
		dialog.setMessage(PreferencesMessages.FavoriteStaticMemberInputDialog_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.FavoriteStaticMemberInputDialog_ChooseTypeDialog_title, PreferencesMessages.FavoriteStaticMemberInputDialog_ChooseTypeDialog_error_message);
	}
}
 
Example #8
Source File: AbstractSuperTypeSelectionDialog.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Creates a searching scope including only one project.
 *
 * @param project the scope of the search.
 * @param type the expected super type.
 * @param onlySubTypes indicates if only the subtypes of the given types are allowed. If
 *     <code>false</code>, the super type is allowed too.
 * @return the search scope.
 */
public static IJavaSearchScope createSearchScope(IJavaProject project, Class<?> type, boolean onlySubTypes) {
	try {
		final IType superType = project.findType(type.getName());
		return SearchEngine.createStrictHierarchyScope(
				project,
				superType,
				// only sub types
				onlySubTypes,
				// include the type
				true,
				null);
	} catch (JavaModelException e) {
		SARLEclipsePlugin.getDefault().log(e);
	}
	return SearchEngine.createJavaSearchScope(new IJavaElement[] {project});
}
 
Example #9
Source File: OriginalEditorSelector.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
private SearchResult findTypesBySimpleName(String simpleTypeName, final boolean searchForSources) {
	final SearchResult result = new SearchResult();
	try {
		new SearchEngine().searchAllTypeNames(null, 0, // match all package names
				simpleTypeName.toCharArray(), SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE,
					IJavaSearchConstants.TYPE,
					SearchEngine.createWorkspaceScope(),
					new TypeNameMatchRequestor() {
						@Override
						public void acceptTypeNameMatch(TypeNameMatch match) {
							IPackageFragmentRoot fragmentRoot = match.getPackageFragmentRoot();
							boolean externalLib = fragmentRoot.isArchive() || fragmentRoot.isExternal();
							if (externalLib ^ searchForSources) {
								result.foundTypes.add(match.getType());
							}
						}
					}, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, // wait for the jdt index to be ready
					new NullProgressMonitor());
	} catch (JavaModelException e) {
		logger.error(e.getMessage(), e);
	}
	return result;
}
 
Example #10
Source File: JavaContext.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, ICompilationUnit cu) throws JavaModelException {
	boolean is50OrHigher= JavaModelUtil.is50OrHigher(cu.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);
	new SearchEngine().searchAllTypeNames(null, 0, simpleTypeName.toCharArray(), SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE, getSearchForConstant(typeKinds), searchScope, requestor, IJavaSearchConstants.FORCE_IMMEDIATE_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, cu)) {
				typeRefsFound.add(curr);
			}
		}
	}
	return typeRefsFound.toArray(new TypeNameMatch[typeRefsFound.size()]);
}
 
Example #11
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 #12
Source File: RenamePackageProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @param scope search scope
 * @param pm mrogress monitor
 * @return all package fragments in <code>scope</code> with same name as <code>fPackage</code>, excluding fPackage
 * @throws CoreException if search failed
 */
private IPackageFragment[] getNamesakePackages(IJavaSearchScope scope, IProgressMonitor pm) throws CoreException {
	SearchPattern pattern= SearchPattern.createPattern(fPackage.getElementName(), IJavaSearchConstants.PACKAGE, IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE);

	final HashSet<IPackageFragment> packageFragments= new HashSet<IPackageFragment>();
	SearchRequestor requestor= new SearchRequestor() {
		@Override
		public void acceptSearchMatch(SearchMatch match) throws CoreException {
			IJavaElement enclosingElement= SearchUtils.getEnclosingJavaElement(match);
			if (enclosingElement instanceof IPackageFragment) {
				IPackageFragment pack= (IPackageFragment) enclosingElement;
				if (! fPackage.equals(pack))
					packageFragments.add(pack);
			}
		}
	};
	new SearchEngine().search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor, pm);

	return packageFragments.toArray(new IPackageFragment[packageFragments.size()]);
}
 
Example #13
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 #14
Source File: RefactoringScopeFactory.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates a new search scope with all compilation units possibly referencing
 * <code>javaElement</code>.
 *
 * @param javaElement
 *            the java element
 * @param considerVisibility
 *            consider visibility of javaElement iff <code>true</code>
 * @param sourceReferencesOnly
 *            consider references in source only (no references in binary)
 * @return the search scope
 * @throws JavaModelException
 *             if an error occurs
 */
public static IJavaSearchScope create(IJavaElement javaElement, boolean considerVisibility, boolean sourceReferencesOnly) throws JavaModelException {
	if (considerVisibility & javaElement instanceof IMember) {
		IMember member = (IMember) javaElement;
		if (JdtFlags.isPrivate(member)) {
			if (member.getCompilationUnit() != null) {
				return SearchEngine.createJavaSearchScope(new IJavaElement[] { member.getCompilationUnit() });
			} else {
				return SearchEngine.createJavaSearchScope(new IJavaElement[] { member });
			}
		}
		// Removed code that does some optimizations regarding package visible members. The problem is that
		// there can be a package fragment with the same name in a different source folder or project. So we
		// have to treat package visible members like public or protected members.
	}

	IJavaProject javaProject = javaElement.getJavaProject();
	return SearchEngine.createJavaSearchScope(getAllScopeElements(javaProject, sourceReferencesOnly), false);
}
 
Example #15
Source File: NewTypeWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Opens a selection dialog that allows to select an enclosing type.
 *
 * @return returns the selected type or <code>null</code> if the dialog has been canceled.
 * The caller typically sets the result to the enclosing type input field.
 * <p>
 * Clients can override this method if they want to offer a different dialog.
 * </p>
 *
 * @since 3.2
 */
protected IType chooseEnclosingType() {
	IPackageFragmentRoot root= getPackageFragmentRoot();
	if (root == null) {
		return null;
	}

	IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaElement[] { root });

	FilteredTypesSelectionDialog dialog= new FilteredTypesSelectionDialog(getShell(),
		false, getWizard().getContainer(), scope, IJavaSearchConstants.TYPE);
	dialog.setTitle(NewWizardMessages.NewTypeWizardPage_ChooseEnclosingTypeDialog_title);
	dialog.setMessage(NewWizardMessages.NewTypeWizardPage_ChooseEnclosingTypeDialog_description);
	dialog.setInitialPattern(Signature.getSimpleName(getEnclosingTypeText()));

	if (dialog.open() == Window.OK) {
		return (IType) dialog.getFirstResult();
	}
	return null;
}
 
Example #16
Source File: IntroduceIndirectionInputPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private IType chooseIntermediaryType() {
	IJavaProject proj= getIntroduceIndirectionRefactoring().getProject();

	if (proj == null)
		return null;

	IJavaElement[] elements= new IJavaElement[] { proj };
	IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements);

	int elementKinds= JavaModelUtil.is18OrHigher(proj) ? IJavaSearchConstants.CLASS_AND_INTERFACE : IJavaSearchConstants.CLASS;
	FilteredTypesSelectionDialog dialog= new FilteredTypesSelectionDialog(getShell(), false, getWizard().getContainer(), scope, elementKinds);

	dialog.setTitle(RefactoringMessages.IntroduceIndirectionInputPage_dialog_choose_declaring_class);
	dialog.setMessage(RefactoringMessages.IntroduceIndirectionInputPage_dialog_choose_declaring_class_long);

	if (dialog.open() == Window.OK) {
		return (IType) dialog.getFirstResult();
	}
	return null;
}
 
Example #17
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 #18
Source File: NewTypeWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Opens a selection dialog that allows to select a super class.
 *
 * @return returns the selected type or <code>null</code> if the dialog has been canceled.
 * The caller typically sets the result to the super class input field.
 * 	<p>
 * Clients can override this method if they want to offer a different dialog.
 * </p>
 *
 * @since 3.2
 */
protected IType chooseSuperClass() {
	IJavaProject project= getJavaProject();
	if (project == null) {
		return null;
	}

	IJavaElement[] elements= new IJavaElement[] { project };
	IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements);

	FilteredTypesSelectionDialog dialog= new FilteredTypesSelectionDialog(getShell(), false,
		getWizard().getContainer(), scope, IJavaSearchConstants.CLASS);
	dialog.setTitle(NewWizardMessages.NewTypeWizardPage_SuperClassDialog_title);
	dialog.setMessage(NewWizardMessages.NewTypeWizardPage_SuperClassDialog_message);
	dialog.setInitialPattern(getSuperClass());

	if (dialog.open() == Window.OK) {
		return (IType) dialog.getFirstResult();
	}
	return null;
}
 
Example #19
Source File: NLSAccessorConfigurationDialog.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected void browseForAccessorClass() {
	IProgressService service= PlatformUI.getWorkbench().getProgressService();
	IPackageFragmentRoot root= fAccessorPackage.getSelectedFragmentRoot();

	IJavaSearchScope scope= root != null ? SearchEngine.createJavaSearchScope(new IJavaElement[] { root }) : SearchEngine.createWorkspaceScope();

	FilteredTypesSelectionDialog  dialog= new FilteredTypesSelectionDialog (getShell(), false,
		service, scope, IJavaSearchConstants.CLASS);
	dialog.setTitle(NLSUIMessages.NLSAccessorConfigurationDialog_Accessor_Selection);
	dialog.setMessage(NLSUIMessages.NLSAccessorConfigurationDialog_Choose_the_accessor_file);
	dialog.setInitialPattern("*Messages"); //$NON-NLS-1$
	if (dialog.open() == Window.OK) {
		IType selectedType= (IType) dialog.getFirstResult();
		if (selectedType != null) {
			fAccessorClassName.setText(selectedType.getElementName());
			fAccessorPackage.setSelected(selectedType.getPackageFragment());
		}
	}


}
 
Example #20
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 #21
Source File: BinaryType.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public ITypeHierarchy newSupertypeHierarchy(
	WorkingCopyOwner owner,
	IProgressMonitor monitor)
	throws JavaModelException {

	ICompilationUnit[] workingCopies = JavaModelManager.getJavaModelManager().getWorkingCopies(owner, true/*add primary working copies*/);
	CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(this, workingCopies, SearchEngine.createWorkspaceScope(), false);
	op.runOperation(monitor);
	return op.getResult();
}
 
Example #22
Source File: FilteredTypesSelectionDialog.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void fillViewMenu(IMenuManager menuManager) {
	super.fillViewMenu(menuManager);

	if (! BUG_184693) {
		fShowContainerForDuplicatesAction= new ShowContainerForDuplicatesAction();
		menuManager.add(fShowContainerForDuplicatesAction);
	}
	if (fAllowScopeSwitching) {
		fFilterActionGroup= new WorkingSetFilterActionGroup(getShell(), JavaPlugin.getActivePage(), new IPropertyChangeListener() {
			public void propertyChange(PropertyChangeEvent event) {
				IWorkingSet ws= (IWorkingSet) event.getNewValue();
				if (ws == null || (ws.isAggregateWorkingSet() && ws.isEmpty())) {
					setSearchScope(SearchEngine.createWorkspaceScope());
					setSubtitle(null);
				} else {
					setSearchScope(JavaSearchScopeFactory.getInstance().createJavaSearchScope(ws, true));
					setSubtitle(ws.getLabel());
				}

				applyFilter();
			}
		});
		fFilterActionGroup.fillViewMenu(menuManager);
	}

	menuManager.add(new Separator());
	menuManager.add(new TypeFiltersPreferencesAction());
}
 
Example #23
Source File: FilteredTypesSelectionDialog.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void restoreDialog(IDialogSettings settings) {
	super.restoreDialog(settings);

	if (! BUG_184693) {
		boolean showContainer= settings.getBoolean(SHOW_CONTAINER_FOR_DUPLICATES);
		fShowContainerForDuplicatesAction.setChecked(showContainer);
		fTypeInfoLabelProvider.setContainerInfo(showContainer);
	} else {
		fTypeInfoLabelProvider.setContainerInfo(true);
	}

	if (fAllowScopeSwitching) {
		String setting= settings.get(WORKINGS_SET_SETTINGS);
		if (setting != null) {
			try {
				IMemento memento= XMLMemento.createReadRoot(new StringReader(setting));
				fFilterActionGroup.restoreState(memento);
			} catch (WorkbenchException e) {
				// don't do anything. Simply don't restore the settings
				JavaPlugin.log(e);
			}
		}
		IWorkingSet ws= fFilterActionGroup.getWorkingSet();
		if (ws == null || (ws.isAggregateWorkingSet() && ws.isEmpty())) {
			setSearchScope(SearchEngine.createWorkspaceScope());
			setSubtitle(null);
		} else {
			setSearchScope(JavaSearchScopeFactory.getInstance().createJavaSearchScope(ws, true));
			setSubtitle(ws.getLabel());
		}
	}

	// TypeNameMatch[] types = OpenTypeHistory.getInstance().getTypeInfos();
	//
	// for (int i = 0; i < types.length; i++) {
	// TypeNameMatch type = types[i];
	// accessedHistoryItem(type);
	// }
}
 
Example #24
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);
}
 
Example #25
Source File: BinaryType.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public ITypeHierarchy newTypeHierarchy(
	ICompilationUnit[] workingCopies,
	IProgressMonitor monitor)
	throws JavaModelException {

	CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(this, workingCopies, SearchEngine.createWorkspaceScope(), true);
	op.runOperation(monitor);
	return op.getResult();
}
 
Example #26
Source File: SearchScopeProjectAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public IJavaSearchScope getSearchScope(int includeMask) {
	IMember[] members= fGroup.getView().getInputElements();
	if (members == null) {
		return null;
	}

	HashSet<IJavaProject> projects= new HashSet<IJavaProject>();
	for (int i= 0; i < members.length; i++) {
		projects.add(members[i].getJavaProject());
	}
	return SearchEngine.createJavaSearchScope(
			projects.toArray(new IJavaProject[projects.size()]),
			includeMask);
}
 
Example #27
Source File: ReferencesHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private IJavaSearchScope createSearchScope() throws JavaModelException {
	IJavaProject[] projects = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()).getJavaProjects();
	int scope = IJavaSearchScope.SOURCES;
	if (preferenceManager.isClientSupportsClassFileContent()) {
		scope |= IJavaSearchScope.APPLICATION_LIBRARIES;
	}
	return SearchEngine.createJavaSearchScope(projects, scope);
}
 
Example #28
Source File: MoveCuUpdateCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private TypeReference(IJavaElement enclosingElement, int accuracy, int start, int length,
		boolean insideDocComment, IResource resource, int simpleNameStart, String simpleName) {
	super(enclosingElement, accuracy, start, length,
			insideDocComment, SearchEngine.getDefaultSearchParticipant(), resource);
	fSimpleNameStart= simpleNameStart;
	fSimpleTypeName= simpleName;
}
 
Example #29
Source File: TargetProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public ICompilationUnit[] getAffectedCompilationUnits(final RefactoringStatus status, ReferencesInBinaryContext binaryRefs, IProgressMonitor pm) throws CoreException {
	IMethod method= (IMethod)fMethodBinding.getJavaElement();
	Assert.isTrue(method != null);

	SearchPattern pattern= SearchPattern.createPattern(method, IJavaSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
	IJavaSearchScope scope= RefactoringScopeFactory.create(method, true, false);
	final HashSet<ICompilationUnit> affectedCompilationUnits= new HashSet<ICompilationUnit>();
	CollectingSearchRequestor requestor= new CollectingSearchRequestor(binaryRefs) {
		private ICompilationUnit fLastCU;
		@Override
		public void acceptSearchMatch(SearchMatch match) throws CoreException {
			if (filterMatch(match))
				return;
			if (match.isInsideDocComment())
				return; // TODO: should warn user (with something like a ReferencesInBinaryContext)

			ICompilationUnit unit= SearchUtils.getCompilationUnit(match);
			if (match.getAccuracy() == SearchMatch.A_INACCURATE) {
				if (unit != null) {
					status.addError(RefactoringCoreMessages.TargetProvider_inaccurate_match,
						JavaStatusContext.create(unit, new SourceRange(match.getOffset(), match.getLength())));
				} else {
					status.addError(RefactoringCoreMessages.TargetProvider_inaccurate_match);
				}
			} else if (unit != null) {
				if (! unit.equals(fLastCU)) {
					fLastCU= unit;
					affectedCompilationUnits.add(unit);
				}
			}
		}
	};
	new SearchEngine().search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor, new SubProgressMonitor(pm, 1));
	return affectedCompilationUnits.toArray(new ICompilationUnit[affectedCompilationUnits.size()]);
}
 
Example #30
Source File: CreateCopyOfCompilationUnitChange.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.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);
		public SearchMatch acceptSearchMatch(SearchMatch match) {
			try {
				return fTypeOccurrenceCollector.acceptSearchMatch2(copy, match);
			} catch (CoreException e) {
				JavaPlugin.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;
}