com.intellij.psi.JavaPsiFacade Java Examples

The following examples show how to use com.intellij.psi.JavaPsiFacade. 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: SpecLookupElement.java    From litho with Apache License 2.0 6 votes vote down vote up
/**
 * @param qualifiedName the name of the class to create lookup
 * @param project to find the lookup annotation class
 * @param insertHandler adds custom actions to the insert handling
 * @throws IncorrectOperationException if the qualifiedName does not specify a valid type
 * @return new {@link LookupElement} or cached instance if it was created previously
 */
static LookupElement create(
    String qualifiedName, Project project, InsertHandler<LookupElement> insertHandler)
    throws IncorrectOperationException {
  if (CACHE.containsKey(qualifiedName)) {
    return CACHE.get(qualifiedName);
  }
  PsiClass typeCls = PsiSearchUtils.findClass(project, qualifiedName);
  if (typeCls != null) {
    SpecLookupElement lookupElement = new SpecLookupElement(typeCls, insertHandler);
    CACHE.put(qualifiedName, lookupElement);
    return lookupElement;
  }
  // This is a dummy class, we don't want to cache it.
  typeCls =
      JavaPsiFacade.getInstance(project)
          .getElementFactory()
          .createClass(LithoClassNames.shortName(qualifiedName));
  return new SpecLookupElement(typeCls, insertHandler);
}
 
Example #2
Source File: PsiCustomUtil.java    From intellij-spring-assistant with MIT License 6 votes vote down vote up
@Nullable
public static PsiType safeGetValidType(@NotNull Module module, @NotNull String fqn) {
  try {
    // Intellij expects inner classes to be referred via `.` instead of `$`
    PsiType type = JavaPsiFacade.getInstance(module.getProject()).getParserFacade()
        .createTypeFromText(fqn.replaceAll("\\$", "."), null);
    boolean typeValid = isValidType(type);
    if (typeValid) {
      if (type instanceof PsiClassType) {
        return PsiClassType.class.cast(type);
      } else if (type instanceof PsiArrayType) {
        return PsiArrayType.class.cast(type);
      }
    }
    return null;
  } catch (IncorrectOperationException e) {
    debug(() -> log.debug("Unable to find class fqn " + fqn));
    return null;
  }
}
 
Example #3
Source File: AddControllerForm.java    From r2m-plugin-android with Apache License 2.0 6 votes vote down vote up
@Override
public void onGenerateFinished(boolean result, File file) {
    SaveAndSyncHandlerImpl.refreshOpenFiles();
    VirtualFileManager.getInstance().refreshWithoutFileWatcher(false);
    ProjectManagerEx.getInstanceEx().unblockReloadingProjectOnExternalChanges();
    project.getBaseDir().refresh(false, true);

    if (null == JavaPsiFacade.getInstance(project).findPackage("com.magnet.android.mms.async")) {
        showMissingDependencies();
    }

    if (!result) {
        showCloseDialog(file);
    } else {
        getThis().setVisible(true);
    }
}
 
Example #4
Source File: AddArgumentFixTest.java    From litho with Apache License 2.0 6 votes vote down vote up
@Test
public void createAddMethodCallFix() {
  testHelper.getPsiClass(
      classes -> {
        // Setup test environment
        PsiClass cls = classes.get(0);
        PsiMethodCallExpression call =
            PsiTreeUtil.findChildOfType(cls, PsiMethodCallExpression.class);
        Project project = testHelper.getFixture().getProject();
        PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
        Editor editor = mock(Editor.class);
        when(editor.getCaretModel()).thenReturn(mock(CaretModel.class));

        IntentionAction fix =
            AddArgumentFix.createAddMethodCallFix(call, "ClassName", "methodName", factory);

        assertThat(call.getArgumentList().getExpressions()[0].getText())
            .isNotEqualTo("ClassName.methodName()");
        fix.invoke(project, editor, testHelper.getFixture().getFile());
        assertThat(call.getArgumentList().getExpressions()[0].getText())
            .isEqualTo("ClassName.methodName()");
        return true;
      },
      "RequiredPropAnnotatorTest.java");
}
 
