Java Code Examples for com.intellij.psi.search.GlobalSearchScope

The following are top voted examples for showing how to use com.intellij.psi.search.GlobalSearchScope. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: TS-IJ   File: TSGlobalCachedListGenerator.java   View source code 6 votes vote down vote up
@Override
public Set<TSVarExpr> generate(Project project) {
    Set<TSVarExpr> items = new HashSet<>();
    //Search every file in the project
    Collection<VirtualFile> virtualFiles = FileBasedIndex.getInstance().getContainingFiles(FileTypeIndex.NAME, TSFileType.INSTANCE, GlobalSearchScope.projectScope(project));
    for (VirtualFile virtualFile : virtualFiles) {
        TSFile tsFile = (TSFile) PsiManager.getInstance(project).findFile(virtualFile);
        if (tsFile != null) {
            Collection<TSAssignExpr> assignments = PsiTreeUtil.findChildrenOfType(tsFile, TSAssignExpr.class);
            for (TSAssignExpr assignment : assignments) {
                PsiElement first = assignment.getFirstChild();
                if (!(first instanceof TSVarExpr))
                    continue;

                if (((TSVarExpr)first).isLocal())
                    continue;

                items.add((TSVarExpr) first);

            }
        }
        ProgressManager.progress("Loading Symbols");
    }
    return items;
}
 
Example 2
Project: jgiven-intellij-plugin   File: ReferenceProviderTest.java   View source code 6 votes vote down vote up
@Test
public void should_process_reference() throws Exception {
    // given
    PsiReference reference1 = mock(PsiReference.class);
    PsiReference reference2 = mock(PsiReference.class);

    PsiField field = mock(PsiField.class);
    ReferencesSearch.SearchParameters searchParameters = mock(ReferencesSearch.SearchParameters.class);
    when(searchParameters.getElementToSearch()).thenReturn(field);
    when(searchParameters.getEffectiveSearchScope()).thenReturn(mock(GlobalSearchScope.class));
    when(scenarioStateReferenceProvider.findReferences(field)).thenReturn(Arrays.asList(reference1, reference2));
    when(scenarioStateProvider.isJGivenScenarioState(field)).thenReturn(true);

    // when
    referenceProvider.processQuery(searchParameters, processor);

    // then
    verify(processor).process(reference1);
    verify(processor).process(reference2);
}
 
Example 3
Project: reasonml-idea-plugin   File: PsiVarNameReference.java   View source code 6 votes vote down vote up
@Nullable
@Override
public PsiElement resolve() {
    PsiElement parent = PsiTreeUtil.getParentOfType(myElement, PsiLet.class);

    // If name is used in a let definition, it's already the reference
    if (parent instanceof PsiLet && ((PsiLet) parent).getNameIdentifier() == myElement) {
        return myElement;
    }

    // Find the name in the index
    Collection<PsiLet> elements = StubIndex.getElements(IndexKeys.LETS, m_referenceName, myElement.getProject(), GlobalSearchScope.allScope(myElement.getProject()), PsiLet.class);
    if (!elements.isEmpty()) {
        // TODO: only let with correct QN
        PsiLet let = elements.iterator().next();
        return let.getNameIdentifier();
    }

    return null;
}
 
Example 4
Project: manifold-ij   File: MoveTypeManifoldFileProcessor.java   View source code 6 votes vote down vote up
@Nullable
@Override
public List<UsageInfo> findUsages( PsiFile psiFile, PsiDirectory newParent, boolean searchInComments, boolean searchInNonJavaFiles )
{
  Module mod = ModuleUtilCore.findModuleForPsiElement( psiFile );
  ManModule module = ManProject.getModule( mod );
  PsiClass psiClass = findPsiClass( psiFile );
  if( psiClass == null )
  {
    return Collections.emptyList();
  }

  Query<PsiReference> search = ReferencesSearch.search( psiClass, GlobalSearchScope.moduleWithDependenciesAndLibrariesScope( module.getIjModule() ) );
  List<UsageInfo> usages = new ArrayList<>();
  for( PsiReference ref: search.findAll() )
  {
    usages.add( new MoveRenameUsageInfo( ref.getElement(), ref, ref.getRangeInElement().getStartOffset(),
      ref.getRangeInElement().getEndOffset(), psiClass,
      ref.resolve() == null && !(ref instanceof PsiPolyVariantReference && ((PsiPolyVariantReference)ref).multiResolve( true ).length > 0) ) );
  }
  return usages;
}
 
