protected void performRefactoring(
      Project project,
      PsiDirectory directory,
      PsiPackage aPackage,
      boolean searchInComments,
      boolean searchForTextOccurences) {
    final VirtualFile sourceRoot =
        ProjectRootManager.getInstance(project)
            .getFileIndex()
            .getSourceRootForFile(directory.getVirtualFile());
    if (sourceRoot == null) {
      Messages.showErrorDialog(
          project,
          RefactoringBundle.message("destination.directory.does.not.correspond.to.any.package"),
          RefactoringBundle.message("cannot.move"));
      return;
    }
    final JavaRefactoringFactory factory = JavaRefactoringFactory.getInstance(project);
    final MoveDestination destination =
        myPreserveSourceRoot.isSelected() && myPreserveSourceRoot.isVisible()
            ? factory.createSourceFolderPreservingMoveDestination(aPackage.getQualifiedName())
            : factory.createSourceRootMoveDestination(aPackage.getQualifiedName(), sourceRoot);

    MoveClassesOrPackagesProcessor processor =
        new MoveClassesOrPackagesProcessor(
            myDirectory.getProject(),
            myElementsToMove,
            destination,
            searchInComments,
            searchForTextOccurences,
            myMoveCallback);
    if (processor.verifyValidPackageName()) {
      processor.run();
    }
  }
コード例 #2
0
  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();
  }
コード例 #3
0
 @NotNull
 private DefaultMutableTreeNode addPackage(PsiPackage aPackage) {
   final String qualifiedPackageName = aPackage.getQualifiedName();
   final PsiPackage parentPackage = aPackage.getParentPackage();
   if (parentPackage == null) {
     final DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode) myModel.getRoot();
     if (qualifiedPackageName.length() == 0) {
       rootNode.setUserObject(aPackage);
       return rootNode;
     } else {
       DefaultMutableTreeNode packageNode = findPackageNode(rootNode, qualifiedPackageName);
       if (packageNode != null) return packageNode;
       packageNode = new DefaultMutableTreeNode(aPackage);
       rootNode.add(packageNode);
       return packageNode;
     }
   } else {
     final DefaultMutableTreeNode parentNode = addPackage(parentPackage);
     DefaultMutableTreeNode packageNode = findPackageNode(parentNode, qualifiedPackageName);
     if (packageNode != null) {
       return packageNode;
     }
     packageNode = new DefaultMutableTreeNode(aPackage);
     parentNode.add(packageNode);
     return packageNode;
   }
 }
コード例 #4
0
  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;
  }
コード例 #5
0
 public String getText() {
   if (myPackageName != null) {
     return myPackageName;
   } else {
     return myRefPackage.getQualifiedName();
   }
 }
コード例 #6
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);
 }
コード例 #7
0
 @Override
 public boolean value(PsiPackage aPackage) {
   return JavaPsiFacade.getInstance(aPackage.getProject())
           .getNameHelper()
           .isQualifiedName(aPackage.getQualifiedName())
       && Character.isLowerCase(aPackage.getName().charAt(0));
 }
コード例 #8
0
 @PsiUtil.AccessLevel
 private static int getEffectiveLevel(
     @NotNull PsiElement element,
     @NotNull PsiFile file,
     @NotNull PsiFile memberFile,
     PsiClass memberClass,
     PsiPackage memberPackage) {
   PsiClass aClass = PsiTreeUtil.getParentOfType(element, PsiClass.class);
   if (memberClass != null && PsiTreeUtil.isAncestor(aClass, memberClass, false)
       || aClass != null && PsiTreeUtil.isAncestor(memberClass, aClass, false)) {
     // access from the same file can be via private
     // except when used in annotation:
     // @Ann(value = C.VAL) class C { public static final String VAL = "xx"; }
     PsiAnnotation annotation = PsiTreeUtil.getParentOfType(element, PsiAnnotation.class);
     if (annotation != null
         && annotation.getParent() instanceof PsiModifierList
         && annotation.getParent().getParent() == aClass) {
       return PsiUtil.ACCESS_LEVEL_PACKAGE_LOCAL;
     }
     return PsiUtil.ACCESS_LEVEL_PRIVATE;
   }
   // if (file == memberFile) {
   //  return PsiUtil.ACCESS_LEVEL_PACKAGE_LOCAL;
   // }
   PsiDirectory directory = file.getContainingDirectory();
   PsiPackage aPackage =
       directory == null ? null : JavaDirectoryService.getInstance().getPackage(directory);
   if (aPackage == memberPackage
       || aPackage != null
           && memberPackage != null
           && Comparing.strEqual(
               aPackage.getQualifiedName(), memberPackage.getQualifiedName())) {
     return PsiUtil.ACCESS_LEVEL_PACKAGE_LOCAL;
   }
   if (aClass != null && memberClass != null && aClass.isInheritor(memberClass, true)) {
     // access from subclass can be via protected, except for constructors
     PsiElement resolved =
         element instanceof PsiReference ? ((PsiReference) element).resolve() : null;
     boolean isConstructor =
         resolved instanceof PsiClass && element.getParent() instanceof PsiNewExpression
             || resolved instanceof PsiMethod && ((PsiMethod) resolved).isConstructor();
     if (!isConstructor) {
       return PsiUtil.ACCESS_LEVEL_PROTECTED;
     }
   }
   return PsiUtil.ACCESS_LEVEL_PUBLIC;
 }
