com.intellij.psi.JavaDirectoryService Java Examples

The following examples show how to use com.intellij.psi.JavaDirectoryService. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EntityAdapter.java    From CleanArchitecturePlugin with Apache License 2.0 6 votes vote down vote up
/**
 * 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);


}
 
Example #2
Source File: EntityPresenter.java    From CleanArchitecturePlugin with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #3
Source File: NewClassCommandAction.java    From json2java4idea with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #4
Source File: PolygeneCreateActionGroup.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
private boolean shouldActionGroupVisible( AnActionEvent e )
    {
        Module module = e.getData( LangDataKeys.MODULE );
        if( module == null )
        {
            return false;
        }

        // TODO: Enable this once PolygeneFacet can be automatically added/removed
//        if( PolygeneFacet.getInstance( module ) == null )
//        {
//            return false;
//        }

        // Are we on IDE View and under project source folder?
        Project project = e.getData( PlatformDataKeys.PROJECT );
        IdeView view = e.getData( LangDataKeys.IDE_VIEW );
        if( view != null && project != null )
        {
            ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance( project ).getFileIndex();
            PsiDirectory[] dirs = view.getDirectories();
            for( PsiDirectory dir : dirs )
            {
                if( projectFileIndex.isInSourceContent( dir.getVirtualFile() ) && JavaDirectoryService.getInstance().getPackage( dir ) != null )
                {
                    return true;
                }
            }
        }

        return false;
    }
 
Example #5
Source File: CreateConcernOfInPackageAction.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@NotNull
protected PsiClass doCreate( final PsiDirectory dir, final String className )
    throws IncorrectOperationException
{
    JavaDirectoryService javaDirectoryService = JavaDirectoryService.getInstance();
    return javaDirectoryService.createClass( dir, className, TEMPLATE_GENERIC_CONCERN_OF );
}
 
Example #6
Source File: MultipleJavaClassesTestContextProvider.java    From intellij with Apache License 2.0 5 votes vote down vote up
private static void addClassesInDirectory(
    WorkspaceFileFinder finder, PsiDirectory dir, Set<PsiClass> set, int currentDepth) {
  if (currentDepth > MAX_DEPTH_TO_SEARCH || !relevantDirectory(finder, dir)) {
    return;
  }
  PsiClass[] classes = JavaDirectoryService.getInstance().getClasses(dir);
  set.addAll(
      Arrays.stream(classes).filter(ProducerUtils::isTestClass).collect(toImmutableList()));
  for (PsiDirectory child : dir.getSubdirectories()) {
    addClassesInDirectory(finder, child, set, currentDepth + 1);
  }
}
 
Example #7
Source File: BlazeAndroidModuleTemplate.java    From intellij with Apache License 2.0 5 votes vote down vote up
/**
 * The new component wizard uses {@link NamedModuleTemplate#getName()} for the default package
 * name of the new component. If we can figure it out from the target directory here, then we can
 * pass it to the new component wizard.
 */
private static String getPackageName(Project project, VirtualFile targetDirectory) {
  PsiDirectory psiDirectory = PsiManager.getInstance(project).findDirectory(targetDirectory);
  if (psiDirectory == null) {
    return null;
  }
  PsiPackage psiPackage = JavaDirectoryService.getInstance().getPackage(psiDirectory);
  if (psiPackage == null) {
    return null;
  }
  return psiPackage.getQualifiedName();
}
 
Example #8
Source File: EntityCache.java    From CleanArchitecturePlugin with Apache License 2.0 5 votes vote down vote up
public static void create() {

        // Create cache package
        cacheDirectory = createDirectory(getDataPackage(), CACHE.toLowerCase());

        // Create entity cache class
        String className = getEntityConfig().getEntityName() + CACHE;

        Runnable runnable = () -> JavaDirectoryService.getInstance().createClass(cacheDirectory, className, CACHE_TEMPLATE);
        WriteCommandAction.runWriteCommandAction(getProject(), runnable);
    }
 
Example #9
Source File: EntityFragment.java    From CleanArchitecturePlugin with Apache License 2.0 5 votes vote down vote up
/**
 * Create package fragment and EntityFragment.class
 */
