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

The following examples show how to use org.eclipse.jdt.core.search.SearchEngine. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: uima-uimaj   Source File: MultiPageEditor.java    License: 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 2
/**
 * 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 3
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 4
/**
 * 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 5
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 6
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 7
Source Project: sarl   Source File: AbstractSuperTypeSelectionDialog.java    License: 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 8
/**
 * 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 9
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 10
@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 11
/**
 * 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 12
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 13
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
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 15
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 16
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 17
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 18
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 19
/**
 * @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 20
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 21
/**
 * Creates a selection dialog that lists all packages of the given Java project.
 * The caller is responsible for opening the dialog with <code>Window.open</code>,
 * and subsequently extracting the selected package (of type
 * <code>IPackageFragment</code>) via <code>SelectionDialog.getResult</code>.
 *
 * @param parent the parent shell of the dialog to be created
 * @param project the Java project
 * @param style flags defining the style of the dialog; the valid flags are:
 *   <code>IJavaElementSearchConstants.CONSIDER_BINARIES</code>, indicating that
 *   packages from binary package fragment roots should be included in addition
 *   to those from source package fragment roots;
 *   <code>IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS</code>, indicating that
 *   packages from required projects should be included as well.
 * @param filter the initial pattern to filter the set of packages. For example "com" shows
 * all packages starting with "com". The meta character '?' representing any character and
 * '*' representing any string are supported. Clients can pass an empty string if no filtering
 * is required.
 * @return a new selection dialog
 * @exception JavaModelException if the selection dialog could not be opened
 *
 * @since 2.0
 */
public static SelectionDialog createPackageDialog(Shell parent, IJavaProject project, int style, String filter) throws JavaModelException {
	Assert.isTrue((style | IJavaElementSearchConstants.CONSIDER_BINARIES | IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS) ==
		(IJavaElementSearchConstants.CONSIDER_BINARIES | IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS));

	IPackageFragmentRoot[] roots= null;
	if ((style & IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS) != 0) {
	    roots= project.getAllPackageFragmentRoots();
	} else {
		roots= project.getPackageFragmentRoots();
	}

	List<IPackageFragmentRoot> consideredRoots= null;
	if ((style & IJavaElementSearchConstants.CONSIDER_BINARIES) != 0) {
		consideredRoots= Arrays.asList(roots);
	} else {
		consideredRoots= new ArrayList<IPackageFragmentRoot>(roots.length);
		for (int i= 0; i < roots.length; i++) {
			IPackageFragmentRoot root= roots[i];
			if (root.getKind() != IPackageFragmentRoot.K_BINARY)
				consideredRoots.add(root);

		}
	}

	IJavaSearchScope searchScope= SearchEngine.createJavaSearchScope(consideredRoots.toArray(new IJavaElement[consideredRoots.size()]));
	BusyIndicatorRunnableContext context= new BusyIndicatorRunnableContext();
	if (style == 0 || style == IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS) {
		return createPackageDialog(parent, context, searchScope, false, true, filter);
	} else {
		return createPackageDialog(parent, context, searchScope, false, false, filter);
	}
}
 
Example 22
@Override
protected void fillContentProvider(AbstractContentProvider provider, ItemsFilter itemsFilter, IProgressMonitor progressMonitor) throws CoreException {
	TypeItemsFilter typeSearchFilter= (TypeItemsFilter) itemsFilter;
	TypeSearchRequestor requestor= new TypeSearchRequestor(provider, typeSearchFilter);
	SearchEngine engine= new SearchEngine((WorkingCopyOwner) null);
	String packPattern= typeSearchFilter.getPackagePattern();
	progressMonitor.setTaskName(JavaUIMessages.FilteredTypesSelectionDialog_searchJob_taskName);

	/*
	 * Setting the filter into match everything mode avoids filtering twice
	 * by the same pattern (the search engine only provides filtered
	 * matches). For the case when the pattern is a camel case pattern with
	 * a terminator, the filter is not set to match everything mode because
	 * jdt.core's SearchPattern does not support that case.
	 */
	String typePattern= typeSearchFilter.getNamePattern();
	int matchRule= typeSearchFilter.getMatchRule();
	typeSearchFilter.setMatchEverythingMode(true);

	try {
		engine.searchAllTypeNames(packPattern == null ? null : packPattern.toCharArray(),
				typeSearchFilter.getPackageFlags(),
				typePattern.toCharArray(),
				matchRule,
				typeSearchFilter.getElementKind(),
				typeSearchFilter.getSearchScope(),
				requestor,
				IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
				progressMonitor);
	} finally {
		typeSearchFilter.setMatchEverythingMode(false);
	}
}
 
Example 23
Source Project: lapse-plus   Source File: CallerFinder.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static Collection/*<MethodUnitPair>*/ findDeclarations(IProgressMonitor progressMonitor, String methodName, IJavaProject project, boolean isConstructor) {
    try {
        SearchRequestor searchRequestor = new MethodSearchRequestor.MethodDeclarationsSearchRequestor(); 
        SearchEngine searchEngine = new SearchEngine();

        IProgressMonitor monitor = new SubProgressMonitor(
                progressMonitor, 5, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
        monitor.beginTask("Searching for calls to " + 
                methodName + (project != null ? " in " + project.getProject().getName() : ""), 100);            
        IJavaSearchScope searchScope = getSearchScope(project);
        // This is kind of hacky: we need to make up a string name for the search to work right
        log("Looking for " + methodName);
        int matchType = !isConstructor ? IJavaSearchConstants.METHOD : IJavaSearchConstants.CONSTRUCTOR;
        SearchPattern pattern = SearchPattern.createPattern(
                methodName, 
                matchType,
                IJavaSearchConstants.DECLARATIONS,
                SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE );
        
        searchEngine.search(
                pattern, 
                new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() },
                searchScope, 
                searchRequestor, 
                monitor
                );

        if(searchRequestor instanceof MethodSearchRequestor.MethodDeclarationsSearchRequestor){                
            return ((MethodSearchRequestor.MethodDeclarationsSearchRequestor)searchRequestor).getMethodUnitPairs();
        }else{
            return ((MethodSearchRequestor.MethodReferencesSearchRequestor)searchRequestor).getMethodUnitPairs();
        }
    } catch (CoreException e) {
        JavaPlugin.log(e);

        return new LinkedList();
    }
}
 