コード例 #9
0
ファイル: ClojureFilter.java プロジェクト: halcwb/la-clojure
 @Nullable
 protected String getContainerText(final PsiElement element, final String name) {
   final PsiDirectory parent = ((PsiFile) element).getParent();
   if (parent == null) return null;
   final PsiPackage psiPackage = JavaDirectoryService.getInstance().getPackage(parent);
   if (psiPackage == null) return null;
   return "(" + psiPackage.getQualifiedName() + ")";
 }
コード例 #10
0
 @NotNull
 @Override
 public PsiReferenceExpression createReferenceExpression(@NotNull final PsiPackage aPackage)
     throws IncorrectOperationException {
   if (aPackage.getQualifiedName().isEmpty()) {
     throw new IncorrectOperationException("Cannot create reference to default package.");
   }
   return new LightPackageReferenceExpression(myManager, aPackage);
 }
コード例 #11
0
 public boolean isConfiguredByElement(
     final JUnitConfiguration configuration,
     PsiClass testClass,
     PsiMethod testMethod,
     PsiPackage testPackage) {
   return testPackage != null
       && Comparing.equal(
           testPackage.getQualifiedName(), configuration.getPersistentData().getPackageName());
 }
コード例 #12
0
 private JUnitConfiguration createConfiguration(PsiPackage psiPackage, Module module) {
   JUnitConfiguration configuration =
       new JUnitConfiguration(
           "", myProject, JUnitConfigurationType.getInstance().getConfigurationFactories()[0]);
   configuration.getPersistentData().TEST_OBJECT = JUnitConfiguration.TEST_PACKAGE;
   configuration.getPersistentData().PACKAGE_NAME = psiPackage.getQualifiedName();
   configuration.getPersistentData().setScope(TestSearchScope.WHOLE_PROJECT);
   configuration.setModule(module);
   return configuration;
 }
コード例 #13
0
 public static String getPackageName(PsiPackage psiPackage) {
   if (psiPackage == null) {
     return null;
   }
   String name = psiPackage.getQualifiedName();
   if (name.length() > 0) {
     return name;
   }
   return DEFAULT_PACKAGE_NAME;
 }
コード例 #14
0
 @Nullable
 private static DefaultMutableTreeNode findPackageNode(
     DefaultMutableTreeNode rootNode, String qualifiedName) {
   for (int i = 0; i < rootNode.getChildCount(); i++) {
     final DefaultMutableTreeNode child = (DefaultMutableTreeNode) rootNode.getChildAt(i);
     final PsiPackage nodePackage = (PsiPackage) child.getUserObject();
     if (nodePackage != null) {
       if (Comparing.equal(nodePackage.getQualifiedName(), qualifiedName)) return child;
     }
   }
   return null;
 }
コード例 #15
0
 public static boolean isVisibleSubPackage(PsiPackage subPackage, PbFile curFile) {
   String qSubPackageName = subPackage.getQualifiedName();
   if (curFile.getPackageName().startsWith(qSubPackageName)) {
     return true;
   }
   PbFile[] importedFiles = getImportedFiles(curFile, true);
   for (PbFile importedFile : importedFiles) {
     if (importedFile.getPackageName().startsWith(qSubPackageName)) {
       return true;
     }
   }
   return false;
 }
コード例 #16
0
 private static List<String> extractAllInPackageTests(
     JavaParameters parameters, PsiPackage psiPackage) throws IOException {
   String filePath =
       ContainerUtil.find(
               parameters.getProgramParametersList().getArray(),
               value ->
                   StringUtil.startsWithChar(value, '@') && !StringUtil.startsWith(value, "@w@"))
           .substring(1);
   List<String> lines = readLinesFrom(new File(filePath));
   assertEquals(psiPackage.getQualifiedName(), lines.get(0));
   // lines.remove(0);
   lines.remove(0);
   return lines;
 }