Example #5
Source File: OSSPantsJvmRunConfigurationIntegrationTest.java    From intellij-pants-plugin with Apache License 2.0 6 votes vote down vote up
public void testModuleRunConfiguration() throws Throwable {
  doImport("testprojects/tests/java/org/pantsbuild/testproject/testjvms");

  PsiPackage testPackage = JavaPsiFacade.getInstance(myProject).findPackage("org.pantsbuild.testproject.testjvms");
  assertEquals(1, testPackage.getDirectories().length);

  ExternalSystemRunConfiguration esc = getExternalSystemRunConfiguration(testPackage.getDirectories()[0]);

  Set<String> expectedItems = ProjectTestJvms.testClasses(myProject, getProjectPath())
    .map(aClass -> "--test-junit-test=" + aClass.getQualifiedName())
    .collect(Collectors.toSet());
  assertNotEmpty(expectedItems);

  Set<String> items = new HashSet<>(Arrays.asList(esc.getSettings().getScriptParameters().split(" ")));
  assertContains(items, expectedItems);
}
 
Example #6
Source File: RunConfigurationFactory.java    From tmc-intellij with MIT License 6 votes vote down vote up
/** Ui for the user to pick the Main class. */
@NotNull
public TreeClassChooser chooseMainClassForProject() {
    logger.info("Choosing main class for project.");
    TreeClassChooser chooser;
    Project project = new ObjectFinder().findCurrentProject();
    while (true) {
        TreeClassChooserFactory factory = TreeClassChooserFactory.getInstance(project);
        GlobalSearchScope scope;
        scope = GlobalSearchScope.moduleScope(module);
        PsiClass ecClass = JavaPsiFacade.getInstance(project).findClass("", scope);
        ClassFilter filter = createClassFilter();
        chooser =
                factory.createInheritanceClassChooser(
                        "Choose main class", scope, ecClass, null, filter);
        chooser.showDialog();
        if (chooser.getSelected() == null
                || chooser.getSelected().findMethodsByName("main", true).length > 0) {
            logger.info("Choosing main class aborted.");
            break;
        }
    }
    logger.info("Main class chosen successfully.");
    return chooser;
}
 
Example #7
Source File: BlazeRenderErrorContributor.java    From intellij with Apache License 2.0 6 votes vote down vote up
private File getSourceFileForClass(String className) {
  return ApplicationManager.getApplication()
      .runReadAction(
          (Computable<File>)
              () -> {
                try {
                  PsiClass psiClass =
                      JavaPsiFacade.getInstance(project)
                          .findClass(className, GlobalSearchScope.projectScope(project));
                  if (psiClass == null) {
                    return null;
                  }
                  return VfsUtilCore.virtualToIoFile(
                      psiClass.getContainingFile().getVirtualFile());
                } catch (IndexNotReadyException ignored) {
                  // We're in dumb mode. Abort! Abort!
                  return null;
                }
              });
}
 
Example #8
Source File: PsiConsultantImpl.java    From dagger-intellij-plugin with Apache License 2.0 6 votes vote down vote up
public static Set<String> getQualifierAnnotations(PsiElement element) {
  Set<String> qualifiedClasses = new HashSet<String>();

  if (element instanceof PsiModifierListOwner) {
    PsiModifierListOwner listOwner = (PsiModifierListOwner) element;
    PsiModifierList modifierList = listOwner.getModifierList();

    if (modifierList != null) {
      for (PsiAnnotation psiAnnotation : modifierList.getAnnotations()) {
        if (psiAnnotation != null && psiAnnotation.getQualifiedName() != null) {
          JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(element.getProject());
          PsiClass psiClass = psiFacade.findClass(psiAnnotation.getQualifiedName(),
              GlobalSearchScope.projectScope(element.getProject()));

          if (hasAnnotation(psiClass, CLASS_QUALIFIER)) {
            qualifiedClasses.add(psiAnnotation.getQualifiedName());
          }
        }
      }
    }
  }

  return qualifiedClasses;
}
 