public static void create() {

    // Create fragment directory
    PsiDirectory fragmentDirectory = createDirectory(getViewPackage(), FRAGMENT.toLowerCase());

    // Create fragment class
    String className = getEntityConfig().getEntityName() + FRAGMENT;

    HashMap<String, String> varTemplate = new HashMap<>();
    varTemplate.put("PACKAGE_PROJECT", getPackageNameProject(getProjectDirectory()));
    varTemplate.put("LAYOUT_NAME", getEntityConfig().getEntityName().toLowerCase());
    varTemplate.put("PACKAGE_BASE_FRAGMENT", getPackageNameProject(ParentFragment.getFragmentDirectory()));
    varTemplate.put("BASE_FRAGMENT", PARENT_FRAGMENT);
    varTemplate.put("PACKAGE_BASE_PRESENTER", getPackageNameProject(Presenter.getPresenterDirectory()));
    varTemplate.put("BASE_PRESENTER", PRESENTER);

    if (EntityPresenter.getPresenterDirectory() != null && getEntityConfig().isContainsPresenter()) {  // With presenter or not
        varTemplate.put("PACKAGE_PRESENTER", getPackageNameProject(EntityPresenter.getPresenterDirectory()));
        varTemplate.put("PRESENTER", getEntityConfig().getEntityName() + PRESENTER);
    }

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

}
 
Example #10
Source File: ParentDialogFragment.java    From CleanArchitecturePlugin with Apache License 2.0 5 votes vote down vote up
public static void create() {

        if (ParentFragment.getFragmentDirectory().findFile(PARENT_DIALOG_FRAGMENT + ".java") == null) { // Not contains ParentDialogFragment.java
            // Create Parent Fragment class
            HashMap<String, String> varTemplate = new HashMap<>();

            varTemplate.put("PACKAGE_PRESENTER", getPackageNameProject(Presenter.getPresenterDirectory()));
            varTemplate.put("PRESENTER", PRESENTER);

            Runnable runnable = () -> JavaDirectoryService.getInstance().createClass(ParentFragment.getFragmentDirectory(), PARENT_DIALOG_FRAGMENT, BASE_DIALOG_FRAGMENT_TEMPLATE, false, varTemplate);
            WriteCommandAction.runWriteCommandAction(getProject(), runnable);
        }
    }
 
Example #11
Source File: DefaultProviderImpl.java    From CodeGen with MIT License 5 votes vote down vote up
@Override
public void create(CodeTemplate template, CodeContext context, Map<String, Object> extraMap){

    VelocityContext velocityContext = new VelocityContext(BuilderUtil.transBean2Map(context));
    velocityContext.put("serialVersionUID", BuilderUtil.computeDefaultSUID(context.getModel(), context.getFields()));
    // $!dateFormatUtils.format($!now,'yyyy-MM-dd')
    velocityContext.put("dateFormatUtils", new org.apache.commons.lang.time.DateFormatUtils());
    if (extraMap != null && extraMap.size() > 0) {
        for (Map.Entry<String, Object> entry: extraMap.entrySet()) {
            velocityContext.put(entry.getKey(), entry.getValue());
        }
    }

    String fileName = VelocityUtil.evaluate(velocityContext, template.getFilename());
    String subPath = VelocityUtil.evaluate(velocityContext, template.getSubPath());
    String temp = VelocityUtil.evaluate(velocityContext, template.getTemplate());

    WriteCommandAction.runWriteCommandAction(this.project, () -> {
        try {
            VirtualFile vFile = VfsUtil.createDirectoryIfMissing(outputPath);
            PsiDirectory psiDirectory = PsiDirectoryFactory.getInstance(this.project).createDirectory(vFile);
            PsiDirectory directory = subDirectory(psiDirectory, subPath, template.getResources());
            // TODO: 这里干啥用的, 没用的话是不是可以删除了
            if (JavaFileType.INSTANCE == this.languageFileType) {
                PsiPackage psiPackage = JavaDirectoryService.getInstance().getPackage(directory);
                if (psiPackage != null && !StringUtils.isEmpty(psiPackage.getQualifiedName())) {
                    extraMap.put(fileName, new StringBuilder(psiPackage.getQualifiedName()).append(".").append(fileName));
                }
            }
            createFile(project, directory, fileName + "." + this.languageFileType.getDefaultExtension(), temp, this.languageFileType);
        } catch (Exception e) {
            LOGGER.error(StringUtils.getStackTraceAsString(e));
        }
    });
}
 
Example #12
Source File: GenerateAction.java    From RIBs with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #13
Source File: GenerateAction.java    From RIBs with Apache License 2.0 5 votes vote down vote up
/**
 * @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();
}
 
Example #14
Source File: EntityActivity.java    From CleanArchitecturePlugin with Apache License 2.0 4 votes vote down vote up
/**
 * Create package activity and EntityActivity.class
 */
