private Object[] processPackage(final PsiPackage aPackage) {
    final ArrayList<Object> list = new ArrayList<Object>();
    final int startOffset =
        StringUtil.isEmpty(aPackage.getName()) ? 0 : aPackage.getQualifiedName().length() + 1;
    final GlobalSearchScope scope = getScope();
    for (final PsiPackage subPackage : aPackage.getSubPackages(scope)) {
      final String shortName = subPackage.getQualifiedName().substring(startOffset);
      if (JavaPsiFacade.getInstance(subPackage.getProject())
          .getNameHelper()
          .isIdentifier(shortName)) {
        list.add(subPackage);
      }
    }

    final PsiClass[] classes = aPackage.getClasses(scope);
    final Map<CustomizableReferenceProvider.CustomizationKey, Object> options = getOptions();
    if (options != null) {
      final boolean instantiatable =
          JavaClassReferenceProvider.INSTANTIATABLE.getBooleanValue(options);
      final boolean concrete = JavaClassReferenceProvider.CONCRETE.getBooleanValue(options);
      final boolean notInterface =
          JavaClassReferenceProvider.NOT_INTERFACE.getBooleanValue(options);
      final boolean notEnum = JavaClassReferenceProvider.NOT_ENUM.getBooleanValue(options);
      final ClassKind classKind = getClassKind();

      for (PsiClass clazz : classes) {
        if (isClassAccepted(clazz, classKind, instantiatable, concrete, notInterface, notEnum)) {
          list.add(clazz);
        }
      }
    } else {
      ContainerUtil.addAll(list, classes);
    }
    return list.toArray();
  }
  public PsiElement bindToElement(@NotNull PsiElement element) throws IncorrectOperationException {
    if (isReferenceTo(element)) return getElement();

    final String newName;
    if (element instanceof PsiClass) {
      PsiClass psiClass = (PsiClass) element;
      final boolean jvmFormat =
          Boolean.TRUE.equals(JavaClassReferenceProvider.JVM_FORMAT.getValue(getOptions()));
      newName = jvmFormat ? ClassUtil.getJVMClassName(psiClass) : psiClass.getQualifiedName();
    } else if (element instanceof PsiPackage) {
      PsiPackage psiPackage = (PsiPackage) element;
      newName = psiPackage.getQualifiedName();
    } else {
      throw new IncorrectOperationException("Cannot bind to " + element);
    }
    assert newName != null;

    TextRange range =
        new TextRange(
            myJavaClassReferenceSet.getReference(0).getRangeInElement().getStartOffset(),
            getRangeInElement().getEndOffset());
    final ElementManipulator<PsiElement> manipulator = getManipulator(getElement());
    if (manipulator != null) {
      final PsiElement finalElement = manipulator.handleContentChange(getElement(), range, newName);
      range = new TextRange(range.getStartOffset(), range.getStartOffset() + newName.length());
      myJavaClassReferenceSet.reparse(finalElement, range);
      return finalElement;
    }
    return element;
  }
Exemplo n.º 3
0
 @Nullable
 public static CreateClassOrPackageFix createFix(
     @NotNull final String qualifiedName,
     @NotNull final GlobalSearchScope scope,
     @NotNull final PsiElement context,
     @Nullable final PsiPackage basePackage,
     @Nullable ClassKind kind,
     @Nullable String superClass,
     @Nullable String templateName) {
   final List<PsiDirectory> directories =
       getWritableDirectoryListDefault(basePackage, scope, context.getManager());
   if (directories.isEmpty()) {
     return null;
   }
   final String redPart =
       basePackage == null
           ? qualifiedName
           : qualifiedName.substring(basePackage.getQualifiedName().length() + 1);
   final int dot = redPart.indexOf('.');
   final boolean fixPath = dot >= 0;
   final String firstRedName = fixPath ? redPart.substring(0, dot) : redPart;
   for (Iterator<PsiDirectory> i = directories.iterator(); i.hasNext(); ) {
     if (!checkCreateClassOrPackage(kind != null && !fixPath, i.next(), firstRedName)) {
       i.remove();
     }
   }
   return new CreateClassOrPackageFix(
       directories,
       context,
       fixPath ? qualifiedName : redPart,
       redPart,
       kind,
       superClass,
       templateName);
 }
 @Nullable
 private static Object createSubclassLookupValue(
     @NotNull final PsiPackage context, @NotNull final PsiClass clazz) {
   String name = clazz.getQualifiedName();
   if (name == null) return null;
   final String pack = context.getQualifiedName();
   if (pack.length() > 0) {
     if (name.startsWith(pack)) {
       name = name.substring(pack.length() + 1);
     } else {
       return null;
     }
   }
   final LookupItem<PsiClass> lookup =
       LookupElementFactoryImpl.getInstance().createLookupElement(clazz, name);
   lookup.addLookupStrings(clazz.getName());
   return JavaCompletionUtil.setShowFQN(lookup).setTailType(TailType.NONE);
 }