Example #9
Source File: OnEventGenerateUtils.java    From litho with Apache License 2.0 6 votes vote down vote up
/**
 * Adds comment to the given method "// An event handler ContextClassName.methodName(c,
 * parameterName)
 */
public static void addComment(PsiClass contextClass, PsiMethod method) {
  final Project project = contextClass.getProject();
  final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);

  final StringBuilder builder =
      new StringBuilder("// An event handler ")
          .append(LithoPluginUtils.getLithoComponentNameFromSpec(contextClass.getName()))
          .append(".")
          .append(method.getName())
          .append("(")
          .append(CONTEXT_PARAMETER_NAME);
  for (PsiParameter parameter : method.getParameterList().getParameters()) {
    if (LithoPluginUtils.isParam(parameter)) {
      builder.append(", ").append(parameter.getName());
    }
  }

  builder.append(")");
  final PsiComment comment = factory.createCommentFromText(builder.toString(), method);
  method.addBefore(comment, method.getModifierList());
}
 
Example #10
Source File: MethodChainLookupElement.java    From litho with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static PsiExpression createMethodChain(
    Project project, String firstName, List<? extends String> methodNames) {
  PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
  StringBuilder expressionText =
      new StringBuilder(firstName + "(" + TEMPLATE_INSERT_PLACEHOLDER_C + ")");
  methodNames.forEach(
      methodName ->
          expressionText
              .append("\n.")
              .append(methodName)
              .append("(")
              .append(TEMPLATE_INSERT_PLACEHOLDER)
              .append(")"));
  return factory.createExpressionFromText(expressionText.toString(), null);
}
 
Example #11
Source File: ConstructorInjectToProvidesHandler.java    From dagger-intellij-plugin with Apache License 2.0 6 votes vote down vote up
private boolean navigateToConstructorIfProvider(PsiParameter psiParameter) {
  PsiTypeElement declaringTypeElement = psiParameter.getTypeElement();
  PsiClass classElement = JavaPsiFacade.getInstance(psiParameter.getProject()).findClass(
          declaringTypeElement.getType().getCanonicalText(),
          declaringTypeElement.getResolveScope());

  if (classElement == null) {
    return false;
  }

  for (PsiMethod method : classElement.getConstructors()) {
    if (PsiConsultantImpl.hasAnnotation(method, CLASS_INJECT) && navigateToElement(method)) {
        return true;
    }
  }
  return false;
}
 
Example #12
Source File: BuckAutoDepsQuickFixProvider.java    From buck with Apache License 2.0 6 votes vote down vote up
private static Set<PsiClass> findPsiClasses(Project project, String className) {
  GlobalSearchScope scope = GlobalSearchScope.everythingScope(project);
  JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(project);
  PsiShortNamesCache psiShortNamesCache = PsiShortNamesCache.getInstance(project);
  Set<PsiClass> results = new HashSet<>();
  BuckAutoDepsSearchableClassNameContributor.EP_NAME.getExtensions(project).stream()
      .filter(contributor -> contributor.isApplicable(project, className))
      .forEach(
          contributor ->
              contributor
                  .getSearchableClassNames(project, className)
                  .forEach(
                      name ->
                          Stream.concat(
                                  Stream.of(javaPsiFacade.findClasses(name, scope)),
                                  Stream.of(psiShortNamesCache.getClassesByName(name, scope)))
                              .distinct()
                              .forEach(
                                  psiClass -> {
                                    if (!results.contains(psiClass)
                                        && contributor.filter(project, className, psiClass)) {
                                      results.add(psiClass);
                                    }
                                  })));
  return results;
}
 
