com.intellij.util.Query Java Examples

The following examples show how to use com.intellij.util.Query. 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: AbstractPropertiesProvider.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Return an instance of search pattern.
 */
public Query<PsiModifierListOwner> createSearchPattern(SearchContext context) {
	Query<PsiModifierListOwner> query = null;
	String[] patterns = getPatterns();
	if (patterns == null) {
		return null;
	}

	for (String pattern : patterns) {
		if (query == null) {
			query = createSearchPattern(context, pattern);
		} else {
			Query<PsiModifierListOwner> rightQuery = createSearchPattern(context, pattern);
			if (rightQuery != null) {
				query = new MergeQuery<>(query, rightQuery);
			}
		}
	}
	return query;
}
 
Example #2
Source File: FileMoveHandler.java    From netbeans-mmd-plugin with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public List<UsageInfo> findUsages(final PsiFile psiFile, final PsiDirectory newParent, final boolean searchInComments, final boolean searchInNonJavaFiles) {
  Query<PsiReference> search = ReferencesSearch.search(psiFile);
  final List<PsiExtraFileReference> extraFileRefs = new ArrayList<PsiExtraFileReference>();
  search.forEach(new Processor<PsiReference>() {
    @Override
    public boolean process(PsiReference psiReference) {
      if (psiReference instanceof PsiExtraFileReference) {
        extraFileRefs.add((PsiExtraFileReference) psiReference);
      }
      return true;
    }
  });

  if (extraFileRefs.isEmpty()) {
    return null;
  } else {
    final List<UsageInfo> result = new ArrayList<UsageInfo>(extraFileRefs.size());
    for (final PsiExtraFileReference e : extraFileRefs) {
      result.add(new FileUsageInfo(e));
    }
    return result;
  }
}
 
Example #3
Source File: QuerySearchRequest.java    From consulo with Apache License 2.0 6 votes vote down vote up
public QuerySearchRequest(@Nonnull Query<PsiReference> query,
                          @Nonnull final SearchRequestCollector collector,
                          boolean inReadAction,
                          @Nonnull final PairProcessor<? super PsiReference, ? super SearchRequestCollector> processor) {
  this.query = query;
  this.collector = collector;
  if (inReadAction) {
    this.processor = new ReadActionProcessor<PsiReference>() {
      @Override
      public boolean processInReadAction(PsiReference psiReference) {
        return processor.process(psiReference, collector);
      }
    };
  }
  else {
    this.processor = psiReference -> processor.process(psiReference, collector);
  }
}
 
Example #4
Source File: PsiPackageManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
private PsiPackage createPackage(@Nonnull String qualifiedName, @Nonnull Class<? extends ModuleExtension> extensionClass) {
  Query<VirtualFile> dirs = myDirectoryIndex.getDirectoriesByPackageName(qualifiedName, true);
  if (dirs.findFirst() == null) {
    return null;
  }

  for (VirtualFile directory : dirs) {
    PsiPackage packageFromProviders = createPackageFromProviders(directory, extensionClass, qualifiedName);
    if (packageFromProviders != null) {
      return packageFromProviders;
    }

    PsiPackage packageFromLibrary = createPackageFromLibrary(directory, extensionClass, qualifiedName);
    if (packageFromLibrary != null) {
      return packageFromLibrary;
    }
  }
  return null;
}
 
Example #5
Source File: PsiPackageManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredReadAction
@Override
public PsiPackage findAnyPackage(@Nonnull String packageName) {
  Query<VirtualFile> dirs = myDirectoryIndex.getDirectoriesByPackageName(packageName, true);
  if (dirs.findFirst() == null) {
    return null;
  }

  PsiPackage packageFromCache = findAnyPackageFromCache(packageName);
  if (packageFromCache != null) {
    return packageFromCache;
  }

  for (VirtualFile dir : dirs) {
    PsiPackage psiPackage = findAnyPackage(dir);
    if (psiPackage != null) {
      return psiPackage;
    }
  }
  return null;
}
 
