private static PsiDirectory[] suggestMostAppropriateDirectories(PsiPackage psiPackage) {
    final Project project = psiPackage.getProject();
    PsiDirectory[] directories = null;
    final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
    if (editor != null) {
      final Document document = editor.getDocument();
      final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);
      if (psiFile != null) {
        final Module module = ModuleUtil.findModuleForPsiElement(psiFile);
        if (module != null) {
          directories =
              psiPackage.getDirectories(GlobalSearchScope.moduleWithDependenciesScope(module));
        } else {
          directories =
              psiPackage.getDirectories(
                  GlobalSearchScope.notScope(GlobalSearchScope.projectScope(project)));
        }
      }
    }

    if (directories == null || directories.length == 0) {
      directories = psiPackage.getDirectories();
    }
    return directories;
  }
 private static void addClassesInPackage(
     PsiPackage aPackage, boolean includeSubpackages, ArrayList<PsiClass> array) {
   PsiDirectory[] dirs = aPackage.getDirectories();
   for (PsiDirectory dir : dirs) {
     addClassesInDirectory(dir, includeSubpackages, array);
   }
 }
 public static PsiDirectory[] getIntentionDescriptionsDirs(Module module) {
   final PsiPackage aPackage =
       JavaPsiFacade.getInstance(module.getProject()).findPackage(INSPECTION_DESCRIPTIONS);
   if (aPackage != null) {
     return aPackage.getDirectories(GlobalSearchScope.moduleWithDependenciesScope(module));
   } else {
     return PsiDirectory.EMPTY_ARRAY;
   }
 }
 private static boolean isWritablePackage(PsiPackage aPackage) {
   PsiDirectory[] directories = aPackage.getDirectories();
   for (PsiDirectory directory : directories) {
     if (directory.isValid() && directory.isWritable()) {
       return true;
     }
   }
   return false;
 }
 @Override
 protected void notifyByBalloon(
     JUnitRunningModel model, boolean started, final JUnitConsoleProperties consoleProperties) {
   if (myFoundTests) {
     super.notifyByBalloon(model, started, consoleProperties);
   } else {
     final String packageName = myConfiguration.getPackage();
     if (packageName == null) return;
     final Project project = myConfiguration.getProject();
     final PsiPackage aPackage = JavaPsiFacade.getInstance(project).findPackage(packageName);
     if (aPackage == null) return;
     final Module module = myConfiguration.getConfigurationModule().getModule();
     if (module == null) return;
     final Set<Module> modulesWithPackage = new HashSet<Module>();
     final PsiDirectory[] directories = aPackage.getDirectories();
     for (PsiDirectory directory : directories) {
       final Module currentModule =
           ModuleUtil.findModuleForFile(directory.getVirtualFile(), project);
       if (module != currentModule && currentModule != null) {
         modulesWithPackage.add(currentModule);
       }
     }
     if (!modulesWithPackage.isEmpty()) {
       final String testRunDebugId =
           consoleProperties.isDebug() ? ToolWindowId.DEBUG : ToolWindowId.RUN;
       final ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project);
       final Function<Module, String> moduleNameRef =
           new Function<Module, String>() {
             @Override
             public String fun(Module module) {
               final String moduleName = module.getName();
               return "<a href=\"" + moduleName + "\">" + moduleName + "</a>";
             }
           };
       String message = "Tests were not found in module \"" + module.getName() + "\".\n" + "Use ";
       if (modulesWithPackage.size() == 1) {
         message += "module \"" + moduleNameRef.fun(modulesWithPackage.iterator().next()) + "\" ";
       } else {
         message += "one of\n" + StringUtil.join(modulesWithPackage, moduleNameRef, "\n") + "\n";
       }
       message += "instead";
       toolWindowManager.notifyByBalloon(
           testRunDebugId,
           MessageType.WARNING,
           message,
           null,
           new ResetConfigurationModuleAdapter(
               project, consoleProperties, toolWindowManager, testRunDebugId));
     }
   }
 }
  @Override
  public void visitPackage(final PsiPackage aPackage) {
    final PsiDirectory[] dirs = aPackage.getDirectories();

    for (PsiDirectory dir : dirs) {
      final PsiFile[] files = dir.getFiles();

      for (final PsiFile file : files) {
        if (file instanceof PsiJavaFile) {
          super.visitJavaFile(((PsiJavaFile) file));
        }
      }
    }
  }