public static void create() {

    // Create activity directory
    PsiDirectory activityDirectory = createDirectory(getViewPackage(), ACTIVITY.toLowerCase());

    // Create activity class
    String className = getEntityConfig().getEntityName() + ACTIVITY;

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


    if (ParentActivity.getActivityDirectory() != null) { // With Parent Activity
        varTemplate.put("PACKAGE_BASE_ACTIVITY", getPackageNameProject(ParentActivity.getActivityDirectory()));
        varTemplate.put("BASE_ACTIVITY", PARENT_ACTIVITY);
    }

    if (Presenter.getPresenterDirectory() != null) { // With Parent Presenter
        varTemplate.put("PACKAGE_BASE_PRESENTER", getPackageNameProject(Presenter.getPresenterDirectory()));
        varTemplate.put("BASE_PRESENTER", PRESENTER);
    }

    if (EntityPresenter.getPresenterDirectory() != null && getEntityConfig().isContainsPresenter()) { // With presenter
        varTemplate.put("PACKAGE_PRESENTER", getPackageNameProject(EntityPresenter.getPresenterDirectory()));
        varTemplate.put("PRESENTER", getEntityConfig().getEntityName() + PRESENTER);
    }

    Runnable runnable = () -> {
        JavaDirectoryService.getInstance().createClass(activityDirectory, className, ACTIVITY_TEMPLATE, false, varTemplate);
        try {
            createLayout(getPackageNameProject(activityDirectory), className, ACTIVITY);
        } catch (Exception e) {
            e.printStackTrace();
        }

    };
    WriteCommandAction.runWriteCommandAction(getProject(), runnable);

}
 
Example #15
Source File: EntityAPI.java    From CleanArchitecturePlugin with Apache License 2.0 4 votes vote down vote up
public static void create() {

        // Create API package
        apiDirectory = createDirectory(getDataPackage(), API.toLowerCase());

        // Create service class
        String className = getEntityConfig().getEntityName() + SERVICE;

        HashMap<String, String> varTemplate = new HashMap<>();
        varTemplate.put("PACKAGE_BASE_SERVICE", getPackageNameProject(ParentAPI.getApiDirectory()));
        varTemplate.put("BASE_SERVICE", BASE_SERVICE);

        Runnable runnable = () -> JavaDirectoryService.getInstance().createClass(apiDirectory, className, SERVICE_TEMPLATE, false, varTemplate);
        WriteCommandAction.runWriteCommandAction(getProject(), runnable);

    }
 
Example #16
Source File: EntityRepository.java    From CleanArchitecturePlugin with Apache License 2.0 4 votes vote down vote up
public static void create() {

        // Create Repository package
        PsiDirectory repositoryDirectory = createDirectory(getDataPackage(), REPOSITORY.toLowerCase());

        // Create DataSource package
        PsiDirectory dataSourceDirectory = createDirectory(repositoryDirectory, DATASOURCE.toLowerCase());

        // Create Cloud Entity Data Source class
        String cloudEntityDataSourceName = CLOUD + getEntityConfig().getEntityName() + DATASOURCE;

        HashMap<String, String> cloudTemplate = new HashMap<>();
        cloudTemplate.put("PACKAGE_SERVICE", getPackageNameProject(EntityAPI.getApiDirectory()));
        cloudTemplate.put("SERVICE", getEntityConfig().getEntityName() + SERVICE);

        // Create Disk Entity Data Source class
        String diskEntityDataSourceName = DISK + getEntityConfig().getEntityName() + DATASOURCE;

        HashMap<String, String> diskTemplate = new HashMap<>();
        diskTemplate.put("PACKAGE_BASE_SERVICE", getPackageNameProject(ParentAPI.getApiDirectory()));
        diskTemplate.put("BASE_SERVICE", BASE_SERVICE);
        diskTemplate.put("PACKAGE_CACHE", getPackageNameProject(EntityCache.getCacheDirectory()));
        diskTemplate.put("CACHE", getEntityConfig().getEntityName() + CACHE);

        // Create Data Store Factory class
        String dataStoreFactoryName = getEntityConfig().getEntityName() + DATASTOREFACTORY;

        HashMap<String, String> dataStoreFactoryTemplate = new HashMap<>();
        dataStoreFactoryTemplate.put("PACKAGE_ENTITY_SERVICE", getPackageNameProject(EntityAPI.getApiDirectory()));
        dataStoreFactoryTemplate.put("ENTITY_SERVICE", getEntityConfig().getEntityName() + SERVICE);
        dataStoreFactoryTemplate.put("PACKAGE_ENTITY_CACHE", getPackageNameProject(EntityCache.getCacheDirectory()));
        dataStoreFactoryTemplate.put("ENTITY_CACHE", getEntityConfig().getEntityName() + CACHE);
        dataStoreFactoryTemplate.put("PACKAGE_CLOUD_ENTITY_DATA_SOURCE", getPackageNameProject(dataSourceDirectory));
        dataStoreFactoryTemplate.put("CLOUD_ENTITY_DATA_SOURCE", cloudEntityDataSourceName);
        dataStoreFactoryTemplate.put("PACKAGE_DISK_ENTITY_DATA_SOURCE", getPackageNameProject(dataSourceDirectory));
        dataStoreFactoryTemplate.put("DISK_ENTITY_DATA_SOURCE", diskEntityDataSourceName);

        // Create Repository class
        String repositoryName = getEntityConfig().getEntityName() + REPOSITORY;

        HashMap<String, String> repositoryTemplate = new HashMap<>();
        repositoryTemplate.put("DATA_STORE_FACTORY", getEntityConfig().getEntityName() + DATASTOREFACTORY);


        Runnable repositoryRunnable = () -> {
            JavaDirectoryService.getInstance().createClass(dataSourceDirectory, cloudEntityDataSourceName, CLOUD_ENTITY_DATA_SOURCE_TEMPLATE, false, cloudTemplate);
            JavaDirectoryService.getInstance().createClass(dataSourceDirectory, diskEntityDataSourceName, DISK_ENTITY_DATA_SOURCE_TEMPLATE, false, diskTemplate);
            JavaDirectoryService.getInstance().createClass(repositoryDirectory, dataStoreFactoryName, DATA_STORE_FACTORY_TEMPLATE, false, dataStoreFactoryTemplate);
            JavaDirectoryService.getInstance().createClass(repositoryDirectory, repositoryName, REPOSITORY_TEMPLATE, false, repositoryTemplate);
        };

        WriteCommandAction.runWriteCommandAction(getProject(), repositoryRunnable);

    }
 
