Search in sources :

Example 31 with SearchEngine

use of org.eclipse.jdt.core.search.SearchEngine in project java-debug by microsoft.

the class ResolveMainClassHandler method resolveMainClassUnderPaths.

private List<ResolutionItem> resolveMainClassUnderPaths(List<IPath> parentPaths) {
    // Limit to search main method from source code only.
    IJavaSearchScope searchScope = SearchEngine.createJavaSearchScope(ProjectUtils.getJavaProjects(), IJavaSearchScope.REFERENCED_PROJECTS | IJavaSearchScope.SOURCES);
    SearchPattern pattern = SearchPattern.createPattern("main(String[]) void", IJavaSearchConstants.METHOD, IJavaSearchConstants.DECLARATIONS, SearchPattern.R_CASE_SENSITIVE | SearchPattern.R_EXACT_MATCH);
    final List<ResolutionItem> res = new ArrayList<>();
    SearchRequestor requestor = new SearchRequestor() {

        @Override
        public void acceptSearchMatch(SearchMatch match) {
            Object element = match.getElement();
            if (element instanceof IMethod) {
                IMethod method = (IMethod) element;
                try {
                    if (method.isMainMethod()) {
                        IResource resource = method.getResource();
                        if (resource != null) {
                            IProject project = resource.getProject();
                            if (project != null) {
                                String mainClass = method.getDeclaringType().getFullyQualifiedName();
                                IJavaProject javaProject = JdtUtils.getJavaProject(project);
                                if (javaProject != null) {
                                    String moduleName = JdtUtils.getModuleName(javaProject);
                                    if (moduleName != null) {
                                        mainClass = moduleName + "/" + mainClass;
                                    }
                                }
                                String projectName = ProjectsManager.DEFAULT_PROJECT_NAME.equals(project.getName()) ? null : project.getName();
                                if (parentPaths.isEmpty() || ResourceUtils.isContainedIn(project.getLocation(), parentPaths) || isContainedInInvisibleProject(project, parentPaths)) {
                                    String filePath = null;
                                    if (match.getResource() instanceof IFile) {
                                        try {
                                            filePath = match.getResource().getLocation().toOSString();
                                        } catch (Exception ex) {
                                        // ignore
                                        }
                                    }
                                    res.add(new ResolutionItem(mainClass, projectName, filePath));
                                }
                            }
                        }
                    }
                } catch (JavaModelException e) {
                // ignore
                }
            }
        }
    };
    SearchEngine searchEngine = new SearchEngine();
    try {
        searchEngine.search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, searchScope, requestor, null);
    } catch (Exception e) {
        logger.log(Level.SEVERE, String.format("Searching the main class failure: %s", e.toString()), e);
    }
    List<ResolutionItem> resolutions = res.stream().distinct().collect(Collectors.toList());
    Collections.sort(resolutions);
    return resolutions;
}
Also used : SearchMatch(org.eclipse.jdt.core.search.SearchMatch) JavaModelException(org.eclipse.jdt.core.JavaModelException) IFile(org.eclipse.core.resources.IFile) ArrayList(java.util.ArrayList) IProject(org.eclipse.core.resources.IProject) JavaModelException(org.eclipse.jdt.core.JavaModelException) CoreException(org.eclipse.core.runtime.CoreException) SearchRequestor(org.eclipse.jdt.core.search.SearchRequestor) IJavaProject(org.eclipse.jdt.core.IJavaProject) SearchEngine(org.eclipse.jdt.core.search.SearchEngine) IJavaSearchScope(org.eclipse.jdt.core.search.IJavaSearchScope) SearchPattern(org.eclipse.jdt.core.search.SearchPattern) IMethod(org.eclipse.jdt.core.IMethod) IResource(org.eclipse.core.resources.IResource)

Example 32 with SearchEngine

use of org.eclipse.jdt.core.search.SearchEngine in project java-debug by microsoft.

the class ResolveClasspathsHandler method findMainClassInTestFolders.

