@Nullable private PsiJavaFile getOrCreatePackageInfoFile(PsiFile file) { if (!(file instanceof PsiJavaFile)) { return null; } PsiPackageStatement packageStatement = ((PsiJavaFile) file).getPackageStatement(); if (packageStatement == null) { return null; } PsiJavaCodeReferenceElement packageReference = packageStatement.getPackageReference(); PsiElement target = packageReference.resolve(); if (!(target instanceof PsiPackage)) { return null; } PsiJavaFile packageInfoFile = packageInfoFile((PsiPackage) target, file.getContainingDirectory()); if (packageInfoFile == null) { packageInfoFile = createPackageInfoFile(file, (PsiPackage) target); } return packageInfoFile; }
@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); } }
private Optional<PropertiesFile> findResourceBundle(Project project, PsiClass configClass) { String qualifiedName = configClass.getQualifiedName(); if (qualifiedName != null) { int lastDotIndex = qualifiedName.lastIndexOf("."); String packageName = qualifiedName.substring(0, lastDotIndex); String className = qualifiedName.substring(lastDotIndex + 1); PsiPackage psiPackage = JavaPsiFacade.getInstance(project).findPackage(packageName); if (psiPackage != null) { return Arrays.stream(psiPackage.getFiles(GlobalSearchScope.allScope(project))) .filter(psiFile -> psiFile instanceof PropertiesFile && psiFile.getVirtualFile().getNameWithoutExtension().equals(className)) .map(psiFile -> (PropertiesFile) psiFile) .findFirst(); } } return Optional.empty(); }
@Override public boolean processPackageDirectories(@NotNull PsiPackage psiPackage, @NotNull final GlobalSearchScope scope, @NotNull final Processor<PsiDirectory> consumer, boolean includeLibrarySources) { //System.out.println( "processDirectories() : " + psiPackage + " : " + scope ); final PsiManager psiManager = PsiManager.getInstance( _project ); return PackageIndex.getInstance( _project ) .getDirsByPackageName(psiPackage.getQualifiedName(), includeLibrarySources) .forEach(new ReadActionProcessor<VirtualFile>() { @Override public boolean processInReadAction(final VirtualFile dir) { if (!scope.contains(dir)) return true; PsiDirectory psiDir = psiManager.findDirectory(dir); return psiDir == null || consumer.process(psiDir); } }); }
@Override public PsiPackage findPackage( String fqn ) { //System.out.println( "findPackage() : " + fqn ); List<ManModule> modules = ManProject.manProjectFrom( _project ).getModules(); PsiManager manager = PsiManagerImpl.getInstance( _project ); for( ManModule mm : modules ) { for( ITypeManifold sp : mm.getTypeManifolds() ) { if( sp.getProducerKind() != Supplemental && sp.isPackage( fqn ) ) { return new NonDirectoryPackage( manager, fqn ); } } } return null; }
@NotNull @Override public PsiClass[] getClasses(@NotNull PsiPackage psiPackage, @NotNull GlobalSearchScope scope) { String fqn = psiPackage.getQualifiedName(); if (isShortCircuit(fqn)) { return PsiClass.EMPTY_ARRAY; } addShortCircuit(fqn); try { PsiClass[] classes = psiPackage.getClasses(scope); return Arrays.stream(classes).map(LightClass::new).toArray(PsiClass[]::new); } finally { removeShortCircuit(fqn); } }
@Override public ItemPresentation getPresentation(@NotNull final PsiPackage aPackage) { return new ColoredItemPresentation() { @Override public TextAttributesKey getTextAttributesKey() { return null; } @Override public String getPresentableText() { return aPackage.getName(); } @Override public String getLocationString() { return aPackage.getQualifiedName(); } @Override public Icon getIcon(boolean open) { return PlatformIcons.PACKAGE_ICON; } }; }
@Override public void actionPerformed(final AnActionEvent e) { final Project project = CommonDataKeys.PROJECT.getData(e.getDataContext()); PackageChooserDialog chooser = new PackageChooserDialog("Choose packages", project); chooser.show(); final List<PsiPackage> packages = chooser.getSelectedPackages(); for (PsiPackage aPackage : packages) { final String qualifiedName = aPackage.getQualifiedName(); if (qualifiedName.isEmpty()){ myDataModel.addElement(GroovyDocConfiguration.ALL_PACKAGES); } myDataModel.addElement(qualifiedName); } }
@Override protected boolean setupConfigurationFromContext(TestNGConfiguration configuration, ConfigurationContext context, Ref<PsiElement> sourceElement) { final PsiElement element = context.getPsiLocation(); PsiPackage aPackage = JavaRuntimeConfigurationProducerBase.checkPackage(element); if (aPackage == null) { return false; } final Location location = context.getLocation(); if (location == null) { return false; } if (!LocationUtil.isJarAttached(location, aPackage, TestNGUtil.TEST_ANNOTATION_FQN)) { return false; } final TestData data = configuration.data; data.PACKAGE_NAME = aPackage.getQualifiedName(); data.TEST_OBJECT = TestType.PACKAGE.getType(); data.setScope(setupPackageConfiguration(context, configuration, data.getScope())); configuration.setGeneratedName(); sourceElement.set(aPackage); return true; }
@Override public boolean isConfigurationFromContext(ExternalSystemRunConfiguration configuration, ConfigurationContext context) { if (configuration == null) return false; if (!GradleConstants.SYSTEM_ID.equals(configuration.getSettings().getExternalSystemId())) return false; final PsiPackage psiPackage = JavaRuntimeConfigurationProducerBase.checkPackage(context.getPsiLocation()); if (psiPackage == null) return false; if (context.getModule() == null) return false; if (!StringUtil.equals( context.getModule().getOptionValue(ExternalSystemConstants.LINKED_PROJECT_PATH_KEY), configuration.getSettings().getExternalProjectPath())) { return false; } if (!configuration.getSettings().getTaskNames().containsAll(TASKS_TO_RUN)) return false; final String scriptParameters = configuration.getSettings().getScriptParameters() + ' '; return psiPackage.getQualifiedName().isEmpty() ? scriptParameters.contains("--tests * ") : scriptParameters.contains(String.format("--tests %s.* ", psiPackage.getQualifiedName())); }
private static void checkResult(HashMap<String, String[][]> expected, HashMap<PsiPackage, Set<List<PsiPackage>>> cycles, boolean forceContains){ assertEquals(expected.size(), cycles.size()); for (final PsiPackage psiPackage : cycles.keySet()) { assertTrue(expected.containsKey(psiPackage.getQualifiedName())); final String packs = psiPackage.getQualifiedName(); if (forceContains) { assertEquals(expected.get(packs).length, cycles.get(psiPackage).size()); } for (final List<PsiPackage> cycle : cycles.get(psiPackage)) { final String[][] expectedCycles = expected.get(packs); final String[] string = new String[cycle.size()]; int i = 0; for (final PsiPackage packageInCycle : cycle) { string[i++] = packageInCycle.getQualifiedName(); } assertTrue(findInMatrix(expectedCycles, string) > -1); } } }
public void testBackwardPackageScope(){ final PsiPackage bPackage = JavaPsiFacade.getInstance(myPsiManager.getProject()).findPackage("com.a"); final DependenciesBuilder builder = new BackwardDependenciesBuilder(myProject, new JavaAnalysisScope(bPackage, null)); builder.analyze(); final Set<PsiFile> searchFor = new HashSet<PsiFile>(); searchFor.add(myJavaFacade.findClass("com.a.A", GlobalSearchScope.allScope(myProject)).getContainingFile()); final Set<PsiFile> searchIn = new HashSet<PsiFile>(); final PsiClass bClass = myJavaFacade.findClass("com.b.B", GlobalSearchScope.allScope(myProject)); searchIn.add(bClass.getContainingFile()); final PsiClass cClass = myJavaFacade.findClass("com.a.C", GlobalSearchScope.allScope(myProject)); searchFor.add(cClass.getContainingFile()); final UsageInfo[] usagesInfos = FindDependencyUtil.findBackwardDependencies(builder, searchIn, searchFor); final UsageInfo2UsageAdapter[] usages = UsageInfo2UsageAdapter.convert(usagesInfos); final String [] psiUsages = new String [usagesInfos.length]; for (int i = 0; i < usagesInfos.length; i++) { psiUsages[i] = toString(usages[i]); } checkResult(new String []{"(4: 3) A myA = new A();", "(4: 15) A myA = new A();", "(5: 3) C myC = new C();", "(5: 15) C myC = new C();", "(7: 9) myA.aa();", "(8: 9) myC.cc();"}, psiUsages); }
private boolean spansMultipleModules() { final String qualifiedName = getConfiguration().getPackage(); if (qualifiedName != null) { final Project project = getConfiguration().getProject(); final PsiPackage aPackage = JavaPsiFacade.getInstance(project).findPackage(qualifiedName); if (aPackage != null) { final TestSearchScope scope = getScope(); if (scope != null) { final SourceScope sourceScope = scope.getSourceScope(getConfiguration()); if (sourceScope != null) { final GlobalSearchScope configurationSearchScope = GlobalSearchScopesCore.projectTestScope(project).intersectWith( sourceScope.getGlobalSearchScope()); final PsiDirectory[] directories = aPackage.getDirectories(configurationSearchScope); return directories.length > 1; } } } } return false; }
public void testReusingConfiguration() { RunManagerEx runManager = RunManagerEx.getInstanceEx(myProject); PsiClass psiClass = findClass(getModule1(), CLASS_NAME); PsiPackage psiPackage = JUnitUtil.getContainingPackage(psiClass); ConfigurationContext context = createContext(psiClass); assertEquals(null, context.findExisting()); RunnerAndConfigurationSettings testClass = context.getConfiguration(); runManager.addConfiguration(testClass, false); context = createContext(psiClass); assertSame(testClass, context.findExisting()); runManager.setSelectedConfiguration(testClass); context = createContext(psiPackage); assertEquals(null, context.findExisting()); RunnerAndConfigurationSettings testPackage = context.getConfiguration(); runManager.addConfiguration(testPackage, false); context = createContext(psiPackage); assertSame(testPackage, context.findExisting()); assertSame(testClass, runManager.getSelectedConfiguration()); runManager.setSelectedConfiguration(context.findExisting()); assertSame(testPackage, runManager.getSelectedConfiguration()); }
private void updateLeftTreeModel() { final Set<PsiPackage> psiPackages = myDependencies.keySet(); final Set<PsiFile> psiFiles = new HashSet<PsiFile>(); for (PsiPackage psiPackage : psiPackages) { final Set<List<PsiPackage>> cycles = myDependencies.get(psiPackage); if (!mySettings.UI_FILTER_OUT_OF_CYCLE_PACKAGES || cycles != null && !cycles.isEmpty()) { psiFiles.addAll(getPackageFiles(psiPackage)); } } boolean showFiles = mySettings.UI_SHOW_FILES; //do not show files in the left tree mySettings.UI_FLATTEN_PACKAGES = true; mySettings.UI_SHOW_FILES = false; myLeftTreeExpansionMonitor.freeze(); myLeftTree.setModel(TreeModelBuilder.createTreeModel(myProject, false, psiFiles, new Marker() { public boolean isMarked(VirtualFile file) { return false; } }, mySettings)); myLeftTreeExpansionMonitor.restore(); expandFirstLevel(myLeftTree); mySettings.UI_SHOW_FILES = showFiles; mySettings.UI_FLATTEN_PACKAGES = false; }
@Nullable public PsiElement resolveImportReference(QualifiedName name, QualifiedNameResolveContext context, boolean withRoots) { String fqn = name.toString(); final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(context.getProject()); final PsiPackage aPackage = psiFacade.findPackage(fqn); if (aPackage != null) { return aPackage; } Module module = context.getModule(); if (module != null) { final PsiClass aClass = psiFacade.findClass(fqn, module.getModuleWithDependenciesAndLibrariesScope(false)); if (aClass != null) return aClass; } return null; }
@Override public PsiPackage createPackage(String qualifiedName) { assertValid(); ApplicationManager.getApplication().assertWriteAccessAllowed(); final MigrationPackageImpl migrationPackage = new MigrationPackageImpl(this, qualifiedName); final MigrationPackageImpl oldMigrationPackage = myQNameToPackageMap.put(qualifiedName, migrationPackage); LOG.assertTrue(oldMigrationPackage == null, qualifiedName); final String parentName = parentPackageName(qualifiedName); final PsiPackage aPackage = myFacade.findPackage(parentName); if (aPackage == null) { createPackage(parentName); } List<PsiPackage> psiPackages = getSubpackagesList(parentName); psiPackages.add(migrationPackage); myMigrationManager.migrationModified(false); return migrationPackage; }
@Override public Collection<PsiPackage> resolvePackageName(@Nullable final PsiPackage context, final String packageName) { if (context == null) return Collections.emptySet(); if (packageName.contains("*")) { final Set<PsiPackage> packages = new LinkedHashSet<PsiPackage>(); int indexOf = packageName.indexOf("*"); if (indexOf == 0 || context.getQualifiedName().startsWith(packageName.substring(0, indexOf))) { final Pattern pattern = PatternUtil.fromMask(packageName); processSubPackages(context, new Processor<PsiPackage>() { @Override public boolean process(PsiPackage psiPackage) { String name = psiPackage.getName(); if (name != null && pattern.matcher(name).matches()) { packages.add(psiPackage); } return true; } }); } return packages; } return super.resolvePackageName(context, packageName); }
public @Nullable PackageDependenciesNode getFileParentNode(VirtualFile vFile) { LOG.assertTrue(vFile != null); final VirtualFile containingDirectory = vFile.getParent(); LOG.assertTrue(containingDirectory != null); PsiPackage aPackage = null; final String packageName = myFileIndex.getPackageNameByDirectory(containingDirectory); if (packageName != null) { aPackage = myJavaPsiFacade.findPackage(packageName); } if (aPackage != null) { if (myFileIndex.isInLibrarySource(vFile) || myFileIndex.isInLibraryClasses(vFile)) { return getLibraryDirNode(aPackage, getLibraryForFile(vFile)); } else { return getModuleDirNode(aPackage, myFileIndex.getModuleForFile(vFile), getFileScopeType(vFile)); } } return myFileIndex.isInLibrarySource(vFile) ? null : getModuleNode(myFileIndex.getModuleForFile(vFile), getFileScopeType(vFile)); }
private PackageDependenciesNode getLibraryDirNode(PsiPackage aPackage, OrderEntry libraryOrJdk) { if (aPackage == null || aPackage.getName() == null) { return getLibraryOrJDKNode(libraryOrJdk); } if (!myShowModules && !myGroupByScopeType) { return getModuleDirNode(aPackage, null, ScopeType.LIB); } Pair<OrderEntry, PsiPackage> descriptor = Pair.create(myShowIndividualLibs ? libraryOrJdk : null, aPackage); PackageNode node = getMap(myLibraryPackageNodes, ScopeType.LIB).get(descriptor); if (node != null) return node; node = new PackageNode(aPackage, myFlattenPackages); getMap(myLibraryPackageNodes, ScopeType.LIB).put(descriptor, node); if (myFlattenPackages) { getLibraryOrJDKNode(libraryOrJdk).add(node); } else { getLibraryDirNode(aPackage.getParentPackage(), libraryOrJdk).add(node); } return node; }
@Override protected boolean setupConfigurationFromContext(JUnitConfiguration configuration, ConfigurationContext context, Ref<PsiElement> sourceElement) { final Project project = configuration.getProject(); final PsiElement element = context.getPsiLocation(); if (!(element instanceof PsiDirectory)) return false; final PsiPackage aPackage = JavaRuntimeConfigurationProducerBase.checkPackage(element); if (aPackage == null) return false; final VirtualFile virtualFile = ((PsiDirectory)element).getVirtualFile(); final Module module = ModuleUtilCore.findModuleForFile(virtualFile, project); if (module == null) return false; if (!ModuleRootManager.getInstance(module).getFileIndex().isInTestSourceContent(virtualFile)) return false; int testRootCount = ModuleRootManager.getInstance(module).getSourceRoots(JavaSourceRootType.TEST_SOURCE).size(); if (testRootCount < 2) return false; if (!LocationUtil.isJarAttached(context.getLocation(), aPackage, JUnitUtil.TESTCASE_CLASS)) return false; setupConfigurationModule(context, configuration); final JUnitConfiguration.Data data = configuration.getPersistentData(); data.setDirName(virtualFile.getPath()); data.TEST_OBJECT = JUnitConfiguration.TEST_DIRECTORY; configuration.setGeneratedName(); return true; }
@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); }
private boolean addPackageElementToUpdate(final PsiPackage aPackage, Module module) { final ProjectTreeStructure packageTreeStructure = (ProjectTreeStructure)myTreeStructure; PsiPackage packageToUpdateFrom = aPackage; if (!packageTreeStructure.isFlattenPackages() && packageTreeStructure.isHideEmptyMiddlePackages()) { // optimization: this check makes sense only if flattenPackages == false && HideEmptyMiddle == true while (packageToUpdateFrom != null && packageToUpdateFrom.isValid() && PackageUtil.isPackageEmpty(packageToUpdateFrom, module, true, false)) { packageToUpdateFrom = packageToUpdateFrom.getParentPackage(); } } boolean addedOk; while (!(addedOk = super.addSubtreeToUpdateByElement(getTreeElementToUpdateFrom(packageToUpdateFrom, module)))) { if (packageToUpdateFrom == null) { break; } packageToUpdateFrom = packageToUpdateFrom.getParentPackage(); } return addedOk; }
@Override public List<? extends RatedResolveResult> resolveMember(@NotNull String name, @Nullable PyExpression location, @NotNull AccessDirection direction, @NotNull PyResolveContext resolveContext) { Project project = myPackage.getProject(); JavaPsiFacade facade = JavaPsiFacade.getInstance(project); String childName = myPackage.getQualifiedName() + "." + name; GlobalSearchScope scope = getScope(project); ResolveResultList result = new ResolveResultList(); final PsiClass[] classes = facade.findClasses(childName, scope); for (PsiClass aClass : classes) { result.poke(aClass, RatedResolveResult.RATE_NORMAL); } final PsiPackage psiPackage = facade.findPackage(childName); if (psiPackage != null) { result.poke(psiPackage, RatedResolveResult.RATE_NORMAL); } return result; }
private boolean setupAllInPackageConfiguration(AndroidTestRunConfiguration configuration, PsiElement element, ConfigurationContext context, Ref<PsiElement> sourceElement) { final PsiPackage p = JavaRuntimeConfigurationProducerBase.checkPackage(element); if (p == null) { return false; } final String packageName = p.getQualifiedName(); setupConfiguration(configuration, p, context, sourceElement); configuration.TESTING_TYPE = packageName.length() > 0 ? AndroidTestRunConfiguration.TEST_ALL_IN_PACKAGE : AndroidTestRunConfiguration.TEST_ALL_IN_MODULE; configuration.PACKAGE_NAME = packageName; configuration.setGeneratedName(); return true; }
@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)); }
private static boolean shouldAbbreviateName(PsiPackage aPackage) { final Project project = aPackage.getProject(); ConcurrentMap<PsiPackage, Boolean> map = project.getUserData(SHOULD_ABBREV_PACK_KEY); if (map == null) { final ConcurrentMap<PsiPackage, Boolean> newMap = ContainerUtil.createConcurrentWeakMap(); map = ((UserDataHolderEx)project).putUserDataIfAbsent(SHOULD_ABBREV_PACK_KEY, newMap); if (map == newMap) { ((PsiManagerEx)PsiManager.getInstance(project)).registerRunnableToRunOnChange(new Runnable() { @Override public void run() { newMap.clear(); } }); } } Boolean ret = map.get(aPackage); if (ret != null) return ret; ret = scanPackages(aPackage, 1); map.put(aPackage, ret); return ret; }
@NotNull public static String calcAbbreviatedPackageFQName(@NotNull PsiPackage aPackage) { final StringBuilder name = new StringBuilder(aPackage.getName()); for (PsiPackage parentPackage = aPackage.getParentPackage(); parentPackage != null; parentPackage = parentPackage.getParentPackage()) { final String packageName = parentPackage.getName(); if (packageName == null || packageName.isEmpty()) { break; // reached default package } name.insert(0, "."); if (packageName.length() > 2 && shouldAbbreviateName(parentPackage)) { name.insert(0, packageName.substring(0, 1)); } else { name.insert(0, packageName); } } return name.toString(); }
public void testSimple() { CoverageSuitesBundle bundle = loadCoverageSuite(IDEACoverageRunner.class, "simple$foo_in_simple.coverage"); PsiPackage psiPackage = JavaPsiFacade.getInstance(myProject).findPackage("foo"); PackageAnnotator annotator = new PackageAnnotator(psiPackage); PackageAnnotationConsumer consumer = new PackageAnnotationConsumer(); annotator.annotate(bundle, consumer); PackageAnnotator.ClassCoverageInfo barClassCoverage = consumer.myClassCoverageInfo.get("foo.bar.BarClass"); assertEquals(3, barClassCoverage.totalMethodCount); assertEquals(1, barClassCoverage.coveredMethodCount); PackageAnnotator.PackageCoverageInfo barPackageCoverage = consumer.myPackageCoverage.get("foo.bar"); assertEquals(2, barPackageCoverage.coveredLineCount); assertEquals(9, barPackageCoverage.totalLineCount); assertEquals(1, barPackageCoverage.coveredMethodCount); assertEquals(7, barPackageCoverage.totalMethodCount); PackageAnnotator.ClassCoverageInfo uncoveredClassInfo = consumer.myClassCoverageInfo.get("foo.bar.UncoveredClass"); assertEquals(4, uncoveredClassInfo.totalMethodCount); assertEquals(0, uncoveredClassInfo.coveredMethodCount); }
public Couple<List<String>> collectExtensions(GlobalSearchScope resolveScope) { PsiPackage aPackage = JavaPsiFacade.getInstance(myProject).findPackage("META-INF.services"); if (aPackage == null) { return Couple.of(Collections.<String>emptyList(), Collections.<String>emptyList()); } List<String> instanceClasses = new ArrayList<String>(); List<String> staticClasses = new ArrayList<String>(); for (PsiDirectory directory : aPackage.getDirectories(resolveScope)) { PsiFile file = directory.findFile(ORG_CODEHAUS_GROOVY_RUNTIME_EXTENSION_MODULE); if (file instanceof PropertiesFile) { IProperty inst = ((PropertiesFile)file).findPropertyByKey("extensionClasses"); IProperty stat = ((PropertiesFile)file).findPropertyByKey("staticExtensionClasses"); if (inst != null) collectClasses(inst, instanceClasses); if (stat != null) collectClasses(stat, staticClasses); } } return Couple.of(instanceClasses, staticClasses); }
@Nullable private PsiJavaFile createPackageInfoFile(PsiFile file, PsiPackage target) { DataManager.getInstance().getDataContextFromFocus().doWhenDone((Consumer<DataContext>) context -> { AnActionEvent event = new AnActionEvent(null, context, "", new Presentation(), ActionManager.getInstance(), 0); new CreatePackageInfoAction().actionPerformed(event); }); return packageInfoFile(target, file.getContainingDirectory()); }
/** @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(); }
/** * 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); }
@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 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, template.getSubPath(), template.getResources()); if (JavaFileType.INSTANCE == this.languageFileType) { PsiPackage psiPackage = JavaDirectoryService.getInstance().getPackage(directory); if (!StringUtils.isEmpty(psiPackage.getQualifiedName())) { extraMap.put(fileName, new StringBuilder(psiPackage.getQualifiedName()).append(".").append(fileName)); } } createFile(project, directory, new StringBuilder(fileName).append(".").append(this.languageFileType.getDefaultExtension()).toString(), temp, this.languageFileType); } catch (Exception e) { LOGGER.error(StringUtils.getStackTraceAsString(e)); } }); }
@Override public void update( AnActionEvent e ) { super.update( e ); boolean enabled; final DataContext dataContext = e.getDataContext(); final IdeView view = LangDataKeys.IDE_VIEW.getData( dataContext ); if( view == null ) { enabled = false; } else { final Project project = PlatformDataKeys.PROJECT.getData( dataContext ); final PsiDirectory dir = view.getOrChooseDirectory(); if( dir == null || project == null ) { enabled = false; } else { PsiPackage pkg = JavaDirectoryService.getInstance().getPackage( dir ); ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance( project).getFileIndex(); enabled = pkg != null && projectFileIndex.isUnderSourceRootOfType( dir.getVirtualFile(), JavaModuleSourceRootTypes.SOURCES ); } } e.getPresentation().setEnabled( enabled ); }
@Override public PsiPackage[] getSubPackages( PsiPackage psiPackage, GlobalSearchScope scope ) { //System.out.println( "getSubPackages() : " + psiPackage + " : " + scope ); List<ManModule> modules = findModules( scope ); if( modules.isEmpty() ) { return PsiPackage.EMPTY_ARRAY; } String parentPackage = psiPackage.getQualifiedName(); Set<PsiPackage> children = new HashSet<>(); PsiManager manager = PsiManagerImpl.getInstance( scope.getProject() ); for( ManModule mm : modules ) { for( ITypeManifold sp : mm.getTypeManifolds() ) { if( sp.getProducerKind() == Supplemental ) { continue; } Collection<TypeName> typeNames = sp.getTypeNames( parentPackage ); for( TypeName child : typeNames ) { if( child.kind == TypeName.Kind.NAMESPACE ) { children.add( new NonDirectoryPackage( manager, parentPackage + '.' + child.name ) ); } } } } if( !children.isEmpty() ) { return children.toArray( new PsiPackage[children.size()] ); } return PsiPackage.EMPTY_ARRAY; }
@Nullable @Override public FindUsagesHandler createFindUsagesHandler( @NotNull PsiElement element, boolean forHighlightUsages ) { List<PsiElement> javaElements = ResourceToManifoldUtil.findJavaElementsFor( element ); if( javaElements.isEmpty() ) { return null; } if( element instanceof PsiDirectory ) { final PsiPackage psiPackage = JavaDirectoryService.getInstance().getPackage( (PsiDirectory)element ); return psiPackage == null ? null : new JavaFindUsagesHandler( psiPackage, this ); } if( element instanceof PsiMethod && !forHighlightUsages ) { final PsiMethod[] methods = SuperMethodWarningUtil.checkSuperMethods( (PsiMethod)element, ACTION_STRING ); if( methods.length > 1 ) { return new JavaFindUsagesHandler( element, methods, this ); } if( methods.length == 1 ) { return new JavaFindUsagesHandler( methods[0], this ); } return FindUsagesHandler.NULL_HANDLER; } return new JavaFindUsagesHandler( element, this ) { @NotNull @Override public PsiElement[] getPrimaryElements() { return javaElements.toArray( new PsiElement[javaElements.size()] ); } }; }
public void testPackageScope2() { //com.b<->com.a - find //com.c<->com.d - not in scope final CyclicDependenciesBuilder builder = new CyclicDependenciesBuilder(myProject, new JavaAnalysisScope(JavaPsiFacade .getInstance(myPsiManager.getProject()).findPackage( "com.subscope1"), null)); builder.analyze(); final HashMap<PsiPackage, Set<List<PsiPackage>>> cyclicDependencies = builder.getCyclicDependencies(); HashMap<String, String[][]> expected = new HashMap<String, String[][]>(); expected.put("com.subscope1.b", new String[][]{{"com.subscope1.a", "com.subscope1.b"}}); expected.put("com.subscope1.a", new String[][]{{"com.subscope1.b", "com.subscope1.a"}}); checkResult(expected, cyclicDependencies); }
/** * The new component wizard uses {@link AndroidSourceSet#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(); }
public void testPackageScope1(){ // com.a<->com.b final CyclicDependenciesBuilder builder = new CyclicDependenciesBuilder(myProject, new JavaAnalysisScope(JavaPsiFacade .getInstance(myPsiManager.getProject()).findPackage("com"), null)); builder.analyze(); final HashMap<PsiPackage, Set<List<PsiPackage>>> cyclicDependencies = builder.getCyclicDependencies(); HashMap<String, String[][]> expected = new HashMap<String, String[][]>(); expected.put("com.b", new String[][]{{"com.a", "com.b"}}); expected.put("com.a", new String[][]{{"com.b", "com.a"}}); checkResult(expected, cyclicDependencies); }