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

项目:smcplugin    文件:CreateFsmFileAction.java   
@Nullable
@Override
protected SmcFile createFile(String name, String templateName, PsiDirectory dir) {
    String aPackageName = getPackageName(dir);
    boolean validName = PsiNameHelper.getInstance(dir.getProject()).isQualifiedName(name);
    String shortClassName = StringUtils.capitalize(PsiNameHelper.getShortClassName(name));
    String smClassName = validName ? shortClassName + STATE_MACHINE_SUFFIX : "";
    String smContextClassName = validName ?  shortClassName + CONTEXT_SUFFIX : "";
    if (validName && !DO_NOT_CREATE_CONTEXT_KIND.equals(templateName)) {
        JavaDirectoryService.getInstance().createClass(dir, smContextClassName, templateName, true);
    }
    String nameWithExtension = name + DOT_EXTENSION;
    SmcFile newFile = SmcElementFactory.createNewFile(dir.getProject(), nameWithExtension, aPackageName,
            smClassName, smContextClassName);
    dir.add(newFile);
    return newFile;
}
项目:CleanArchitecturePlugin    文件:EntityAdapter.java   
/**
 * Create EntityAdapter.class
 */
public static void create() {
    PsiDirectory adapterDirectory = createDirectory(getViewPackage(), ADAPTER.toLowerCase());

    String className = getEntityConfig().getEntityName() + ADAPTER;

    HashMap<String, String> varTemplate = new HashMap<>();
    varTemplate.put("PACKAGE_PROJECT", getPackageNameProject(getProjectDirectory()));
    varTemplate.put("LAYOUT_NAME", getEntityConfig().getEntityName().toLowerCase());


    Runnable runnable = () -> {
        JavaDirectoryService.getInstance().createClass(adapterDirectory, className, ADAPTER_TEMPLATE, false, varTemplate);
        try {
            createLayout(getPackageNameProject(adapterDirectory), className, ADAPTER);
        } catch (Exception e) {
            e.printStackTrace();
        }
    };
    WriteCommandAction.runWriteCommandAction(getProject(), runnable);


}
项目:CleanArchitecturePlugin    文件:EntityPresenter.java   
/**
 * Create EntityPresenter.class
 */
public static void create() {

    // Create presenter directory
    presenterDirectory = createDirectory(getViewPackage(), PRESENTER.toLowerCase());

    // Create presenter class
    String className = getEntityConfig().getEntityName() + PRESENTER;

    HashMap<String, String> varTemplate = new HashMap<>();
    varTemplate.put("PACKAGE_PRESENTER_IMPL", getPackageNameProject(Presenter.getPresenterDirectory()));
    varTemplate.put("PRESENTER_IMPL", PRESENTER_IMPL);

    Runnable runnable = () -> JavaDirectoryService.getInstance().createClass(presenterDirectory, className, PRESENTER_TEMPLATE, false, varTemplate);
    WriteCommandAction.runWriteCommandAction(getProject(), runnable);
}
项目:intellij-ce-playground    文件:MoveClassToSeparateFileFix.java   
@Override
public void invoke(@NotNull Project project, @Nullable Editor editor, @NotNull PsiFile file) {
  if (!FileModificationService.getInstance().prepareFileForWrite(myClass.getContainingFile())) return;

  PsiDirectory dir = file.getContainingDirectory();
  try{
    String name = myClass.getName();
    JavaDirectoryService directoryService = JavaDirectoryService.getInstance();
    PsiClass placeHolder = myClass.isInterface() ? directoryService.createInterface(dir, name) : directoryService.createClass(dir, name);
    PsiClass newClass = (PsiClass)placeHolder.replace(myClass);
    myClass.delete();

    OpenFileDescriptor descriptor = new OpenFileDescriptor(project, newClass.getContainingFile().getVirtualFile(), newClass.getTextOffset());
    FileEditorManager.getInstance(project).openTextEditor(descriptor, true);
  }
  catch(IncorrectOperationException e){
    LOG.error(e);
  }
}
项目:intellij-ce-playground    文件:PsiJavaDirectoryImpl.java   
@Override
public PsiElement add(@NotNull final PsiElement element) throws IncorrectOperationException {
  if (element instanceof PsiClass) {
    final String name = ((PsiClass)element).getName();
    if (name != null) {
      final PsiClass newClass = JavaDirectoryService.getInstance().createClass(this, name);
      return newClass.replace(element);
    }
    else {
      LOG.error("not implemented");
      return null;
    }
  }
  else {
    return super.add(element);
  }
}
项目:intellij-ce-playground    文件:PackageViewPane.java   
@Override
public boolean addSubtreeToUpdateByElement(Object element) {
  // should convert PsiDirectories into PackageElements
  if (element instanceof PsiDirectory) {
    PsiDirectory dir = (PsiDirectory)element;
    final PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage(dir);
    if (ProjectView.getInstance(myProject).isShowModules(getId())) {
      Module[] modules = getModulesFor(dir);
      boolean rv = false;
      for (Module module : modules) {
        rv |= addPackageElementToUpdate(aPackage, module);
      }
      return rv;
    }
    else {
      return addPackageElementToUpdate(aPackage, null);
    }
  }

  return super.addSubtreeToUpdateByElement(element);
}
项目:intellij-ce-playground    文件:JavaProjectViewDirectoryHelper.java   
@Nullable
@Override
public String getNodeName(final ViewSettings settings, final Object parentValue, final PsiDirectory directory) {
  if (JrtFileSystem.isRoot(directory.getVirtualFile())) {
    return LangBundle.message("jrt.node.short");
  }

  PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage(directory);

  PsiPackage parentPackage;
  if (!ProjectRootsUtil.isSourceRoot(directory) && aPackage != null && !aPackage.getQualifiedName().isEmpty() && parentValue instanceof PsiDirectory) {
    parentPackage = JavaDirectoryService.getInstance().getPackage(((PsiDirectory)parentValue));
  }
  else if (ProjectRootsUtil.isSourceRoot(directory) && aPackage != null) {   //package prefix
    aPackage = null;
    parentPackage = null;
  }
  else {
    parentPackage = null;
  }

  return PackageUtil.getNodeName(settings, aPackage, parentPackage, directory.getName(), isShowFQName(settings, parentValue, directory));
}
项目:intellij-ce-playground    文件:TreeViewUtil.java   
/**
 * a directory is considered "empty" if it has at least one child and all its children are only directories
 *
 * @param strictlyEmpty if true, the package is considered empty if it has only 1 child and this child  is a directory
 *                      otherwise the package is considered as empty if all direct children that it has are directories
 */