Example #13
Source File: JNIFunction2JavaMethodBinding.java    From CppTools with Apache License 2.0 6 votes vote down vote up
public JNIFunction2JavaMethodBinding(String jniFunctionName, PsiManager psiManager) {
  int lastUnderscoreIndex = jniFunctionName.lastIndexOf('_');
  String className = jniFunctionName.substring(0, lastUnderscoreIndex).replace('_','.').substring(JAVA_NATIVE_PREFIX.length());
  String methodName = jniFunctionName.substring(lastUnderscoreIndex + 1);
  Project project = psiManager.getProject();
  clazz = JavaPsiFacade.getInstance(project).findClass(className, GlobalSearchScope.projectScope(project));
  PsiMethod m = null;

  if (clazz != null) {
    PsiMethod[] psiMethods = clazz.findMethodsByName(methodName, false);
    if (psiMethods.length > 0) {
      m = psiMethods[0];
    }
  }

  method = m;
}
 
Example #14
Source File: DocCommentProcessor.java    From markdown-doclet with GNU General Public License v3.0 6 votes vote down vote up
public DocCommentProcessor(PsiFile file) {
    this.file = file;
    if ( file == null ) {
        project = null;
        markdownOptions = null;
        psiElementFactory = null;
    }
    else {
        project = file.getProject();
        psiElementFactory = JavaPsiFacade.getInstance(project).getElementFactory();
        ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
        Module module = fileIndex.getModuleForFile(file.getVirtualFile());
        if ( module == null ) {
            markdownOptions = null;
        }
        else if ( !fileIndex.isInSourceContent(file.getVirtualFile()) ) {
            markdownOptions = null;
        }
        else if ( !Plugin.moduleConfiguration(module).isMarkdownEnabled() ) {
            markdownOptions = null;
        }
        else {
            markdownOptions = Plugin.moduleConfiguration(module).getRenderingOptions();
        }
    }
}
 
Example #15
Source File: OttoProjectHandler.java    From otto-intellij-plugin with Apache License 2.0 6 votes vote down vote up
private void scheduleRefreshOfEventFiles() {
  ApplicationManager.getApplication().invokeLater(new Runnable() {
    @Override
    public void run() {
      Set<String> eventClasses;
      synchronized (allEventClasses) {
        eventClasses = new HashSet<String>(allEventClasses);
      }
      JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(myProject);
      DaemonCodeAnalyzer codeAnalyzer = DaemonCodeAnalyzer.getInstance(myProject);
      for (String eventClass : eventClasses) {
        PsiClass eventPsiClass = javaPsiFacade.findClass(eventClass,
              GlobalSearchScope.allScope(myProject));
        if (eventPsiClass == null) continue;
        PsiFile psiFile = eventPsiClass.getContainingFile();
        if (psiFile == null) continue;
        codeAnalyzer.restart(psiFile);
      }
    }
  });
}
 
Example #16
Source File: PsiQuickFixFactory.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static LocalQuickFix createAddAnnotationQuickFix(@NotNull PsiClass psiClass, @NotNull String annotationFQN, @Nullable String annotationParam) {
  PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(psiClass.getProject());
  PsiAnnotation newAnnotation = elementFactory.createAnnotationFromText("@" + annotationFQN + "(" + StringUtil.notNullize(annotationParam) + ")", psiClass);
  final PsiNameValuePair[] attributes = newAnnotation.getParameterList().getAttributes();

  return new AddAnnotationFix(annotationFQN, psiClass, attributes);
}
 