Example 5
Project: manifold-ij   File: ManShortNamesCache.java   View source code 6 votes vote down vote up
private void findPsiClasses( @NotNull @NonNls String name, @NotNull GlobalSearchScope scope, Set<PsiClass> psiClasses, ManModule start, ManModule module )
{
  for( ITypeManifold tm: module.getTypeManifolds() )
  {
    for( String fqn: tm.getAllTypeNames() )
    {
      String simpleName = ClassUtil.extractClassName( fqn );
      if( simpleName.equals( name ) )
      {
        PsiClass psiClass = ManifoldPsiClassCache.instance().getPsiClass( scope, module, fqn );
        if( psiClass == null )
        {
          return;
        }
        psiClasses.add( psiClass );
      }
    }
  }
  for( Dependency d : module.getDependencies() )
  {
    if( module == start || d.isExported() )
    {
      findPsiClasses( name, scope, psiClasses, start, (ManModule)d.getModule() );
    }
  }
}
 
Example 6
Project: idea-php-typo3-plugin   File: RouteHelper.java   View source code 6 votes vote down vote up
@NotNull
private static PsiElement[] getTargetMethods(@NotNull Project project, @NotNull String routeName) {
    List<PsiElement> result = new ArrayList<>();
    List<RouteStub> values = FileBasedIndex.getInstance().getValues(RouteIndex.KEY, routeName, GlobalSearchScope.allScope(project));
    PhpIndex phpIndex = PhpIndex.getInstance(project);

    for (RouteStub routeStub : values) {
        String fqn = routeStub.getController();

        Collection<PhpClass> classesByFQN = phpIndex.getClassesByFQN(fqn);
        classesByFQN.forEach(c -> {
            if (c.findMethodByName(routeStub.getMethod()) != null) {
                result.add(c.findMethodByName(routeStub.getMethod()));
            }
        });
    }

    return result.toArray(new PsiElement[result.size()]);
}
 
Example 7
Project: manifold-ij   File: VarHandler.java   View source code 6 votes vote down vote up
@Nullable
public PsiType inferType( PsiTypeElement typeElement )
{
  PsiType psiType = null;

  final PsiElement parent = typeElement.getParent();
  if( (parent instanceof PsiLocalVariable && isVar( (PsiLocalVariable)parent )) ||
      (parent instanceof PsiParameter && isVarForEach( (PsiParameter)parent )) )
  {

    if( parent instanceof PsiLocalVariable )
    {
      psiType = processLocalVariableInitializer( ((PsiLocalVariable)parent).getInitializer() );
    }
    else
    {
      psiType = processForeach( ((PsiParameter)parent).getDeclarationScope() );
    }

    if( null == psiType )
    {
      psiType = PsiType.getJavaLangObject( typeElement.getManager(), GlobalSearchScope.allScope( typeElement.getProject() ) );
    }
  }
  return psiType;
}
 
Example 8
Project: idea-php-typo3-plugin   File: IconIndex.java   View source code 6 votes vote down vote up
public static Map<VirtualFile, IconStub> getIconDefinitionByIdentifier(@NotNull Project project, String iconIdentifier) {
    Set<String> identifiers = new HashSet<>();
    identifiers.add(iconIdentifier);

    Map<VirtualFile, IconStub> icons = new THashMap<>();

    FileBasedIndex.getInstance().getFilesWithKey(KEY, identifiers, virtualFile -> {
        FileBasedIndex.getInstance().processValues(KEY, iconIdentifier, virtualFile, (file, value) -> {
            icons.put(file, value);

            return true;
        }, GlobalSearchScope.allScope(project));

        return true;
    }, GlobalSearchScope.allScope(project));

    return icons;
}
 
Example 9
Project: idea-php-typo3-plugin   File: ConstantMatcherInspection.java   View source code 6 votes vote down vote up
private Set<String> getRemovedConstantsFQNs(ConstantReference element) {
    Set<PsiElement> elements = new HashSet<>();
    PsiFile[] constantMatcherFiles = FilenameIndex.getFilesByName(element.getProject(), "ConstantMatcher.php", GlobalSearchScope.allScope(element.getProject()));
    for (PsiFile file : constantMatcherFiles) {

        Collections.addAll(
                elements,
                PsiTreeUtil.collectElements(file, el -> PlatformPatterns
                        .psiElement(StringLiteralExpression.class)
                        .withParent(
                                PlatformPatterns.psiElement(PhpElementTypes.ARRAY_KEY)
                                        .withAncestor(
                                                4,
                                                PlatformPatterns.psiElement(PhpElementTypes.RETURN)
                                        )
                        )
                        .accepts(el)
                )
        );
    }

    return elements.stream()
            .map(stringLiteral -> "\\" + ((StringLiteralExpression)stringLiteral).getContents())
            .collect(Collectors.toSet());
}
 