Exemplo n.º 5
0
 public static List<PsiDirectory> getWritableDirectoryListDefault(
     @Nullable final PsiPackage context,
     final GlobalSearchScope scope,
     final PsiManager psiManager) {
   if (LOG.isDebugEnabled()) {
     LOG.debug(
         "Getting writable directory list for package '"
             + (context == null ? null : context.getQualifiedName())
             + "', scope="
             + scope);
   }
   final List<PsiDirectory> writableDirectoryList = new ArrayList<PsiDirectory>();
   if (context != null) {
     for (PsiDirectory directory : context.getDirectories()) {
       if (LOG.isDebugEnabled()) {
         LOG.debug("Package directory: " + directory);
       }
       if (directory.isWritable() && scope.contains(directory.getVirtualFile())) {
         writableDirectoryList.add(directory);
       }
     }
   } else {
     for (VirtualFile root :
         ProjectRootManager.getInstance(psiManager.getProject()).getContentSourceRoots()) {
       PsiDirectory directory = psiManager.findDirectory(root);
       if (LOG.isDebugEnabled()) {
         LOG.debug("Root: " + root + ", directory: " + directory);
       }
       if (directory != null
           && directory.isWritable()
           && scope.contains(directory.getVirtualFile())) {
         writableDirectoryList.add(directory);
       }
     }
   }
   if (LOG.isDebugEnabled()) {
     LOG.debug("Result " + writableDirectoryList);
   }
   return writableDirectoryList;
 }
  static boolean isSideEffectFreeConstructor(PsiNewExpression newExpression) {
    PsiJavaCodeReferenceElement classReference = newExpression.getClassReference();
    PsiClass aClass = classReference == null ? null : (PsiClass) classReference.resolve();
    String qualifiedName = aClass == null ? null : aClass.getQualifiedName();
    if (qualifiedName == null) return false;
    if (ourSideEffectFreeClasses.contains(qualifiedName)) return true;

    PsiFile file = aClass.getContainingFile();
    PsiDirectory directory = file.getContainingDirectory();
    PsiPackage classPackage = JavaDirectoryService.getInstance().getPackage(directory);
    String packageName = classPackage == null ? null : classPackage.getQualifiedName();

    // all Throwable descendants from java.lang are side effects free
    if ("java.lang".equals(packageName) || "java.io".equals(packageName)) {
      PsiClass throwableClass =
          JavaPsiFacade.getInstance(aClass.getProject())
              .findClass("java.lang.Throwable", aClass.getResolveScope());
      if (throwableClass != null
          && InheritanceUtil.isInheritorOrSelf(aClass, throwableClass, true)) {
        return true;
      }
    }
    return false;
  }
 public void setPsiElement(final PsiPackage psiPackage) {
   setName(psiPackage.getQualifiedName());
 }
