com.intellij.psi.PsiPackage Java Examples

The following examples show how to use com.intellij.psi.PsiPackage. 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: SelectPathDialog.java    From code-generator with Apache License 2.0 6 votes vote down vote up
private void initBtn() {
    basePackageBtn.addActionListener(e -> {
        PackageChooser packageChooser = new PackageChooserDialog("Select Base Package", project);
        packageChooser.show();
        PsiPackage psiPackage = packageChooser.getSelectedPackage();
        if (Objects.nonNull(psiPackage)) {
            basePackageField.setText(psiPackage.getQualifiedName());
        }
    });

    outputPathBtn.addActionListener(e -> {
        FileChooserDescriptor descriptor = new FileChooserDescriptor(false, true, false, false, false, false);
        VirtualFile virtualFile = FileChooser.chooseFile(descriptor, project, null);
        if (Objects.nonNull(virtualFile)) {
            outputPathField.setText(virtualFile.getPath());
        }
    });
}
 
Example #2
Source File: NewClassCommandAction.java    From json2java4idea with Apache License 2.0 6 votes vote down vote up
@Override
protected void run(@NotNull Result<PsiFile> result) throws Throwable {
    final PsiPackage packageElement = directoryService.getPackage(directory);
    if (packageElement == null) {
        throw new InvalidDirectoryException("Target directory does not provide a package");
    }

    final String fileName = Extensions.append(name, StdFileTypes.JAVA);
    final PsiFile found = directory.findFile(fileName);
    if (found != null) {
        throw new ClassAlreadyExistsException("Class '" + name + "'already exists in " + packageElement.getName());
    }

    final String packageName = packageElement.getQualifiedName();
    final String className = Extensions.remove(this.name, StdFileTypes.JAVA);
    try {
        final String java = converter.convert(packageName, className, json);
        final PsiFile classFile = fileFactory.createFileFromText(fileName, JavaFileType.INSTANCE, java);
        CodeStyleManager.getInstance(classFile.getProject()).reformat(classFile);
        JavaCodeStyleManager.getInstance(classFile.getProject()).optimizeImports(classFile);
        final PsiFile created = (PsiFile) directory.add(classFile);
        result.setResult(created);
    } catch (IOException e) {
        throw new ClassCreationException("Failed to create new class from JSON", e);
    }
}
 
Example #3
Source File: JavaImportsUtil.java    From KodeBeagle with Apache License 2.0 6 votes vote down vote up
private Map<String, Set<String>> getImportsAndMethodsAfterValidation(
        final PsiJavaFile javaFile, final Map<String, Set<String>> importsVsMethods) {
    Map<String, Set<String>> finalImportsWithMethods =
            getFullyQualifiedImportsWithMethods(javaFile, importsVsMethods);
    Set<String> imports = importsVsMethods.keySet();
    Set<PsiPackage> importedPackages = getOnDemandImports(javaFile);
    if (!importedPackages.isEmpty()) {
        for (PsiPackage psiPackage : importedPackages) {
            for (String psiImport : imports) {
                if (psiPackage.containsClassNamed(ClassUtil.extractClassName(psiImport))) {
                    finalImportsWithMethods.put(psiImport, importsVsMethods.get(psiImport));
                }
            }
        }
    }
    return finalImportsWithMethods;
}
 
Example #4
Source File: OSSPantsJvmRunConfigurationIntegrationTest.java    From intellij-pants-plugin with Apache License 2.0 6 votes vote down vote up
public void testModuleRunConfiguration() throws Throwable {
  doImport("testprojects/tests/java/org/pantsbuild/testproject/testjvms");

  PsiPackage testPackage = JavaPsiFacade.getInstance(myProject).findPackage("org.pantsbuild.testproject.testjvms");
  assertEquals(1, testPackage.getDirectories().length);

  ExternalSystemRunConfiguration esc = getExternalSystemRunConfiguration(testPackage.getDirectories()[0]);

  Set<String> expectedItems = ProjectTestJvms.testClasses(myProject, getProjectPath())
    .map(aClass -> "--test-junit-test=" + aClass.getQualifiedName())
    .collect(Collectors.toSet());
  assertNotEmpty(expectedItems);

  Set<String> items = new HashSet<>(Arrays.asList(esc.getSettings().getScriptParameters().split(" ")));
  assertContains(items, expectedItems);
}
 
Example #5
Source File: ComponentFinder.java    From litho with Apache License 2.0 5 votes vote down vote up
@Override
public PsiClass[] getClasses(PsiPackage psiPackage, GlobalSearchScope scope) {
  if (!scope.contains(dummyFile)) return PsiClass.EMPTY_ARRAY;

  // We don't create own package, but provide additional classes to existing one
  final String packageQN = psiPackage.getQualifiedName();
  return Arrays.stream(ComponentsCacheService.getInstance(project).getAllComponents())
      .filter(cls -> StringUtil.getPackageName(cls.getQualifiedName()).equals(packageQN))
      .toArray(PsiClass[]::new);
}
 