/**
 * 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);
            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;
}
Also used : SearchRequestor(org.eclipse.jdt.core.search.SearchRequestor) IJavaElement(org.eclipse.jdt.core.IJavaElement) SearchMatch(org.eclipse.jdt.core.search.SearchMatch) SearchEngine(org.eclipse.jdt.core.search.SearchEngine) IJavaSearchScope(org.eclipse.jdt.core.search.IJavaSearchScope) ArrayList(java.util.ArrayList) SearchPattern(org.eclipse.jdt.core.search.SearchPattern) CoreException(org.eclipse.core.runtime.CoreException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException)

Example 33 with SearchEngine

use of org.eclipse.jdt.core.search.SearchEngine in project vscode-java-test by microsoft.

the class TestNavigationUtils method findTestOrTarget.

/**
 * find test or test subject according to the given java source file uri.
 * @param arguments arguments
 * @param monitor monitor
 * @return the search result for test navigation
 * @throws JavaModelException
 */
public static TestNavigationResult findTestOrTarget(List<Object> arguments, IProgressMonitor monitor) throws JavaModelException {
    if (arguments == null || arguments.size() < 2) {
        throw new IllegalArgumentException("Wrong arguments passed to findTestOrTarget().");
    }
    final String typeUri = (String) arguments.get(0);
    final ICompilationUnit unit = JDTUtils.resolveCompilationUnit(typeUri);
    if (unit == null) {
        JUnitPlugin.logError("Failed to resolve compilation unit from " + typeUri);
        return null;
    }
    final IType primaryType = unit.findPrimaryType();
    final String typeName;
    Location location = null;
    if (primaryType != null) {
        typeName = primaryType.getElementName();
        location = JDTUtils.toLocation(primaryType, LocationType.NAME_RANGE);
    } else {
        typeName = unit.getElementName().substring(0, unit.getElementName().lastIndexOf(".java"));
    }
    final SearchEngine searchEngine = new SearchEngine();
    final boolean goToTest = (boolean) arguments.get(1);
    final String nameToSearch = goToTest ? typeName : guessTestSubjectName(typeName);
    final IJavaSearchScope scope = getSearchScope(goToTest);
    final IJavaProject javaProject = unit.getJavaProject();
    final Set<TestNavigationItem> items = new HashSet<>();
    searchEngine.searchAllTypeNames(null, SearchPattern.R_EXACT_MATCH, ("*" + nameToSearch + "*").toCharArray(), SearchPattern.R_PATTERN_MATCH, IJavaSearchConstants.CLASS, scope, new TestNavigationNameRequestor(items, javaProject, nameToSearch, typeName, goToTest), IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, monitor);
    return new TestNavigationResult(items, location);
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IType(org.eclipse.jdt.core.IType) SearchEngine(org.eclipse.jdt.core.search.SearchEngine) IJavaProject(org.eclipse.jdt.core.IJavaProject) IJavaSearchScope(org.eclipse.jdt.core.search.IJavaSearchScope) Location(org.eclipse.lsp4j.Location) HashSet(java.util.HashSet)

Example 34 with SearchEngine

use of org.eclipse.jdt.core.search.SearchEngine in project vscode-java-test by microsoft.

the class TestSearchUtils method findType.

protected static final IType findType(final IJavaProject project, String className, IProgressMonitor monitor) {
    final IType[] result = { null };
    // for nested classes...
    final String dottedName = className.replace('$', '.');
    try {
        if (project != null) {
            result[0] = internalFindType(project, dottedName, new HashSet<IJavaProject>(), monitor);
        }
        if (result[0] == null) {
            final int lastDot = dottedName.lastIndexOf('.');
            final TypeNameMatchRequestor nameMatchRequestor = new TypeNameMatchRequestor() {

                @Override
                public void acceptTypeNameMatch(TypeNameMatch match) {
                    result[0] = match.getType();
                }
            };
            new SearchEngine().searchAllTypeNames(lastDot >= 0 ? dottedName.substring(0, lastDot).toCharArray() : null, SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE, (lastDot >= 0 ? dottedName.substring(lastDot + 1) : dottedName).toCharArray(), SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE, IJavaSearchConstants.TYPE, SearchEngine.createWorkspaceScope(), nameMatchRequestor, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, monitor);
        }
    } catch (JavaModelException e) {
        JUnitPlugin.log(e);
    }
    return result[0];
}
Also used : JavaModelException(org.eclipse.jdt.core.JavaModelException) CoreTestSearchEngine(org.eclipse.jdt.internal.junit.util.CoreTestSearchEngine) SearchEngine(org.eclipse.jdt.core.search.SearchEngine) TypeNameMatch(org.eclipse.jdt.core.search.TypeNameMatch) TypeNameMatchRequestor(org.eclipse.jdt.core.search.TypeNameMatchRequestor) IType(org.eclipse.jdt.core.IType) HashSet(java.util.HashSet)

Example 35 with SearchEngine

use of org.eclipse.jdt.core.search.SearchEngine in project vscode-java-test by microsoft.

the class AnnotationSearchRequestor method findTestsInContainer.

/*
     * (non-Javadoc)
     *
     * @see org.testng.eclipse.launch.TestFinder#findTestsInContainer
     */
private void findTestsInContainer(final IJavaElement element, final Set result, IProgressMonitor pm) throws CoreException {
    if (element == null || result == null) {
        throw new IllegalArgumentException();
    }
    if (element instanceof IType) {
        if (internalIsTest((IType) element, pm)) {
            result.add(element);
            return;
        }
    }
    if (pm == null) {
        pm = new NullProgressMonitor();
    }
    try {
        final IRegion region = CoreTestSearchEngine.getRegion(element);
        final ITypeHierarchy hierarchy = JavaCore.newTypeHierarchy(region, null, new SubProgressMonitor(pm, 1));
        final IType[] allClasses = hierarchy.getAllClasses();
        // search for all types with references to RunWith and Test and all subclasses
        final Set<IType> candidates = new HashSet<>(allClasses.length);
        final SearchRequestor requestor = new AnnotationSearchRequestor(hierarchy, candidates);
        final IJavaSearchScope scope = SearchEngine.createJavaSearchScope(allClasses, IJavaSearchScope.SOURCES);
        final int matchRule = SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE;
        final SearchPattern annotationsPattern = SearchPattern.createPattern("org.testng.annotations.Test", IJavaSearchConstants.ANNOTATION_TYPE, IJavaSearchConstants.ANNOTATION_TYPE_REFERENCE, matchRule);
        final SearchParticipant[] searchParticipants = new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() };
        new SearchEngine().search(annotationsPattern, searchParticipants, scope, requestor, new SubProgressMonitor(pm, 2));
        // find all classes in the region
        for (final IType curr : candidates) {
            if (CoreTestSearchEngine.isAccessibleClass(curr) && !Flags.isAbstract(curr.getFlags()) && region.contains(curr)) {
                result.add(curr);
            }
        }
    } finally {
        pm.done();
    }
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) IRegion(org.eclipse.jdt.core.IRegion) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) IType(org.eclipse.jdt.core.IType) SearchParticipant(org.eclipse.jdt.core.search.SearchParticipant) SearchRequestor(org.eclipse.jdt.core.search.SearchRequestor) ITypeHierarchy(org.eclipse.jdt.core.ITypeHierarchy) CoreTestSearchEngine(org.eclipse.jdt.internal.junit.util.CoreTestSearchEngine) SearchEngine(org.eclipse.jdt.core.search.SearchEngine) IJavaSearchScope(org.eclipse.jdt.core.search.IJavaSearchScope) SearchPattern(org.eclipse.jdt.core.search.SearchPattern) HashSet(java.util.HashSet)