Exemplo n.º 8
0
  /**
   * Adds import if it is needed.
   *
   * @return false when the FQ-name have to be used in code (e.g. when conflicting imports already
   *     exist)
   */
  public boolean addImport(@NotNull PsiJavaFile file, @NotNull PsiClass refClass) {
    final JavaPsiFacade facade = JavaPsiFacade.getInstance(file.getProject());
    PsiElementFactory factory = facade.getElementFactory();
    PsiResolveHelper helper = facade.getResolveHelper();

    String className = refClass.getQualifiedName();
    if (className == null) return true;
    String packageName = getPackageOrClassName(className);
    String shortName = PsiNameHelper.getShortClassName(className);

    PsiClass conflictSingleRef = findSingleImportByShortName(file, shortName);
    if (conflictSingleRef != null) {
      return className.equals(conflictSingleRef.getQualifiedName());
    }

    PsiClass curRefClass = helper.resolveReferencedClass(shortName, file);
    if (file.getManager().areElementsEquivalent(refClass, curRefClass)) {
      return true;
    }

    boolean useOnDemand = true;
    if (packageName.length() == 0) {
      useOnDemand = false;
    }

    PsiElement conflictPackageRef = findImportOnDemand(file, packageName);
    if (conflictPackageRef != null) {
      useOnDemand = false;
    }

    List<PsiElement> classesToReimport = new ArrayList<PsiElement>();

    List<PsiJavaCodeReferenceElement> importRefs = getImportsFromPackage(file, packageName);
    if (useOnDemand) {
      if (mySettings.USE_SINGLE_CLASS_IMPORTS
          && importRefs.size() + 1 < mySettings.CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND
          && !mySettings.PACKAGES_TO_USE_IMPORT_ON_DEMAND.contains(packageName)) {
        useOnDemand = false;
      }
      // name of class we try to import is the same as of the class defined in this file
      if (curRefClass != null) {
        useOnDemand = true;
      }
      // check conflicts
      if (useOnDemand) {
        PsiElement[] onDemandRefs = file.getOnDemandImports(false, true);
        if (onDemandRefs.length > 0) {
          PsiPackage aPackage = facade.findPackage(packageName);
          if (aPackage != null) {
            PsiDirectory[] dirs = aPackage.getDirectories();
            for (PsiDirectory dir : dirs) {
              PsiFile[] files = dir.getFiles(); // do not iterate classes - too slow when not loaded
              for (PsiFile aFile : files) {
                if (aFile instanceof PsiJavaFile) {
                  String name = aFile.getVirtualFile().getNameWithoutExtension();
                  for (PsiElement ref : onDemandRefs) {
                    String refName =
                        ref instanceof PsiClass
                            ? ((PsiClass) ref).getQualifiedName()
                            : ((PsiPackage) ref).getQualifiedName();
                    String conflictClassName = refName + "." + name;
                    GlobalSearchScope resolveScope = file.getResolveScope();
                    PsiClass conflictClass = facade.findClass(conflictClassName, resolveScope);
                    if (conflictClass != null && helper.isAccessible(conflictClass, file, null)) {
                      String conflictClassName2 = aPackage.getQualifiedName() + "." + name;
                      PsiClass conflictClass2 = facade.findClass(conflictClassName2, resolveScope);
                      if (conflictClass2 != null
                          && helper.isAccessible(conflictClass2, file, null)) {
                        if (ReferencesSearch.search(
                                    conflictClass, new LocalSearchScope(file), false)
                                .findFirst()
                            != null) {
                          classesToReimport.add(conflictClass);
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }

    try {
      PsiImportList importList = file.getImportList();
      PsiImportStatement statement;
      if (useOnDemand) {
        statement = factory.createImportStatementOnDemand(packageName);
      } else {
        statement = factory.createImportStatement(refClass);
      }
      importList.add(statement);
      if (useOnDemand) {
        for (PsiJavaCodeReferenceElement ref : importRefs) {
          LOG.assertTrue(ref.getParent() instanceof PsiImportStatement);
          if (!ref.isValid()) continue; // todo[dsl] Q?
          classesToReimport.add(ref.resolve());
          PsiImportStatement importStatement = (PsiImportStatement) ref.getParent();
          importStatement.delete();
        }
      }

      for (PsiElement aClassesToReimport : classesToReimport) {
        PsiClass aClass = (PsiClass) aClassesToReimport;
        if (aClass != null) {
          addImport(file, aClass);
        }
      }
    } catch (IncorrectOperationException e) {
      LOG.error(e);
    }
    return true;
  }
 public Module setMainClass(final PsiClass testClass) {
   MAIN_CLASS_NAME = JavaExecutionUtil.getRuntimeQualifiedName(testClass);
   PsiPackage containingPackage = JUnitUtil.getContainingPackage(testClass);
   PACKAGE_NAME = containingPackage != null ? containingPackage.getQualifiedName() : "";
   return JavaExecutionUtil.findModule(testClass);
 }