Example 10
Project: idea-php-typo3-plugin   File: ClassConstantMatcherInspection.java   View source code 6 votes vote down vote up
private Set<String> getDeprecatedClassConstants(PhpPsiElement element) {
    Set<PsiElement> elements = new HashSet<>();
    PsiFile[] classConstantMatcherFiles = FilenameIndex.getFilesByName(element.getProject(), "ClassConstantMatcher.php", GlobalSearchScope.allScope(element.getProject()));
    for (PsiFile file : classConstantMatcherFiles) {

        Collections.addAll(
                elements,
                PsiTreeUtil.collectElements(file, el -> PlatformPatterns
                        .psiElement(StringLiteralExpression.class)
                        .withParent(
                                PlatformPatterns.psiElement(PhpElementTypes.ARRAY_KEY)
                                        .withAncestor(
                                                4,
                                                PlatformPatterns.psiElement(PhpElementTypes.RETURN)
                                        )
                        )
                        .accepts(el)
                )
        );
    }

    return elements.stream().map(stringLiteral -> ((StringLiteralExpression)stringLiteral).getContents()).collect(Collectors.toSet());
}
 
Example 11
Project: manifold-ij   File: RenameResourceElementProcessor.java   View source code 6 votes vote down vote up
private static List<UsageInfo> findUsages( PsiElement element, PsiElement ctx )
  {
//    Module mod = ModuleUtilCore.findModuleForPsiElement( element );
//    if( mod == null )
//    {
//      return Collections.emptyList();
//    }

    Query<PsiReference> search = ReferencesSearch.search( element, GlobalSearchScope.moduleScope( ModuleUtilCore.findModuleForPsiElement( ctx ) ) );
    List<UsageInfo> usages = new ArrayList<>();
    for( PsiReference ref : search.findAll() )
    {
      MoveRenameUsageInfo usageInfo = new MoveRenameUsageInfo( ref.getElement(), ref, ref.getRangeInElement().getStartOffset(),
                                                               ref.getRangeInElement().getEndOffset(), element,
                                                               ref.resolve() == null && !(ref instanceof PsiPolyVariantReference && ((PsiPolyVariantReference)ref).multiResolve( true ).length > 0) );
      usages.add( usageInfo );
    }
    return usages;
  }
 
Example 12
Project: idea-php-typo3-plugin   File: TranslationUtil.java   View source code 6 votes vote down vote up
public static PsiElement[] findDefinitionElements(@NotNull Project project, @NotNull String translationId) {
    Set<String> keys = new HashSet<>();
    keys.add(translationId);

    List<PsiElement> elements = new ArrayList<>();
    FileBasedIndex.getInstance().getFilesWithKey(TranslationIndex.KEY, keys, virtualFile -> {
        FileBasedIndex.getInstance().processValues(TranslationIndex.KEY, translationId, virtualFile, (file, value) -> {
            PsiFile file1 = PsiManager.getInstance(project).findFile(file);
            if (file1 != null) {
                PsiElement elementAt = file1.findElementAt(value.getTextRange().getStartOffset());
                if (elementAt != null) {
                    elements.add(elementAt.getParent());
                }
            }

            return true;
        }, GlobalSearchScope.allScope(project));

        return true;
    }, GlobalSearchScope.allScope(project));

    return elements.toArray(new PsiElement[elements.size()]);
}
 
Example 13
Project: manifold-ij   File: ManTypeFinder.java   View source code 6 votes vote down vote up
@Override
public boolean processPackageDirectories(@NotNull PsiPackage psiPackage,
                                         @NotNull final GlobalSearchScope scope,
                                         @NotNull final Processor<PsiDirectory> consumer,
                                         boolean includeLibrarySources) {
  //System.out.println( "processDirectories() : " + psiPackage + " : " + scope );

  final PsiManager psiManager = PsiManager.getInstance( _project );
  return PackageIndex.getInstance( _project )
    .getDirsByPackageName(psiPackage.getQualifiedName(), includeLibrarySources)
    .forEach(new ReadActionProcessor<VirtualFile>() {
      @Override
      public boolean processInReadAction(final VirtualFile dir) {
        if (!scope.contains(dir)) return true;
        PsiDirectory psiDir = psiManager.findDirectory(dir);
        return psiDir == null || consumer.process(psiDir);
      }
    });
}
 
Example 14
Project: manifold-ij   File: MoveTypeManifoldFileProcessor.java   View source code 6 votes vote down vote up
@Nullable
private PsiClass findPsiClass( PsiFileSystemItem element )
{
  Module mod = ModuleUtilCore.findModuleForPsiElement( element );
  if( mod == null )
  {
    return null;
  }

  ManModule module = ManProject.getModule( mod );
  String[] fqns = module.getTypesForFile( FileUtil.toIFile( module.getProject(), element.getVirtualFile() ) );
  PsiClass psiClass = null;
  for( String fqn: fqns )
  {
    psiClass = ManifoldPsiClassCache.instance().getPsiClass( GlobalSearchScope.moduleWithDependenciesAndLibrariesScope( module.getIjModule() ), module, fqn );
    if( psiClass != null )
    {
      break;
    }
  }
  return psiClass;
}
 