Example #6
Source File: PropertiesManager.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
public MicroProfileProjectInfo getMicroProfileProjectInfo(Module module,
                                                          List<MicroProfilePropertiesScope> scopes, ClasspathKind classpathKind, IPsiUtils utils,
                                                          DocumentFormat documentFormat) {
    MicroProfileProjectInfo info = createInfo(module, classpathKind);
    long startTime = System.currentTimeMillis();
    boolean excludeTestCode = classpathKind == ClasspathKind.SRC;
    PropertiesCollector collector = new PropertiesCollector(info, scopes);
    SearchScope scope = createSearchScope(module, scopes, classpathKind == ClasspathKind.TEST);
    SearchContext context = new SearchContext(module, scope, collector, utils, documentFormat);
    DumbService.getInstance(module.getProject()).runReadActionInSmartMode(() -> {
        Query<PsiModifierListOwner> query = createSearchQuery(context);
        beginSearch(context);
        query.forEach((Consumer<? super PsiModifierListOwner>) psiMember -> collectProperties(psiMember, context));
        endSearch(context);
    });
    LOGGER.info("End computing MicroProfile properties for '" + info.getProjectURI() + "' in "
            + (System.currentTimeMillis() - startTime) + "ms.");
    return info;
}
 
Example #7
Source File: ResourceFileUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public static VirtualFile findResourceFileInScope(final String resourceName,
                                                  final Project project,
                                                  final GlobalSearchScope scope) {
  int index = resourceName.lastIndexOf('/');
  String packageName = index >= 0 ? resourceName.substring(0, index).replace('/', '.') : "";
  final String fileName = index >= 0 ? resourceName.substring(index+1) : resourceName;
  Query<VirtualFile> directoriesByPackageName = DirectoryIndex.getInstance(project).getDirectoriesByPackageName(packageName, true);
  for (VirtualFile virtualFile : directoriesByPackageName) {
    final VirtualFile child = virtualFile.findChild(fileName);
    if(child != null && scope.contains(child)) {
      return child;
    }
  }
  return null;
}
 
Example #8
Source File: PsiFileReferenceHelper.java    From consulo with Apache License 2.0 6 votes vote down vote up
static Collection<PsiFileSystemItem> getContextsForModule(@Nonnull Module module, @Nonnull String packageName, @Nullable GlobalSearchScope scope) {
  List<PsiFileSystemItem> result = null;
  Query<VirtualFile> query = DirectoryIndex.getInstance(module.getProject()).getDirectoriesByPackageName(packageName, false);
  PsiManager manager = null;

  for (VirtualFile file : query) {
    if (scope != null && !scope.contains(file)) continue;
    if (result == null) {
      result = new ArrayList<>();
      manager = PsiManager.getInstance(module.getProject());
    }
    PsiDirectory psiDirectory = manager.findDirectory(file);
    if (psiDirectory != null) result.add(psiDirectory);
  }

  return result != null ? result : Collections.emptyList();
}
 
Example #9
Source File: PsiPackageBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected Collection<PsiDirectory> getAllDirectories(boolean inLibrarySources) {
  List<PsiDirectory> directories = new ArrayList<PsiDirectory>();
  PsiManager manager = PsiManager.getInstance(getProject());
  Query<VirtualFile> directoriesByPackageName =
    DirectoryIndex.getInstance(getProject()).getDirectoriesByPackageName(getQualifiedName(), inLibrarySources);
  for (VirtualFile virtualFile : directoriesByPackageName) {
    PsiDirectory directory = manager.findDirectory(virtualFile);
    if (directory != null) {
      directories.add(directory);
    }
  }

  return directories;
}
 
Example #10
Source File: PlatformPackageUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private static PsiDirectory getWritableModuleDirectory(@Nonnull Query<VirtualFile> vFiles,
                                                       GlobalSearchScope scope,
                                                       PsiManager manager) {
  for (VirtualFile vFile : vFiles) {
    if (!scope.contains(vFile)) continue;
    PsiDirectory directory = manager.findDirectory(vFile);
    if (directory != null && directory.isValid() && directory.isWritable()) {
      return directory;
    }
  }
  return null;
}
 
Example #11
Source File: PlatformPackageUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static PsiDirectory[] getPackageDirectories(Project project, String rootPackage, final GlobalSearchScope scope) {
  final PsiManager manager = PsiManager.getInstance(project);

  Query<VirtualFile> query = DirectoryIndex.getInstance(scope.getProject()).getDirectoriesByPackageName(rootPackage, true);
  query = new FilteredQuery<>(query, scope::contains);

  List<PsiDirectory> directories = ContainerUtil.mapNotNull(query.findAll(), manager::findDirectory);
  return directories.toArray(new PsiDirectory[directories.size()]);
}
 
Example #12
Source File: InplaceRefactoring.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected Collection<PsiReference> collectRefs(SearchScope referencesSearchScope) {
  final Query<PsiReference> search = ReferencesSearch.search(myElementToRename, referencesSearchScope, false);

  final CommonProcessors.CollectProcessor<PsiReference> processor = new CommonProcessors.CollectProcessor<PsiReference>() {
    @Override
    protected boolean accept(PsiReference reference) {
      return acceptReference(reference);
    }
  };

  search.forEach(processor);
  return processor.getResults();
}
 