コード例 #17
0
  public static void checkCreateClassOrInterface(@NotNull PsiDirectory directory, String name)
      throws IncorrectOperationException {
    PsiUtil.checkIsIdentifier(directory.getManager(), name);

    String fileName = name + "." + StdFileTypes.JAVA.getDefaultExtension();
    directory.checkCreateFile(fileName);

    PsiNameHelper helper = JavaPsiFacade.getInstance(directory.getProject()).getNameHelper();
    PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage(directory);
    String qualifiedName = aPackage == null ? null : aPackage.getQualifiedName();
    if (!StringUtil.isEmpty(qualifiedName) && !helper.isQualifiedName(qualifiedName)) {
      throw new IncorrectOperationException(
          "Cannot create class in invalid package: '" + qualifiedName + "'");
    }
  }
コード例 #18
0
 private DefaultMutableTreeNode findNodeForPackage(String qualifiedPackageName) {
   DefaultMutableTreeNode root = (DefaultMutableTreeNode) myModel.getRoot();
   Enumeration enumeration = root.depthFirstEnumeration();
   while (enumeration.hasMoreElements()) {
     Object o = enumeration.nextElement();
     if (o instanceof DefaultMutableTreeNode) {
       DefaultMutableTreeNode node = (DefaultMutableTreeNode) o;
       PsiPackage nodePackage = (PsiPackage) node.getUserObject();
       if (nodePackage != null) {
         if (Comparing.equal(nodePackage.getQualifiedName(), qualifiedPackageName)) return node;
       }
     }
   }
   return null;
 }
コード例 #19
0
  @Override
  public boolean canFindUsagesFor(@NotNull PsiElement element) {
    if (element instanceof PsiDirectory) {
      PsiPackage psiPackage = JavaDirectoryService.getInstance().getPackage((PsiDirectory) element);
      return psiPackage != null && psiPackage.getQualifiedName().length() != 0;
    }

    return element instanceof PsiClass
        || element instanceof PsiVariable
        || element instanceof PsiMethod
        || element instanceof PsiPackage
        || element instanceof PsiJavaModule
        || element instanceof PsiLabeledStatement
        || ThrowSearchUtil.isSearchable(element)
        || element instanceof PsiMetaOwner && ((PsiMetaOwner) element).getMetaData() != null;
  }
コード例 #20
0
  private boolean processDeclarationsForMultipleElements(
      @NotNull final PsiScopeProcessor processor,
      @Nullable PsiElement lastParent,
      @NotNull PsiElement place,
      @NotNull ResolveState state) {
    GrCodeReferenceElement ref = getImportReference();
    if (ref == null) return true;

    if (isStatic()) {
      final PsiElement resolved = ref.resolve();
      if (resolved instanceof PsiClass) {
        state = state.put(ClassHint.RESOLVE_CONTEXT, this);
        final PsiClass clazz = (PsiClass) resolved;
        for (final PsiScopeProcessor each : GroovyResolverProcessor.allProcessors(processor)) {
          if (!clazz.processDeclarations(
              new DelegatingScopeProcessor(each) {
                @Override
                public boolean execute(@NotNull PsiElement element, @NotNull ResolveState state) {
                  if (element instanceof PsiMember
                      && ((PsiMember) element).hasModifierProperty(PsiModifier.STATIC)) {
                    return super.execute(element, state);
                  }
                  return true;
                }
              },
              state,
              lastParent,
              place)) return false;
        }
      }
    } else {
      if (ResolveUtil.shouldProcessClasses(processor.getHint(ElementClassHint.KEY))) {
        String qName = PsiUtil.getQualifiedReferenceText(ref);
        if (qName != null) {
          PsiPackage aPackage = JavaPsiFacade.getInstance(getProject()).findPackage(qName);
          if (aPackage != null
              && !((GroovyFile) getContainingFile())
                  .getPackageName()
                  .equals(aPackage.getQualifiedName())) {
            state = state.put(ClassHint.RESOLVE_CONTEXT, this);
            if (!aPackage.processDeclarations(processor, state, lastParent, place)) return false;
          }
        }
      }
    }
    return true;
  }
