public void testExternalFileModificationWhileProjectClosed() throws Exception {
    VirtualFile root = ProjectRootManager.getInstance(myProject).getContentRoots()[0];

    PsiClass objectClass =
        myJavaFacade.findClass(
            CommonClassNames.JAVA_LANG_OBJECT, GlobalSearchScope.allScope(getProject()));
    assertNotNull(objectClass);
    checkUsages(objectClass, new String[] {});
    FileBasedIndex.getInstance()
        .getContainingFiles(
            TodoIndex.NAME,
            new TodoIndexEntry("todo", true),
            GlobalSearchScope.allScope(getProject()));

    final String projectLocation = myProject.getPresentableUrl();
    assert projectLocation != null : myProject;
    PlatformTestUtil.saveProject(myProject);
    final VirtualFile content = ModuleRootManager.getInstance(getModule()).getContentRoots()[0];
    Project project = myProject;
    ProjectUtil.closeAndDispose(project);
    InjectedLanguageManagerImpl.checkInjectorsAreDisposed(project);

    assertTrue("Project was not disposed", myProject.isDisposed());
    myModule = null;

    final File file = new File(root.getPath(), "1.java");
    assertTrue(file.exists());

    FileUtil.writeToFile(file, "class A{ Object o;}".getBytes(CharsetToolkit.UTF8_CHARSET));
    root.refresh(false, true);

    LocalFileSystem.getInstance().refresh(false);

    myProject = ProjectManager.getInstance().loadAndOpenProject(projectLocation);
    InjectedLanguageManagerImpl.pushInjectors(getProject());

    setUpModule();
    setUpJdk();
    ProjectManagerEx.getInstanceEx().openTestProject(myProject);
    UIUtil.dispatchAllInvocationEvents(); // startup activities

    runStartupActivities();
    PsiTestUtil.addSourceContentToRoots(getModule(), content);

    assertNotNull(myProject);
    myPsiManager = (PsiManagerImpl) PsiManager.getInstance(myProject);
    myJavaFacade = JavaPsiFacadeEx.getInstanceEx(myProject);

    objectClass =
        myJavaFacade.findClass(
            CommonClassNames.JAVA_LANG_OBJECT, GlobalSearchScope.allScope(getProject()));
    assertNotNull(objectClass);
    checkUsages(objectClass, new String[] {"1.java"});
  }
 @NotNull
 public static GlobalSearchScope getMaximalScope(@NotNull FindUsagesHandler handler) {
   PsiElement element = handler.getPsiElement();
   Project project = element.getProject();
   PsiFile file = element.getContainingFile();
   if (file != null
       && ProjectFileIndex.SERVICE
           .getInstance(project)
           .isInContent(file.getViewProvider().getVirtualFile())) {
     return GlobalSearchScope.projectScope(project);
   }
   return GlobalSearchScope.allScope(project);
 }
 public void testProtectedMethodInPackageLocalClass() throws Throwable {
   PsiMethod method =
       myJavaFacade.findClass("foo.PackageLocal", GlobalSearchScope.allScope(myProject))
           .getMethods()[0];
   assertEquals(1, OverridingMethodsSearch.search(method).findAll().size());
   assertEquals(1, ReferencesSearch.search(method).findAll().size());
 }
 public void testLibraryClassUsageFromDecompiledSource() {
   PsiElement decompiled =
       ((PsiCompiledElement)
               myJavaFacade.findClass("javax.swing.JLabel", GlobalSearchScope.allScope(myProject)))
           .getMirror();
   assertEquals(2, ReferencesSearch.search(decompiled).findAll().size());
 }
  public void testSCR6066() throws Exception {
    ProjectRootManagerEx rootManager =
        (ProjectRootManagerEx) ProjectRootManager.getInstance(myProject);
    final VirtualFile root = rootManager.getContentRoots()[0];

    PsiTodoSearchHelper.SERVICE
        .getInstance(myProject)
        .findFilesWithTodoItems(); // to initialize caches

    new WriteCommandAction.Simple(getProject()) {
      @Override
      protected void run() throws Throwable {
        VirtualFile newFile = createChildData(root, "New.java");
        setFileText(newFile, "class A{ Exception e;} //todo");
      }
    }.execute().throwException();

    PsiDocumentManager.getInstance(myProject).commitAllDocuments();

    PsiTodoSearchHelper.SERVICE.getInstance(myProject).findFilesWithTodoItems(); // to update caches

    PsiTestUtil.addExcludedRoot(myModule, root);

    PsiClass exceptionClass =
        myJavaFacade.findClass("java.lang.Exception", GlobalSearchScope.allScope(getProject()));
    assertNotNull(exceptionClass);
    checkUsages(exceptionClass, new String[] {});
    checkTodos(new String[] {});
  }
  public void testRemoveSourceRoot() {
    final VirtualFile root = ModuleRootManager.getInstance(myModule).getContentRoots()[0];

    PsiTodoSearchHelper.SERVICE
        .getInstance(myProject)
        .findFilesWithTodoItems(); // to initialize caches

    new WriteCommandAction.Simple(getProject()) {
      @Override
      protected void run() throws Throwable {
        VirtualFile newFile = createChildData(root, "New.java");
        setFileText(newFile, "class A{ Exception e;} //todo");
      }
    }.execute().throwException();

    PsiDocumentManager.getInstance(myProject).commitAllDocuments();

    PsiTodoSearchHelper.SERVICE.getInstance(myProject).findFilesWithTodoItems(); // to update caches

    VirtualFile[] sourceRoots = ModuleRootManager.getInstance(myModule).getSourceRoots();
    LOG.assertTrue(sourceRoots.length == 1);
    PsiTestUtil.removeSourceRoot(myModule, sourceRoots[0]);

    PsiClass exceptionClass =
        myJavaFacade.findClass("java.lang.Exception", GlobalSearchScope.allScope(getProject()));
    assertNotNull(exceptionClass);
    // currently it actually finds usages by FQN due to Java PSI enabled for out-of-source java
    // files
    // so the following check is disabled
    // checkUsages(exceptionClass, new String[]{});
    checkTodos(new String[] {"2.java", "New.java"});
  }
  public void testAddSourceRoot() throws Exception {
    File dir = createTempDirectory();

    final VirtualFile root =
        LocalFileSystem.getInstance()
            .refreshAndFindFileByPath(dir.getCanonicalPath().replace(File.separatorChar, '/'));

    new WriteCommandAction.Simple(getProject()) {
      @Override
      protected void run() throws Throwable {
        PsiTestUtil.addContentRoot(myModule, root);

        VirtualFile newFile = createChildData(root, "New.java");
        setFileText(newFile, "class A{ Exception e;} //todo");
      }
    }.execute().throwException();

    PsiDocumentManager.getInstance(myProject).commitAllDocuments();

    PsiTodoSearchHelper.SERVICE
        .getInstance(myProject)
        .findFilesWithTodoItems(); // to initialize caches

    PsiTestUtil.addSourceRoot(myModule, root);

    PsiClass exceptionClass =
        myJavaFacade.findClass("java.lang.Exception", GlobalSearchScope.allScope(getProject()));
    assertNotNull(exceptionClass);
    checkUsages(exceptionClass, new String[] {"1.java", "2.java", "New.java"});
    checkTodos(new String[] {"2.java", "New.java"});
  }
  public void testXml() throws Exception {
    PsiClass aClass = myJavaFacade.findClass("com.Foo", GlobalSearchScope.allScope(myProject));
    doTest(aClass, new String[] {"Test.xml"}, new int[] {32}, new int[] {35});

    final PsiFile nonCodeUsage =
        PsiFileFactory.getInstance(myProject)
            .createFileFromText("a.xml", StdFileTypes.XML, "<root action='com.Foo'/>", 0, true);
    assertTrue(new UsageInfo(nonCodeUsage, 14, 21, true).getNavigationOffset() > 0);
  }
  public void testImplicitConstructorUsage() throws Throwable {
    PsiMethod[] ctrs =
        myJavaFacade.findClass("Foo", GlobalSearchScope.allScope(myProject)).getConstructors();
    PsiMethod method = ctrs[0];
    assertEquals(0, method.getParameterList().getParametersCount());
    assertEquals(0, ReferencesSearch.search(method).findAll().size());

    PsiMethod usedMethod = ctrs[1];
    assertEquals(1, usedMethod.getParameterList().getParametersCount());
    assertEquals(1, ReferencesSearch.search(usedMethod).findAll().size());
  }
  public void testExternalDirDeletion() throws Exception {
    VirtualFile root = ProjectRootManager.getInstance(myProject).getContentRoots()[0];

    VirtualFile file = root.findChild("aDir");
    assertNotNull(file);
    delete(file);

    PsiClass threadClass =
        myJavaFacade.findClass("java.lang.Thread", GlobalSearchScope.allScope(getProject()));
    assertNotNull(threadClass);
    checkUsages(threadClass, ArrayUtil.EMPTY_STRING_ARRAY);
  }
 @NotNull
 static SearchScope getScopeFromModel(@NotNull Project project, @NotNull FindModel findModel) {
   SearchScope customScope = findModel.getCustomScope();
   VirtualFile directory = getDirectory(findModel);
   Module module =
       findModel.getModuleName() == null
           ? null
           : ModuleManager.getInstance(project).findModuleByName(findModel.getModuleName());
   return findModel.isCustomScope() && customScope != null
       ? customScope.intersectWith(GlobalSearchScope.allScope(project))
       :
       // we don't have to check for myProjectFileIndex.isExcluded(file) here like
       // FindInProjectTask.collectFilesInScope() does
       // because all found usages are guaranteed to be not in excluded dir
       directory != null
           ? forDirectory(project, findModel.isWithSubdirectories(), directory)
           : module != null
               ? module.getModuleContentScope()
               : findModel.isProjectScope()
                   ? ProjectScope.getContentScope(project)
                   : GlobalSearchScope.allScope(project);
 }
  public void testExternalFileModification() throws Exception {
    VirtualFile root = ProjectRootManager.getInstance(myProject).getContentRoots()[0];

    VirtualFile file = root.findChild("1.java");
    assertNotNull(file);
    setFileText(file, "class A{ Object o;}");
    PsiDocumentManager.getInstance(myProject).commitAllDocuments();

    PsiClass objectClass =
        myJavaFacade.findClass(
            CommonClassNames.JAVA_LANG_OBJECT, GlobalSearchScope.allScope(getProject()));
    assertNotNull(objectClass);
    checkUsages(objectClass, new String[] {"1.java"});
  }
 public void testOverloadConstructors() throws Exception {
   PsiClass aClass = myJavaFacade.findClass("B", GlobalSearchScope.allScope(myProject));
   PsiMethod constructor;
   //    constructor = myJavaFacade.getElementFactory().createConstructor();
   //    constructor = aClass.findMethodBySignature(constructor, false);
   constructor = aClass.findMethodsByName("B", false)[0];
   PsiMethodCallExpression superCall =
       (PsiMethodCallExpression) constructor.getBody().getStatements()[0].getFirstChild();
   PsiReferenceExpression superExpr = superCall.getMethodExpression();
   String[] fileNames = new String[] {"B.java", "A.java", "A.java", "B.java"};
   int[] starts = new int[] {};
   int[] ends = new int[] {};
   final ArrayList<PsiFile> filesList = new ArrayList<PsiFile>();
   final IntArrayList startsList = new IntArrayList();
   final IntArrayList endsList = new IntArrayList();
   PsiReference[] refs =
       MethodReferencesSearch.search(
               (PsiMethod) superExpr.resolve(), GlobalSearchScope.projectScope(myProject), false)
           .toArray(PsiReference.EMPTY_ARRAY);
   for (PsiReference ref : refs) {
     addReference(ref, filesList, startsList, endsList);
   }
   checkResult(fileNames, filesList, starts, startsList, ends, endsList);
 }
  public void testExternalFileCreation() throws Exception {
    VirtualFile root = ProjectRootManager.getInstance(myProject).getContentRoots()[0];

    String newFilePath = root.getPresentableUrl() + File.separatorChar + "New.java";
    FileUtil.writeToFile(
        new File(newFilePath), "class A{ Object o;}".getBytes(CharsetToolkit.UTF8_CHARSET));
    VirtualFile file =
        LocalFileSystem.getInstance()
            .refreshAndFindFileByPath(newFilePath.replace(File.separatorChar, '/'));
    assertNotNull(file);
    PsiDocumentManager.getInstance(myProject).commitAllDocuments();

    PsiClass objectClass =
        myJavaFacade.findClass(
            CommonClassNames.JAVA_LANG_OBJECT, GlobalSearchScope.allScope(getProject()));
    assertNotNull(objectClass);
    checkUsages(objectClass, new String[] {"New.java"});
  }
  public static void doTest(PsiElement element, String[] fileNames, int[] starts, int[] ends)
      throws Exception {
    final ArrayList<PsiFile> filesList = new ArrayList<PsiFile>();
    final IntArrayList startsList = new IntArrayList();
    final IntArrayList endsList = new IntArrayList();
    ReferencesSearch.search(element, GlobalSearchScope.projectScope(element.getProject()), false)
        .forEach(
            new PsiReferenceProcessorAdapter(
                new PsiReferenceProcessor() {
                  @Override
                  public boolean execute(PsiReference ref) {
                    addReference(ref, filesList, startsList, endsList);
                    return true;
                  }
                }));

    checkResult(fileNames, filesList, starts, startsList, ends, endsList);
  }
 public boolean execute(
     ReferencesSearch.SearchParameters params, final Processor<PsiReference> consumer) {
   final PsiElement elem = params.getElementToSearch();
   SearchScope scope = params.getEffectiveSearchScope();
   if (elem instanceof PsiNamedElement
       /* An optimization for Java refactorings */
       && !(elem instanceof PsiVariable)) {
     final PsiNamedElement symbolToSearch = (PsiNamedElement) elem;
     final String name = symbolToSearch.getName();
     if (name != null) {
       RequestResultProcessor processor =
           new RequestResultProcessor() {
             @Override
             public boolean processTextOccurrence(
                 @NotNull PsiElement element,
                 int offsetInElement,
                 @NotNull Processor<PsiReference> consumer) {
               if (element instanceof ClSymbol) {
                 ClSymbol refSymbol = (ClSymbol) element;
                 for (PsiReference ref : refSymbol.getReferences()) {
                   if (ref.getRangeInElement().contains(offsetInElement)
                       &&
                       // atom may refer to definition or to the symbol in it
                       (ref.resolve() == symbolToSearch
                           || ref.resolve() == symbolToSearch.getParent())) {
                     if (!consumer.process(ref)) return false;
                   }
                 }
               }
               return true;
             }
           };
       if (scope instanceof GlobalSearchScope) {
         scope =
             GlobalSearchScope.getScopeRestrictedByFileTypes(
                 (GlobalSearchScope) scope, ClojureFileType.CLOJURE_FILE_TYPE);
       }
       for (String word : StringUtil.getWordsIn(name)) {
         params.getOptimizer().searchWord(word, scope, UsageSearchContext.ANY, true, processor);
       }
     }
   }
   return true;
 }
  public void testFileCreation() throws Exception {
    PsiDirectory root = ProjectRootUtil.getAllContentRoots(myProject)[0];

    PsiFile file =
        PsiFileFactory.getInstance(myProject)
            .createFileFromText("New.java", JavaFileType.INSTANCE, "class A{ Object o;}");
    final PsiFile finalFile = file;
    file =
        new WriteAction<PsiFile>() {
          @Override
          protected void run(Result<PsiFile> result) throws Throwable {
            PsiFile res = (PsiFile) root.add(finalFile);
            result.setResult(res);
          }
        }.execute().throwException().getResultObject();
    assertNotNull(file);

    PsiClass objectClass =
        myJavaFacade.findClass(
            CommonClassNames.JAVA_LANG_OBJECT, GlobalSearchScope.allScope(getProject()));
    assertNotNull(objectClass);
    checkUsages(objectClass, new String[] {"New.java"});
  }
  private void checkUsages(PsiElement element, @NonNls String[] expectedFiles) {
    PsiReference[] refs =
        ReferencesSearch.search(element, GlobalSearchScope.projectScope(myProject), false)
            .toArray(PsiReference.EMPTY_ARRAY);

    List<PsiFile> files = new ArrayList<PsiFile>();
    for (PsiReference ref : refs) {
      PsiFile file = ref.getElement().getContainingFile();
      if (!files.contains(file)) {
        files.add(file);
      }
    }

    assertEquals(expectedFiles.length, files.size());

    Collections.sort(files, (file1, file2) -> file1.getName().compareTo(file2.getName()));
    Arrays.sort(expectedFiles);

    for (int i = 0; i < expectedFiles.length; i++) {
      String name = expectedFiles[i];
      PsiFile file = files.get(i);
      assertEquals(name, file.getName());
    }
  }
  @NotNull
  private Collection<PsiFile> collectFilesInScope(
      @NotNull final Set<PsiFile> alreadySearched, final boolean skipIndexed) {
    SearchScope customScope = myFindModel.getCustomScope();
    final GlobalSearchScope globalCustomScope = toGlobal(customScope);

    final ProjectFileIndex fileIndex = ProjectFileIndex.SERVICE.getInstance(myProject);
    final boolean hasTrigrams = hasTrigrams(myFindModel.getStringToFind());

    class EnumContentIterator implements ContentIterator {
      final Set<PsiFile> myFiles = new LinkedHashSet<PsiFile>();

      @Override
      public boolean processFile(@NotNull final VirtualFile virtualFile) {
        ApplicationManager.getApplication()
            .runReadAction(
                new Runnable() {
                  @Override
                  public void run() {
                    ProgressManager.checkCanceled();
                    if (virtualFile.isDirectory()
                        || !virtualFile.isValid()
                        || !myFileMask.value(virtualFile)
                        || globalCustomScope != null && !globalCustomScope.contains(virtualFile)) {
                      return;
                    }

                    if (skipIndexed
                        && isCoveredByIndex(virtualFile)
                        && (fileIndex.isInContent(virtualFile)
                            || fileIndex.isInLibraryClasses(virtualFile)
                            || fileIndex.isInLibrarySource(virtualFile))) {
                      return;
                    }

                    PsiFile psiFile = myPsiManager.findFile(virtualFile);
                    if (psiFile != null
                        && !(psiFile instanceof PsiBinaryFile)
                        && !alreadySearched.contains(psiFile)) {
                      PsiFile sourceFile = (PsiFile) psiFile.getNavigationElement();
                      if (sourceFile != null) psiFile = sourceFile;
                      if (!psiFile.getFileType().isBinary()) {
                        myFiles.add(psiFile);
                      }
                    }
                  }

                  final FileBasedIndexImpl fileBasedIndex =
                      (FileBasedIndexImpl) FileBasedIndex.getInstance();

                  private boolean isCoveredByIndex(VirtualFile file) {
                    FileType fileType = file.getFileType();
                    if (hasTrigrams) {
                      return TrigramIndex.isIndexable(fileType)
                          && fileBasedIndex.isIndexingCandidate(file, TrigramIndex.INDEX_ID);
                    }
                    return IdIndex.isIndexable(fileType)
                        && fileBasedIndex.isIndexingCandidate(file, IdIndex.NAME);
                  }
                });
        return true;
      }

      @NotNull
      private Collection<PsiFile> getFiles() {
        return myFiles;
      }
    }

    final EnumContentIterator iterator = new EnumContentIterator();

    if (customScope instanceof LocalSearchScope) {
      for (VirtualFile file : getLocalScopeFiles((LocalSearchScope) customScope)) {
        iterator.processFile(file);
      }
    } else if (customScope
        instanceof
        Iterable) { // GlobalSearchScope can span files out of project roots e.g. FileScope /
                    // FilesScope
      //noinspection unchecked
      for (VirtualFile file : (Iterable<VirtualFile>) customScope) {
        iterator.processFile(file);
      }
    } else if (myPsiDirectory != null) {
      ApplicationManager.getApplication()
          .runReadAction(
              new Runnable() {
                @Override
                public void run() {
                  if (myPsiDirectory.isValid()) {
                    addFilesUnderDirectory(myPsiDirectory, iterator);
                  }
                }
              });

      myFileIndex.iterateContentUnderDirectory(myPsiDirectory.getVirtualFile(), iterator);
    } else {
      boolean success = myFileIndex.iterateContent(iterator);
      if (success && globalCustomScope != null && globalCustomScope.isSearchInLibraries()) {
        final VirtualFile[] librarySources =
            ApplicationManager.getApplication()
                .runReadAction(
                    new Computable<VirtualFile[]>() {
                      @Override
                      public VirtualFile[] compute() {
                        OrderEnumerator enumerator =
                            myModule == null
                                ? OrderEnumerator.orderEntries(myProject)
                                : OrderEnumerator.orderEntries(myModule);
                        return enumerator
                            .withoutModuleSourceEntries()
                            .withoutDepModules()
                            .getSourceRoots();
                      }
                    });
        iterateAll(librarySources, globalCustomScope, iterator);
      }
    }
    return iterator.getFiles();
  }
 public void testSiblingImplement() throws Exception {
   PsiClass anInterface = myJavaFacade.findClass("A.I", GlobalSearchScope.allScope(myProject));
   PsiMethod method = anInterface.getMethods()[0];
   final Collection<PsiMethod> overriders = OverridingMethodsSearch.search(method).findAll();
   assertEquals(1, overriders.size());
 }
 public void testFieldInJavadoc() throws Exception {
   PsiClass aClass = myJavaFacade.findClass("A", GlobalSearchScope.allScope(myProject));
   PsiField field = aClass.findFieldByName("FIELD", false);
   doTest(field, new String[] {"A.java"}, new int[] {}, new int[] {});
 }
  public void testNonCodeClassUsages() throws Exception {
    final TempDirTestFixture tdf =
        IdeaTestFixtureFactory.getFixtureFactory().createTempDirTestFixture();
    tdf.setUp();

    try {
      new WriteCommandAction(getProject()) {
        @Override
        protected void run(Result result) throws Throwable {
          final ModifiableModuleModel moduleModel =
              ModuleManager.getInstance(getProject()).getModifiableModel();
          moduleModel.newModule("independent/independent.iml", StdModuleTypes.JAVA.getId());
          moduleModel.commit();

          tdf.createFile(
              "plugin.xml",
              "<document>\n"
                  + "  <action class=\"com.Foo\" />\n"
                  + "  <action class=\"com.Foo.Bar\" />\n"
                  + "  <action class=\"com.Foo$Bar\" />\n"
                  + "</document>");

          PsiTestUtil.addContentRoot(
              ModuleManager.getInstance(getProject()).findModuleByName("independent"),
              tdf.getFile(""));
        }
      }.execute();

      GlobalSearchScope scope = GlobalSearchScope.allScope(getProject());
      PsiClass foo = myJavaFacade.findClass("com.Foo", scope);
      PsiClass bar = myJavaFacade.findClass("com.Foo.Bar", scope);

      final int[] count = {0};
      Processor<UsageInfo> processor =
          new Processor<UsageInfo>() {
            @Override
            public boolean process(UsageInfo usageInfo) {
              int navigationOffset = usageInfo.getNavigationOffset();
              assertTrue(navigationOffset > 0);
              String textAfter = usageInfo.getFile().getText().substring(navigationOffset);
              assertTrue(
                  textAfter,
                  textAfter.startsWith("Foo")
                      || textAfter.startsWith("Bar")
                      || textAfter.startsWith(
                          "com.Foo.Bar") // sorry, can't get references with dollar-dot mismatch to
                  // work now
                  );
              count[0]++;
              return true;
            }
          };
      JavaFindUsagesHandler handler =
          new JavaFindUsagesHandler(bar, JavaFindUsagesHandlerFactory.getInstance(getProject()));

      count[0] = 0;
      handler.processUsagesInText(foo, processor, scope);
      assertEquals(3, count[0]);

      count[0] = 0;
      handler.processUsagesInText(bar, processor, scope);
      assertEquals(2, count[0]);
    } finally {
      tdf.tearDown();
    }
  }