Example #17
Source File: OSSPantsCompileActionsTest.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
public void testCompileTargetsInSelectedEditor() throws Throwable {
  doImport("examples/tests/scala/org/pantsbuild/example");
  ArrayList<Pair<String, String>> testClassAndTarget = Lists.newArrayList(
    // Pair of class reference and its containing target
    Pair.create(
      "org.pantsbuild.example.hello.welcome.WelSpec",
      "examples/tests/scala/org/pantsbuild/example/hello/welcome:welcome"
    ),
    Pair.create(
      "org.pantsbuild.example.hello.welcome.WelcomeEverybody",
      "examples/src/scala/org/pantsbuild/example/hello/welcome:welcome"
    )
  );

  for (Pair<String, String> classAndTarget : testClassAndTarget) {
    // Preparation
    String clazzName = classAndTarget.getFirst();
    String target = classAndTarget.getSecond();

    PsiClass clazz = JavaPsiFacade.getInstance(myProject)
      .findClass(clazzName, GlobalSearchScope.projectScope(myProject));

    assertNotNull(String.format("%s does not exist, but should.", clazz), clazz);

    // Open the file and have the editor focus on it
    FileEditorManager.getInstance(myProject).openFile(clazz.getContainingFile().getVirtualFile(), true);
    PantsCompileCurrentTargetAction compileCurrentTargetAction = new PantsCompileCurrentTargetAction();

    // Execute body
    Set<String> currentTargets = compileCurrentTargetAction
      .getTargets(getPantsActionEvent(), myProject)
      .collect(Collectors.toSet());
    assertContainsElements(currentTargets, target);
    assertActionSucceeds(compileCurrentTargetAction, currentTargets);
  }
}
 
Example #18
Source File: ChangeAnnotationParameterQuickFix.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void invoke(@NotNull Project project, @NotNull PsiFile psiFile, @NotNull PsiElement startElement, @NotNull PsiElement endElement) {
  final PsiAnnotation myAnnotation = (PsiAnnotation) startElement;
  final Editor editor = CodeInsightUtil.positionCursor(project, psiFile, myAnnotation);
  if (editor != null) {
    WriteCommandAction.writeCommandAction(project, psiFile).run(() ->
      {
        final PsiNameValuePair valuePair = selectAnnotationAttribute(myAnnotation);

        if (null != valuePair) {
          // delete this parameter
          valuePair.delete();
        }

        if (null != myNewValue) {
          //add new parameter
          final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(myAnnotation.getProject());
          PsiAnnotation newAnnotation = elementFactory.createAnnotationFromText("@" + myAnnotation.getQualifiedName() + "(" + myName + "=" + myNewValue + ")", myAnnotation.getContext());
          final PsiNameValuePair[] attributes = newAnnotation.getParameterList().getAttributes();

          myAnnotation.setDeclaredAttributeValue(attributes[0].getName(), attributes[0].getValue());
        }

        UndoUtil.markPsiFileForUndo(psiFile);
      }
    );
  }
}
 
Example #19
Source File: CreateFieldQuickFix.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void invoke(@NotNull Project project, @NotNull PsiFile psiFile, @NotNull PsiElement startElement, @NotNull PsiElement endElement) {
  final PsiClass myClass = (PsiClass) startElement;
  final Editor editor = CodeInsightUtil.positionCursor(project, psiFile, myClass.getLBrace());
  if (editor != null) {
    WriteCommandAction.writeCommandAction(project, psiFile).run(() ->
      {
        final PsiElementFactory psiElementFactory = JavaPsiFacade.getElementFactory(project);
        final PsiField psiField = psiElementFactory.createField(myName, myType);

        final PsiModifierList modifierList = psiField.getModifierList();
        if (null != modifierList) {
          for (String modifier : myModifiers) {
            modifierList.setModifierProperty(modifier, true);
          }
        }
        if (null != myInitializerText) {
          PsiExpression psiInitializer = psiElementFactory.createExpressionFromText(myInitializerText, psiField);
          psiField.setInitializer(psiInitializer);
        }

        final List<PsiGenerationInfo<PsiField>> generationInfos = GenerateMembersUtil.insertMembersAtOffset(myClass.getContainingFile(), editor.getCaretModel().getOffset(),
          Collections.singletonList(new PsiGenerationInfo<>(psiField)));
        if (!generationInfos.isEmpty()) {
          PsiField psiMember = generationInfos.iterator().next().getPsiMember();
          editor.getCaretModel().moveToOffset(psiMember.getTextRange().getEndOffset());
        }

        UndoUtil.markPsiFileForUndo(psiFile);
      }
    );
  }
}
 