Example 15
Project: idea-php-typo3-plugin   File: ControllerActionUtil.java   View source code 6 votes vote down vote up
public static PsiElement[] getDefinitionElements(@NotNull Project project, @NotNull String actionName) {
    Set<String> keys = new HashSet<>();
    keys.add(actionName);

    List<PsiElement> elements = new ArrayList<>();
    FileBasedIndex.getInstance().getFilesWithKey(ControllerActionIndex.KEY, keys, virtualFile -> {
        FileBasedIndex.getInstance().processValues(ControllerActionIndex.KEY, actionName, virtualFile, (file, value) -> {
            PsiFile file1 = PsiManager.getInstance(project).findFile(file);
            if (file1 != null) {
                PsiElement elementAt = file1.findElementAt(value.getTextRange().getStartOffset());
                if (elementAt != null) {
                    elements.add(elementAt.getParent().getParent());
                }
            }

            return true;
        }, GlobalSearchScope.allScope(project));

        return true;
    }, GlobalSearchScope.allScope(project));

    return elements.toArray(new PsiElement[elements.size()]);
}
 
Example 16
Project: idea-php-typo3-plugin   File: CoreServiceParser.java   View source code 6 votes vote down vote up
private void collectServices(Project project) {
    FileBasedIndex index = FileBasedIndex.getInstance();
    Collection<VirtualFile> containingFiles = index.getContainingFiles(
            FileTypeIndex.NAME,
            PhpFileType.INSTANCE,
            GlobalSearchScope.allScope(project)
    );
    containingFiles.removeIf(virtualFile -> !(virtualFile.getName().contains("ext_localconf.php")));

    for (VirtualFile projectFile : containingFiles) {
        PsiFile psiFile = PsiManager.getInstance(project).findFile(projectFile);
        if (psiFile != null) {
            psiFile.accept(new CoreServiceDefinitionParserVisitor(serviceMap));
        }
    }
}
 
Example 17
Project: magento2-phpstorm-plugin   File: DiIndex.java   View source code 6 votes vote down vote up
public Collection<PsiElement> getVirtualTypeElements(final String name, final GlobalSearchScope scope) {
    Collection<PsiElement> result = new ArrayList<>();

    Collection<VirtualFile> virtualFiles =
            FileBasedIndex.getInstance().getContainingFiles(VirtualTypeIndex.KEY, name, scope);

    for (VirtualFile virtualFile : virtualFiles) {
        XmlFile xmlFile = (XmlFile) PsiManager.getInstance(project).findFile(virtualFile);
        if (xmlFile != null) {
            Collection<XmlAttributeValue> valueElements = XmlPsiTreeUtil
                    .findAttributeValueElements(xmlFile, "virtualType", "name", name);
            result.addAll(valueElements);
        }
    }
    return result;
}
 
Example 18
Project: magento2-phpstorm-plugin   File: DiIndex.java   View source code 6 votes vote down vote up
@NotNull
private String getTopTypeOfVirtualType(@NonNull String name) {
    List<String> values;
    int parentNestingLevel = 0;
    int maxNestingLevel = 5;

    do {
        values = FileBasedIndex.getInstance()
                .getValues(VirtualTypeIndex.KEY, name, GlobalSearchScope.allScope(project));
        if (values.size() > 0 && values.get(0) != null) {
            name = values.get(0);
        }
    } while (values.size() > 0 || maxNestingLevel > parentNestingLevel++);

    return name;
}
 
Example 19
Project: manifold-ij   File: ManTypeFinder.java   View source code 6 votes vote down vote up
@Override
public PsiClass findClass( String fqn, GlobalSearchScope globalSearchScope )
{
  //System.out.println( "findClass() : " + fqn + " : " + globalSearchScope );

  if( DumbService.getInstance( globalSearchScope.getProject() ).isDumb() )
  {
    // skip processing during index rebuild
    return null;
  }

  List<ManModule> modules = findModules( globalSearchScope );

  for( ManModule m : modules )
  {
    PsiClass psiClass = ManifoldPsiClassCache.instance().getPsiClass( globalSearchScope, m, fqn );
    if( psiClass != null )
    {
      return psiClass;
    }
  }
  return null;
}
 
Example 20
Project: magento2-phpstorm-plugin   File: FileBasedIndexUtil.java   View source code 6 votes vote down vote up
private static Collection<VirtualFile> getValues(String moduleName, VirtualFile moduleVf, Project project)
{
    Collection<VirtualFile> viewVfs = new ArrayList<>();
    FileBasedIndex.getInstance()
            .processValues(
                    ModuleNameIndex.KEY, moduleName, moduleVf,
                    (file, value) -> {
                        VirtualFile viewVf = file.getParent().findFileByRelativePath(value.concat("/view"));
                        if (viewVf != null) {
                            viewVfs.add(viewVf);
                        }
                        return false;
                    },
                    GlobalSearchScope.fileScope(project, moduleVf)
            );
    return viewVfs;
}
 
