Java Code Examples for org.eclipse.jdt.core.search.SearchEngine#createJavaSearchScope()

The following examples show how to use org.eclipse.jdt.core.search.SearchEngine#createJavaSearchScope() . 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: 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 2
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 3
Source File: IntroduceFactoryInputPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private IType chooseFactoryClass() {
	IJavaProject	proj= getUseFactoryRefactoring().getProject();

	if (proj == null)
		return null;

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

	FilteredTypesSelectionDialog dialog= new FilteredTypesSelectionDialog(
		getShell(), false, getWizard().getContainer(), scope, IJavaSearchConstants.CLASS);

	dialog.setTitle(RefactoringMessages.IntroduceFactoryInputPage_chooseFactoryClass_title);
	dialog.setMessage(RefactoringMessages.IntroduceFactoryInputPage_chooseFactoryClass_message);

	if (dialog.open() == Window.OK) {
		return (IType) dialog.getFirstResult();
	}
	return null;
}
 
Example 4
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 5
Source File: TypeContextChecker.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static List<TypeNameMatch> findTypeInfos(String typeName, IType contextType, IProgressMonitor pm) throws JavaModelException {
	IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaProject[]{contextType.getJavaProject()}, true);
	IPackageFragment currPackage= contextType.getPackageFragment();
	ArrayList<TypeNameMatch> collectedInfos= new ArrayList<TypeNameMatch>();
	TypeNameMatchCollector requestor= new TypeNameMatchCollector(collectedInfos);
	int matchMode= SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE;
	new SearchEngine().searchAllTypeNames(null, matchMode, typeName.toCharArray(), matchMode, IJavaSearchConstants.TYPE, scope, requestor, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, pm);

	List<TypeNameMatch> result= new ArrayList<TypeNameMatch>();
	for (Iterator<TypeNameMatch> iter= collectedInfos.iterator(); iter.hasNext();) {
		TypeNameMatch curr= iter.next();
		IType type= curr.getType();
		if (type != null) {
			boolean visible=true;
			try {
				visible= JavaModelUtil.isVisible(type, currPackage);
			} catch (JavaModelException e) {
				//Assume visibile if not available
			}
			if (visible) {
				result.add(curr);
			}
		}
	}
	return result;
}
 
Example 6
Source File: RefactoringScopeFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.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
 * @param includeMask the include mask
 * @return the search scope
 */
public static IJavaSearchScope createReferencedScope(IJavaElement[] javaElements, int includeMask) {
	Set<IJavaProject> projects= new HashSet<IJavaProject>();
	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, includeMask);
}
 
Example 7
Source File: RenamePackageProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @return search scope with
 * <p>- fPackage and
 * <p>- all CUs from fOccurrences which are not in a namesake package
 */
private IJavaSearchScope getPackageAndOccurrencesWithoutNamesakesScope() {
	List<IJavaElement> scopeList= new ArrayList<IJavaElement>();
	scopeList.add(fPackage);
	for (int i= 0; i < fOccurrences.length; i++) {
		ICompilationUnit cu= fOccurrences[i].getCompilationUnit();
		if (cu == null)
			continue;
		IPackageFragment pack= (IPackageFragment) cu.getParent();
		if (! pack.getElementName().equals(fPackage.getElementName()))
			scopeList.add(cu);
	}
	return SearchEngine.createJavaSearchScope(scopeList.toArray(new IJavaElement[scopeList.size()]));
}
 
Example 8
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;
}
 
Example 9
Source File: SourceRepositoryStore.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
private boolean isSourceType(final String qualifiedClassname, final IJavaProject javaProject)
        throws JavaModelException {
    final SearchEngine sEngine = new SearchEngine();
    final IJavaSearchScope searchScope = SearchEngine.createJavaSearchScope(new IJavaElement[] { javaProject },
            IJavaSearchScope.SOURCES);
    final TypeNameFoundRequestor nameRequestor = new TypeNameFoundRequestor();
    sEngine.searchAllTypeNames(NamingUtils.getPackageName(qualifiedClassname).toCharArray(),
            SearchPattern.R_EXACT_MATCH,
            NamingUtils.getSimpleName(qualifiedClassname)
                    .toCharArray(),
            SearchPattern.R_EXACT_MATCH, IJavaSearchConstants.CLASS_AND_INTERFACE, searchScope, nameRequestor,
            IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
            Repository.NULL_PROGRESS_MONITOR);
    return nameRequestor.isFound();
}
 
Example 10
Source File: JdtBasedConstructorScope.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected Iterable<IEObjectDescription> internalGetAllElements() {
	IJavaProject javaProject = getTypeProvider().getJavaProject();
	if (javaProject == null)
		return Collections.emptyList();
	final List<IEObjectDescription> allScopedElements = Lists.newArrayListWithExpectedSize(25000);
	try {
		IJavaSearchScope searchScope = SearchEngine.createJavaSearchScope(new IJavaElement[] { javaProject });
		SearchRequestor searchRequestor = new SearchRequestor() {
			@Override
			public void acceptSearchMatch(SearchMatch match) throws CoreException {
				Object element = match.getElement();
				if (element instanceof IMethod) {
					IMethod constructor = (IMethod) element;
					allScopedElements.add(createScopedElement(constructor));	
				} else if (element instanceof IType) {
					allScopedElements.add(createScopedElement((IType)element));
				}
			}
		};
		collectContents(searchScope, searchRequestor);
	}
	catch (CoreException e) {
		logger.error("CoreException when searching for constructors.", e);
	}
	return allScopedElements;
}
 
