Java 类com.intellij.psi.JavaPsiFacade 实例源码

项目:nullability-annotations-inspection    文件:AddPackageInfoWithNullabilityDefaultsFix.java   
private void addAnnotationToPackageInfo(Project project, PsiJavaFile packageInfoFile) {
    if (!FileModificationService.getInstance().preparePsiElementForWrite(packageInfoFile)) {
        return;
    }

    PsiPackageStatement packageStatement = packageInfoFile.getPackageStatement();
    if (packageStatement == null) {
        return;
    }

    PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
    PsiAnnotation annotation = factory.createAnnotationFromText("@" + annotationForTypeQualifierFqn,
            packageInfoFile.getContext());
    PsiElement addedAnnotation = packageInfoFile.addBefore(annotation, packageStatement);
    JavaCodeStyleManager.getInstance(project).shortenClassReferences(addedAnnotation);

    removeRedundantAnnotationsInPackage(project, packageInfoFile.getContainingDirectory().getFiles(), annotation);
}
项目:nullability-annotations-inspection    文件:NullabilityAnnotationsWithTypeQualifierDefault.java   
static List<String> findAnnotations(PsiModifierListOwner element, boolean nullable) {
    if (overridesSuper(element)) {
        return Collections.emptyList();
    }

    List<String> annotations = new ArrayList<>();
    Project project = element.getProject();
    PsiModifierList modifierList = element.getModifierList();
    List<String> nullabilityAnnotations = nullable
            ? NullableNotNullManager.getInstance(project).getNullables()
            : NullableNotNullManager.getInstance(project).getNotNulls();
    for (String notNullAnnotationFqn : nullabilityAnnotations) {
        PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
        PsiAnnotation annotation = factory.createAnnotationFromText("@" + notNullAnnotationFqn, null);
        PsiAnnotation.TargetType[] targetTypes = getTargetsForLocation(modifierList);
        if (isNullabilityAnnotationForTypeQualifierDefault(annotation, nullable, targetTypes)) {
            annotations.add(annotation.getQualifiedName());
        }
    }
    return annotations;
}
项目:intellij-plugin    文件:CoffigDocumentationProvider.java   
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();
}
项目:intellij-plugin    文件:AnnotatedInterfaceNode.java   
@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;
}
项目:intellij-plugin    文件:AggregateNode.java   
@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;
}
项目:intellij-plugin    文件:AggregatesNode.java   
@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;
}
项目:intellij-plugin    文件:ResourcesNode.java   
@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;
}
项目:intellij-plugin    文件:ToolsNode.java   
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;
}
项目:manifold-ij    文件:ManAugmentProvider.java   
private PsiMethod makePsiMethod( AbstractSrcMethod method, PsiClass psiClass )
{
  PsiElementFactory elementFactory = JavaPsiFacade.getInstance( psiClass.getProject() ).getElementFactory();
  StringBuilder sb = new StringBuilder();
  method.render( sb, 0 );
  try
  {
    return elementFactory.createMethodFromText( sb.toString(), psiClass );
  }
  catch( IncorrectOperationException ioe )
  {
    // the text of the method does not conform to method grammar, probably being edited in an IJ editor,
    // ignore these since the editor provides error information
    return null;
  }
}
项目:manifold-ij    文件:ManifoldPsiClassCache.java   
private PsiClass addExtensions( GlobalSearchScope scope, ManModule module, String fqn, PsiClass psiClass )
{
  if( isExtended( module, fqn ) )
  {
    // Find the class excluding our ManTypeFinder to avoid circularity
    psiClass = psiClass != null ? psiClass : JavaPsiFacade.getInstance( module.getIjProject() ).findClass( fqn, scope );
    if( psiClass != null )
    {
      psiClass = new ManifoldExtendedPsiClass( module.getIjModule(), psiClass );
      psiClass.putUserData( ModuleUtil.KEY_MODULE, module.getIjModule() );
      FqnCache<PsiClass> map = _type2Class.computeIfAbsent( module, k -> new FqnCache<>() );
      map.add( fqn, psiClass );
    }
  }
  return psiClass;
}
项目:tmc-intellij    文件:RunConfigurationFactory.java   
/** 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;
}
项目:AndroidStudioPlugin    文件:CreateDialogAction.java   
@Override
public void actionPerformed(AnActionEvent e) {

    // 获取编辑器中的文件
    Project project = e.getData(PlatformDataKeys.PROJECT);
    Editor editor = e.getData(PlatformDataKeys.EDITOR);
    PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);

    // 获取当前类
    PsiClass targetClass = getTargetClass(editor, file);
    // 获取元素操作的工厂类
    PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);

    // 生成代码
    new LayoutCreator(project, targetClass, factory, file).execute();
}
项目:intellij-ce-playground    文件:PsiAnnotationStubImpl.java   
@Override
public PsiAnnotation getPsiElement() {
  PsiAnnotation annotation = SoftReference.dereference(myParsedFromRepository);
  if (annotation != null) {
    return annotation;
  }

  final String text = getText();
  try {
    PsiJavaParserFacade facade = JavaPsiFacade.getInstance(getProject()).getParserFacade();
    annotation = facade.createAnnotationFromText(text, getPsi());
    myParsedFromRepository = new SoftReference<PsiAnnotation>(annotation);
    return annotation;
  }
  catch (IncorrectOperationException e) {
    LOG.error("Bad annotation in repository!", e);
    return null;
  }
}
项目:intellij-ce-playground    文件:JavaCoreProjectEnvironment.java   
public JavaCoreProjectEnvironment(Disposable parentDisposable, CoreApplicationEnvironment applicationEnvironment) {
  super(parentDisposable, applicationEnvironment);

  myProject.registerService(PsiElementFactory.class, new PsiElementFactoryImpl(myPsiManager));
  myProject.registerService(JavaPsiImplementationHelper.class, createJavaPsiImplementationHelper());
  myProject.registerService(PsiResolveHelper.class, new PsiResolveHelperImpl(myPsiManager));
  myProject.registerService(LanguageLevelProjectExtension.class, new CoreLanguageLevelProjectExtension());
  myProject.registerService(JavaResolveCache.class, new JavaResolveCache(myMessageBus));
  myProject.registerService(JavaCodeStyleSettingsFacade.class, new CoreJavaCodeStyleSettingsFacade());
  myProject.registerService(JavaCodeStyleManager.class, new CoreJavaCodeStyleManager());

  myPackageIndex = createCorePackageIndex();
  myProject.registerService(PackageIndex.class, myPackageIndex);

  myFileManager = createCoreFileManager();
  myProject.registerService(JavaFileManager.class, myFileManager);

  JavaPsiFacadeImpl javaPsiFacade = new JavaPsiFacadeImpl(myProject, myPsiManager, myFileManager, myMessageBus);
  myProject.registerService(JavaPsiFacade.class, javaPsiFacade);
}
项目:intellij    文件:BlazeAndroidModelTest.java   
@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());
  projectServices.register(
      BlazeProjectDataManager.class, new BlazeProjectDataManagerImpl(project));

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

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

  projectServices.register(JavaPsiFacade.class, facade);
  module = new MockModule(() -> {});
  model = new BlazeAndroidModel(project, module, null, mock(SourceProvider.class), null, "", 0);
}
项目:intellij-ce-playground    文件:TestNGVersionChecker.java   
public static boolean isVersionIncompatible(Project project, GlobalSearchScope scope) {
  final String protocolClassMessageClass = TestResultMessage.class.getName();
  final PsiClass psiProtocolClass = JavaPsiFacade.getInstance(project).findClass(protocolClassMessageClass, scope);
  if (psiProtocolClass != null) {
    final String instanceFieldName = "m_instanceName";
    try {
      final boolean userHasNewJar = psiProtocolClass.findFieldByName(instanceFieldName, false) != null;

      boolean ideaHasNewJar = true;
      final Class aClass = Class.forName(protocolClassMessageClass);
      try {
        aClass.getDeclaredField(instanceFieldName);
      }
      catch (NoSuchFieldException e) {
        ideaHasNewJar = false;
      }

      return userHasNewJar != ideaHasNewJar;
    }
    catch (Exception ignore) {
    }
  }
  return false;
}
项目:intellij-ce-playground    文件:FieldDescriptorImpl.java   
@Override
public PsiExpression getDescriptorEvaluation(DebuggerContext context) throws EvaluateException {
  PsiElementFactory elementFactory = JavaPsiFacade.getInstance(context.getProject()).getElementFactory();
  String fieldName;
  if(isStatic()) {
    String typeName = myField.declaringType().name().replace('$', '.');
    typeName = DebuggerTreeNodeExpression.normalize(typeName, PositionUtil.getContextElement(context), context.getProject());
    fieldName = typeName + "." + getName();
  }
  else {
    //noinspection HardCodedStringLiteral
    fieldName = isOuterLocalVariableValue()? StringUtil.trimStart(getName(), OUTER_LOCAL_VAR_FIELD_PREFIX) : "this." + getName();
  }
  try {
    return elementFactory.createExpressionFromText(fieldName, null);
  }
  catch (IncorrectOperationException e) {
    throw new EvaluateException(DebuggerBundle.message("error.invalid.field.name", getName()), e);
  }
}
项目:intellij-ce-playground    文件:TestNGRunnableState.java   
public static boolean supportSerializationProtocol(TestNGConfiguration config) {
  final Project project = config.getProject();
  final GlobalSearchScope scopeToDetermineTestngIn;
  if (config.getPersistantData().getScope() == TestSearchScope.WHOLE_PROJECT) {
    scopeToDetermineTestngIn = GlobalSearchScope.allScope(project);
  }
  else {
    final Module module = config.getConfigurationModule().getModule();
    scopeToDetermineTestngIn = module != null ? GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module) 
                                              : GlobalSearchScope.allScope(project);
  }

  final JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
  final PsiClass aClass = facade.findClass(SerializedMessageSender.class.getName(), scopeToDetermineTestngIn);
  if (aClass == null) return false;

  final PsiClass[] starters = facade.findClasses(RemoteTestNG.class.getName(), scopeToDetermineTestngIn);
  for (PsiClass starter : starters) {
    if (starter.findFieldByName("m_serPort", false) == null) {
      LOG.info("Multiple TestNG versions found");
      return false;
    }
  }
  return Registry.is("testng.serialized.protocol.enabled") && !TestNGVersionChecker.isVersionIncompatible(project, scopeToDetermineTestngIn);
}
项目:intellij-ce-playground    文件:JavaTestFrameworkRunnableState.java   
private boolean spansMultipleModules() {
  final String qualifiedName = getConfiguration().getPackage();
  if (qualifiedName != null) {
    final Project project = getConfiguration().getProject();
    final PsiPackage aPackage = JavaPsiFacade.getInstance(project).findPackage(qualifiedName);
    if (aPackage != null) {
      final TestSearchScope scope = getScope();
      if (scope != null) {
        final SourceScope sourceScope = scope.getSourceScope(getConfiguration());
        if (sourceScope != null) {
          final GlobalSearchScope configurationSearchScope = GlobalSearchScopesCore.projectTestScope(project).intersectWith(
            sourceScope.getGlobalSearchScope());
          final PsiDirectory[] directories = aPackage.getDirectories(configurationSearchScope);
          return directories.length > 1;
        }
      }
    }
  }
  return false;
}
项目:intellij-ce-playground    文件:RenderErrorPanel.java   
@NotNull
private static Collection<PsiClass> findInheritors(@NotNull final Module module, @NotNull final String name) {
  if (!ApplicationManager.getApplication().isReadAccessAllowed()) {
    return ApplicationManager.getApplication().runReadAction(new Computable<Collection<PsiClass>>() {
      @Override
      public Collection<PsiClass> compute() {
        return findInheritors(module, name);
      }
    });
  }

  Project project = module.getProject();
  try {
    PsiClass base = JavaPsiFacade.getInstance(project).findClass(name, GlobalSearchScope.allScope(project));
    if (base != null) {
      GlobalSearchScope scope = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module, false);
      return ClassInheritorsSearch.search(base, scope, true).findAll();
    }
  }
  catch (IndexNotReadyException ignored) {
  }
  return Collections.emptyList();
}
项目:intellij-ce-playground    文件:ClassBrowser.java   
public static ClassBrowser createAppletClassBrowser(final Project project,
                                                    final ConfigurationModuleSelector moduleSelector) {
  final String title = ExecutionBundle.message("choose.applet.class.dialog.title");
  return new MainClassBrowser(project, moduleSelector, title) {

    @Override
    protected TreeClassChooser createClassChooser(ClassFilter.ClassFilterWithScope classFilter) {
      final Module module = moduleSelector.getModule();
      final GlobalSearchScope scope =
        module == null ? GlobalSearchScope.allScope(myProject) : GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module);
      final PsiClass appletClass = JavaPsiFacade.getInstance(project).findClass("java.applet.Applet", scope);
      return TreeClassChooserFactory.getInstance(getProject())
        .createInheritanceClassChooser(title, classFilter.getScope(), appletClass, false, false,
                                       ConfigurationUtil.PUBLIC_INSTANTIATABLE_CLASS);
    }
  };
}
项目:intellij-ce-playground    文件:AppletConfigurationProducer.java   
private static boolean isAppletClass(final PsiClass aClass, final PsiManager manager) {
  if (!PsiClassUtil.isRunnableClass(aClass, true)) return false;

  final Module module = JavaExecutionUtil.findModule(aClass);
  final GlobalSearchScope scope = module != null
                            ? GlobalSearchScope.moduleWithLibrariesScope(module)
                            : GlobalSearchScope.projectScope(manager.getProject());
  PsiClass appletClass = JavaPsiFacade.getInstance(manager.getProject()).findClass("java.applet.Applet", scope);
  if (appletClass != null) {
    if (aClass.isInheritor(appletClass, true)) return true;
  }
  appletClass = JavaPsiFacade.getInstance(manager.getProject()).findClass("javax.swing.JApplet", scope);
  if (appletClass != null) {
    if (aClass.isInheritor(appletClass, true)) return true;
  }
  return false;
}
项目:intellij-ce-playground    文件:GrMapTypeFromNamedArgs.java   
public GrMapTypeFromNamedArgs(@NotNull JavaPsiFacade facade, @NotNull GlobalSearchScope scope, @NotNull GrNamedArgument[] namedArgs) {
  super(facade, scope);

  myStringEntries = ContainerUtil.newLinkedHashMap();
  myOtherEntries = ContainerUtil.newArrayList();
  for (GrNamedArgument namedArg : namedArgs) {
    final GrArgumentLabel label = namedArg.getLabel();
    final GrExpression expression = namedArg.getExpression();
    if (label == null || expression == null) {
      continue;
    }

    final String name = label.getName();
    if (name != null) {
      myStringEntries.put(name, expression);
    }
    else if (label.getExpression() != null) {
      myOtherEntries.add(Couple.of(label.getExpression(), expression));
    }
  }
}
项目:intellij-ce-playground    文件:GradleUrlProvider.java   
@NotNull
@Override
public List<Location> getLocation(@NotNull String protocol, @NotNull String path, @NotNull Project project, @NotNull GlobalSearchScope scope) {
  if (!PROTOCOL_ID.equals(protocol)) return Collections.emptyList();

  final String className = extractFullClassName(path);
  if (className == null) return Collections.emptyList();
  final PsiClass testClass = JavaPsiFacade.getInstance(project).findClass(className, GlobalSearchScope.allScope(project));
  if (testClass == null) return Collections.emptyList();

  final String methodName = extractMethodName(path);
  if (methodName == null) {
    return Collections.<Location>singletonList(new PsiLocation<PsiClass>(project, testClass));
  }

  final PsiMethod[] methods = testClass.findMethodsByName(methodName, true);
  final List<Location> list = new ArrayList<Location>(methods.length);
  for (PsiMethod method : methods) {
    list.add(new PsiLocation<PsiMethod>(project, method));
  }
  return list;
}
项目:intellij-ce-playground    文件:SmartCompletionTemplateItem.java   
@Override
public PsiType getType() {
  final Template template = getTemplate();
  String text = template.getTemplateText();
  StringBuilder resultingText = new StringBuilder(text);

  int segmentsCount = template.getSegmentsCount();

  for (int j = segmentsCount - 1; j >= 0; j--) {
    if (template.getSegmentName(j).equals(TemplateImpl.END)) {
      continue;
    }

    resultingText.insert(template.getSegmentOffset(j), "xxx");
  }

  try {
    final PsiExpression templateExpression = JavaPsiFacade.getElementFactory(myContext.getProject()).createExpressionFromText(resultingText.toString(), myContext);
    return templateExpression.getType();
  }
  catch (IncorrectOperationException e) { // can happen when text of the template does not form an expression
    return null;
  }
}
项目:intellij-ce-playground    文件:GroovyRunnerUtil.java   
public static String getConfigurationName(PsiClass aClass, RunConfigurationModule module) {
  String qualifiedName = aClass.getQualifiedName();
  Project project = module.getProject();
  if (qualifiedName == null) {
    return module.getModuleName();
  }

  PsiClass psiClass =
    JavaPsiFacade.getInstance(project).findClass(qualifiedName.replace('$', '.'), GlobalSearchScope.projectScope(project));
  if (psiClass != null) {
    return psiClass.getName();
  }
  else {
    int lastDot = qualifiedName.lastIndexOf('.');
    if (lastDot == -1 || lastDot == qualifiedName.length() - 1) {
      return qualifiedName;
    }
    return qualifiedName.substring(lastDot + 1, qualifiedName.length());
  }
}
项目:intellij-ce-playground    文件:InsertComponentProcessor.java   
private boolean checkAddDependencyOnInsert(final ComponentItem item) {
  if (item.getClassName().equals(HSpacer.class.getName()) || item.getClassName().equals(VSpacer.class.getName())) {
    // this is mostly required for IDEA developers, so that developers don't receive prompt to offer ui-designer-impl dependency
    return true;
  }
  PsiManager manager = PsiManager.getInstance(myEditor.getProject());
  final GlobalSearchScope projectScope = GlobalSearchScope.allScope(myEditor.getProject());
  final GlobalSearchScope moduleScope = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(myEditor.getModule());
  final PsiClass componentClass = JavaPsiFacade.getInstance(manager.getProject()).findClass(item.getClassName(), projectScope);
  if (componentClass != null && JavaPsiFacade.getInstance(manager.getProject()).findClass(item.getClassName(), moduleScope) == null) {
    final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myEditor.getProject()).getFileIndex();
    List<OrderEntry> entries = fileIndex.getOrderEntriesForFile(componentClass.getContainingFile().getVirtualFile());
    if (entries.size() > 0) {
      if (entries.get(0) instanceof ModuleSourceOrderEntry) {
        if (!checkAddModuleDependency(item, (ModuleSourceOrderEntry)entries.get(0))) return false;
      }
      else if (entries.get(0) instanceof LibraryOrderEntry) {
        if (!checkAddLibraryDependency(item, (LibraryOrderEntry)entries.get(0))) return false;
      }
    }
  }
  return true;
}
项目:intellij-ce-playground    文件:ConfigSlurperMapContentProvider.java   
@Override
public PsiType getValueType(@NotNull GrExpression qualifier, @Nullable PsiElement resolve, @NotNull final String key) {
  Pair<ConfigSlurperSupport.PropertiesProvider, List<String>> info = getInfo(qualifier, resolve);
  if (info == null) return null;

  final Ref<Boolean> res = new Ref<Boolean>();

  info.first.collectVariants(info.second, new PairConsumer<String, Boolean>() {
    @Override
    public void consume(String variant, Boolean isFinal) {
      if (variant.equals(key)) {
        res.set(isFinal);
      }
      else if (variant.startsWith(key) && variant.length() > key.length() && variant.charAt(key.length()) == '.') {
        res.set(false);
      }
    }
  });

  if (res.get() != null && !res.get()) {
    return JavaPsiFacade.getElementFactory(qualifier.getProject()).createTypeByFQClassName(GroovyCommonClassNames.GROOVY_UTIL_CONFIG_OBJECT, qualifier.getResolveScope());
  }

  return null;
}
项目:intellij-ce-playground    文件:AddComponentAction.java   
@Nullable
private static PsiElement findElementToAdd(final PsiFile psiFile) {
  if (psiFile.getFileType().equals(StdFileTypes.GUI_DESIGNER_FORM)) {
    return psiFile;
  }
  else if (psiFile.getFileType().equals(StdFileTypes.JAVA)) {
    final PsiClass psiClass = PsiTreeUtil.getChildOfType(psiFile, PsiClass.class);
    Project project = psiFile.getProject();
    final PsiClass componentClass =
      JavaPsiFacade.getInstance(project).findClass(JComponent.class.getName(), ProjectScope.getAllScope(project));
    if (psiClass != null && componentClass != null && psiClass.isInheritor(componentClass, true) && psiClass.getQualifiedName() != null) {
      return psiClass;
    }
  }
  return null;
}
项目:intellij-ce-playground    文件:PsiClassFavoriteNodeProvider.java   
@Override
public Object[] createPathFromUrl(final Project project, final String url, final String moduleName) {
  if (DumbService.isDumb(project)) {
    return null;
  }

  GlobalSearchScope scope = null;
  if (moduleName != null) {
    final Module module = ModuleManager.getInstance(project).findModuleByName(moduleName);
    if (module != null) {
      scope = GlobalSearchScope.moduleScope(module);
    }
  }
  if (scope == null) {
    scope = GlobalSearchScope.allScope(project);
  }
  final PsiClass aClass = JavaPsiFacade.getInstance(project).findClass(url, scope);
  if (aClass == null) return null;
  return new Object[]{aClass};
}
项目:intellij    文件:BlazeRenderErrorContributor.java   
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;
                }
              });
}
项目:intellij-ce-playground    文件:Properties.java   
public boolean isPropertyDeprecated(final Module module, final Class aClass, final String propertyName) {
  // TODO[yole]: correct module-dependent caching
  Set<String> deprecated = myClass2DeprecatedProperties.get(aClass.getName());
  if (deprecated == null) {
    deprecated = new HashSet<String>();
    PsiClass componentClass =
      JavaPsiFacade.getInstance(module.getProject()).findClass(aClass.getName(), module.getModuleWithDependenciesAndLibrariesScope(true));
    if (componentClass != null) {
      PsiMethod[] methods = componentClass.getAllMethods();
      for(PsiMethod method: methods) {
        if (method.isDeprecated() && PropertyUtil.isSimplePropertySetter(method)) {
          deprecated.add(PropertyUtil.getPropertyNameBySetter(method));
        }
      }
    }
    myClass2DeprecatedProperties.put(aClass.getName(), deprecated);
  }

  return deprecated.contains(propertyName);
}
项目:intellij-ce-playground    文件:Java15FormInspection.java   
protected void checkComponentProperties(Module module, final IComponent component, final FormErrorCollector collector) {
  final GlobalSearchScope scope = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module);
  final PsiManager psiManager = PsiManager.getInstance(module.getProject());
  final PsiClass aClass = JavaPsiFacade.getInstance(psiManager.getProject()).findClass(component.getComponentClassName(), scope);
  if (aClass == null) {
    return;
  }

  for(final IProperty prop: component.getModifiedProperties()) {
    final PsiMethod getter = PropertyUtil.findPropertyGetter(aClass, prop.getName(), false, true);
    if (getter == null) continue;
    final LanguageLevel languageLevel = LanguageLevelUtil.getEffectiveLanguageLevel(module);
    if (Java15APIUsageInspection.isForbiddenApiUsage(getter, languageLevel)) {
      registerError(component, collector, prop, "@since " + Java15APIUsageInspection.getShortName(languageLevel));
    }
  }
}
项目:intellij-ce-playground    文件:GroovyExtensionProvider.java   
public Couple<List<String>> collectExtensions(GlobalSearchScope resolveScope) {
  PsiPackage aPackage = JavaPsiFacade.getInstance(myProject).findPackage("META-INF.services");
  if (aPackage == null) {
    return Couple.of(Collections.<String>emptyList(), Collections.<String>emptyList());
  }


  List<String> instanceClasses = new ArrayList<String>();
  List<String> staticClasses = new ArrayList<String>();
  for (PsiDirectory directory : aPackage.getDirectories(resolveScope)) {
    PsiFile file = directory.findFile(ORG_CODEHAUS_GROOVY_RUNTIME_EXTENSION_MODULE);
    if (file instanceof PropertiesFile) {
      IProperty inst = ((PropertiesFile)file).findPropertyByKey("extensionClasses");
      IProperty stat = ((PropertiesFile)file).findPropertyByKey("staticExtensionClasses");

      if (inst != null) collectClasses(inst, instanceClasses);
      if (stat != null) collectClasses(stat, staticClasses);
    }
  }

  return Couple.of(instanceClasses, staticClasses);
}
项目:intellij-ce-playground    文件:AndroidConfigurationProducer.java   
@Nullable
private static PsiClass getActivityClass(Location location, ConfigurationContext context) {
  final Module module = context.getModule();
  if (module == null) return null;
  location = JavaExecutionUtil.stepIntoSingleClass(location);
  if (location == null) {
    return null;
  }
  PsiElement element = location.getPsiElement();
  JavaPsiFacade facade = JavaPsiFacade.getInstance(element.getProject());
  GlobalSearchScope scope = module.getModuleWithDependenciesAndLibrariesScope(true);
  PsiClass activityClass = facade.findClass(AndroidUtils.ACTIVITY_BASE_CLASS_NAME, scope);
  if (activityClass == null) return null;

  PsiClass elementClass = PsiTreeUtil.getParentOfType(element, PsiClass.class, false);
  while (elementClass != null) {
    if (elementClass.isInheritor(activityClass, true)) {
      return elementClass;
    }
    elementClass = PsiTreeUtil.getParentOfType(elementClass, PsiClass.class);
  }
  return null;
}
项目:intellij-ce-playground    文件:JavaFormatterTest.java   
public void testSpaceAfterCommaInEnum() throws IncorrectOperationException {
  getSettings().SPACE_AFTER_COMMA = true;

  final JavaPsiFacade facade = getJavaFacade();
  final LanguageLevel effectiveLanguageLevel = LanguageLevelProjectExtension.getInstance(facade.getProject()).getLanguageLevel();
  try {
    LanguageLevelProjectExtension.getInstance(facade.getProject()).setLanguageLevel(LanguageLevel.JDK_1_5);


    doTextTest("public enum StringExDirection {\n" + "\n" + "    RIGHT_TO_LEFT, LEFT_TO_RIGHT\n" + "\n" + "}",
               "public enum StringExDirection {\n" + "\n" + "    RIGHT_TO_LEFT, LEFT_TO_RIGHT\n" + "\n" + "}");
  }
  finally {
    LanguageLevelProjectExtension.getInstance(facade.getProject()).setLanguageLevel(effectiveLanguageLevel);
  }
}
项目:intellij-ce-playground    文件:CreateClassFixTest.java   
@Test
public void runSingle() throws Throwable {
  Runnable runnable = new Runnable() {
    public void run() {
      IntentionAction resultAction = null;
      final String createAction = QuickFixBundle.message(myCreateClass ? "create.class.text" : "create.interface.text", myTestName);
      final List<IntentionAction> actions = myFixture.getAvailableIntentions(getSourceRoot() + "/plugin" + myTestName + ".xml");
      for (IntentionAction action : actions) {
        if (Comparing.strEqual(action.getText(), createAction)) {
          resultAction = action;
          break;
        }
      }
      Assert.assertNotNull(resultAction);
      myFixture.launchAction(resultAction);
      final Project project = myFixture.getProject();
      Assert.assertNotNull(JavaPsiFacade.getInstance(project).findClass(myTestName, GlobalSearchScope.allScope(project)));
    }
  };
  invokeTestRunnable(runnable);
}
项目:intellij-ce-playground    文件:GrDescriptorReturnTypeCalculator.java   
@Override
public PsiType calculateReturnType(@NotNull GrMethodCall callExpression, @NotNull PsiMethod method) {
  for (GroovyMethodInfo methodInfo : GroovyMethodInfo.getInfos(method)) {
    String returnType = methodInfo.getReturnType();
    if (returnType != null) {
      if (methodInfo.isApplicable(method)) {
        return JavaPsiFacade.getElementFactory(callExpression.getProject()).createTypeFromText(returnType, callExpression);
      }
    }
    else {
      if (methodInfo.isReturnTypeCalculatorDefined()) {
        if (methodInfo.isApplicable(method)) {
          PsiType result = methodInfo.getReturnTypeCalculator().fun(callExpression, method);
          if (result != null) {
            return result;
          }
        }
      }
    }
  }

  return null;
}
项目:intellij-ce-playground    文件:MovePackageTest.java   
private void performAction(String[] packageNames, String newPackageName) throws Exception {
  final PsiPackage[] packages = new PsiPackage[packageNames.length];
  for (int i = 0; i < packages.length; i++) {
    String packageName = packageNames[i];
    packages[i] = JavaPsiFacade.getInstance(myPsiManager.getProject()).findPackage(packageName);
    assertNotNull("Package " + packageName + " not found", packages[i]);
  }

  PsiPackage newParentPackage = JavaPsiFacade.getInstance(myPsiManager.getProject()).findPackage(newPackageName);
  assertNotNull(newParentPackage);
  final PsiDirectory[] dirs = newParentPackage.getDirectories();
  assertEquals(dirs.length, 1);

  new MoveClassesOrPackagesProcessor(myProject, packages,
                                     new SingleSourceRootMoveDestination(PackageWrapper.create(newParentPackage), dirs[0]),
                                     true, false, null).run();
  FileDocumentManager.getInstance().saveAllDocuments();
}
项目:intellij-ce-playground    文件:UsagesInAnalyzingDependenciesTest.java   
public void testBackwardPackageScope(){
   final PsiPackage bPackage = JavaPsiFacade.getInstance(myPsiManager.getProject()).findPackage("com.a");
  final DependenciesBuilder builder = new BackwardDependenciesBuilder(myProject, new JavaAnalysisScope(bPackage, null));
  builder.analyze();
  final Set<PsiFile> searchFor = new HashSet<PsiFile>();
  searchFor.add(myJavaFacade.findClass("com.a.A", GlobalSearchScope.allScope(myProject)).getContainingFile());
  final Set<PsiFile> searchIn = new HashSet<PsiFile>();
  final PsiClass bClass = myJavaFacade.findClass("com.b.B", GlobalSearchScope.allScope(myProject));
  searchIn.add(bClass.getContainingFile());
  final PsiClass cClass = myJavaFacade.findClass("com.a.C", GlobalSearchScope.allScope(myProject));
  searchFor.add(cClass.getContainingFile());
  final UsageInfo[] usagesInfos = FindDependencyUtil.findBackwardDependencies(builder, searchIn, searchFor);
  final UsageInfo2UsageAdapter[] usages = UsageInfo2UsageAdapter.convert(usagesInfos);
  final String [] psiUsages = new String [usagesInfos.length];
  for (int i = 0; i < usagesInfos.length; i++) {
    psiUsages[i] = toString(usages[i]);
  }
  checkResult(new String []{"(4: 3) A myA = new A();", "(4: 15) A myA = new A();", "(5: 3) C myC = new C();", "(5: 15) C myC = new C();", "(7: 9) myA.aa();", "(8: 9) myC.cc();"}, psiUsages);
}