Example 21
Project: magento2-phpstorm-plugin   File: PluginLineMarkerProvider.java   View source code 6 votes vote down vote up
List<PhpClass> getPluginsForClass(@NotNull PhpClass phpClass, @NotNull String classFQN) {
    List<PhpClass> results = new ArrayList<>();

    if (classPluginsMap.containsKey(classFQN)) {
        return classPluginsMap.get(classFQN);
    }

    List<Set<String>> plugins = FileBasedIndex.getInstance()
        .getValues(PluginIndex.KEY, classFQN, GlobalSearchScope.allScope(phpClass.getProject()));

    if (plugins.size() == 0) {
        classPluginsMap.put(classFQN, results);
        return results;
    }

    PhpIndex phpIndex = PhpIndex.getInstance(phpClass.getProject());

    for (Set<String> pluginClassNames: plugins) {
        for (String pluginClassName: pluginClassNames) {
            results.addAll(phpIndex.getClassesByFQN(pluginClassName));
        }
    }
    classPluginsMap.put(classFQN, results);
    return results;
}
 
Example 22
Project: magento2-phpstorm-plugin   File: EventDispatchReferenceProvider.java   View source code 6 votes vote down vote up
@NotNull
@Override
public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) {
    String value = StringUtil.unquoteString(element.getText());
    Collection<PsiElement> targets = EventIndex.getInstance(element.getProject())
            .getEventElements(
                    value,
                    GlobalSearchScope.getScopeRestrictedByFileTypes(
                            GlobalSearchScope.allScope(element.getProject()),
                            XmlFileType.INSTANCE
                    )
    );

    if (targets.size() > 0) {
        return new PsiReference[] {new PolyVariantReferenceBase(element, targets)};
    }
    return PsiReference.EMPTY_ARRAY;
}
 
Example 23
Project: magento2-phpstorm-plugin   File: EventNameReferenceProvider.java   View source code 6 votes vote down vote up
@NotNull
@Override
public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) {
    String value = StringUtil.unquoteString(element.getText());
    Collection<VirtualFile> containingFiles = FileBasedIndex.getInstance()
        .getContainingFiles(EventNameIndex.KEY, value,
                GlobalSearchScope.getScopeRestrictedByFileTypes(
                        GlobalSearchScope.allScope(element.getProject()),
                        PhpFileType.INSTANCE
                )
        );

    PsiManager psiManager = PsiManager.getInstance(element.getProject());
    for (VirtualFile virtualFile: containingFiles) {
        PhpFile phpFile = (PhpFile) psiManager.findFile(virtualFile);
        if (phpFile != null) {
            List<PsiElement> psiElements = new ArrayList<>();
            recursiveFill(psiElements, phpFile, value);
            if (psiElements.size() > 0) {
                return new PsiReference[] {new PolyVariantReferenceBase(element, psiElements)};
            }
        }
    }
    return PsiReference.EMPTY_ARRAY;
}
 
Example 24
Project: bamboo-soy   File: TemplateNameUtils.java   View source code 6 votes vote down vote up
/** Finds the matching SoyTemplateBlock by their exact name. */
public static List<SoyTemplateBlock> findTemplateDeclarations(
    PsiElement element, String identifier) {
  if (identifier.startsWith(".")) {
    identifier = ((SoyFile) element.getContainingFile()).getNamespace() + identifier;
  } else {
    AliasMapper mapper = new AliasMapper(element.getContainingFile());
    identifier = mapper.normalizeIdentifier(identifier);
  }

  Project project = element.getProject();
  return TemplateBlockIndex.INSTANCE
      .get(identifier, project, GlobalSearchScope.allScope(project))
      .stream()
      .filter((block) -> block.getDefinitionIdentifier() != null)
      .collect(Collectors.toList());
}
 
Example 25
Project: bamboo-soy   File: TemplateNameUtils.java   View source code 6 votes vote down vote up
/** Finds all local template names in the given file. */
public static List<String> findLocalTemplateNames(PsiElement element) {
  PsiFile file = element.getContainingFile();
  return TemplateBlockIndex.INSTANCE
      .getAllKeys(file.getProject())
      .stream()
      .flatMap(
          (key) ->
              TemplateBlockIndex.INSTANCE
                  .get(
                      key, file.getProject(), GlobalSearchScope.fileScope(file.getOriginalFile()))
                  .stream()
                  .filter((block) -> !block.isDelegate())
                  .map(SoyTemplateBlock::getName))
      .collect(Collectors.toList());
}
 
Example 26
Project: manifold-ij   File: ManTypeFinder.java   View source code 6 votes vote down vote up
@Override
public PsiClass[] findClasses( String fqn, GlobalSearchScope globalSearchScope )
{
  //System.out.println( "PsiClass[] findClasses() : " + fqn + " : " + globalSearchScope );

  if( DumbService.getInstance( globalSearchScope.getProject() ).isDumb() )
  {
    // skip processing during index rebuild
    return PsiClass.EMPTY_ARRAY;
  }

  List<PsiClass> psiClasses = new ArrayList<>();
  List<ManModule> modules = findModules( globalSearchScope );
  for( ManModule m : modules )
  {
    PsiClass psiClass = ManifoldPsiClassCache.instance().getPsiClass( globalSearchScope, m, fqn );
    if( psiClass != null )
    {
      psiClasses.add( psiClass );
    }
  }
  return psiClasses.toArray( new PsiClass[psiClasses.size()] );
}
 