Example #20
Source File: PsiConsultantImpl.java    From dagger-intellij-plugin with Apache License 2.0 5 votes vote down vote up
private static boolean isLazyOrProvider(PsiClass psiClass) {
  if (psiClass == null) {
    return false;
  }
  Project project = psiClass.getProject();
  JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(project);
  GlobalSearchScope globalSearchScope = GlobalSearchScope.allScope(project);

  PsiClass lazyClass = javaPsiFacade.findClass(CLASS_LAZY, globalSearchScope);
  PsiClass providerClass = javaPsiFacade.findClass(CLASS_PROVIDER, globalSearchScope);

  return psiClass.equals(lazyClass) || psiClass.equals(providerClass);
}
 
Example #21
Source File: SubscriberMetadata.java    From otto-intellij-plugin with Apache License 2.0 5 votes vote down vote up
@Nullable
public PsiMethod getBusPostMethod(Project project) {
  JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(project);
  GlobalSearchScope globalSearchScope = GlobalSearchScope.allScope(project);

  PsiClass busClass = javaPsiFacade.findClass(getBusClassName(), globalSearchScope);
  if (busClass != null) {
    for (PsiMethod psiMethod : busClass.getMethods()) {
      if (psiMethod.getName().equals("post")) {
        return psiMethod;
      }
    }
  }
  return null;
}
 
Example #22
Source File: LombokToStringHandler.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected void processClass(@NotNull PsiClass psiClass) {
  final PsiElementFactory factory = JavaPsiFacade.getElementFactory(psiClass.getProject());
  final PsiClassType stringClassType = factory.createTypeByFQClassName(CommonClassNames.JAVA_LANG_STRING, psiClass.getResolveScope());

  final PsiMethod toStringMethod = findPublicNonStaticMethod(psiClass, "toString", stringClassType);
  if (null != toStringMethod) {
    toStringMethod.delete();
  }
  addAnnotation(psiClass, ToString.class);
}
 
Example #23
Source File: GodClassUserInputDialog.java    From IntelliJDeodorant with MIT License 5 votes vote down vote up
public GodClassUserInputDialog(AbstractExtractClassRefactoring abstractRefactoring, AbstractRefactoringPanel godClassPanel) {
    super(abstractRefactoring.getRefactoring().getSourceFile().getProject(), true);
    this.abstractRefactoring = abstractRefactoring;
    this.refactoring = abstractRefactoring.getRefactoring();
    String packageName = PsiUtil.getPackageName(refactoring.getSourceClass());
    parentPackage = JavaPsiFacade.getInstance(refactoring.getProject()).findPackage(packageName);
    this.godClassPanel = godClassPanel;
    initialiseControls();
    setTitle(IntelliJDeodorantBundle.message("god.class.dialog.title"));
    init();
}
 
Example #24
Source File: DataWriter.java    From GsonFormat with Apache License 2.0 5 votes vote down vote up
public DataWriter(PsiFile file, Project project, PsiClass cls) {
    super(project, file);
    factory = JavaPsiFacade.getElementFactory(project);
    this.file = file;
    this.project = project;
    this.cls = cls;
}
 
Example #25
Source File: ProjectTestJvms.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
public static Stream<PsiClass> testClasses(Project project, String projectPath) throws IOException {
  JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
  return testClassFiles(projectPath)
    .map(path -> path.getFileName().toString())
    .map(name -> name.substring(0, name.length() - ".java".length()))
    .map(name -> PACKAGE_NAME + "." + name)
    .map(qualifiedName -> psiFacade.findClass(qualifiedName, GlobalSearchScope.allScope(project)));
}
 