Example 24
public ITypeHierarchy newSupertypeHierarchy(
	ICompilationUnit[] workingCopies,
	IProgressMonitor monitor)
	throws JavaModelException {

	CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(this, workingCopies, SearchEngine.createWorkspaceScope(), false);
	op.runOperation(monitor);
	return op.getResult();
}
 
Example 25
Source Project: CogniCrypt   Source File: Utils.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * This method searches the passed project for the class that contains the main method.
 *
 * @param project Project that is searched
 * @param requestor Object that handles the search results
 */
public static void findMainMethodInCurrentProject(final IJavaProject project, final SearchRequestor requestor) {
	final SearchPattern sp = SearchPattern.createPattern("main", IJavaSearchConstants.METHOD, IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH);

	final SearchEngine se = new SearchEngine();
	final SearchParticipant[] searchParticipants = new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()};
	final IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaElement[] {project});

	try {
		se.search(sp, searchParticipants, scope, requestor, null);
	}
	catch (final CoreException e) {
		Activator.getDefault().logError(e);
	}
}
 
Example 26
Source Project: hadoop-gpu   Source File: LocalMapReduceLaunchTabGroup.java    License: Apache License 2.0 5 votes vote down vote up
private void createRow(final Composite parent, Composite panel,
    final Text text) {
  text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
  Button button = new Button(panel, SWT.BORDER);
  button.setText("Browse...");
  button.addListener(SWT.Selection, new Listener() {
    public void handleEvent(Event arg0) {
      try {
        AST ast = AST.newAST(3);

        SelectionDialog dialog = JavaUI.createTypeDialog(parent.getShell(),
            new ProgressMonitorDialog(parent.getShell()), SearchEngine
                .createWorkspaceScope(),
            IJavaElementSearchConstants.CONSIDER_CLASSES, false);
        dialog.setMessage("Select Mapper type (implementing )");
        dialog.setBlockOnOpen(true);
        dialog.setTitle("Select Mapper Type");
        dialog.open();

        if ((dialog.getReturnCode() == Window.OK)
            && (dialog.getResult().length > 0)) {
          IType type = (IType) dialog.getResult()[0];
          text.setText(type.getFullyQualifiedName());
          setDirty(true);
        }
      } catch (JavaModelException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  });
}
 
Example 27
@Override
QuerySpecification createQuery(IJavaElement element) throws JavaModelException, InterruptedException {
	IType type= getType(element);
	if (type == null) {
		return super.createQuery(element);
	}
	JavaSearchScopeFactory factory= JavaSearchScopeFactory.getInstance();
	IJavaSearchScope scope= SearchEngine.createHierarchyScope(type);
	String description= factory.getHierarchyScopeDescription(type);
	return new ElementQuerySpecification(element, getLimitTo(), scope, description);
}
 
Example 28
public void createTypeProposals(IJavaProject project, ICompletionProposalFactory proposalFactory, ContentAssistContext context,
		EReference typeReference, Filter filter, IValueConverter<String> valueConverter, ICompletionProposalAcceptor acceptor) {
	try {
		IJavaSearchScope searchScope = SearchEngine.createJavaSearchScope(new IJavaElement[] { project });
		searchAndCreateProposals(searchScope, proposalFactory, context, typeReference, filter, valueConverter, acceptor);
	}
	catch (JavaModelException e) {
		// ignore
	}
}
 
Example 29
public void collectContents(IJavaSearchScope searchScope, TypeNameRequestor nameMatchRequestor) throws JavaModelException {
	new SearchEngine().searchAllTypeNames(
			null, 0, // match all package names
			null, 0, // and all type names,
			IJavaSearchConstants.TYPE, // search for types
			searchScope, // in the scope of the current project
			nameMatchRequestor, 
			IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, // wait for the jdt index to be ready
			new NullProgressMonitor());
}
 
Example 30
public void generateIndexForJar(String pathToJar, String pathToIndexFile) throws IOException {
	File f = new File(pathToJar);
	if (!f.exists()) {
		throw new FileNotFoundException(pathToJar + " not found"); //$NON-NLS-1$
	}
	IndexLocation indexLocation = new FileIndexLocation(new File(pathToIndexFile));
	Index index = new Index(indexLocation, pathToJar, false /*reuse index file*/);
	SearchParticipant participant = SearchEngine.getDefaultSearchParticipant();
	index.separator = JAR_SEPARATOR;
	ZipFile zip = new ZipFile(pathToJar);
	try {
		for (Enumeration e = zip.entries(); e.hasMoreElements();) {
			// iterate each entry to index it
			ZipEntry ze = (ZipEntry) e.nextElement();
			String zipEntryName = ze.getName();
			if (Util.isClassFileName(zipEntryName)) {
				final byte[] classFileBytes = org.eclipse.jdt.internal.compiler.util.Util.getZipEntryByteContent(ze, zip);
				JavaSearchDocument entryDocument = new JavaSearchDocument(ze, new Path(pathToJar), classFileBytes, participant);
				entryDocument.setIndex(index);
				new BinaryIndexer(entryDocument).indexDocument();
			}
		}
		index.save();
	} finally {
		zip.close();
	}
	return;
}