Example 27
Project: idea-php-dotenv-plugin   File: EnvironmentVariablesApi.java   View source code 6 votes vote down vote up
/**
 *
 * @param project project
 * @param key environment variable key
 * @return All key declarations, in .env files, Dockerfile, docker-compose.yml, etc
 */
@NotNull
public static PsiElement[] getKeyDeclarations(Project project, String key) {
    List<PsiElement> targets = new ArrayList<>();

    FileBasedIndex.getInstance().getFilesWithKey(DotEnvKeysIndex.KEY, new HashSet<>(Collections.singletonList(key)), virtualFile -> {
        PsiFile psiFileTarget = PsiManager.getInstance(project).findFile(virtualFile);
        if(psiFileTarget == null) {
            return true;
        }

        for(EnvironmentVariablesProvider provider : EnvironmentVariablesProviderUtil.PROVIDERS) {
            if(provider.acceptFile(virtualFile)) {
                targets.addAll(EnvironmentVariablesUtil.getElementsByKey(key, provider.getElements(psiFileTarget)));
            }
        }

        return true;
    }, GlobalSearchScope.allScope(project));

    return targets.toArray(new PsiElement[0]);
}
 
Example 28
Project: idea-php-dotenv-plugin   File: EnvironmentVariablesApi.java   View source code 6 votes vote down vote up
/**
 *
 * @param project project
 * @param key environment variable key
 * @return All key usages, like getenv('KEY')
 */
@NotNull
public static PsiElement[] getKeyUsages(Project project, String key) {
    List<PsiElement> targets = new ArrayList<>();

    FileBasedIndex.getInstance().getFilesWithKey(DotEnvUsagesIndex.KEY, new HashSet<>(Collections.singletonList(key)), virtualFile -> {
        PsiFile psiFileTarget = PsiManager.getInstance(project).findFile(virtualFile);
        if(psiFileTarget == null) {
            return true;
        }

        for(EnvironmentVariablesUsagesProvider provider : EnvironmentVariablesProviderUtil.USAGES_PROVIDERS) {
            if(provider.acceptFile(virtualFile)) {
                targets.addAll(EnvironmentVariablesUtil.getUsagesElementsByKey(key, provider.getUsages(psiFileTarget)));
            }
        }

        return true;
    }, GlobalSearchScope.allScope(project));

    return targets.toArray(new PsiElement[0]);
}
 
Example 29
Project: idea-php-dotenv-plugin   File: DotEnvLightCodeInsightFixtureTestCase.java   View source code 6 votes vote down vote up
public void assertIndex(@NotNull ID<String, ?> id, boolean notCondition, @NotNull String... keys) {
    for (String key : keys) {

        final Collection<VirtualFile> virtualFiles = new ArrayList<VirtualFile>();

        FileBasedIndexImpl.getInstance().getFilesWithKey(id, new HashSet<String>(Arrays.asList(key)), new Processor<VirtualFile>() {
            @Override
            public boolean process(VirtualFile virtualFile) {
                virtualFiles.add(virtualFile);
                return true;
            }
        }, GlobalSearchScope.allScope(getProject()));

        if(notCondition && virtualFiles.size() > 0) {
            fail(String.format("Fail that ID '%s' not contains '%s'", id.toString(), key));
        } else if(!notCondition && virtualFiles.size() == 0) {
            fail(String.format("Fail that ID '%s' contains '%s'", id.toString(), key));
        }
    }
}
 
Example 30
Project: intellij-postfix-templates   File: CptUtil.java   View source code 6 votes vote down vote up
public static List<CptMapping> findMappings(Project project, String key) {
	List<CptMapping> result = null;

	Collection<VirtualFile> virtualFiles =
		FileBasedIndex.getInstance().getContainingFiles(FileTypeIndex.NAME, CptFileType.INSTANCE,
			GlobalSearchScope.allScope(project));

	for (VirtualFile virtualFile : virtualFiles) {
		CptFile cptFile = (CptFile) PsiManager.getInstance(project).findFile(virtualFile);

		if (cptFile != null) {
			CptMapping[] mappings = PsiTreeUtil.getChildrenOfType(cptFile, CptMapping.class);
			if (mappings != null) {
				for (CptMapping mapping : mappings) {
					if (key.equals(mapping.getMatchingClass())) {
						if (result == null) {
							result = new ArrayList<>();
						}
						result.add(mapping);
					}
				}
			}
		}
	}
	return result != null ? result : Collections.emptyList();
}
 