Example #6
Source File: SuggestionServiceImpl.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
private String getFamilyFromPackageInfo(final PsiPackage psiPackage, final Module module) {
    return of(FilenameIndex
            .getFilesByName(psiPackage.getProject(), "package-info.java", GlobalSearchScope.moduleScope(module)))
                    .map(psiFile -> {
                        if (!PsiJavaFile.class
                                .cast(psiFile)
                                .getPackageName()
                                .equals(psiPackage.getQualifiedName())) {
                            return null;
                        }
                        final String[] family = { null };
                        PsiJavaFile.class.cast(psiFile).accept(new JavaRecursiveElementWalkingVisitor() {

                            @Override
                            public void visitAnnotation(final PsiAnnotation annotation) {
                                super.visitAnnotation(annotation);
                                if (!COMPONENTS.equals(annotation.getQualifiedName())) {
                                    return;
                                }
                                final PsiAnnotationMemberValue familyAttribute =
                                        annotation.findAttributeValue("family");
                                if (familyAttribute == null) {
                                    return;
                                }
                                family[0] = removeQuotes(familyAttribute.getText());
                            }
                        });
                        return family[0];
                    })
                    .filter(Objects::nonNull)
                    .findFirst()
                    .orElseGet(() -> {
                        final PsiPackage parent = psiPackage.getParentPackage();
                        if (parent == null) {
                            return null;
                        }
                        return getFamilyFromPackageInfo(parent, module);
                    });
}
 
Example #7
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 #8
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 #9
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 #10
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 #11
Source File: JavaImportsUtil.java    From KodeBeagle with Apache License 2.0 5 votes vote down vote up
private Set<PsiPackage> getOnDemandImports(final PsiJavaFile javaFile) {
    Set<PsiPackage> psiPackages = new HashSet<>();
    PsiElement[] packageImports = javaFile.getOnDemandImports(false, false);
    for (PsiElement packageImport : packageImports) {
        if (packageImport instanceof PsiPackage) {
            psiPackages.add((PsiPackage) packageImport);
        }
    }
    return psiPackages;
}
 
Example #12
Source File: PantsJUnitTestRunConfigurationProducer.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
private boolean hasJUnitTestClasses(PsiPackage psiPackage, Module module) {
  if (psiPackage == null) return false;
  for (PsiClass psiClass : psiPackage.getClasses(module.getModuleScope())) {
    if (TestIntegrationUtils.isTest(psiClass)) {
      return true;
    }
  }
  return false;
}
 
Example #13
Source File: LombokProjectValidatorActivity.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private boolean hasLombokLibrary(Project project) {
  PsiPackage lombokPackage;
  try {
    lombokPackage = JavaPsiFacade.getInstance(project).findPackage("lombok");
  } catch (ProcessCanceledException ex) {
    lombokPackage = null;
  }
  return lombokPackage != null;
}
 
Example #14
Source File: SuggestionServiceImpl.java    From component-runtime with Apache License 2.0 4 votes vote down vote up
@Override
public List<LookupElement> computeKeySuggestions(final Project project, final Module module,
        final String packageName, final List<String> containerElements, final String query) {
    final JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(project);
    final PsiPackage pkg = javaPsiFacade.findPackage(packageName);
    if (pkg == null) {
        return Collections.emptyList();
    }

    final String defaultFamily = getFamilyFromPackageInfo(pkg, module);
    return Stream
            .concat(Stream
                    .concat(of(pkg.getClasses())
                            .flatMap(this::unwrapInnerClasses)
                            .filter(c -> AnnotationUtil
                                    .findAnnotation(c, PARTITION_MAPPER, PROCESSOR, EMITTER) != null)
                            .flatMap(clazz -> fromComponent(clazz, defaultFamily)),
                            of(pkg.getClasses())
                                    .flatMap(this::unwrapInnerClasses)
                                    .filter(c -> of(c.getAllFields())
                                            .anyMatch(f -> AnnotationUtil.findAnnotation(f, OPTION) != null))
                                    .flatMap(c -> fromConfiguration(defaultFamily, c.getName(), c))),
                    of(pkg.getClasses())
                            .flatMap(this::unwrapInnerClasses)
                            .flatMap(c -> of(c.getMethods())
                                    .filter(m -> ACTIONS
                                            .stream()
                                            .anyMatch(action -> AnnotationUtil.findAnnotation(m, action) != null)))
                            .map(m -> ACTIONS
                                    .stream()
                                    .map(action -> AnnotationUtil.findAnnotation(m, action))
                                    .filter(Objects::nonNull)
                                    .findFirst()
                                    .get())
                            .map(action -> fromAction(action, defaultFamily))
                            .filter(Optional::isPresent)
                            .map(Optional::get))
            .filter(s -> containerElements.isEmpty() || !containerElements.contains(s.getKey()))
            .filter(s -> query == null || query.isEmpty() || s.getKey().startsWith(query))
            .map(s -> s.newLookupElement(withPriority(s.getType())))
            .collect(toList());
}
 
Example #15
Source File: BlazeLightResourceClassService.java    From intellij with Apache License 2.0 4 votes vote down vote up
@Override
@Nullable
public PsiPackage findRClassPackage(String qualifiedName) {
  return rClassPackages.get(qualifiedName);
}
 
Example #16
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;
    }
}