public static boolean isEmptyMiddlePackage(@NotNull PsiDirectory dir, boolean strictlyEmpty) {
  final VirtualFile[] files = dir.getVirtualFile().getChildren();
  if (files.length == 0) {
    return false;
  }
  PsiManager manager = dir.getManager();
  int subpackagesCount = 0;
  int directoriesCount = 0;
  for (VirtualFile file : files) {
    if (FileTypeManager.getInstance().isFileIgnored(file)) continue;
    if (!file.isDirectory()) return false;
    PsiDirectory childDir = manager.findDirectory(file);
    if (childDir != null) {
      directoriesCount++;
      if (strictlyEmpty && directoriesCount > 1) return false;
      if (JavaDirectoryService.getInstance().getPackage(childDir) != null) {
        subpackagesCount++;
      }
    }
  }
  if (strictlyEmpty) {
    return directoriesCount == subpackagesCount && directoriesCount == 1;
  }
  return directoriesCount == subpackagesCount && directoriesCount > 0;
}
项目:intellij-ce-playground    文件:JavaTreeStructureTest.java   
private void dotest(CheckAction checkAction) throws Exception {
  final PsiClass psiClass = JavaDirectoryService.getInstance().getClasses(getPackageDirectory("com/package1"))[0];
  final VirtualFile virtualFile = psiClass.getContainingFile().getVirtualFile();
  final FileEditorManager fileEditorManager = FileEditorManager.getInstance(myProject);
  FileEditor[] fileEditors = fileEditorManager.openFile(virtualFile, false);
  final FileEditor fileEditor = fileEditors[0];
  try {
    final StructureViewComponent structureViewComponent =
      (StructureViewComponent)fileEditor.getStructureViewBuilder().createStructureView(fileEditor, myProject);

    checkAction.testClassStructure(structureViewComponent);
    Disposer.dispose(structureViewComponent);

  }
  finally {
    fileEditorManager.closeFile(virtualFile);
  }
}
项目:intellij-ce-playground    文件:LegacyNewAndroidComponentAction.java   
private static boolean isAvailable(DataContext dataContext) {
  final Module module = LangDataKeys.MODULE.getData(dataContext);
  final IdeView view = LangDataKeys.IDE_VIEW.getData(dataContext);

  if (module == null ||
      view == null ||
      view.getDirectories().length == 0) {
    return false;
  }
  final AndroidFacet facet = AndroidFacet.getInstance(module);

  if (facet == null || facet.isGradleProject()) {
    return false;
  }
  final ProjectFileIndex projectIndex = ProjectRootManager.getInstance(module.getProject()).getFileIndex();
  final JavaDirectoryService dirService = JavaDirectoryService.getInstance();

  for (PsiDirectory dir : view.getDirectories()) {
    if (projectIndex.isUnderSourceRootOfType(dir.getVirtualFile(), JavaModuleSourceRootTypes.SOURCES) &&
        dirService.getPackage(dir) != null) {
      return true;
    }
  }
  return false;
}
项目:intellij-ce-playground    文件:JavaSourceAction.java   
protected static boolean isAvailable(DataContext dataContext) {
  final Module module = LangDataKeys.MODULE.getData(dataContext);
  final IdeView view = LangDataKeys.IDE_VIEW.getData(dataContext);

  if (module == null ||
      view == null ||
      view.getDirectories().length == 0 ||
      AndroidFacet.getInstance(module) == null) {
    return false;
  }
  final ProjectFileIndex projectIndex = ProjectRootManager.getInstance(module.getProject()).getFileIndex();
  final JavaDirectoryService dirService = JavaDirectoryService.getInstance();

  for (PsiDirectory dir : view.getDirectories()) {
    if (projectIndex.isUnderSourceRootOfType(dir.getVirtualFile(), JavaModuleSourceRootTypes.SOURCES) &&
        dirService.getPackage(dir) != null &&
        !dirService.getPackage(dir).getQualifiedName().isEmpty()) {
      return true;
    }
  }
  return false;
}
项目:intellij-ce-playground    文件:AbstractCreateFormAction.java   
public void update(final AnActionEvent e) {
  super.update(e);
  final Project project = e.getData(CommonDataKeys.PROJECT);
  final Presentation presentation = e.getPresentation();
  if (presentation.isEnabled()) {
    final IdeView view = e.getData(LangDataKeys.IDE_VIEW);
    if (view != null) {
      final ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex();
      final PsiDirectory[] dirs = view.getDirectories();
      for (final PsiDirectory dir : dirs) {
        if (projectFileIndex.isUnderSourceRootOfType(dir.getVirtualFile(), JavaModuleSourceRootTypes.SOURCES) && JavaDirectoryService.getInstance().getPackage(dir) != null) {
          return;
        }
      }
    }

    presentation.setEnabled(false);
    presentation.setVisible(false);
  }
}
项目:intellij-ce-playground    文件:NewGroovyClassAction.java   
@Override
protected void buildDialog(Project project, PsiDirectory directory, CreateFileFromTemplateDialog.Builder builder) {
  builder
    .setTitle(GroovyBundle.message("newclass.dlg.title"))
    .addKind("Class", JetgroovyIcons.Groovy.Class, GroovyTemplates.GROOVY_CLASS)
    .addKind("Interface", JetgroovyIcons.Groovy.Interface, GroovyTemplates.GROOVY_INTERFACE);

  if (GroovyConfigUtils.getInstance().isVersionAtLeast(directory, GroovyConfigUtils.GROOVY2_3, true)) {
    builder.addKind("Trait", JetgroovyIcons.Groovy.Trait, GroovyTemplates.GROOVY_TRAIT);
  }

  builder
    .addKind("Enum", JetgroovyIcons.Groovy.Enum, GroovyTemplates.GROOVY_ENUM)
    .addKind("Annotation", JetgroovyIcons.Groovy.AnnotationType, GroovyTemplates.GROOVY_ANNOTATION);

  for (FileTemplate template : FileTemplateManager.getInstance(project).getAllTemplates()) {
    FileType fileType = FileTypeManagerEx.getInstanceEx().getFileTypeByExtension(template.getExtension());
    if (fileType.equals(GroovyFileType.GROOVY_FILE_TYPE) && JavaDirectoryService.getInstance().getPackage(directory) != null) {
      builder.addKind(template.getName(), JetgroovyIcons.Groovy.Class, template.getName());
    }
  }
}
项目:idea-pitest    文件:DirectoryBasedConfigurator.java   
@Override
public void configure(JUnitConfiguration jUnitConfiguration, PitestConfiguration configuration) {
    JUnitConfiguration.Data data = jUnitConfiguration.getPersistentData();
    String targetTests = "";
    String targetClasses = "";
    String dirName = data.getDirName();
    VirtualFile dir = LocalFileSystem.getInstance().findFileByPath(FileUtil.toSystemIndependentName(dirName));
    if (dir != null) {
        PsiDirectory directory = PsiManager.getInstance(jUnitConfiguration.getProject()).findDirectory(dir);
        if (directory != null) {
            PsiPackage psiPackage = JavaDirectoryService.getInstance().getPackage(directory);
            if (psiPackage != null) {
                String packageName = psiPackage.getQualifiedName();
                targetTests = isEmpty(packageName) ? "" : packageName + ANY_IN_PACKAGE_PATTERN;
                targetClasses = targetTests;
            }
        }
    }
    configure(configuration, targetTests, targetClasses);
}
项目:tools-idea    文件:MoveClassToSeparateFileFix.java   
@Override
public void invoke(@NotNull Project project, @Nullable Editor editor, @NotNull PsiFile file) {
  if (!FileModificationService.getInstance().prepareFileForWrite(myClass.getContainingFile())) return;

  PsiDirectory dir = file.getContainingDirectory();
  try{
    String name = myClass.getName();
    JavaDirectoryService directoryService = JavaDirectoryService.getInstance();
    PsiClass placeHolder = myClass.isInterface() ? directoryService.createInterface(dir, name) : directoryService.createClass(dir, name);
    PsiClass newClass = (PsiClass)placeHolder.replace(myClass);
    myClass.delete();

    OpenFileDescriptor descriptor = new OpenFileDescriptor(project, newClass.getContainingFile().getVirtualFile(), newClass.getTextOffset());
    FileEditorManager.getInstance(project).openTextEditor(descriptor, true);
  }
  catch(IncorrectOperationException e){
    LOG.error(e);
  }
}
项目:tools-idea    文件:PsiJavaDirectoryImpl.java   
@Override
public PsiElement add(@NotNull final PsiElement element) throws IncorrectOperationException {
  if (element instanceof PsiClass) {
    final String name = ((PsiClass)element).getName();
    if (name != null) {
      final PsiClass newClass = JavaDirectoryService.getInstance().createClass(this, name);
      return newClass.replace(element);
    }
    else {
      LOG.error("not implemented");
      return null;
    }
  }
  else {
    return super.add(element);
  }
}
项目:tools-idea    文件:PackageViewPane.java   
@Override
public boolean addSubtreeToUpdateByElement(Object element) {
  // should convert PsiDirectories into PackageElements
  if (element instanceof PsiDirectory) {
    PsiDirectory dir = (PsiDirectory)element;
    final PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage(dir);
    if (ProjectView.getInstance(myProject).isShowModules(getId())) {
      Module[] modules = getModulesFor(dir);
      boolean rv = false;
      for (Module module : modules) {
        rv |= addPackageElementToUpdate(aPackage, module);
      }
      return rv;
    }
    else {
      return addPackageElementToUpdate(aPackage, null);
    }
  }

  return super.addSubtreeToUpdateByElement(element);
}
项目:tools-idea    文件:PackageUtil.java   
@NotNull
public static PsiPackage[] getSubpackages(@NotNull PsiPackage aPackage,
                                          @Nullable Module module,
                                          @NotNull Project project,
                                          final boolean searchInLibraries) {
  final PsiDirectory[] dirs = getDirectories(aPackage, project, module, searchInLibraries);
  final Set<PsiPackage> subpackages = new HashSet<PsiPackage>();
  for (PsiDirectory dir : dirs) {
    final PsiDirectory[] subdirectories = dir.getSubdirectories();
    for (PsiDirectory subdirectory : subdirectories) {
      final PsiPackage psiPackage = JavaDirectoryService.getInstance().getPackage(subdirectory);
      if (psiPackage != null) {
        final String name = psiPackage.getName();
        // skip "default" subpackages as they should be attributed to other modules
        // this is the case when contents of one module is nested into contents of another
        if (name != null && !name.isEmpty()) {
          subpackages.add(psiPackage);
        }
      }
    }
  }
  return subpackages.toArray(new PsiPackage[subpackages.size()]);
}
项目:tools-idea    文件:JavaProjectViewDirectoryHelper.java   
@Nullable
@Override
public String getNodeName(final ViewSettings settings, final Object parentValue, final PsiDirectory directory) {
  PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage(directory);

  PsiPackage parentPackage;
  if (!ProjectRootsUtil.isSourceRoot(directory) && aPackage != null && !aPackage.getQualifiedName().isEmpty() &&
                            parentValue instanceof PsiDirectory) {

    parentPackage = JavaDirectoryService.getInstance().getPackage(((PsiDirectory)parentValue));
  }
  else if (ProjectRootsUtil.isSourceRoot(directory) && aPackage != null) {   //package prefix
    aPackage = null;
    parentPackage = null;
  }
  else {
    parentPackage = null;
  }

  return PackageUtil.getNodeName(settings, aPackage, parentPackage, directory.getName(), isShowFQName(settings, parentValue, directory));

}
项目:tools-idea    文件:TreeViewUtil.java   
/**
 * a directory is considered "empty" if it has at least one child and all its children are only directories
 *
 * @param strictlyEmpty if true, the package is considered empty if it has only 1 child and this child  is a directory
 *                      otherwise the package is considered as empty if all direct children that it has are directories
 */