Example #13
Source File: PullUpProcessor.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
private void processMethodsDuplicates() {
  ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
    @Override
    public void run() {
      ApplicationManager.getApplication().runReadAction(new Runnable() {
        @Override
        public void run() {
          if (!myTargetSuperClass.isValid()) return;
          final Query<PsiClass> search = ClassInheritorsSearch.search(myTargetSuperClass);
          final Set<VirtualFile> hierarchyFiles = new HashSet<VirtualFile>();
          for (PsiClass aClass : search) {
            final PsiFile containingFile = aClass.getContainingFile();
            if (containingFile != null) {
              final VirtualFile virtualFile = containingFile.getVirtualFile();
              if (virtualFile != null) {
                hierarchyFiles.add(virtualFile);
              }
            }
          }
          final Set<PsiMember> methodsToSearchDuplicates = new HashSet<PsiMember>();
          for (PsiMember psiMember : myMembersAfterMove) {
            if (psiMember instanceof PsiMethod && psiMember.isValid() && ((PsiMethod)psiMember).getBody() != null) {
              methodsToSearchDuplicates.add(psiMember);
            }
          }

          MethodDuplicatesHandler.invokeOnScope(myProject, methodsToSearchDuplicates, new AnalysisScope(myProject, hierarchyFiles), true);
        }
      });
    }
  }, MethodDuplicatesHandler.REFACTORING_NAME, true, myProject);
}
 
Example #14
Source File: CallerChooserBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected Collection<PsiElement> findElementsToHighlight(M caller, PsiElement callee) {
  Query<PsiReference> references = ReferencesSearch.search(callee, new LocalSearchScope(caller), false);
  return ContainerUtil.mapNotNull(references, new Function<PsiReference, PsiElement>() {
    @Override
    public PsiElement fun(PsiReference psiReference) {
      return psiReference.getElement();
    }
  });
}
 
Example #15
Source File: HaxeMethodsSearch.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
public static Query<PsiMethod> search(final PsiMethod method, final boolean checkDeep, HaxeHierarchyTimeoutHandler timeoutHandler) {
  return search(method, ApplicationManager.getApplication().runReadAction(new Computable<SearchScope>() {
    @Override
    public SearchScope compute() {
      return method.getUseScope();
    }
  }), checkDeep, timeoutHandler);
}
 
Example #16
Source File: HaxeMethodsSearch.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
public static Query<PsiMethod> search(final PsiMethod method, SearchScope scope, final boolean checkDeep, HaxeHierarchyTimeoutHandler timeoutHandler) {
  if (ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {
    @Override
    public Boolean compute() {
      return cannotBeOverriden(method);
    }
  })) return EmptyQuery.getEmptyQuery(); // Optimization
  return INSTANCE.createUniqueResultsQuery(new SearchParameters(method, scope, checkDeep));
}
 
Example #17
Source File: CS0169.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
@Nullable
@Override
public HighlightInfoFactory checkImpl(@Nonnull CSharpLanguageVersion languageVersion, @Nonnull CSharpHighlightContext highlightContext, @Nonnull CSharpFieldDeclaration element)
{
	if(!element.hasModifier(CSharpModifier.PRIVATE))
	{
		return null;
	}

	PsiElement parent = element.getParent();
	if(!(parent instanceof CSharpTypeDeclaration))
	{
		return null;
	}

	PsiElement nameIdentifier = element.getNameIdentifier();
	if(nameIdentifier == null)
	{
		return null;
	}

	Query<PsiReference> search = ReferencesSearch.search(element, CSharpCompositeTypeDeclaration.createLocalScope((DotNetTypeDeclaration) parent));
	if(search.findFirst() == null)
	{
		return newBuilder(nameIdentifier, formatElement(element));
	}

	return null;
}
 
Example #18
Source File: AbstractPropertiesProvider.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Create a search pattern for the given <code>className</code> class name.
 * 
 * @param annotationName the class name to search.
 * @return a search pattern for the given <code>className</code> class name.
 */
protected static Query<PsiModifierListOwner> createAnnotationTypeDeclarationSearchPattern(SearchContext context, String annotationName) {
	JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(context.getModule().getProject());
	PsiClass annotationClass = javaPsiFacade.findClass(annotationName, GlobalSearchScope.allScope(context.getModule().getProject()));
	if (annotationClass != null) {
		return new ArrayQuery<>(annotationClass);
	} else {
		return new EmptyQuery<>();
	}
}
 