Example 11
Source File: JavaTypeQuickfixes.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected IJavaSearchScope getJavaSearchScope(EObject model) {
	if (model == null || model.eResource() == null || model.eResource().getResourceSet() == null) {
		return null;
	} else {
		IJavaProject javaProject = projectProvider.getJavaProject(model.eResource().getResourceSet());
		IJavaSearchScope searchScope = SearchEngine.createJavaSearchScope(new IJavaElement[] { javaProject });
		return searchScope;
	}
}
 
Example 12
Source File: WebXmlValidator.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static boolean classExists(IJavaProject project, String typeName) {
  if (Strings.isNullOrEmpty(typeName)) {
    return false;
  }
  SearchPattern pattern = SearchPattern.createPattern(typeName,
      IJavaSearchConstants.CLASS,
      IJavaSearchConstants.DECLARATIONS,
      SearchPattern.R_EXACT_MATCH | SearchPattern.R_ERASURE_MATCH);
  IJavaSearchScope scope = project == null ? SearchEngine.createWorkspaceScope()
      : SearchEngine.createJavaSearchScope(new IJavaElement[] {project});
  return performSearch(pattern, scope, null);
}
 
Example 13
Source File: RippleMethodFinder.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private IJavaSearchScope createSearchScope() throws JavaModelException {
	IJavaProject[] projects = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()).getJavaProjects();
	return SearchEngine.createJavaSearchScope(projects, IJavaSearchScope.SOURCES);
}
 
Example 14
Source File: JavaContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Adds an import for type with type name <code>type</code> if possible.
 * Returns a string which can be used to reference the type.
 *
 * @param type the fully qualified name of the type to import
 * @return returns a type to which the type binding can be assigned to.
 * 	The returned type contains is unqualified when an import could be added or was already known.
 * 	It is fully qualified, if an import conflict prevented the import.
 * @since 3.4
 */
public String addImport(String type) {
	if (isReadOnly())
		return type;

	ICompilationUnit cu= getCompilationUnit();
	if (cu == null)
		return type;

	try {
		boolean qualified= type.indexOf('.') != -1;
		if (!qualified) {
			IJavaSearchScope searchScope= SearchEngine.createJavaSearchScope(new IJavaElement[] { cu.getJavaProject() });
			SimpleName nameNode= null;
			TypeNameMatch[] matches= findAllTypes(type, searchScope, nameNode, null, cu);
			if (matches.length != 1) // only add import if we have a single match
				return type;
			type= matches[0].getFullyQualifiedName();
		}

		CompilationUnit root= getASTRoot(cu);
		if (fImportRewrite == null) {
			if (root == null) {
				fImportRewrite= StubUtility.createImportRewrite(cu, true);
			} else {
				fImportRewrite= StubUtility.createImportRewrite(root, true);
			}
		}

		ImportRewriteContext context;
		if (root == null)
			context= null;
		else
			context= new ContextSensitiveImportRewriteContext(root, getCompletionOffset(), fImportRewrite);

		return fImportRewrite.addImport(type, context);
	} catch (JavaModelException e) {
		handleException(null, e);
		return type;
	}
}
 
Example 15
Source File: InteractiveUnresolvedTypeResolver.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
protected IJavaSearchScope getJavaSearchScope(XtextResource resource) {
	IJavaProject javaProject = projectProvider.getJavaProject(resource.getResourceSet());
	IJavaSearchScope searchScope = SearchEngine.createJavaSearchScope(new IJavaElement[] { javaProject });
	return searchScope;
}
 
Example 16
Source File: JavaSearchScopeFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public IJavaSearchScope createJavaProjectSearchScope(IJavaProject project, int includeMask) {
	return SearchEngine.createJavaSearchScope(new IJavaElement[] { project }, getSearchFlags(includeMask));
}
 
Example 17
Source File: MoveMembersWizard.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private IJavaSearchScope createWorkspaceSourceScope(){
	IJavaElement[] project= new IJavaElement[] { getMoveProcessor().getDeclaringType().getJavaProject() };
	return SearchEngine.createJavaSearchScope(project, IJavaSearchScope.REFERENCED_PROJECTS | IJavaSearchScope.SOURCES);
}
 
Example 18
Source File: TypeHierarchy.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates a TypeHierarchy on the given type.
 */
public TypeHierarchy(IType type, ICompilationUnit[] workingCopies, IJavaProject project, boolean computeSubtypes) {
	this(type, workingCopies, SearchEngine.createJavaSearchScope(new IJavaElement[] {project}), computeSubtypes);
	this.project = project;
}
 
Example 19
Source File: ResolveClasspathsHandler.java    From java-debug with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Try to find the associated java element with the main class from the test folders.
 *
 * @param project the java project containing the main class
 * @param mainClass the main class name
 * @return the associated java element
 */
private static IJavaElement findMainClassInTestFolders(IJavaProject project, String mainClass) {
    if (project == null || StringUtils.isBlank(mainClass)) {
        return null;
    }

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

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

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

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

    return null;
}
 
Example 20
Source File: JavaReferenceCodeMining.java    From jdt-codemining with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Create Java workspace scope.
 * 
 * @return the Java workspace scope.
 * @throws JavaModelException when java error.
 */
private static IJavaSearchScope createSearchScope() throws JavaModelException {
	IJavaProject[] projects = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()).getJavaProjects();
	return SearchEngine.createJavaSearchScope(projects, IJavaSearchScope.SOURCES);
}