Example #26
Source File: LombokProjectValidatorActivity.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private boolean hasLombokLibrary(Project project) {
  PsiPackage lombokPackage;
  try {
    lombokPackage = JavaPsiFacade.getInstance(project).findPackage("lombok");
  } catch (ProcessCanceledException ex) {
    lombokPackage = null;
  }
  return lombokPackage != null;
}
 
Example #27
Source File: PantsIntegrationTestCase.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
@NotNull
protected PsiClass findClassAndAssert(@NonNls @NotNull String qualifiedName) {
  final PsiClass[] classes = JavaPsiFacade.getInstance(myProject).findClasses(qualifiedName, GlobalSearchScope.allScope(myProject));
  Set<PsiClass> deduppedClasses = Stream.of(classes).collect(Collectors.toSet());
  assertTrue("Several classes with the same qualified name " + qualifiedName, deduppedClasses.size() < 2);
  assertFalse(qualifiedName + " class not found!", deduppedClasses.isEmpty());
  return deduppedClasses.iterator().next();
}
 
Example #28
Source File: ProducerUtils.java    From intellij with Apache License 2.0 5 votes vote down vote up
private static boolean isTestCaseInheritor(PsiClass psiClass) {
  // unlike JUnitUtil#isTestCaseInheritor, works even if the class isn't in the project
  PsiClass testCaseClass =
      JavaPsiFacade.getInstance(psiClass.getProject())
          .findClass(
              JUnitUtil.TEST_CASE_CLASS, GlobalSearchScope.allScope(psiClass.getProject()));
  if (testCaseClass != null) {
    return psiClass.isInheritor(testCaseClass, true);
  }
  // TestCase isn't indexed, instead use heuristics to check
  return extendsTestCase(psiClass, new HashSet<>());
}
 
Example #29
Source File: BlazeAndroidModelTest.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Override
protected void initTest(Container applicationServices, Container projectServices) {
  applicationServices.register(FileTypeManager.class, new MockFileTypeManager());
  applicationServices.register(
      FileDocumentManager.class, new MockFileDocumentManagerImpl(null, null));
  applicationServices.register(VirtualFileManager.class, mock(VirtualFileManager.class));
  applicationServices.register(BlazeBuildService.class, new BlazeBuildService());
  projectServices.register(ProjectScopeBuilder.class, new ProjectScopeBuilderImpl(project));
  projectServices.register(ProjectViewManager.class, new MockProjectViewManager());

  BlazeProjectDataManager mockProjectDataManager =
      new MockBlazeProjectDataManager(MockBlazeProjectDataBuilder.builder().build());
  projectServices.register(BlazeProjectDataManager.class, mockProjectDataManager);

  BlazeImportSettingsManager manager = new BlazeImportSettingsManager(project);
  manager.setImportSettings(new BlazeImportSettings("", "", "", "", BuildSystem.Blaze));
  projectServices.register(BlazeImportSettingsManager.class, manager);
  projectServices.register(JvmPsiConversionHelper.class, new JvmPsiConversionHelperImpl());

  facade =
      new MockJavaPsiFacade(
          project,
          ImmutableList.of("com.google.example.Modified", "com.google.example.NotModified"));

  projectServices.register(JavaPsiFacade.class, facade);
  module = new MockModule(() -> {});
  model = new BlazeAndroidModel(project, null, mock(SourceProvider.class), null, 0, false);
}
 
Example #30
Source File: BlazeAndroidTestLocator.java    From intellij with Apache License 2.0 5 votes vote down vote up
private static List<PsiClass> findClasses(
    Project project, GlobalSearchScope scope, String className) {
  PsiClass psiClass = JavaPsiFacade.getInstance(project).findClass(className, scope);
  if (psiClass != null) {
    return ImmutableList.of(psiClass);
  }
  // handle unqualified class names
  return Arrays.stream(PsiShortNamesCache.getInstance(project).getClassesByName(className, scope))
      .filter(JUnitUtil::isTestClass)
      .collect(Collectors.toList());
}