com.intellij.psi.PsiJavaFile Java Examples
The following examples show how to use
com.intellij.psi.PsiJavaFile.
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: CrudUtils.java From crud-intellij-plugin with Apache License 2.0 | 6 votes |
public static void doOptimize(Project project) { DumbService.getInstance(project).runWhenSmart((DumbAwareRunnable) () -> new WriteCommandAction(project) { @Override protected void run(@NotNull Result result) { for (VirtualFile virtualFile : virtualFiles) { try { PsiJavaFile javaFile = (PsiJavaFile) PsiManager.getInstance(project).findFile(virtualFile); if (javaFile != null) { CodeStyleManager.getInstance(project).reformat(javaFile); JavaCodeStyleManager.getInstance(project).optimizeImports(javaFile); JavaCodeStyleManager.getInstance(project).shortenClassReferences(javaFile); } } catch (Exception e) { e.printStackTrace(); } } virtualFiles.clear(); } }.execute()); }
Example #2
Source File: JavaClassRenameTest.java From intellij with Apache License 2.0 | 6 votes |
@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\"])"); }
Example #3
Source File: ResolveRedSymbolsAction.java From litho with Apache License 2.0 | 6 votes |
@Override public void update(AnActionEvent e) { super.update(e); final Project project = e.getProject(); final VirtualFile virtualFile = e.getData(CommonDataKeys.VIRTUAL_FILE); final PsiFile psiFile = e.getData(CommonDataKeys.PSI_FILE); final Editor editor = e.getData(CommonDataKeys.EDITOR); final Presentation presentation = e.getPresentation(); if (project == null || virtualFile == null || editor == null || !(psiFile instanceof PsiJavaFile)) { presentation.setEnabledAndVisible(false); return; } final Module currentModule = FileIndexFacade.getInstance(project).getModuleForFile(virtualFile); if (currentModule == null) { presentation.setEnabledAndVisible(false); return; } presentation.setEnabledAndVisible(true); }
Example #4
Source File: ResolveRedSymbolsAction.java From litho with Apache License 2.0 | 6 votes |
@Override public void actionPerformed(AnActionEvent e) { // Verified nonNull in #update final Project project = e.getProject(); final VirtualFile virtualFile = e.getData(CommonDataKeys.VIRTUAL_FILE); final PsiJavaFile psiFile = (PsiJavaFile) e.getData(CommonDataKeys.PSI_FILE); final Editor editor = e.getData(CommonDataKeys.EDITOR); Map<String, String> eventMetadata = new HashMap<>(); resolveRedSymbols( psiFile, virtualFile, editor, project, eventMetadata, finished -> { eventMetadata.put(EventLogger.KEY_TYPE, "action"); eventMetadata.put(EventLogger.KEY_RESULT, finished ? "success" : "fail"); LithoLoggerProvider.getEventLogger().log(EventLogger.EVENT_RED_SYMBOLS, eventMetadata); }); }
Example #5
Source File: JavaImportsUtil.java From KodeBeagle with Apache License 2.0 | 6 votes |
public final Map<String, Set<String>> getImportInLines(final Editor projectEditor, final Pair<Integer, Integer> pair) { PsiDocumentManager psiInstance = PsiDocumentManager.getInstance(windowObjects.getProject()); PsiJavaFile psiJavaFile = (PsiJavaFile) psiInstance.getPsiFile(projectEditor.getDocument()); PsiJavaElementVisitor psiJavaElementVisitor = new PsiJavaElementVisitor(pair.getFirst(), pair.getSecond()); Map<String, Set<String>> finalImports = new HashMap<>(); if (psiJavaFile != null && psiJavaFile.findElementAt(pair.getFirst()) != null) { PsiElement psiElement = psiJavaFile.findElementAt(pair.getFirst()); final PsiElement psiMethod = PsiTreeUtil.getParentOfType(psiElement, PsiMethod.class); if (psiMethod != null) { psiMethod.accept(psiJavaElementVisitor); } else { final PsiClass psiClass = PsiTreeUtil.getParentOfType(psiElement, PsiClass.class); if (psiClass != null) { psiClass.accept(psiJavaElementVisitor); } } Map<String, Set<String>> importVsMethods = psiJavaElementVisitor.getImportVsMethods(); finalImports = getImportsAndMethodsAfterValidation(psiJavaFile, importVsMethods); } return removeImplicitImports(finalImports); }
Example #6
Source File: CodeGenerator.java From ParcelablePlease with Apache License 2.0 | 6 votes |
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)); }
Example #7
Source File: FastBuildTestClassFinder.java From intellij with Apache License 2.0 | 6 votes |
private Optional<String> getMatchingClassName(String className, File file) { VirtualFile virtualFile = VfsUtils.resolveVirtualFile(file, /* refreshIfNeeded= */ true); if (virtualFile == null) { return Optional.empty(); } PsiFile psiFile = psiManager.findFile(virtualFile); if (!(psiFile instanceof PsiJavaFile)) { return Optional.empty(); } return Arrays.stream(psiFile.getChildren()) .filter(PsiClass.class::isInstance) .map(PsiClass.class::cast) .filter(c -> className.equals(c.getName()) && c.getQualifiedName() != null) .map(PsiClass::getQualifiedName) .findAny(); }
Example #8
Source File: VirtualFileCellRenderer.java From intellij-reference-diagram with Apache License 2.0 | 6 votes |
public static void render(SimpleColoredComponent renderer, FileFQNReference ref, Project project) { VirtualFile virtualFile = ref.getPsiElement().getContainingFile().getVirtualFile(); PsiJavaFile psiFile = (PsiJavaFile) PsiManager.getInstance(project).findFile(virtualFile); int style = SimpleTextAttributes.STYLE_PLAIN; Color color = SimpleTextAttributes.LINK_BOLD_ATTRIBUTES.getFgColor(); Icon icon = getIcon(virtualFile); String comment = null; if (!virtualFile.isValid()) style |= SimpleTextAttributes.STYLE_STRIKEOUT; boolean fileHidden = isFileHidden(virtualFile); if (fileHidden) { color = HIDDEN; } ; renderer.setIcon(!fileHidden || icon == null ? icon : getTransparentIcon(icon)); SimpleTextAttributes attributes = new SimpleTextAttributes(style, color); renderer.append(psiFile.getPackageName() + "." + psiFile.getName(), attributes); renderer.append(" " + ref.toUsageString(), new SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, SimpleTextAttributes.GRAY_ATTRIBUTES.getFgColor())); if (comment != null) renderer.append(comment, attributes); }
Example #9
Source File: JavaImportsUtil.java From KodeBeagle with Apache License 2.0 | 6 votes |
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 #10
Source File: BlazeSourceJarNavigationPolicy.java From intellij with Apache License 2.0 | 6 votes |
@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.getSourceJars()) { VirtualFile root = getSourceJarRoot(project, blazeProjectData.getArtifactLocationDecoder(), jar); if (root != null) { return root; } } return null; }
Example #11
Source File: JavaImportsUtil.java From KodeBeagle with Apache License 2.0 | 6 votes |
private Map<String, Set<String>> getFullyQualifiedImportsWithMethods( final PsiJavaFile javaFile, final Map<String, Set<String>> importVsMethods) { Map<String, Set<String>> fullyQualifiedImportsWithMethods = new HashMap<>(); PsiImportList importList = javaFile.getImportList(); Collection<PsiImportStatement> importStatements = PsiTreeUtil.findChildrenOfType(importList, PsiImportStatement.class); for (PsiImportStatement importStatement : importStatements) { if (!importStatement.isOnDemand()) { String qualifiedName = importStatement.getQualifiedName(); if (importVsMethods.containsKey(qualifiedName)) { fullyQualifiedImportsWithMethods.put(qualifiedName, importVsMethods.get(qualifiedName)); } } } return fullyQualifiedImportsWithMethods; }
Example #12
Source File: NoPolAction.java From nopol with GNU General Public License v2.0 | 5 votes |
/** * This method is responsible to add the current test case, if the current file is, otherwise it * it will send a empty array of String in that way nopol will run all tests cases * @param project * @param editor * @param currentFile * @return */ private VirtualFile buildTestProject(Project project, Editor editor, PsiFile currentFile) { VirtualFile file = PsiUtilBase.getPsiFileInEditor(editor, project).getVirtualFile(); String fullQualifiedNameOfCurrentFile = ((PsiJavaFile) currentFile).getPackageName() + "." + currentFile.getName(); fullQualifiedNameOfCurrentFile = fullQualifiedNameOfCurrentFile.substring(0, fullQualifiedNameOfCurrentFile.length() - JavaFileType.DEFAULT_EXTENSION.length() - 1); if (ProjectRootManager.getInstance(project).getFileIndex().isInTestSourceContent(file)) { nopolContext.setProjectTests(fullQualifiedNameOfCurrentFile.split(" ")); } else { nopolContext.setProjectTests(new String[0]);// we will hit all the test case in the project } return file; }
Example #13
Source File: InnerBuilderHandler.java From innerbuilder with Apache License 2.0 | 5 votes |
@Override public boolean isValidFor(final Editor editor, final PsiFile file) { if (!(file instanceof PsiJavaFile)) { return false; } final Project project = editor.getProject(); if (project == null) { return false; } return InnerBuilderUtils.getStaticOrTopLevelClass(file, editor) != null && isApplicable(file, editor); }
Example #14
Source File: JavaImportsUtil.java From KodeBeagle with Apache License 2.0 | 5 votes |
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 #15
Source File: PackageReferenceDiagramDataModel.java From intellij-reference-diagram with Apache License 2.0 | 5 votes |
@NotNull @Override protected Collection<PsiReference> resolveOuterReferences(PsiElement psiElement) { Collection<PsiReference> result = new ArrayList<>(); if (!(psiElement instanceof PsiJavaFile)) { return result; } PsiClass[] classes = ((PsiJavaFile) psiElement).getClasses(); for (PsiClass psiClass : classes) { result.addAll(ReferencesSearch.search(psiClass, GlobalSearchScopes.projectProductionScope(getProject())).findAll()); } return result; }
Example #16
Source File: PsiElementDispatcher.java From intellij-reference-diagram with Apache License 2.0 | 5 votes |
public T dispatch(PsiElement psiElement) { if (psiElement instanceof PsiClass) { if (((PsiClass) psiElement).getContainingClass() == null) { return processClass((PsiClass) psiElement); } else { if (((PsiClass) psiElement).isEnum()) { return processEnum((PsiClass) psiElement); } else { if (((PsiClass) psiElement).hasModifierProperty("static")) { return processStaticInnerClass((PsiClass) psiElement); } else { return processInnerClass((PsiClass) psiElement); } } } } if (psiElement instanceof PsiMethod) { return processMethod((PsiMethod) psiElement); } if (psiElement instanceof PsiField) { return processField((PsiField) psiElement); } if (psiElement instanceof PsiClassInitializer) { return processClassInitializer((PsiClassInitializer) psiElement); } if (psiElement instanceof PsiJavaDirectoryImpl) { return processPackage((PsiJavaDirectoryImpl) psiElement); } if (psiElement instanceof PsiJavaFile) { return processFile((PsiJavaFile) psiElement); } throw new IllegalArgumentException("Type of PsiElement not supported: " + psiElement); }
Example #17
Source File: FileFQN.java From intellij-reference-diagram with Apache License 2.0 | 5 votes |
private FileFQN(String packageName, String fileName, PsiJavaFile psiJavaFile) { this.psiJavaFile = psiJavaFile; if (packageName == null) { throw new IllegalArgumentException("packageName: null not allowed"); } if (fileName == null) { throw new IllegalArgumentException("fileName: null not allowed"); } this.packageName = packageName; this.fileName = fileName; }
Example #18
Source File: FileFQN.java From intellij-reference-diagram with Apache License 2.0 | 5 votes |
public static FileFQN resolveHierarchically(PsiElement psiElement) { PsiJavaFile psiJavaFile = PsiTreeUtil.getParentOfType(psiElement, PsiJavaFile.class, true); if (psiJavaFile == null) { return null; } return from((PsiJavaFile) psiJavaFile); }
Example #19
Source File: FileManager.java From Intellij-Plugin with Apache License 2.0 | 5 votes |
public static String getJavaFileName(PsiFile value) { PsiJavaFile javaFile = (PsiJavaFile) value; if (!javaFile.getPackageName().equals("")) { return javaFile.getPackageName() + "." + javaFile.getName(); } return javaFile.getName(); }
Example #20
Source File: AbstractDelombokAction.java From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License | 5 votes |
private void processFile(Project project, VirtualFile file) { if (StdFileTypes.JAVA.equals(file.getFileType())) { final PsiManager psiManager = PsiManager.getInstance(project); PsiJavaFile psiFile = (PsiJavaFile) psiManager.findFile(file); if (psiFile != null) { process(project, psiFile); } } }
Example #21
Source File: AbstractDelombokAction.java From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License | 5 votes |
private boolean isValidForFile(@NotNull Editor editor, @NotNull PsiFile file) { if (!(file instanceof PsiJavaFile)) { return false; } if (file instanceof PsiCompiledElement) { return false; } if (!file.isWritable()) { return false; } PsiClass targetClass = getTargetClass(editor, file); return targetClass != null && isValidForClass(targetClass); }
Example #22
Source File: AbstractLombokConfigSystemTestCase.java From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License | 5 votes |
protected void doTest(final String beforeFileName, final String afterFileName) { final PsiFile psiDelombokFile = loadToPsiFile(afterFileName); final PsiFile psiLombokFile = loadToPsiFile(beforeFileName); if (!(psiLombokFile instanceof PsiJavaFile) || !(psiDelombokFile instanceof PsiJavaFile)) { fail("The test file type is not supported"); } compareFiles((PsiJavaFile) psiLombokFile, (PsiJavaFile) psiDelombokFile); }
Example #23
Source File: ScopeChooserCombo.java From IntelliJDeodorant with MIT License | 5 votes |
private AnalysisScope getCurrentFileScope() { FileEditor currentEditor = FileEditorManager.getInstance(project).getSelectedEditor(); if (currentEditor != null) { VirtualFile currentFile = currentEditor.getFile(); PsiFile file = PsiManager.getInstance(project).findFile(currentFile); if (file instanceof PsiJavaFile) return new AnalysisScope(project, Collections.singletonList(currentFile)); } return null; }
Example #24
Source File: BlazeSourceJarNavigationPolicy.java From intellij with Apache License 2.0 | 5 votes |
@Nullable private Library findLibrary(Project project, PsiJavaFile clsFile) { OrderEntry libraryEntry = LibraryUtil.findLibraryEntry(clsFile.getVirtualFile(), project); if (!(libraryEntry instanceof LibraryOrderEntry)) { return null; } return ((LibraryOrderEntry) libraryEntry).getLibrary(); }
Example #25
Source File: AbstractFileProvider.java From CodeGen with MIT License | 5 votes |
protected PsiFile createFile(Project project, @NotNull PsiDirectory psiDirectory, String fileName, String context, FileType fileType) { PsiFile psiFile = PsiFileFactory.getInstance(project).createFileFromText(fileName, fileType, context); // reformat class CodeStyleManager.getInstance(project).reformat(psiFile); if (psiFile instanceof PsiJavaFile) { JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(project); styleManager.optimizeImports(psiFile); styleManager.shortenClassReferences(psiFile); } // TODO: 加入覆盖判断 psiDirectory.add(psiFile); return psiFile; }
Example #26
Source File: SuggestionServiceImpl.java From component-runtime with Apache License 2.0 | 5 votes |
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 #27
Source File: ClassesExportAction.java From patcher with Apache License 2.0 | 5 votes |
@Override public void actionPerformed(AnActionEvent e) { try { com.intellij.openapi.actionSystem.DataContext dataContext = e.getDataContext(); PsiJavaFile javaFile = (PsiJavaFile) ((PsiFile) DataKeys.PSI_FILE.getData(dataContext)).getContainingFile(); String sourceName = javaFile.getName(); Module module = (Module) DataKeys.MODULE.getData(dataContext); String compileRoot = CompilerModuleExtension.getInstance(module).getCompilerOutputPath().getPath(); getVirtualFile(sourceName, CompilerModuleExtension.getInstance(module).getCompilerOutputPath().getChildren(), compileRoot); VirtualFileManager.getInstance().syncRefresh(); } catch (Exception ex) { ex.printStackTrace(); Messages.showErrorDialog("Please build your module or project!!!", "error"); } }
Example #28
Source File: LithoPluginIntellijTest.java From litho with Apache License 2.0 | 5 votes |
/** * Converts list of class names to the list of psi classes. * * @param handler calling class should pass handler for the psi classes. Passes null if * conversion was unsuccessful at any step. * @param clsNames names of the classes to found in the test root directory (MyClass.java) */ public void getPsiClass(Function<List<PsiClass>, Boolean> handler, String... clsNames) { ApplicationManager.getApplication() .invokeAndWait( () -> { List<PsiClass> psiClasses = Stream.of(clsNames) .filter(Objects::nonNull) .map( clsName -> { String content = getContentOrNull(clsName); if (content != null) { return PsiFileFactory.getInstance(fixture.getProject()) .createFileFromText(clsName, JavaFileType.INSTANCE, content); } return null; }) .filter(PsiJavaFile.class::isInstance) .map(PsiJavaFile.class::cast) .map(PsiClassOwner::getClasses) .filter(fileClasses -> fileClasses.length > 0) .map(fileClasses -> fileClasses[0]) .collect(Collectors.toList()); if (psiClasses.isEmpty()) { handler.apply(null); } else { handler.apply(psiClasses); } }); }
Example #29
Source File: CodeGeneratorAction.java From code-generator with Apache License 2.0 | 5 votes |
@Override public void actionPerformed(AnActionEvent anActionEvent) { Project project = anActionEvent.getProject(); if (project == null) { return; } DumbService dumbService = DumbService.getInstance(project); if (dumbService.isDumb()) { dumbService.showDumbModeNotification("CodeGenerator plugin is not available during indexing"); return; } SelectPathDialog dialog = new SelectPathDialog(project, templateSettings.getTemplateGroupMap()); dialog.show(); if (dialog.isOK()) { String basePackage = dialog.getBasePackage(); String outputPath = dialog.getOutputPath(); String templateGroup = dialog.getTemplateGroup(); PsiFile psiFile = anActionEvent.getData(CommonDataKeys.PSI_FILE); if (Objects.isNull(psiFile) || !(psiFile instanceof PsiJavaFile)) { return; } PsiJavaFile psiJavaFile = (PsiJavaFile) psiFile; PsiClass[] psiClasses = psiJavaFile.getClasses(); try { Map<String, Template> templateMap = templateSettings.getTemplateGroup(templateGroup).getTemplateMap(); Entity entity = buildClassEntity(psiClasses[0]); TemplateUtils.generate(templateMap, entity, basePackage, outputPath); } catch (Exception e) { Messages.showMessageDialog(project, e.getMessage(), "Generate Failed", null); return; } Messages.showMessageDialog(project, "Code generation successful", "Success", null); } }
Example #30
Source File: ResolveRedSymbolsActionTest.java From litho with Apache License 2.0 | 5 votes |
@Test public void resolveRedSymbols() throws IOException { final Project project = testHelper.getFixture().getProject(); final PsiJavaFile pf = (PsiJavaFile) testHelper.configure("ResolveRedSymbolsActionTest.java"); final VirtualFile vf = pf.getViewProvider().getVirtualFile(); final Editor editor = testHelper.getFixture().getEditor(); final PsiFile specPsiFile = testHelper.configure("LayoutSpec.java"); ApplicationManager.getApplication() .invokeAndWait( () -> { PsiSearchUtils.addMock( "LayoutSpec", PsiTreeUtil.findChildOfType(specPsiFile, PsiClass.class)); final HashMap<String, String> eventMetadata = new HashMap<>(); ResolveRedSymbolsAction.resolveRedSymbols( pf, vf, editor, project, eventMetadata, ignore -> { assertThat(eventMetadata).isNotEmpty(); }); assertThat(eventMetadata.get("resolved_red_symbols")).isEqualTo("[Layout]"); final PsiClass cached = ComponentsCacheService.getInstance(project).getComponent("Layout"); assertThat(cached).isNotNull(); assertThat(cached.getName()).isEqualTo("Layout"); }); }