Example 31
Project: hybris-integration-intellij-idea-plugin   File: HybrisEnumLiteralItemReference.java   View source code 6 votes vote down vote up
@NotNull
@Override
public ResolveResult[] multiResolve(final boolean incompleteCode) {
    Project project = myElement.getProject();
    final String enumLiteralJavaModelName = myElement.getText().replaceAll("\"", "").toUpperCase();

    final PsiShortNamesCache psiShortNamesCache = PsiShortNamesCache.getInstance(project);
    final PsiField[] javaEnumLiteralFields = psiShortNamesCache.getFieldsByName(
        enumLiteralJavaModelName, GlobalSearchScope.allScope(project)
    );

    final Set<PsiField> enumFields = stream(javaEnumLiteralFields)
        .filter(literal -> literal.getParent() != null)
        .filter(literal -> literal.getParent() instanceof ClsClassImpl)
        .filter(literal -> ((ClsClassImpl) literal.getParent()).isEnum())
        .collect(Collectors.toSet());

    return PsiElementResolveResult.createResults(enumFields);
}
 
Example 32
Project: hybris-integration-intellij-idea-plugin   File: HybrisModelItemReference.java   View source code 6 votes vote down vote up
@NotNull
@Override
public ResolveResult[] multiResolve(final boolean incompleteCode) {
    final Project project = myElement.getProject();
    final String modelName = PATTERN.matcher(myElement.getText()).replaceAll("");

    final String javaModelName = modelName + JAVA_MODEL_SUFFIX;
    final String jaloModelName = modelName;

    final PsiClass[] javaModelClasses = PsiShortNamesCache.getInstance(project).getClassesByName(
        javaModelName, GlobalSearchScope.allScope(project)
    );

    final PsiClass[] jaloModelClasses = PsiShortNamesCache.getInstance(project).getClassesByName(
        jaloModelName, GlobalSearchScope.projectScope(project)
    );

    final PsiClass[] psiClasses = ArrayUtil.mergeArrays(javaModelClasses, jaloModelClasses);
    return PsiElementResolveResult.createResults(psiClasses);
}
 
Example 33
Project: data-mediator   File: PropertyGenerator.java   View source code 6 votes vote down vote up
private PsiField createConstantField(PsiClass mPsiClass, PsiElementFactory elementFactory, Property prop) {
    // Property PROP_student = SharedProperties.get("com.heaven7.data.mediator.demo.testpackage.TestBind", "student", 0);
    PsiType psiType = PsiType.getTypeByName("com.heaven7.java.data.mediator.Property",
            mPsiClass.getProject(), GlobalSearchScope.allScope(mPsiClass.getProject()));
    PsiField psiField = elementFactory.createField("PROP_" + prop.getName(), psiType);
    PsiExpression psiInitializer = elementFactory.createExpressionFromText(
            String.format("%s.get(%s.class.getName(), \"%s\" ,%d)",
                    "com.heaven7.java.data.mediator.internal.SharedProperties",
                    prop.getTypeString(), prop.getName(), prop.getComplexType()),
            psiField);
    psiField.setInitializer(psiInitializer);
    PsiModifierList modifierList = psiField.getModifierList();
    if (modifierList != null) {
        modifierList.setModifierProperty(PsiModifier.PUBLIC + " " + PsiModifier.STATIC, true);
    }
    return psiField;
}
 
Example 34
Project: intellij-plugin   File: CoffigDocumentationProvider.java   View source code 6 votes vote down vote up
private Optional<PropertiesFile> findResourceBundle(Project project, PsiClass configClass) {
    String qualifiedName = configClass.getQualifiedName();
    if (qualifiedName != null) {
        int lastDotIndex = qualifiedName.lastIndexOf(".");
        String packageName = qualifiedName.substring(0, lastDotIndex);
        String className = qualifiedName.substring(lastDotIndex + 1);
        PsiPackage psiPackage = JavaPsiFacade.getInstance(project).findPackage(packageName);
        if (psiPackage != null) {
            return Arrays.stream(psiPackage.getFiles(GlobalSearchScope.allScope(project)))
                    .filter(psiFile -> psiFile instanceof PropertiesFile && psiFile.getVirtualFile().getNameWithoutExtension().equals(className))
                    .map(psiFile -> (PropertiesFile) psiFile)
                    .findFirst();
        }
    }
    return Optional.empty();
}
 
Example 35
Project: intellij-plugin   File: CoffigResolver.java   View source code 6 votes vote down vote up
Stream<PsiClass> classStream() {
    if (context.isValid()) {
        Stream<PsiClass> stream = StreamSupport.stream(
                AnnotatedElementsSearch.searchPsiClasses(
                        context.getConfigAnnotationClass(),
                        GlobalSearchScope.allScope(context.getProject())).spliterator(),
                false);
        Predicate<PsiClass> filter = context.getFilter();
        if (filter != null) {
            stream = stream.filter(filter);
        }
        return stream;
    } else {
        return Stream.empty();
    }
}
 