public static boolean isEmptyMiddlePackage(@NotNull PsiDirectory dir, boolean strictlyEmpty) {
  final VirtualFile[] files = dir.getVirtualFile().getChildren();
  if (files.length == 0) {
    return false;
  }
  PsiManager manager = dir.getManager();
  int subpackagesCount = 0;
  int directoriesCount = 0;
  for (VirtualFile file : files) {
    if (FileTypeManager.getInstance().isFileIgnored(file)) continue;
    if (!file.isDirectory()) return false;
    PsiDirectory childDir = manager.findDirectory(file);
    if (childDir != null) {
      directoriesCount++;
      if (strictlyEmpty && directoriesCount > 1) return false;
      if (JavaDirectoryService.getInstance().getPackage(childDir) != null) {
        subpackagesCount++;
      }
    }
  }
  if (strictlyEmpty) {
    return directoriesCount == subpackagesCount && directoriesCount == 1;
  }
  return directoriesCount == subpackagesCount && directoriesCount > 0;
}
项目:tools-idea    文件:JavaTreeStructureTest.java   
private void dotest(CheckAction checkAction) throws Exception {
  final PsiClass psiClass = JavaDirectoryService.getInstance().getClasses(getPackageDirectory("com/package1"))[0];
  final VirtualFile virtualFile = psiClass.getContainingFile().getVirtualFile();
  final FileEditorManager fileEditorManager = FileEditorManager.getInstance(myProject);
  FileEditor[] fileEditors = fileEditorManager.openFile(virtualFile, false);
  final FileEditor fileEditor = fileEditors[0];
  try {
    final StructureViewComponent structureViewComponent =
      (StructureViewComponent)fileEditor.getStructureViewBuilder().createStructureView(fileEditor, myProject);

    checkAction.testClassStructure(structureViewComponent);
    Disposer.dispose(structureViewComponent);

  }
  finally {
    fileEditorManager.closeFile(virtualFile);
  }
}
项目:tools-idea    文件:AbstractCreateFormAction.java   
public void update(final AnActionEvent e) {
  super.update(e);
  final Project project = e.getData(PlatformDataKeys.PROJECT);
  final Presentation presentation = e.getPresentation();
  if (presentation.isEnabled()) {
    final IdeView view = e.getData(LangDataKeys.IDE_VIEW);
    if (view != null) {
      final ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex();
      final PsiDirectory[] dirs = view.getDirectories();
      for (final PsiDirectory dir : dirs) {
        if (projectFileIndex.isInSourceContent(dir.getVirtualFile()) && JavaDirectoryService.getInstance().getPackage(dir) != null) {
          return;
        }
      }
    }

    presentation.setEnabled(false);
    presentation.setVisible(false);
  }
}
项目:tools-idea    文件:NewGroovyClassAction.java   
@Override
protected void buildDialog(Project project, PsiDirectory directory, CreateFileFromTemplateDialog.Builder builder) {
  builder
    .setTitle(GroovyBundle.message("newclass.dlg.title"))
    .addKind("Class", JetgroovyIcons.Groovy.Class, GroovyTemplates.GROOVY_CLASS)
    .addKind("Interface", JetgroovyIcons.Groovy.Interface, GroovyTemplates.GROOVY_INTERFACE)
    .addKind("Enum", JetgroovyIcons.Groovy.Enum, GroovyTemplates.GROOVY_ENUM)
    .addKind("Annotation", JetgroovyIcons.Groovy.AnnotationType, GroovyTemplates.GROOVY_ANNOTATION);

  for (FileTemplate template : FileTemplateManager.getInstance().getAllTemplates()) {
    FileType fileType = FileTypeManagerEx.getInstanceEx().getFileTypeByExtension(template.getExtension());
    if (fileType.equals(GroovyFileType.GROOVY_FILE_TYPE) && JavaDirectoryService.getInstance().getPackage(directory) != null) {
      builder.addKind(template.getName(), JetgroovyIcons.Groovy.Class, template.getName());
    }
  }
}
项目:consulo-ui-designer    文件:FormEditingUtil.java   
@Nullable
public static String buildResourceName(final PsiFile file)
{
    PsiDirectory directory = file.getContainingDirectory();
    if(directory != null)
    {
        PsiPackage pkg = JavaDirectoryService.getInstance().getPackage(directory);
        String packageName = pkg != null ? pkg.getQualifiedName() : "";
        if(packageName.length() == 0)
        {
            return file.getName();
        }
        return packageName.replace('.', '/') + '/' + file.getName();
    }
    return null;
}
项目:consulo-ui-designer    文件:CreateDialogAction.java   
@NotNull
protected PsiElement[] create(final String newName, final PsiDirectory directory) throws IncorrectOperationException {
  PsiFile sourceFile = PsiFileFactory.getInstance(directory.getProject())
    .createFileFromText(newName + ".java", createClassBody(newName, myRecentGenerateOK, myRecentGenerateCancel, myRecentGenerateMain));
  sourceFile = (PsiFile)directory.add(sourceFile);

  JavaCodeStyleManager.getInstance(directory.getProject()).shortenClassReferences(sourceFile);
  CodeStyleManager.getInstance(directory.getProject()).reformat(sourceFile);

  final PsiJavaPackage aPackage = JavaDirectoryService.getInstance().getPackage(directory);
  final String packageName = aPackage.getQualifiedName();
  final String fqClassName = packageName.length() == 0 ? newName : packageName + "." + newName;

  final String formBody = createFormBody(fqClassName, "/com/intellij/uiDesigner/NewDialog.xml",
                                         GuiDesignerConfiguration.getInstance(directory.getProject()).DEFAULT_LAYOUT_MANAGER);
  final PsiFile formFile = PsiFileFactory.getInstance(directory.getProject()).createFileFromText(newName + ".form", formBody);
  PsiElement createdFile = directory.add(formFile);

  PsiClass[] classes = ((PsiJavaFile)sourceFile).getClasses();
  return new PsiElement[]{createdFile, classes[0]};
}
项目:consulo-ui-designer    文件:AbstractCreateFormAction.java   
@Override
public void update(final AnActionEvent e) {
  super.update(e);
  final Project project = e.getData(CommonDataKeys.PROJECT);
  final Presentation presentation = e.getPresentation();
  if (presentation.isEnabled()) {
    final Module module = e.getData(LangDataKeys.MODULE);
    if (module != null && ModuleUtilCore.getExtension(module, JavaModuleExtension.class) != null) {
      final IdeView view = e.getData(LangDataKeys.IDE_VIEW);
      if (view != null) {
        final ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex();
        final PsiDirectory[] dirs = view.getDirectories();
        for (final PsiDirectory dir : dirs) {
          if (projectFileIndex.isInSourceContent(dir.getVirtualFile()) && JavaDirectoryService.getInstance().getPackage(dir) != null) {
            return;
          }
        }
      }
    }

    presentation.setEnabled(false);
    presentation.setVisible(false);
  }
}
项目:consulo-google-guice    文件:GuiceActionGroup.java   
@RequiredDispatchThread
@Override
public void update(@NotNull AnActionEvent e)
{
    final Module module = e.getData(LangDataKeys.MODULE);
    final IdeView view = e.getData(LangDataKeys.IDE_VIEW);
    final Project project = e.getData(LangDataKeys.PROJECT);
    final Presentation presentation = e.getPresentation();

    boolean visible = false;
    if(module != null && ModuleUtilCore.getExtension(module, GoogleGuiceModuleExtension.class) != null && project != null && view != null)
    {
        final ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex();
        final PsiDirectory[] dirs = view.getDirectories();
        for(PsiDirectory dir : dirs)
        {
            if(projectFileIndex.isInSourceContent(dir.getVirtualFile()) && JavaDirectoryService.getInstance().getPackage(dir) != null)
            {
                visible = true;
                break;
            }
        }
    }

    presentation.setEnabledAndVisible(visible);
}
项目:consulo-java    文件:PackageUtil.java   
private static PsiJavaPackage findLongestExistingPackage(Module module, String packageName)
{
    final PsiManager manager = PsiManager.getInstance(module.getProject());

    String nameToMatch = packageName;
    while(true)
    {
        Query<VirtualFile> vFiles = DirectoryIndex.getInstance(module.getProject()).getDirectoriesByPackageName(nameToMatch, false);
        PsiDirectory directory = getWritableModuleDirectory(vFiles, module, manager);
        if(directory != null)
        {
            return JavaDirectoryService.getInstance().getPackage(directory);
        }

        int lastDotIndex = nameToMatch.lastIndexOf('.');
        if(lastDotIndex >= 0)
        {
            nameToMatch = nameToMatch.substring(0, lastDotIndex);
        }
        else
        {
            return null;
        }
    }
}
项目:consulo-java    文件:RefactoringListeners.java   
public ClassPackageAccessor(final RefactoringListeners.Accessor<PsiClass> accessor)
{
    myAccessor = accessor;
    PsiClass aClass = myAccessor.getPsiElement();
    aClass = (PsiClass) aClass.getOriginalElement();
    myContainingPackage = JavaDirectoryService.getInstance().getPackage(aClass.getContainingFile().getContainingDirectory());
    myModule = JavaExecutionUtil.findModule(aClass);
    final String classQName = aClass.getQualifiedName();
    final String classPackageQName = myContainingPackage.getQualifiedName();
    if(classQName.startsWith(classPackageQName))
    {
        final String inpackageName = classQName.substring(classPackageQName.length());
        if(StringUtil.startsWithChar(inpackageName, '.'))
        {
            myInpackageName = inpackageName.substring(1);
        }
        else
        {
            myInpackageName = inpackageName;
        }
    }
    else
    {
        myInpackageName = null;
    }
}
项目:consulo-java    文件:JavaCoverageAnnotator.java   
@Nullable
public String getDirCoverageInformationString(@NotNull final PsiDirectory directory,
                                              @NotNull final CoverageSuitesBundle currentSuite,
                                              @NotNull final CoverageDataManager coverageDataManager) {
  final PsiJavaPackage psiPackage = JavaDirectoryService.getInstance().getPackage(directory);
  if (psiPackage == null) return null;

  final ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(directory.getProject()).getFileIndex();
  final VirtualFile virtualFile = directory.getVirtualFile();

  final boolean isInTestContent = projectFileIndex.isInTestSourceContent(virtualFile);

  if (!currentSuite.isTrackTestFolders() && isInTestContent) {
    return null;
  }
  return isInTestContent ? getCoverageInformationString(myTestDirCoverageInfos.get(virtualFile), coverageDataManager.isSubCoverageActive())
                         : getCoverageInformationString(myDirCoverageInfos.get(virtualFile), coverageDataManager.isSubCoverageActive());

}
项目:consulo-java    文件:MoveClassToSeparateFileFix.java   
@Override
public void invoke(@NotNull Project project, @Nullable Editor editor, @NotNull PsiFile file) {
  if (!FileModificationService.getInstance().prepareFileForWrite(myClass.getContainingFile())) return;

  PsiDirectory dir = file.getContainingDirectory();
  try{
    String name = myClass.getName();
    JavaDirectoryService directoryService = JavaDirectoryService.getInstance();
    PsiClass placeHolder = myClass.isInterface() ? directoryService.createInterface(dir, name) : directoryService.createClass(dir, name);
    PsiClass newClass = (PsiClass)placeHolder.replace(myClass);
    myClass.delete();

    OpenFileDescriptor descriptor = new OpenFileDescriptor(project, newClass.getContainingFile().getVirtualFile(), newClass.getTextOffset());
    FileEditorManager.getInstance(project).openTextEditor(descriptor, true);
  }
  catch(IncorrectOperationException e){
    LOG.error(e);
  }
}
项目:consulo-java    文件:CreateClassUtil.java   
@NotNull
private static PsiDirectory createParentDirectories(@NotNull PsiDirectory directoryRoot, @NotNull String className) throws IncorrectOperationException {
  final PsiJavaPackage currentPackage = JavaDirectoryService.getInstance().getPackage(directoryRoot);
  final String packagePrefix = currentPackage == null? null : currentPackage.getQualifiedName() + ".";
  final String packageName = extractPackage(packagePrefix != null && className.startsWith(packagePrefix)?
                                            className.substring(packagePrefix.length()) : className);
  final StringTokenizer tokenizer = new StringTokenizer(packageName, ".");
  while (tokenizer.hasMoreTokens()) {
    String packagePart = tokenizer.nextToken();
    PsiDirectory subdirectory = directoryRoot.findSubdirectory(packagePart);
    if (subdirectory == null) {
      directoryRoot.checkCreateSubdirectory(packagePart);
      subdirectory = directoryRoot.createSubdirectory(packagePart);
    }
    directoryRoot = subdirectory;
  }
  return directoryRoot;
}
项目:consulo-java    文件:JavaPsiDirectoryMethodProxy.java   
@Override
public PsiElement add(@NotNull PsiDirectory psiDirectory,  @NotNull final PsiElement element) throws IncorrectOperationException
{
    if(element instanceof PsiClass)
    {
        final String name = ((PsiClass) element).getName();
        if(name != null)
        {
            final PsiClass newClass = JavaDirectoryService.getInstance().createClass(psiDirectory, name);
            return newClass.replace(element);
        }
        else
        {
            LOG.error("not implemented");
            return null;
        }
    }

    return null;
}
项目:consulo-java    文件:JavaTreeStructureTest.java   
private void dotest(CheckAction checkAction) throws Exception {
  final PsiClass psiClass = JavaDirectoryService.getInstance().getClasses(getPackageDirectory("com/package1"))[0];
  final VirtualFile virtualFile = psiClass.getContainingFile().getVirtualFile();
  final FileEditorManager fileEditorManager = FileEditorManager.getInstance(myProject);
  FileEditor[] fileEditors = fileEditorManager.openFile(virtualFile, false);
  final FileEditor fileEditor = fileEditors[0];
  try {
    final StructureViewComponent structureViewComponent =
      (StructureViewComponent)fileEditor.getStructureViewBuilder().createStructureView(fileEditor, myProject);

    checkAction.testClassStructure(structureViewComponent);
    Disposer.dispose(structureViewComponent);

  }
  finally {
    fileEditorManager.closeFile(virtualFile);
  }
}
项目:consulo-java    文件:NavigateFromSourceTest.java   
public void testShowClassMembers() throws Exception
{
    useStandardProviders();
    final PsiClass[] classes = JavaDirectoryService.getInstance().getClasses(getPackageDirectory());
    sortClassesByName(classes);
    PsiClass psiClass = classes[0];

    final AbstractProjectViewPSIPane pane = myStructure.createPane();
    final PsiFile containingFile = psiClass.getContainingFile();
    final VirtualFile virtualFile = containingFile.getVirtualFile();

    myStructure.checkNavigateFromSourceBehaviour(psiClass, virtualFile, pane);

    PlatformTestUtil.assertTreeEqual(pane.getTree(), "-Project\n" + " -PsiDirectory: showClassMembers\n" + "  -PsiDirectory: src\n" + "   -PsiDirectory: com\n" + "    -PsiDirectory: package1\n"
            + "     [Class1]\n" + "     Class2\n" + getRootFiles() + " +External Libraries\n", true);

    changeClassTextAndTryToNavigate("class Class11 {}", (PsiJavaFile) containingFile, pane, "-Project\n" + " -PsiDirectory: showClassMembers\n" + "  -PsiDirectory: src\n" + "   -PsiDirectory: " +
            "com\n" + "    -PsiDirectory: package1\n" + "     -Class1.java\n" + "      [Class11]\n" + "     Class2\n" + getRootFiles() + " +External Libraries\n");

    changeClassTextAndTryToNavigate("class Class1 {}", (PsiJavaFile) containingFile, pane, "-Project\n" + " -PsiDirectory: showClassMembers\n" + "  -PsiDirectory: src\n" + "   -PsiDirectory: " +
            "com\n" + "    -PsiDirectory: package1\n" + "     -Class1.java\n" + "      [Class1]\n" + "     Class2\n" + getRootFiles() + " +External Libraries\n");

    doTestMultipleSelection(pane, ((PsiJavaFile) containingFile).getClasses()[0]);
}
项目:consulo-java    文件:FileTemplatesTest.java   
public void testDefaultPackage() throws Exception {
  String name = "myclass";
  FileTemplate template = FileTemplateManager.getDefaultInstance().addTemplate(name/*+"ForTest"*/, "java");
  try {
    template.setText("package ${PACKAGE_NAME}; public class ${NAME} {}");

    File temp = FileUtil.createTempDirectory(getTestName(true), "");

    myFilesToDelete.add(temp);
    final VirtualFile tempDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(temp);

    PsiTestUtil.addSourceRoot(getModule(), tempDir);

    VirtualFile sourceRoot = ModuleRootManager.getInstance(getModule()).getSourceRoots()[0];
    PsiDirectory psiDirectory = PsiManager.getInstance(getProject()).findDirectory(sourceRoot);

    PsiClass psiClass = JavaDirectoryService.getInstance().createClass(psiDirectory, "XXX", name);
    assertNotNull(psiClass);
    assertEquals("public class XXX {\n}", psiClass.getContainingFile().getText());
  }
  finally {
    FileTemplateManager.getDefaultInstance().removeTemplate(template);
  }
}
项目:json2java4idea    文件:NewClassCommandAction.java   
@Inject
public NewClassCommandAction(@Nonnull Project project,
                             @Nonnull @Assisted("Name") String name,
                             @Nonnull @Assisted("Json") String json,
                             @Nonnull @Assisted PsiDirectory directory,
                             @Nonnull @Assisted JavaConverter converter) {
    super(project);
    this.fileFactory = PsiFileFactory.getInstance(project);
    this.directoryService = JavaDirectoryService.getInstance();
    this.name = Preconditions.checkNotNull(name);
    this.json = Preconditions.checkNotNull(json);
    this.directory = Preconditions.checkNotNull(directory);
    this.converter = Preconditions.checkNotNull(converter);
}
项目:educational-plugin    文件:EduJavaPluginConfigurator.java   
@Override
public void createTestsForNewSubtask(@NotNull Project project, @NotNull TaskWithSubtasks task) {
  VirtualFile taskDir = task.getTaskDir(project);
  if (taskDir == null) {
    return;
  }
  int prevSubtaskIndex = task.getLastSubtaskIndex();
  PsiDirectory taskPsiDir = PsiManager.getInstance(project).findDirectory(taskDir);
  if (taskPsiDir == null) {
    return;
  }
  int nextSubtaskIndex = prevSubtaskIndex + 1;
  String nextSubtaskTestsClassName = getSubtaskTestsClassName(nextSubtaskIndex);
  JavaDirectoryService.getInstance().createClass(taskPsiDir, nextSubtaskTestsClassName);
}
项目:RIBs    文件:GenerateAction.java   
/** @return gets the current package name for an executing action. */
protected final String getPackageName() {
  /** Preconditions have been validated by {@link GenerateAction#isAvailable(DataContext)}. */
  final Project project = Preconditions.checkNotNull(CommonDataKeys.PROJECT.getData(dataContext));
  final IdeView view = Preconditions.checkNotNull(LangDataKeys.IDE_VIEW.getData(dataContext));
  final PsiDirectory directory = Preconditions.checkNotNull(view.getOrChooseDirectory());
  final PsiPackage psiPackage =
      Preconditions.checkNotNull(JavaDirectoryService.getInstance().getPackage(directory));

  return psiPackage.getQualifiedName();
}
项目:RIBs    文件:GenerateAction.java   
/**
 * Checks if a Java package exists for a directory.
 *
 * @param directory to check.
 * @return {@code true} when a package exists, {@code false} when it does not.
 */
private boolean checkPackageExists(PsiDirectory directory) {
  PsiPackage pkg = JavaDirectoryService.getInstance().getPackage(directory);
  if (pkg == null) {
    return false;
  }

  String name = pkg.getQualifiedName();
  return StringUtil.isEmpty(name)
      || PsiNameHelper.getInstance(directory.getProject()).isQualifiedName(name);
}