コード例 #21
0
 @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);
 }
 @Override
 protected boolean setupConfigurationFromContext(
     JUnitConfiguration configuration,
     ConfigurationContext context,
     Ref<PsiElement> sourceElement) {
   PsiPackage psiPackage =
       JavaRuntimeConfigurationProducerBase.checkPackage(context.getPsiLocation());
   if (psiPackage == null) return false;
   sourceElement.set(psiPackage);
   if (!LocationUtil.isJarAttached(
       context.getLocation(), psiPackage, JUnitUtil.TESTCASE_CLASS, JUnitUtil.TEST5_ANNOTATION))
     return false;
   final JUnitConfiguration.Data data = configuration.getPersistentData();
   data.PACKAGE_NAME = psiPackage.getQualifiedName();
   data.TEST_OBJECT = JUnitConfiguration.TEST_PACKAGE;
   data.setScope(setupPackageConfiguration(context, configuration, data.getScope()));
   configuration.setGeneratedName();
   return true;
 }
コード例 #23
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;
 }
コード例 #24
0
  @Override
  public void handleQualifiedNameChange(
      final PsiPackage psiPackage, final String newQualifiedName) {
    ApplicationManager.getApplication().assertWriteAccessAllowed();
    final String oldQualifedName = psiPackage.getQualifiedName();
    final boolean anyChanged = changePackagePrefixes(psiPackage, oldQualifedName, newQualifiedName);
    if (anyChanged) {
      UndoManager.getInstance(psiPackage.getProject())
          .undoableActionPerformed(
              new GlobalUndoableAction() {
                @Override
                public void undo() {
                  changePackagePrefixes(psiPackage, newQualifiedName, oldQualifedName);
                }

                @Override
                public void redo() {
                  changePackagePrefixes(psiPackage, oldQualifedName, newQualifiedName);
                }
              });
    }
  }
コード例 #25
0
 public void testAllInPackageForCommonAncestorModule() throws IOException, ExecutionException {
   disposeModule(getModule2());
   addModule("module5", true);
   Module ancestor = getModule1();
   Module child1 = getModule2();
   Module child2 = getModule3();
   addDependency(ancestor, child1);
   addDependency(ancestor, child2);
   PsiPackage psiPackage = JavaPsiFacade.getInstance(myProject).findPackage("test1");
   JUnitConfiguration configuration =
       createJUnitConfiguration(
           psiPackage, AllInPackageConfigurationProducer.class, new MapDataContext());
   configuration.getPersistentData().setScope(TestSearchScope.WHOLE_PROJECT);
   assertNotNull(configuration);
   checkPackage(psiPackage.getQualifiedName(), configuration);
   assertEmpty(configuration.getModules());
   JavaParameters parameters = checkCanRun(configuration);
   List<String> tests = extractAllInPackageTests(parameters, psiPackage);
   String childTest1 = findClass(child1, "test1.TestB").getQualifiedName();
   String childTest2 = findClass(child2, "test1.Test5").getQualifiedName();
   String ancestorTest = findClass(ancestor, "test1.TestA").getQualifiedName();
   CHECK.containsAll(tests, new Object[] {ancestorTest, childTest1, childTest2});
 }
コード例 #26
0
  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;
  }
コード例 #27
0
  @Override
  public VirtualFile[] occursInPackagePrefixes(PsiPackage psiPackage) {
    List<VirtualFile> result = new ArrayList<VirtualFile>();
    final Module[] modules = ModuleManager.getInstance(psiPackage.getProject()).getModules();

    for (final Module module : modules) {
      for (final ContentEntry contentEntry :
          ModuleRootManager.getInstance(module).getContentEntries()) {
        final List<SourceFolder> sourceFolders =
            contentEntry.getSourceFolders(JavaModuleSourceRootTypes.SOURCES);
        for (final SourceFolder sourceFolder : sourceFolders) {
          final String packagePrefix = sourceFolder.getPackagePrefix();
          if (packagePrefix.startsWith(psiPackage.getQualifiedName())) {
            final VirtualFile file = sourceFolder.getFile();
            if (file != null) {
              result.add(file);
            }
          }
        }
      }
    }

    return VfsUtil.toVirtualFileArray(result);
  }