Esempio n. 7
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;
 }
  @NotNull
  private static PsiClass createBeanClass(final WizardData wizardData) throws MyException {
    final PsiManager psiManager = PsiManager.getInstance(wizardData.myProject);

    final ProjectRootManager projectRootManager =
        ProjectRootManager.getInstance(wizardData.myProject);
    final ProjectFileIndex fileIndex = projectRootManager.getFileIndex();
    final VirtualFile sourceRoot = fileIndex.getSourceRootForFile(wizardData.myFormFile);
    if (sourceRoot == null) {
      throw new MyException(UIDesignerBundle.message("error.form.file.is.not.in.source.root"));
    }

    final PsiDirectory rootDirectory = psiManager.findDirectory(sourceRoot);
    LOG.assertTrue(rootDirectory != null);

    final PsiPackage aPackage =
        JavaPsiFacade.getInstance(psiManager.getProject()).findPackage(wizardData.myPackageName);
    if (aPackage == null) {
      throw new MyException(
          UIDesignerBundle.message("error.package.does.not.exist", wizardData.myPackageName));
    }

    PsiDirectory targetDir = null;

    final PsiDirectory[] directories = aPackage.getDirectories();
    for (final PsiDirectory psiDirectory : directories) {
      if (PsiTreeUtil.isAncestor(rootDirectory, psiDirectory, false)) {
        targetDir = psiDirectory;
        break;
      }
    }

    if (targetDir == null) {
      // todo
      throw new MyException(
          UIDesignerBundle.message("error.cannot.find.package", wizardData.myPackageName));
    }

    //noinspection HardCodedStringLiteral
    final String body =
        "public class "
            + wizardData.myShortClassName
            + "{\n"
            + "public "
            + wizardData.myShortClassName
            + "(){}\n"
            + "}";

    try {
      PsiFile sourceFile =
          PsiFileFactory.getInstance(psiManager.getProject())
              .createFileFromText(wizardData.myShortClassName + ".java", body);
      sourceFile = (PsiFile) targetDir.add(sourceFile);

      final PsiClass beanClass = ((PsiJavaFile) sourceFile).getClasses()[0];

      final ArrayList<String> properties = new ArrayList<String>();
      final HashMap<String, String> property2fqClassName = new HashMap<String, String>();

      final FormProperty2BeanProperty[] bindings = wizardData.myBindings;
      for (final FormProperty2BeanProperty binding : bindings) {
        if (binding == null || binding.myBeanProperty == null) {
          continue;
        }

        properties.add(binding.myBeanProperty.myName);

        // todo: handle "casts" ?

        final String propertyClassName = binding.myFormProperty.getComponentPropertyClassName();

        property2fqClassName.put(binding.myBeanProperty.myName, propertyClassName);
      }

      generateBean(beanClass, ArrayUtil.toStringArray(properties), property2fqClassName);

      return beanClass;
    } catch (IncorrectOperationException e) {
      throw new MyException(e.getMessage());
    }
  }
Esempio n. 9
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;
  }
Esempio n. 10
0
  /** @deprecated */
  @Nullable
  public static PsiDirectory findOrCreateDirectoryForPackage(
      Project project,
      String packageName,
      PsiDirectory baseDir,
      boolean askUserToCreate,
      boolean filterSourceDirsForTestBaseDir)
      throws IncorrectOperationException {

    PsiDirectory psiDirectory = null;

    if (!"".equals(packageName)) {
      PsiPackage rootPackage = findLongestExistingPackage(project, packageName);
      if (rootPackage != null) {
        int beginIndex = rootPackage.getQualifiedName().length() + 1;
        packageName = beginIndex < packageName.length() ? packageName.substring(beginIndex) : "";
        String postfixToShow = packageName.replace('.', File.separatorChar);
        if (packageName.length() > 0) {
          postfixToShow = File.separatorChar + postfixToShow;
        }
        PsiDirectory[] directories = rootPackage.getDirectories();
        if (filterSourceDirsForTestBaseDir) {
          directories = filterSourceDirectories(baseDir, project, directories);
        }
        psiDirectory =
            DirectoryChooserUtil.selectDirectory(project, directories, baseDir, postfixToShow);
        if (psiDirectory == null) return null;
      }
    }

    if (psiDirectory == null) {
      PsiDirectory[] sourceDirectories = ProjectRootUtil.getSourceRootDirectories(project);
      psiDirectory =
          DirectoryChooserUtil.selectDirectory(
              project,
              sourceDirectories,
              baseDir,
              File.separatorChar + packageName.replace('.', File.separatorChar));
      if (psiDirectory == null) return null;
    }

    String restOfName = packageName;
    boolean askedToCreate = false;
    while (restOfName.length() > 0) {
      final String name = getLeftPart(restOfName);
      PsiDirectory foundExistingDirectory = psiDirectory.findSubdirectory(name);
      if (foundExistingDirectory == null) {
        if (!askedToCreate && askUserToCreate) {
          int toCreate =
              Messages.showYesNoDialog(
                  project,
                  IdeBundle.message("prompt.create.non.existing.package", packageName),
                  IdeBundle.message("title.package.not.found"),
                  Messages.getQuestionIcon());
          if (toCreate != 0) {
            return null;
          }
          askedToCreate = true;
        }
        psiDirectory = createSubdirectory(psiDirectory, name, project);
      } else {
        psiDirectory = foundExistingDirectory;
      }
      restOfName = cutLeftPart(restOfName);
    }
    return psiDirectory;
  }
Esempio n. 11
0
 private static PsiDirectory[] getPackageDirectoriesInModule(
     PsiPackage rootPackage, Module module) {
   return rootPackage.getDirectories(GlobalSearchScope.moduleScope(module));
 }