Example #19
Source File: JavaClassUtils.java    From camel-idea-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Return a list of {@link PsiClass}s annotated with the specified annotation
 * @param project - Project reference to narrow the search inside.
 * @param annotation - the full qualify annotation name to search for
 * @return a list of classes annotated with the specified annotation.
 */
@NotNull
private Collection<PsiClass> getClassesAnnotatedWith(Project project, String annotation) {
    PsiClass stepClass = JavaPsiFacade.getInstance(project).findClass(annotation, ProjectScope.getLibrariesScope(project));
    if (stepClass != null) {
        final Query<PsiClass> psiMethods = AnnotatedElementsSearch.searchPsiClasses(stepClass, GlobalSearchScope.allScope(project));
        return psiMethods.findAll();
    }
    return Collections.emptyList();
}
 
Example #20
Source File: MicroProfileRestClientDiagnosticsParticipant.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
private static void validateInterfaceType(PsiClass interfaceType, List<Diagnostic> diagnostics,
		JavaDiagnosticsContext context) {
	boolean hasRegisterRestClient = AnnotationUtils.hasAnnotation(interfaceType, REGISTER_REST_CLIENT_ANNOTATION);
	if (hasRegisterRestClient) {
		return;
	}

	final AtomicInteger nbReferences = new AtomicInteger(0);
	Query<PsiReference> query = ReferencesSearch.search(interfaceType, createSearchScope(context.getJavaProject()));
	query.forEach(match -> {
		PsiElement o = PsiTreeUtil.getParentOfType(match.getElement(), PsiField.class);
		if (o instanceof PsiField) {
			PsiField field = (PsiField) o;
			boolean hasInjectAnnotation = AnnotationUtils.hasAnnotation(field, INJECT_ANNOTATION);
			boolean hasRestClientAnnotation = AnnotationUtils.hasAnnotation(field, REST_CLIENT_ANNOTATION);
			if (hasInjectAnnotation && hasRestClientAnnotation) {
				nbReferences.incrementAndGet();
			}
		}
	});

	if (nbReferences.get() > 0) {
		String uri = context.getUri();
		Range restInterfaceRange = PositionUtils.toNameRange(interfaceType, context.getUtils());
		Diagnostic d = context.createDiagnostic(uri,
				"The interface `" + interfaceType.getName()
						+ "` does not have the @RegisterRestClient annotation. The " + nbReferences.get()
						+ " fields references will not be injected as CDI beans.",
				restInterfaceRange, MicroProfileRestClientConstants.DIAGNOSTIC_SOURCE,
				MicroProfileRestClientErrorCode.RegisterRestClientAnnotationMissing);
		diagnostics.add(d);
	}
}
 
Example #21
Source File: PropertiesManager.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
private Query<PsiModifierListOwner> createSearchQuery(SearchContext context) {
    Query<PsiModifierListOwner> query = null;

    for(IPropertiesProvider provider : IPropertiesProvider.EP_NAME.getExtensions()) {
      Query<PsiModifierListOwner> providerQuery = provider.createSearchPattern(context);
      if (providerQuery != null) {
          if (query == null) {
              query = providerQuery;
          } else {
              query = new MergeQuery<>(query, providerQuery);
          }
      }
    }
    return query;
}
 
Example #22
Source File: AbstractPropertiesProvider.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Create a search pattern for the given <code>annotationName</code> annotation
 * name.
 * 
 * @param annotationName the annotation name to search.
 * @return a search pattern for the given <code>annotationName</code> annotation
 *         name.
 */
protected static Query<PsiModifierListOwner> createAnnotationTypeReferenceSearchPattern(SearchContext context, String annotationName) {
	PsiClass annotationClass = context.getUtils().findClass(context.getModule(), annotationName);
	if (annotationClass != null) {
		return AnnotatedElementsSearch.searchElements(annotationClass, context.getScope(), PsiModifierListOwner.class);
	} else {
		return new EmptyQuery<>();
	}
}
 
