@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; }
private void addAnnotationToPackageInfo(Project project, PsiJavaFile packageInfoFile) { if (!FileModificationService.getInstance().preparePsiElementForWrite(packageInfoFile)) { return; } PsiPackageStatement packageStatement = packageInfoFile.getPackageStatement(); if (packageStatement == null) { return; } PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); PsiAnnotation annotation = factory.createAnnotationFromText("@" + annotationForTypeQualifierFqn, packageInfoFile.getContext()); PsiElement addedAnnotation = packageInfoFile.addBefore(annotation, packageStatement); JavaCodeStyleManager.getInstance(project).shortenClassReferences(addedAnnotation); removeRedundantAnnotationsInPackage(project, packageInfoFile.getContainingDirectory().getFiles(), annotation); }
@NotNull @Override public FoldingDescriptor[] buildFoldRegions(@NotNull PsiElement psiElement, @NotNull Document document, boolean quick) { if (!(psiElement instanceof PsiJavaFile) || quick || !LoggerFoldingApplicationSettings.getInstance().getState() .getCollapseByDefault()) { return new FoldingDescriptor[0]; } List<FoldingDescriptor> foldingDescriptors = new LinkedList<>(); Project project = psiElement.getProject(); LoggerFoldingProjectSettings.State state = LoggerFoldingProjectSettings.getInstance(project).getState(); buildFoldRegions(psiElement, foldingDescriptors, state); return foldingDescriptors.toArray(new FoldingDescriptor[foldingDescriptors.size()]); }
@NotNull @Override protected StubElement createStubForFile(@NotNull PsiFile file, @NotNull LighterAST tree) { if (!(file instanceof PsiJavaFile)) { return super.createStubForFile(file, tree); } String refText = ""; LighterASTNode pkg = LightTreeUtil.firstChildOfType(tree, tree.getRoot(), JavaElementType.PACKAGE_STATEMENT); if (pkg != null) { LighterASTNode ref = LightTreeUtil.firstChildOfType(tree, pkg, JavaElementType.JAVA_CODE_REFERENCE); if (ref != null) { refText = JavaSourceUtil.getReferenceText(tree, ref); } } return new PsiJavaFileStubImpl((PsiJavaFile)file, StringRef.fromString(refText), false); }
@Override @Nullable public StructureViewBuilder getStructureViewBuilder(final PsiFile psiFile) { if (!(psiFile instanceof PsiJavaFile)) return null; return new TreeBasedStructureViewBuilder() { @Override @NotNull public StructureViewModel createStructureViewModel(@Nullable Editor editor) { return new JavaFileTreeModel((PsiJavaFile)psiFile, editor); } @Override public boolean isRootNodeShown() { return false; } }; }
@Override public Object getData(final DataProvider dataProvider) { final Object psiFile = dataProvider.getData(CommonDataKeys.PSI_FILE.getName()); if (psiFile instanceof PsiJavaFile) { return new JavaAnalysisScope((PsiJavaFile)psiFile); } Object psiTarget = dataProvider.getData(CommonDataKeys.PSI_ELEMENT.getName()); if (psiTarget instanceof PsiPackage) { PsiPackage pack = (PsiPackage)psiTarget; PsiManager manager = pack.getManager(); if (!manager.isInProject(pack)) return null; PsiDirectory[] dirs = pack.getDirectories(GlobalSearchScope.projectScope(manager.getProject())); if (dirs.length == 0) return null; return new JavaAnalysisScope(pack, (Module)dataProvider.getData(LangDataKeys.MODULE.getName())); } return null; }
@Nullable public String getTemplateText(final PsiFile psiFile, String fileText, String nameWithoutExtension) { if(psiFile instanceof PsiJavaFile){ PsiJavaFile javaFile = (PsiJavaFile)psiFile; String packageName = javaFile.getPackageName(); if (packageName.length() > 0){ fileText = StringUtil.replace(fileText, packageName, "${PACKAGE_NAME}"); } PsiClass[] classes = javaFile.getClasses(); PsiClass psiClass = null; if((classes.length > 0)){ for (PsiClass aClass : classes) { if (nameWithoutExtension.equals(aClass.getName())) { psiClass = aClass; break; } } } if(psiClass != null){ //todo[myakovlev] ? PsiIdentifier nameIdentifier = psiClass.getNameIdentifier(); return StringUtil.replace(fileText, nameWithoutExtension,"${NAME}"); } } return null; }
public void testFoldingIsNotBlinkingOnNavigationToSingleLineMethod() { VirtualFile file = getFile("/src/Bar.java"); PsiJavaFile psiFile = (PsiJavaFile)getPsiManager().findFile(file); assertNotNull(psiFile); PsiMethod method = psiFile.getClasses()[0].getMethods()[0]; method.navigate(true); FileEditor[] editors = myManager.getEditors(file); assertEquals(1, editors.length); Editor editor = ((TextEditor)editors[0]).getEditor(); FoldRegion[] regions = editor.getFoldingModel().getAllFoldRegions(); assertEquals(2, regions.length); assertTrue(regions[0].isExpanded()); assertTrue(regions[1].isExpanded()); CodeInsightTestFixtureImpl.instantiateAndRun(psiFile, editor, new int[]{Pass.UPDATE_ALL, Pass.LOCAL_INSPECTIONS}, false); regions = editor.getFoldingModel().getAllFoldRegions(); assertEquals(2, regions.length); assertTrue(regions[0].isExpanded()); assertTrue(regions[1].isExpanded()); }
@Override public void doImport(final PsiJavaFile javaFile) { final PsiClass containingClass = myMethod.getContainingClass(); if (containingClass != null) { if (javaFile.findImportReferenceTo(containingClass) == null) { javaFile.importClass(containingClass); } } if (myReplaceElements != null) { myReplaceElements.forEachValue(new TObjectProcedure<SubLookupElement>() { @Override public boolean execute(final SubLookupElement subLookupElement) { subLookupElement.doImport(javaFile); return false; } }); } }
public void testStandardProviders() { final AbstractProjectViewPSIPane pane = myStructure.createPane(); getProjectTreeStructure().setProviders(new ClassesTreeStructureProvider(myProject), new FormMergerTreeStructureProvider(myProject)); assertStructureEqual(getPackageDirectory(), "PsiDirectory: package1\n" + " PsiClass:Class1\n" + " PsiJavaFile:Class2.java\n" + " PsiClass:Class2\n" + " PsiClass:Class3\n" + " PsiJavaFile:Class4.java\n" + " PsiFile(plain text):Form2.form\n" + " Form:Form1\n" + " PsiClass:Form1\n" + " PsiFile(plain text):Form1.form\n"); PsiClass psiClass = ((PsiJavaFile)getPackageDirectory().findFile("Form1.java")).getClasses()[0]; myStructure.checkNavigateFromSourceBehaviour(psiClass, psiClass.getContainingFile().getVirtualFile(), pane); PsiFile psiFile = getPackageDirectory().findFile("Form1.form"); VirtualFile virtualFile = psiFile.getContainingFile().getVirtualFile(); myStructure.checkNavigateFromSourceBehaviour(psiFile, virtualFile, pane); }
@Override @Nullable protected InspectionGadgetsFix buildFix(Object... infos) { final PsiJavaFile file = (PsiJavaFile)infos[0]; final String fileName = file.getName(); final int prefixIndex = fileName.indexOf((int)'.'); final String filenameWithoutPrefix = fileName.substring(0, prefixIndex); final PsiClass[] classes = file.getClasses(); for (PsiClass psiClass : classes) { final String className = psiClass.getName(); if (filenameWithoutPrefix.equals(className)) { return null; } } return new RenameFix(filenameWithoutPrefix); }
@Override public void visitClass(@NotNull PsiClass aClass) { // no call to super, so that it doesn't drill down to inner classes final PsiElement parent = aClass.getParent(); if (!(parent instanceof PsiJavaFile)) { return; } final PsiJavaFile file = (PsiJavaFile)parent; final String className = aClass.getName(); if (className == null) { return; } final String fileName = file.getName(); final int prefixIndex = fileName.indexOf((int)'.'); if (prefixIndex < 0) { return; } final String filenameWithoutPrefix = fileName.substring(0, prefixIndex); if (className.equals(filenameWithoutPrefix)) { return; } registerClassError(aClass, file); }
@Override public void visitClass(@NotNull PsiClass aClass) { // no call to super, so that it doesn't drill down to inner classes if (!(aClass.getParent() instanceof PsiJavaFile)) { return; } final PsiJavaFile file = (PsiJavaFile)aClass.getParent(); if (file == null) { return; } int numClasses = 0; final PsiElement[] children = file.getChildren(); for (final PsiElement child : children) { if (child instanceof PsiClass) { numClasses++; } } if (numClasses <= 1) { return; } registerClassError(aClass); }
@Override public void collectVariables(@NotNull Map<String, Object> context, Project project, Module module, @NotNull final PsiFile file) { if (file instanceof PsiClassOwner) { final FileInfo info = new FileInfo(file) { @Override public String getClassName() { if (file instanceof PsiJavaFile) { return ((PsiJavaFile)file).getClasses()[0].getName(); } else { return super.getClassName(); } } @Override public String getQualifiedClassName() { if (file instanceof PsiJavaFile) { return ((PsiJavaFile)file).getClasses()[0].getQualifiedName(); } else { return super.getQualifiedClassName(); } } }; context.put("file", info); } }
@Nullable private VirtualFile getSourceJarRoot( Project project, BlazeProjectData blazeProjectData, PsiJavaFile clsFile) { Library library = findLibrary(project, clsFile); if (library == null || library.getFiles(OrderRootType.SOURCES).length != 0) { // If the library already has sources attached, no need to hunt for them. return null; } BlazeJarLibrary blazeLibrary = LibraryActionHelper.findLibraryFromIntellijLibrary(project, blazeProjectData, library); if (blazeLibrary == null) { return null; } // TODO: If there are multiple source jars, search for one containing this PsiJavaFile. for (ArtifactLocation jar : blazeLibrary.libraryArtifact.sourceJars) { VirtualFile root = getSourceJarRoot(project, blazeProjectData.artifactLocationDecoder, jar); if (root != null) { return root; } } return null; }
@Test public void testRenameJavaClass() { PsiJavaFile javaFile = (PsiJavaFile) workspace.createPsiFile( new WorkspacePath("com/google/foo/JavaClass.java"), "package com.google.foo;", "public class JavaClass {}"); BuildFile buildFile = createBuildFile( new WorkspacePath("com/google/foo/BUILD"), "java_library(name = \"ref2\", srcs = [\"JavaClass.java\"])"); new RenameProcessor(getProject(), javaFile.getClasses()[0], "NewName", false, false).run(); assertFileContents(buildFile, "java_library(name = \"ref2\", srcs = [\"NewName.java\"])"); }
/** * For a given file element, gets the enclosed class that is publicly accessible. * * @param file the file * @return the enclosed public class if found */ @NotNull public static Optional<PsiClass> getPublicClassFromFile(@NotNull PsiFile file) { Optional<PsiFile> javaFile = Optional.of(file) .filter(f -> f instanceof PsiJavaFile); Stream<PsiClass> childClasses = optionalToStream(javaFile) .flatMap(f -> Stream.of(f.getChildren())) .filter(c -> c instanceof PsiClass) .map(c -> (PsiClass) c); Optional<PsiClass> publicClass = childClasses .filter(c -> c.hasModifierProperty("public")) .findFirst(); return publicClass; }
@NotNull @Override protected StubElement createStubForFile(@NotNull PsiFile file, @NotNull LighterAST tree) { if (!(file instanceof PsiJavaFile)) { return super.createStubForFile(file, tree); } String refText = ""; LighterASTNode pkg = LightTreeUtil.firstChildOfType(tree, tree.getRoot(), JavaElementType.PACKAGE_STATEMENT); if (pkg != null) { LighterASTNode ref = LightTreeUtil.firstChildOfType(tree, pkg, JavaElementType.JAVA_CODE_REFERENCE); if (ref != null) { refText = SourceUtil.getReferenceText(tree, ref); } } return new PsiJavaFileStubImpl((PsiJavaFile)file, StringRef.fromString(refText), false); }
@Override public Object getData(final DataProvider dataProvider) { final Object psiFile = dataProvider.getData(LangDataKeys.PSI_FILE.getName()); if (psiFile instanceof PsiJavaFile) { return new JavaAnalysisScope((PsiJavaFile)psiFile); } Object psiTarget = dataProvider.getData(LangDataKeys.PSI_ELEMENT.getName()); if (psiTarget instanceof PsiPackage) { PsiPackage pack = (PsiPackage)psiTarget; PsiManager manager = pack.getManager(); if (!manager.isInProject(pack)) return null; PsiDirectory[] dirs = pack.getDirectories(GlobalSearchScope.projectScope(manager.getProject())); if (dirs.length == 0) return null; return new JavaAnalysisScope(pack, (Module)dataProvider.getData(LangDataKeys.MODULE.getName())); } return null; }
@Override public void visitClass(@NotNull PsiClass aClass) { // no call to super, so that it doesn't drill down to inner classes if (FileTypeUtils.isInJsp(aClass)) { return; } if (ClassUtils.isInnerClass(aClass)) { return; } final PsiFile file = aClass.getContainingFile(); if (!(file instanceof PsiJavaFile)) { return; } if (((PsiJavaFile)file).getPackageStatement() != null) { return; } registerClassError(aClass); }
private void addImport(PsiElementFactory elementFactory, String fullyQualifiedName){ final PsiFile file = psiClass.getContainingFile(); if (!(file instanceof PsiJavaFile)) { return; } final PsiJavaFile javaFile = (PsiJavaFile)file; final PsiImportList importList = javaFile.getImportList(); if (importList == null) { return; } // Check if already imported for (PsiImportStatementBase is : importList.getAllImportStatements()) { String impQualifiedName = is.getImportReference().getQualifiedName(); if (fullyQualifiedName.equals(impQualifiedName)){ return; // Already imported so nothing neede } } // Not imported yet so add it importList.add(elementFactory.createImportStatementOnDemand(fullyQualifiedName)); }
public void actionPerformed(AnActionEvent e) { MavenProject mavenProject = MavenActionUtil.getMavenProject(e.getDataContext()); if (mavenProject != null) { PsiFile psiFile = LangDataKeys.PSI_FILE.getData(e.getDataContext()); if (psiFile instanceof PsiJavaFile) { List<String> goals = getGoals(e, (PsiJavaFile) psiFile, MavenActionUtil.getMavenProject(e.getDataContext())); final DataContext context = e.getDataContext(); MavenRunnerParameters params = new MavenRunnerParameters(true, mavenProject.getDirectory(), goals, MavenActionUtil.getProjectsManager(context).getExplicitProfiles()); run(context, params); } else { Messages.showWarningDialog(e.getProject(), "Cannot run for current file", "Maven Test File"); } } }
protected List<String> getGoals(AnActionEvent e, PsiJavaFile psiFile, MavenProject mavenProject) { List<String> goals = new ArrayList<String>(); boolean skipTests = isSkipTests(mavenProject); // so many possibilities... if (skipTests || isExcludedFromSurefire(psiFile, mavenProject)) { MavenPlugin failsafePlugin = mavenProject.findPlugin("org.apache.maven.plugins", "maven-failsafe-plugin"); if (failsafePlugin != null) { addFailSafeParameters(e, psiFile, goals, failsafePlugin); } else { addSurefireParameters(e, psiFile, goals); } goals.add("verify"); } else { addSurefireParameters(e, psiFile, goals); goals.add("test-compile"); goals.add("surefire:test"); } return goals; }
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]); }
public PsiClass getCurrentClass(final Editor editor) { if (editor == null) { return null; } PsiManager psiManager = PsiManager.getInstance(editor.getProject()); VirtualFile vFile = FileDocumentManager.getInstance().getFile(editor.getDocument()); PsiFile psiFile = psiManager.findFile(vFile); if (!(psiFile instanceof PsiJavaFile)) { return null; } PsiJavaFile javaFile = (PsiJavaFile) psiFile; PsiElement element = javaFile.findElementAt(editor.getCaretModel().getOffset()); while (!(element instanceof PsiClass) && element != null) { element = element.getParent(); } if (element == null) { return null; } else { return (PsiClass) element; } }
@Nullable private static String getJavaSymbolContainerText(final PsiElement element) { final String result; PsiElement container = PsiTreeUtil.getParentOfType(element, PsiMember.class, PsiFile.class); if (container instanceof PsiClass) { String qName = ((PsiClass)container).getQualifiedName(); if (qName != null) { result = qName; } else { result = ((PsiClass)container).getName(); } } else if (container instanceof PsiJavaFile) { result = ((PsiJavaFile)container).getPackageName(); } else {//TODO: local classes result = null; } if (result != null) { return PsiBundle.message("aux.context.display", result); } return null; }
@NotNull @Override protected StubElement createStubForFile(@NotNull PsiFile file, @NotNull LighterAST tree) { if(!(file instanceof PsiJavaFile)) { return super.createStubForFile(file, tree); } String refText = ""; LighterASTNode pkg = LightTreeUtil.firstChildOfType(tree, tree.getRoot(), JavaElementType.PACKAGE_STATEMENT); if(pkg != null) { LighterASTNode ref = LightTreeUtil.firstChildOfType(tree, pkg, JavaElementType.JAVA_CODE_REFERENCE); if(ref != null) { refText = JavaSourceUtil.getReferenceText(tree, ref); } } return new PsiJavaFileStubImpl((PsiJavaFile) file, refText, null, false); }
public boolean isSamePackage(PsiElement other) { PsiElement myContext = getContext(); if(other instanceof DummyHolder) { final PsiElement otherContext = other.getContext(); if(myContext == null) { return otherContext == null; } return JavaPsiFacade.getInstance(myContext.getProject()).arePackagesTheSame(myContext, otherContext); } if(other instanceof PsiJavaFile) { if(myContext != null) { return JavaPsiFacade.getInstance(myContext.getProject()).arePackagesTheSame(myContext, other); } final String packageName = ((PsiJavaFile) other).getPackageName(); return packageName.isEmpty(); } return false; }
@Override @RequiredReadAction protected void updateImpl(PresentationData data) { super.updateImpl(data); PsiDirectory value = getValue(); if(value == null) { return; } PsiFile file = value.findFile(PsiJavaModule.MODULE_INFO_CLS_FILE); if(file instanceof PsiJavaFile) { String name = "INVALID"; PsiJavaModule moduleDeclaration = ((PsiJavaFile) file).getModuleDeclaration(); if(moduleDeclaration != null) { name = StringUtil.notNullize(moduleDeclaration.getName(), name); } data.setPresentableText(name); } }
@Override protected boolean isValidForFile(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) { if(!(file instanceof PsiJavaFile)) { return false; } if(file instanceof PsiCompiledElement) { return false; } PsiDocumentManager.getInstance(project).commitAllDocuments(); PsiClass targetClass = getTargetClass(editor, file); return targetClass != null && isValidForClass(targetClass); }
private MultiMap<String, PsiClass> groupClassesByPackage(Project project) { MultiMap<String, PsiClass> map = new MultiMap<String, PsiClass>(); for (String qName : myQNames) { PsiElement psiElement = PsiQNames.findElementByQName(project, qName); if (!(psiElement instanceof PsiClass)) { throw new UnsupportedOperationException("Moving is only supported for classes"); } PsiClass psiClass = (PsiClass) psiElement; if (!(psiClass.getContainingFile() instanceof PsiJavaFile)) { throw new UnsupportedOperationException("Class not in a Java file"); } PsiJavaFile javaFile = (PsiJavaFile) psiClass.getContainingFile(); map.putValue(javaFile.getPackageName(), psiClass); } return map; }
public MoveClassToModuleFix(String referenceName, Module currentModule, PsiDirectory root, PsiElement psiElement) { myReferenceName = referenceName; myCurrentModule = currentModule; mySourceRoot = root; final Project project = psiElement.getProject(); final PsiClass[] classes = PsiShortNamesCache.getInstance(project).getClassesByName(referenceName, GlobalSearchScope.allScope(project)); final JavaPsiFacade facade = JavaPsiFacade.getInstance(project); final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); for (final PsiClass aClass : classes) { if (!facade.getResolveHelper().isAccessible(aClass, psiElement, aClass)) continue; final PsiFile psiFile = aClass.getContainingFile(); if (!(psiFile instanceof PsiJavaFile)) continue; if (aClass.getQualifiedName() == null) continue; VirtualFile virtualFile = psiFile.getVirtualFile(); if (virtualFile == null) continue; final Module classModule = fileIndex.getModuleForFile(virtualFile); if (classModule != null && classModule != currentModule && !ModuleRootManager.getInstance(currentModule).isDependsOn(classModule)) { myModules.put(aClass, classModule); } } }
@Override public boolean isAvailableFor(@NotNull UsageView usageView) { UsageTarget[] targets = ((UsageViewImpl) usageView).getTargets(); if(targets.length == 0) { return false; } UsageTarget target = targets[0]; if(!(target instanceof PsiElementUsageTarget)) { return false; } PsiElement element = ((PsiElementUsageTarget) target).getElement(); if(element == null || !element.isValid()) { return false; } if(!(element instanceof PsiVariable)) { return false; } PsiFile file = element.getContainingFile(); return file instanceof PsiJavaFile; }
public void testReadingOldPersistenceFormat() throws Throwable { addDefaultLibrary(); myFixture.configureByFiles("content/anno/persistence/annotations.xml"); myFixture.configureByFiles("lib/persistence/Test.java"); ExternalAnnotationsManager manager = ExternalAnnotationsManager.getInstance(myProject); PsiMethod method = ((PsiJavaFile)myFixture.getFile()).getClasses()[0].getMethods()[0]; PsiParameter parameter = method.getParameterList().getParameters()[0]; assertNotNull(manager.findExternalAnnotation(method, AnnotationUtil.NULLABLE)); assertNotNull(manager.findExternalAnnotation(method, AnnotationUtil.NLS)); assertEquals(2, manager.findExternalAnnotations(method).length); assertNotNull(manager.findExternalAnnotation(parameter, AnnotationUtil.NOT_NULL)); assertNotNull(manager.findExternalAnnotation(parameter, AnnotationUtil.NON_NLS)); assertEquals(2, manager.findExternalAnnotations(parameter).length); }