Aggregations

SearchEngine (org.eclipse.jdt.core.search.SearchEngine)131 SearchPattern (org.eclipse.jdt.core.search.SearchPattern)73 CoreException (org.eclipse.core.runtime.CoreException)71 SearchMatch (org.eclipse.jdt.core.search.SearchMatch)61 SearchRequestor (org.eclipse.jdt.core.search.SearchRequestor)61 IJavaSearchScope (org.eclipse.jdt.core.search.IJavaSearchScope)58 ArrayList (java.util.ArrayList)52 JavaModelException (org.eclipse.jdt.core.JavaModelException)48 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)38 IType (org.eclipse.jdt.core.IType)38 IJavaElement (org.eclipse.jdt.core.IJavaElement)37 SubProgressMonitor (org.eclipse.core.runtime.SubProgressMonitor)24 SearchParticipant (org.eclipse.jdt.core.search.SearchParticipant)24 TypeNameMatch (org.eclipse.jdt.core.search.TypeNameMatch)21 HashSet (java.util.HashSet)20 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)20 IMethod (org.eclipse.jdt.core.IMethod)20 TypeNameMatchRequestor (org.eclipse.jdt.core.search.TypeNameMatchRequestor)16 IJavaProject (org.eclipse.jdt.core.IJavaProject)15 InvocationTargetException (java.lang.reflect.InvocationTargetException)12