コード例 #28
0
  @Nullable
  public ProblemDescriptor[] checkFile(
      @NotNull PsiFile file, @NotNull InspectionManager manager, boolean isOnTheFly) {
    // does not work in tests since CodeInsightTestCase copies file into temporary location
    if (ApplicationManager.getApplication().isUnitTestMode()) return null;
    if (file instanceof PsiJavaFile) {
      if (JspPsiUtil.isInJspFile(file)) return null;
      PsiJavaFile javaFile = (PsiJavaFile) file;

      PsiDirectory directory = javaFile.getContainingDirectory();
      if (directory == null) return null;
      PsiPackage dirPackage = JavaDirectoryService.getInstance().getPackage(directory);
      if (dirPackage == null) return null;
      PsiPackageStatement packageStatement = javaFile.getPackageStatement();

      // highlight the first class in the file only
      PsiClass[] classes = javaFile.getClasses();
      if (classes.length == 0 && packageStatement == null) return null;

      String packageName = dirPackage.getQualifiedName();
      if (!Comparing.strEqual(packageName, "", true) && packageStatement == null) {
        String description = JavaErrorMessages.message("missing.package.statement", packageName);

        return new ProblemDescriptor[] {
          manager.createProblemDescriptor(
              classes[0].getNameIdentifier(),
              description,
              new AdjustPackageNameFix(javaFile, null, dirPackage),
              ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
              isOnTheFly)
        };
      }
      if (packageStatement != null) {
        final PsiJavaCodeReferenceElement packageReference = packageStatement.getPackageReference();
        PsiPackage classPackage = (PsiPackage) packageReference.resolve();
        List<LocalQuickFix> availableFixes = new ArrayList<LocalQuickFix>();
        if (classPackage == null) {
          availableFixes.add(new AdjustPackageNameFix(javaFile, packageStatement, dirPackage));
        } else if (!Comparing.equal(
            dirPackage.getQualifiedName(), packageReference.getText(), true)) {
          availableFixes.add(new AdjustPackageNameFix(javaFile, packageStatement, dirPackage));
          MoveToPackageFix moveToPackageFix = new MoveToPackageFix(file, classPackage);
          if (moveToPackageFix.isAvailable()) {
            availableFixes.add(moveToPackageFix);
          }
        }
        if (!availableFixes.isEmpty()) {
          String description =
              JavaErrorMessages.message(
                  "package.name.file.path.mismatch",
                  packageReference.getText(),
                  dirPackage.getQualifiedName());
          return new ProblemDescriptor[] {
            manager.createProblemDescriptor(
                packageStatement.getPackageReference(),
                description,
                isOnTheFly,
                availableFixes.toArray(new LocalQuickFix[availableFixes.size()]),
                ProblemHighlightType.GENERIC_ERROR_OR_WARNING)
          };
        }
      }
    }
    return null;
  }