Example #23
Source File: ChangeHelper.java    From MVPManager with MIT License 5 votes vote down vote up
public static void method(Project project, PsiJavaFile psiJavaFile, int type, MethodEntity methodEntity, boolean isDel) {
        for (PsiElement psiInterface :
                getClasses(psiJavaFile)) {
            if (psiInterface instanceof PsiClass) {
                switch (type) {
                    case ChangeMVPDialog.VIEW:
                        if (!ClassHelper.VIEW.equals(((PsiClass) psiInterface).getName())) continue;
                        break;
                    case ChangeMVPDialog.PRESENTER:
                        if (!ClassHelper.PRESENTER.equals(((PsiClass) psiInterface).getName())) continue;
                        break;
                    case ChangeMVPDialog.MODEL:
                        if (!ClassHelper.MODEL.equals(((PsiClass) psiInterface).getName())) continue;
                        break;
                }
                if (isDel) {
                    delMethod(project, psiInterface, methodEntity);
                } else {
                    ClassHelper.addMethodToClass(project, (PsiClass) psiInterface, createList(methodEntity), false);
                }
                if (((PsiClass) psiInterface).getExtendsList() == null) return;
//                ClassInheritorsSearch query = ClassInheritorsSearch.search((PsiClass) psiInterface, true);
                Query<PsiClass> query = ClassInheritorsSearch.search((PsiClass) psiInterface);
                for (Iterator<PsiClass> it = query.iterator(); it.hasNext(); ) {
                    PsiClass p = it.next();
                    if (isDel) {
                        delMethod(project, p, methodEntity);
                    } else {
                        ClassHelper.addMethodToClass(project, p, createList(methodEntity), true);
                    }
                }
            }
        }
    }
 
Example #24
Source File: AddConcernOnType.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
private static List<PsiClass> findConcernsCandidates( final @NotNull PsiClass classToCheck )
{
    GlobalSearchScope searchScope = determineSearchScope( classToCheck );
    PsiClass concernOfClass = getConcernOfClass( classToCheck.getProject(), searchScope );
    if( concernOfClass == null )
    {
        return emptyList();
    }

    Query<PsiClass> psiClassQuery = search( concernOfClass, searchScope, true, false );
    final List<PsiClass> concernCandidates = new ArrayList<PsiClass>();
    psiClassQuery.forEach( new Processor<PsiClass>()
    {
        public boolean process( PsiClass psiClass )
        {
            // TODO: Ideally search for all "extends" as well
            boolean isInheritor = psiClass.isInheritor( classToCheck, true );
            if( isInheritor )
            {
                concernCandidates.add( psiClass );
            }

            return true;
        }
    } );

    return concernCandidates;
}
 
Example #25
Source File: BashFixmeHighlighterTest.java    From BashSupport with Apache License 2.0 5 votes vote down vote up
@Test
public void testComment() {
    PsiFile file = myFixture.configureByText(BashFileType.BASH_FILE_TYPE, "# fixme: a\n#  b");
    Query<IndexPatternOccurrence> result = IndexPatternSearch.search(file, TodoIndexPatternProvider.getInstance(), true);
    Collection<IndexPatternOccurrence> matches = result.findAll();
    Assert.assertEquals(1, matches.size());

    IndexPatternOccurrence first = matches.iterator().next();
    Assert.assertEquals("A multiline comment must be detected as a single occurence with one additional text range", 1, first.getAdditionalTextRanges().size());
}
 
Example #26
Source File: BashFileRenameProcessor.java    From BashSupport with Apache License 2.0 5 votes vote down vote up
/**
 * Returns references to the given element. If it is a BashPsiElement a special search scope is used to locate the elements referencing the file.
 *
 * @param element References to the given element
 * @return
 */
@NotNull
@Override
public Collection<PsiReference> findReferences(PsiElement element) {
    //fixme fix the custom scope
    SearchScope scope = (element instanceof BashPsiElement)
            ? BashElementSharedImpl.getElementUseScope((BashPsiElement) element, element.getProject())
            : GlobalSearchScope.projectScope(element.getProject());

    Query<PsiReference> search = ReferencesSearch.search(element, scope);
    return search.findAll();
}
 
Example #27
Source File: AbstractTreeClassChooserDialog.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
protected abstract Query<T> searchForInheritors(T baseClass, GlobalSearchScope searchScope, boolean checkDeep);
 
Example #28
Source File: AbstractTreeClassChooserDialog.java    From consulo with Apache License 2.0 4 votes vote down vote up
protected Query<T> searchForInheritorsOfBaseClass() {
  return searchForInheritors(myBaseClass, myScope, true);
}
 
Example #29
Source File: DefinitionsScopedSearch.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static Query<PsiElement> search(PsiElement definitionsOf, SearchScope searchScope) {
  return search(definitionsOf, searchScope, true);
}
 
Example #30
Source File: AbstractAnnotationTypeReferencePropertiesProvider.java    From intellij-quarkus with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected Query<PsiModifierListOwner> createSearchPattern(SearchContext context, String annotationName) {
	return createAnnotationTypeReferenceSearchPattern(context, annotationName);
}