Example #17
Source File: CreateConcernOfInPackageAction.java    From attic-polygene-java with Apache License 2.0 4 votes vote down vote up
protected final void doCheckCreate( final PsiDirectory dir, final String className )
    throws IncorrectOperationException
{
    JavaDirectoryService javaDirectoryService = JavaDirectoryService.getInstance();
    javaDirectoryService.checkCreateClass( dir, className );
}
 
Example #18
Source File: ProjectModule.java    From json2java4idea with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Provides
@Singleton
public JavaDirectoryService provideDirectoryService() {
    return JavaDirectoryService.getInstance();
}
 
Example #19
Source File: MarkdownDocumentationProvider.java    From markdown-doclet with GNU General Public License v3.0 4 votes vote down vote up
@Nullable
@Override
public String generateDoc(PsiElement element, @Nullable PsiElement originalElement) {
    boolean process = false;
    for ( Class supported: SUPPORTED_ELEMENT_TYPES ) {
        if ( supported.isInstance(element) ) {
            process = true;
            break;
        }
    }
    if ( !process ) {
        return null;
    }
    PsiFile file = null;
    if ( element instanceof PsiDirectory ) {
        // let's see whether we can map the directory to a package; if so, change the
        // element to the package and continue
        PsiPackage pkg = JavaDirectoryService.getInstance().getPackage((PsiDirectory)element);
        if ( pkg != null ) {
            element = pkg;
        }
        else {
            return null;
        }
    }
    if ( element instanceof PsiPackage ) {
        for ( PsiDirectory dir : ((PsiPackage)element).getDirectories() ) {
            PsiFile info = dir.findFile(PsiPackage.PACKAGE_INFO_FILE);
            if ( info != null ) {
                ASTNode node = info.getNode();
                if ( node != null ) {
                    ASTNode docCommentNode = node.findChildByType(JavaDocElementType.DOC_COMMENT);
                    if ( docCommentNode != null ) {
                        // the default implementation will now use this file
                        // we're going to take over below, if Markdown is enabled in
                        // the corresponding module
                        // see JavaDocInfoGenerator.generatePackageJavaDoc()
                        file = info;
                        break;
                    }
                }
            }
            if ( dir.findFile("package.html") != null ) {
                // leave that to the default
                return null;
            }
        }
    }
    else {
        if ( JavaLanguage.INSTANCE.equals(element.getLanguage()) ) {
            element = element.getNavigationElement();
            if ( element.getContainingFile() != null ) {
                file = element.getContainingFile();
            }
        }
    }
    if ( file != null ) {
        DocCommentProcessor processor = new DocCommentProcessor(file);
        if ( processor.isEnabled() ) {
            String docHtml;
            if ( element instanceof PsiMethod ) {
                docHtml = super.generateDoc(PsiProxy.forMethod((PsiMethod)element), originalElement);
            }
            else if ( element instanceof PsiParameter ) {
                docHtml = super.generateDoc(PsiProxy.forParameter((PsiParameter)element), originalElement);
            }
            else {
                MarkdownJavaDocInfoGenerator javaDocInfoGenerator = new MarkdownJavaDocInfoGenerator(element.getProject(), element, processor);
                List<String> docURLs = getExternalJavaDocUrl(element);
                String text = javaDocInfoGenerator.generateDocInfo(docURLs);
                Plugin.print("Intermediate HTML output", text);
                docHtml = JavaDocExternalFilter.filterInternalDocInfo(text);
            }
            docHtml = extendCss(docHtml);
            Plugin.print("Final HTML output", docHtml);
            return docHtml;
        }
        else {
            return null;
        }
    }
    else {
        return null;
    }
}