コード例 #29
0
 public static MultiMap<PsiElement, String> checkConflicts(
     final MemberInfoBase<? extends PsiMember>[] infos,
     @NotNull final PsiClass subclass,
     @Nullable PsiClass superClass,
     @NotNull final PsiPackage targetPackage,
     @NotNull PsiDirectory targetDirectory,
     final InterfaceContainmentVerifier interfaceContainmentVerifier,
     boolean movedMembers2Super) {
   final Set<PsiMember> movedMembers = new HashSet<PsiMember>();
   final Set<PsiMethod> abstractMethods = new HashSet<PsiMethod>();
   final boolean isInterfaceTarget;
   final PsiElement targetRepresentativeElement;
   if (superClass != null) {
     isInterfaceTarget = superClass.isInterface();
     targetRepresentativeElement = superClass;
   } else {
     isInterfaceTarget = false;
     targetRepresentativeElement = targetDirectory;
   }
   for (MemberInfoBase<? extends PsiMember> info : infos) {
     PsiMember member = info.getMember();
     if (member instanceof PsiMethod) {
       if (!info.isToAbstract() && !isInterfaceTarget) {
         movedMembers.add(member);
       } else {
         abstractMethods.add((PsiMethod) member);
       }
     } else {
       movedMembers.add(member);
     }
   }
   final MultiMap<PsiElement, String> conflicts = new MultiMap<PsiElement, String>();
   final Set<PsiMethod> abstrMethods = new HashSet<PsiMethod>(abstractMethods);
   if (superClass != null) {
     for (PsiMethod method : subclass.getMethods()) {
       if (!movedMembers.contains(method) && !method.hasModifierProperty(PsiModifier.PRIVATE)) {
         if (method.findSuperMethods(superClass).length > 0) {
           abstrMethods.add(method);
         }
       }
     }
   }
   RefactoringConflictsUtil.analyzeAccessibilityConflicts(
       movedMembers,
       superClass,
       conflicts,
       VisibilityUtil.ESCALATE_VISIBILITY,
       targetRepresentativeElement,
       abstrMethods);
   if (superClass != null) {
     if (movedMembers2Super) {
       checkSuperclassMembers(superClass, infos, conflicts);
       if (isInterfaceTarget) {
         checkInterfaceTarget(infos, conflicts);
       }
     } else {
       final String qualifiedName = superClass.getQualifiedName();
       assert qualifiedName != null;
       if (superClass.hasModifierProperty(PsiModifier.PACKAGE_LOCAL)) {
         if (!Comparing.strEqual(
             StringUtil.getPackageName(qualifiedName), targetPackage.getQualifiedName())) {
           conflicts.putValue(
               superClass,
               RefactoringUIUtil.getDescription(superClass, true)
                   + " won't be accessible from "
                   + RefactoringUIUtil.getDescription(targetPackage, true));
         }
       }
     }
   }
   // check if moved methods use other members in the classes between Subclass and Superclass
   List<PsiElement> checkModuleConflictsList = new ArrayList<PsiElement>();
   for (PsiMember member : movedMembers) {
     if (member instanceof PsiMethod
         || member instanceof PsiClass && !(member instanceof PsiCompiledElement)) {
       ClassMemberReferencesVisitor visitor =
           movedMembers2Super
               ? new ConflictingUsagesOfSubClassMembers(
                   member,
                   movedMembers,
                   abstractMethods,
                   subclass,
                   superClass,
                   superClass != null ? null : targetPackage,
                   conflicts,
                   interfaceContainmentVerifier)
               : new ConflictingUsagesOfSuperClassMembers(
                   member, subclass, targetPackage, movedMembers, conflicts);
       member.accept(visitor);
     }
     ContainerUtil.addIfNotNull(checkModuleConflictsList, member);
   }
   for (final PsiMethod method : abstractMethods) {
     ContainerUtil.addIfNotNull(checkModuleConflictsList, method.getParameterList());
     ContainerUtil.addIfNotNull(checkModuleConflictsList, method.getReturnTypeElement());
     ContainerUtil.addIfNotNull(checkModuleConflictsList, method.getTypeParameterList());
   }
   RefactoringConflictsUtil.analyzeModuleConflicts(
       subclass.getProject(),
       checkModuleConflictsList,
       new UsageInfo[0],
       targetRepresentativeElement,
       conflicts);
   final String fqName = subclass.getQualifiedName();
   final String packageName;
   if (fqName != null) {
     packageName = StringUtil.getPackageName(fqName);
   } else {
     final PsiFile psiFile = PsiTreeUtil.getParentOfType(subclass, PsiFile.class);
     if (psiFile instanceof PsiClassOwner) {
       packageName = ((PsiClassOwner) psiFile).getPackageName();
     } else {
       packageName = null;
     }
   }
   final boolean toDifferentPackage =
       !Comparing.strEqual(targetPackage.getQualifiedName(), packageName);
   for (final PsiMethod abstractMethod : abstractMethods) {
     abstractMethod.accept(
         new ClassMemberReferencesVisitor(subclass) {
           @Override
           protected void visitClassMemberReferenceElement(
               PsiMember classMember, PsiJavaCodeReferenceElement classMemberReference) {
             if (classMember != null && willBeMoved(classMember, movedMembers)) {
               boolean isAccessible = false;
               if (classMember.hasModifierProperty(PsiModifier.PRIVATE)) {
                 isAccessible = true;
               } else if (classMember.hasModifierProperty(PsiModifier.PACKAGE_LOCAL)
                   && toDifferentPackage) {
                 isAccessible = true;
               }
               if (isAccessible) {
                 String message =
                     RefactoringUIUtil.getDescription(abstractMethod, false)
                         + " uses "
                         + RefactoringUIUtil.getDescription(classMember, true)
                         + " which won't be accessible from the subclass.";
                 message = CommonRefactoringUtil.capitalize(message);
                 conflicts.putValue(classMember, message);
               }
             }
           }
         });
     if (abstractMethod.hasModifierProperty(PsiModifier.PACKAGE_LOCAL) && toDifferentPackage) {
       if (!isInterfaceTarget) {
         String message =
             "Can't make "
                 + RefactoringUIUtil.getDescription(abstractMethod, false)
                 + " abstract as it won't be accessible from the subclass.";
         message = CommonRefactoringUtil.capitalize(message);
         conflicts.putValue(abstractMethod, message);
       }
     }
   }
   return conflicts;
 }
コード例 #30
0
 public void setPsiElement(final PsiPackage psiPackage) {
   setName(psiPackage.getQualifiedName());
 }