Example 36
Project: intellij-plugin   File: AnnotatedInterfaceNode.java   View source code 6 votes vote down vote up
@Override
protected MultiMap<PsiFile, T> computeChildren(@Nullable PsiFile psiFile) {
    MultiMap<PsiFile, T> children = new MultiMap<>();
    Project project = getProject();
    if (project != null) {
        JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(project);
        PsiClass serviceAnnotation = javaPsiFacade.findClass(getAnnotationQName(), GlobalSearchScope.allScope(project));
        if (serviceAnnotation != null) {
            AnnotatedElementsSearch.searchPsiClasses(serviceAnnotation, GlobalSearchScope.allScope(project)).forEach(psiClass -> {
                if (psiClass.isInterface() && isSatisfying(psiClass)) {
                    children.putValue(psiClass.getContainingFile(), createChild(psiClass));
                }
                return true;
            });
        }
    }
    return children;
}
 
Example 37
Project: intellij-plugin   File: AggregateNode.java   View source code 6 votes vote down vote up
@Override
protected MultiMap<PsiFile, ClassNode> computeChildren(@Nullable PsiFile psiFile) {
    MultiMap<PsiFile, ClassNode> children = new MultiMap<>();
    children.putValue(aggregateRoot.getContainingFile(), new AggregateRootNode(this, aggregateRoot));
    Project project = getProject();
    if (project != null) {
        JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(project);
        PsiClass entityInterface = javaPsiFacade.findClass(ENTITY_INTERFACE, GlobalSearchScope.allScope(project));
        PsiClass valueObjectInterface = javaPsiFacade.findClass(VO_INTERFACE, GlobalSearchScope.allScope(project));
        if (entityInterface != null && valueObjectInterface != null) {
            for (PsiClass psiClass : psiPackage.getClasses(GlobalSearchScope.allScope(project))) {
                if (psiClass.isInheritor(entityInterface, true) && !psiClass.equals(aggregateRoot)) {
                    children.putValue(psiClass.getContainingFile(), new EntityNode(this, psiClass));
                } else if (psiClass.isInheritor(valueObjectInterface, true)) {
                    children.putValue(psiClass.getContainingFile(), new ValueObjectNode(this, psiClass));
                }
            }
        }
    }
    return children;
}
 
Example 38
Project: intellij-plugin   File: AggregatesNode.java   View source code 6 votes vote down vote up
@Override
protected MultiMap computeChildren(@Nullable PsiFile psiFile) {
    MultiMap<PsiFile, AggregateNode> children = new MultiMap<>();
    Project project = getProject();
    if (project != null) {
        JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(project);
        PsiClass psiClass = javaPsiFacade.findClass(AGGREGATE_ROOT_INTERFACE, GlobalSearchScope.allScope(project));
        if (psiClass != null) {
            ClassInheritorsSearch.search(psiClass, GlobalSearchScope.allScope(project), true).forEach(candidate -> {
                String qualifiedName = candidate.getQualifiedName();
                if (qualifiedName != null && !qualifiedName.startsWith(BUSINESS_PACKAGE) && !isAbstract(candidate)) {
                    children.putValue(candidate.getContainingFile(), new AggregateNode(this, candidate));
                }
            });
        }

    }
    return children;
}
 
Example 39
Project: intellij-plugin   File: ResourcesNode.java   View source code 6 votes vote down vote up
@Override
public MultiMap<PsiFile, ResourceNode> computeChildren(PsiFile psiFile) {
    Project project = getProject();
    MultiMap<PsiFile, ResourceNode> children = new MultiMap<>();
    if (project != null) {
        JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(project);
        PsiClass pathAnnotation = javaPsiFacade.findClass(PATH_ANNOTATION, GlobalSearchScope.allScope(project));
        if (pathAnnotation != null) {
            AnnotatedElementsSearch.searchPsiClasses(pathAnnotation, GlobalSearchScope.allScope(project)).forEach(psiClass -> {
                if (!psiClass.isInterface() && !NavigatorUtil.isAbstract(psiClass)) {
                    children.putValue(psiClass.getContainingFile(), new ResourceNode(ResourcesNode.this, pathAnnotation, psiClass));
                }
                return true;
            });
        }
    }
    return children;
}
 
Example 40
Project: intellij-plugin   File: ToolsNode.java   View source code 6 votes vote down vote up
protected MultiMap<PsiFile, ToolNode> computeChildren(PsiFile psiFile) {
    MultiMap<PsiFile, ToolNode> children = new MultiMap<>();
    Project project = getProject();
    if (project != null) {
        PsiClass toolInterface = JavaPsiFacade.getInstance(project).findClass(TOOL_INTERFACE, GlobalSearchScope.allScope(project));
        if (toolInterface != null) {
            ClassInheritorsSearch.search(toolInterface, GlobalSearchScope.allScope(project), true).forEach(psiClass -> {
                PsiFile containingFile = psiClass.getContainingFile();
                if (!isAbstract(psiClass)) {
                    children.putValue(containingFile, new ToolNode(this, psiClass));
                }
            });
        }
    }
    return children;
}