Here are the examples of the java api class com.intellij.openapi.project.Project taken from open source projects.
1. XVariablesViewBase#buildTreeAndRestoreState()
View licenseprotected void buildTreeAndRestoreState(@NotNull final XStackFrame stackFrame) { XSourcePosition position = stackFrame.getSourcePosition(); XDebuggerTree tree = getTree(); tree.setSourcePosition(position); createNewRootNode(stackFrame); final Project project = tree.getProject(); project.putUserData(XVariablesView.DEBUG_VARIABLES, new XVariablesView.InlineVariablesInfo()); project.putUserData(XVariablesView.DEBUG_VARIABLES_TIMESTAMPS, new ObjectLongHashMap<>()); Object newEqualityObject = stackFrame.getEqualityObject(); if (myFrameEqualityObject != null && newEqualityObject != null && myFrameEqualityObject.equals(newEqualityObject) && myTreeState != null) { disposeTreeRestorer(); myTreeRestorer = myTreeState.restoreState(tree); } if (position != null && Registry.is("debugger.valueTooltipAutoShowOnSelection")) { registerInlineEvaluator(stackFrame, position, project); } }
2. XVariablesViewBase#buildTreeAndRestoreState()
View licenseprotected void buildTreeAndRestoreState(@NotNull final XStackFrame stackFrame) { XSourcePosition position = stackFrame.getSourcePosition(); XDebuggerTree tree = getTree(); tree.setSourcePosition(position); createNewRootNode(stackFrame); final Project project = tree.getProject(); project.putUserData(XVariablesView.DEBUG_VARIABLES, new XVariablesView.InlineVariablesInfo()); project.putUserData(XVariablesView.DEBUG_VARIABLES_TIMESTAMPS, new ObjectLongHashMap<VirtualFile>()); Object newEqualityObject = stackFrame.getEqualityObject(); if (myFrameEqualityObject != null && newEqualityObject != null && myFrameEqualityObject.equals(newEqualityObject) && myTreeState != null) { disposeTreeRestorer(); myTreeRestorer = myTreeState.restoreState(tree); } if (position != null && Registry.is("debugger.valueTooltipAutoShowOnSelection")) { registerInlineEvaluator(stackFrame, position, project); } }
3. IdeaHelper#getProject()
View license/** * Find the project that is associated with the repository directory * * @param repoBaseDirectory * @return project based on repo */ public static Project getProject(final String repoBaseDirectory) { final Project[] openProjects = ProjectManager.getInstance().getOpenProjects(); for (final Project project : openProjects) { // standardize the repo path passed in so that both paths being compared are Unix standard if (project.getBasePath().equals(SystemHelper.getUnixPath(repoBaseDirectory))) { return project; } } return null; }
4. DomDescriptorProvider#getDescriptor()
View license@Override @Nullable public XmlElementDescriptor getDescriptor(final XmlTag tag) { Project project = tag.getProject(); if (project.isDefault()) return null; final DomInvocationHandler<?, ?> handler = DomManagerImpl.getDomManager(project).getDomHandler(tag); if (handler != null) { final DefinesXml definesXml = handler.getAnnotation(DefinesXml.class); if (definesXml != null) { return new DomElementXmlDescriptor(handler); } final PsiElement parent = tag.getParent(); if (parent instanceof XmlTag) { final XmlElementDescriptor descriptor = ((XmlTag) parent).getDescriptor(); if (descriptor instanceof DomElementXmlDescriptor) { return descriptor.getElementDescriptor(tag, (XmlTag) parent); } } } return null; }
5. CoverageDataManagerImpl#processGatheredCoverage()
View licensepublic static void processGatheredCoverage(RunConfigurationBase configuration) { final Project project = configuration.getProject(); if (project.isDisposed()) return; final CoverageDataManager coverageDataManager = CoverageDataManager.getInstance(project); final CoverageEnabledConfiguration coverageEnabledConfiguration = CoverageEnabledConfiguration.getOrCreate(configuration); //noinspection ConstantConditions final CoverageSuite coverageSuite = coverageEnabledConfiguration.getCurrentCoverageSuite(); if (coverageSuite != null) { ((BaseCoverageSuite) coverageSuite).setConfiguration(configuration); coverageDataManager.coverageGathered(coverageSuite); } }
6. ProjectUtils#notifyProjectsWhichUsesThisSettings()
View licensepublic static void notifyProjectsWhichUsesThisSettings(Settings deletedSettings, Project project, Settings defaultSettings) { Project[] openProjects = ProjectManagerImpl.getInstance().getOpenProjects(); for (Project openProject : openProjects) { ProjectSettingsComponent component = openProject.getComponent(ProjectSettingsComponent.class); if (component != null) { Settings state = component.getSettings(); if (deletedSettings.getId().equals(state.getId())) { component.loadState(defaultSettings); if (project != openProject) { Notifier.notifyDeletedSettings(component.getProject()); } } } } }
7. ProjectUtils#applyToAllOpenedProjects()
View licensepublic static void applyToAllOpenedProjects(Settings updatedSettings) { Project[] openProjects = ProjectManagerImpl.getInstance().getOpenProjects(); for (Project openProject : openProjects) { ProjectSettingsComponent component = openProject.getComponent(ProjectSettingsComponent.class); if (component != null) { Settings state = component.getSettings(); if (updatedSettings.getId().equals(state.getId())) { component.settingsUpdatedFromOtherProject(updatedSettings); } } } }
8. VimPlugin#showMessage()
View licensepublic static void showMessage(@Nullable String msg) { ProjectManager pm = ProjectManager.getInstance(); Project[] projects = pm.getOpenProjects(); for (Project project : projects) { StatusBar bar = WindowManager.getInstance().getStatusBar(project); if (bar != null) { if (msg == null || msg.length() == 0) { bar.setInfo(""); } else { bar.setInfo("VIM - " + msg); } } } }
9. BuildManager#getOpenProjects()
View licenseprivate List<Project> getOpenProjects() { final Project[] projects = myProjectManager.getOpenProjects(); if (projects.length == 0) { return Collections.emptyList(); } final List<Project> projectList = new SmartList<Project>(); for (Project project : projects) { if (isValidProject(project)) { projectList.add(project); } } return projectList; }
10. InspectionDescriptionLinkHandler#getDescription()
View license@Override public String getDescription(@NotNull final String refSuffix, @NotNull final Editor editor) { final Project project = editor.getProject(); if (project == null) { LOG.error(editor); return null; } if (project.isDisposed()) return null; final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (file == null) { return null; } final InspectionProfile profile = (InspectionProfile) InspectionProfileManager.getInstance().getRootProfile(); final InspectionToolWrapper toolWrapper = profile.getInspectionTool(refSuffix, file); if (toolWrapper == null) return null; String description = toolWrapper.loadDescription(); if (description == null) { LOG.warn("No description for inspection '" + refSuffix + "'"); description = InspectionsBundle.message("inspection.tool.description.under.construction.text"); } return description; }
11. FindAllAction#actionPerformed()
View license@Override public void actionPerformed(final AnActionEvent e) { Editor editor = e.getRequiredData(CommonDataKeys.EDITOR_EVEN_IF_INACTIVE); Project project = e.getRequiredData(CommonDataKeys.PROJECT); EditorSearchSession search = e.getRequiredData(EditorSearchSession.SESSION_KEY); if (project.isDisposed()) return; FindModel oldModel = FindManager.getInstance(project).getFindInFileModel(); FindModel newModel = oldModel.clone(); String text = search.getTextInField(); if (StringUtil.isEmpty(text)) return; newModel.setStringToFind(text); FindUtil.findAllAndShow(project, editor, newModel); }
12. IdeaModifiableModelsProvider#getLibraryTableModifiableModel()
View license@Override public LibraryTable.ModifiableModel getLibraryTableModifiableModel() { final Project[] projects = ProjectManager.getInstance().getOpenProjects(); for (Project project : projects) { if (!project.isInitialized()) { continue; } StructureConfigurableContext context = getProjectStructureContext(project); LibraryTableModifiableModelProvider provider = context != null ? context.createModifiableModelProvider(LibraryTablesRegistrar.APPLICATION_LEVEL) : null; final LibraryTable.ModifiableModel modifiableModel = provider != null ? provider.getModifiableModel() : null; if (modifiableModel != null) { return modifiableModel; } } return LibraryTablesRegistrar.getInstance().getLibraryTable().getModifiableModel(); }
13. JsonSchemaMappingsConfigurable#apply()
View license@Override public void apply() throws ConfigurationException { final List<JsonSchemaMappingsConfigurationBase.SchemaInfo> uiList = getUiList(true); validate(uiList); final Map<String, JsonSchemaMappingsConfigurationBase.SchemaInfo> projectMap = new HashMap<String, JsonSchemaMappingsConfigurationBase.SchemaInfo>(); for (JsonSchemaMappingsConfigurationBase.SchemaInfo info : uiList) { if (!info.isApplicationLevel()) { projectMap.put(info.getName(), info); } } if (myProject != null) { JsonSchemaMappingsProjectConfiguration.getInstance(myProject).setState(projectMap); } final Project[] projects = ProjectManager.getInstance().getOpenProjects(); for (Project project : projects) { final JsonSchemaService service = JsonSchemaService.Impl.get(project); if (service != null) service.reset(); } if (myProject != null) { DaemonCodeAnalyzer.getInstance(myProject).restart(); EditorNotifications.getInstance(myProject).updateAllNotifications(); } }
14. FileManagerImpl#findFile()
View license@Override @Nullable public PsiFile findFile(@NotNull VirtualFile vFile) { if (vFile.isDirectory()) return null; final Project project = myManager.getProject(); if (project.isDefault()) return null; ApplicationManager.getApplication().assertReadAccessAllowed(); if (!vFile.isValid()) { LOG.error("Invalid file: " + vFile); return null; } dispatchPendingEvents(); final FileViewProvider viewProvider = findViewProvider(vFile); return viewProvider.getPsi(viewProvider.getBaseLanguage()); }
15. ApplicationImpl#canExit()
View licenseprivate boolean canExit() { for (ApplicationListener applicationListener : myDispatcher.getListeners()) { if (!applicationListener.canExitApplication()) { return false; } } ProjectManagerEx projectManager = (ProjectManagerEx) ProjectManager.getInstance(); Project[] projects = projectManager.getOpenProjects(); for (Project project : projects) { if (!projectManager.canClose(project)) { return false; } } return true; }
16. ApplicationImpl#saveAll()
View license@Override public void saveAll() { if (myDoNotSave) return; FileDocumentManager.getInstance().saveAllDocuments(); Project[] openProjects = ProjectManager.getInstance().getOpenProjects(); for (Project openProject : openProjects) { openProject.save(); } saveSettings(); }
17. LvcsHelper#addLabel()
View licensepublic static void addLabel(final TestFrameworkRunningModel model) { String label; int color; AbstractTestProxy root = model.getRoot(); if (root.isInterrupted()) return; if (root.isPassed() || root.isIgnored()) { color = GREEN.getRGB(); label = ExecutionBundle.message("junit.runing.info.tests.passed.label"); } else { color = RED.getRGB(); label = ExecutionBundle.message("junit.runing.info.tests.failed.label"); } final TestConsoleProperties consoleProperties = model.getProperties(); String name = label + " " + consoleProperties.getConfiguration().getName(); Project project = consoleProperties.getProject(); if (project.isDisposed()) return; LocalHistory.getInstance().putSystemLabel(project, name, color); }
18. IdeaGateway#isVersioned()
View licensepublic boolean isVersioned(@NotNull VirtualFile f, boolean shouldBeInContent) { if (!f.isInLocalFileSystem()) return false; if (!f.isDirectory() && StringUtil.endsWith(f.getNameSequence(), ".class")) return false; Project[] openProjects = ProjectManager.getInstance().getOpenProjects(); boolean isInContent = false; for (Project each : openProjects) { if (each.isDefault()) continue; if (!each.isInitialized()) continue; if (Comparing.equal(each.getWorkspaceFile(), f)) return false; ProjectFileIndex index = ProjectRootManager.getInstance(each).getFileIndex(); if (index.isExcluded(f)) return false; isInContent |= index.isInContent(f); } if (shouldBeInContent && !isInContent) return false; // optimisation: FileTypeManager.isFileIgnored(f) already checked inside ProjectFileIndex.isIgnored() return openProjects.length != 0 || !FileTypeManager.getInstance().isFileIgnored(f); }
19. FindAllAction#actionPerformed()
View license@Override public void actionPerformed(final AnActionEvent e) { Editor editor = e.getRequiredData(CommonDataKeys.EDITOR_EVEN_IF_INACTIVE); Project project = e.getRequiredData(CommonDataKeys.PROJECT); EditorSearchSession search = e.getRequiredData(EditorSearchSession.SESSION_KEY); if (project.isDisposed()) return; FindModel oldModel = FindManager.getInstance(project).getFindInFileModel(); FindModel newModel = oldModel.clone(); String text = search.getTextInField(); if (StringUtil.isEmpty(text)) return; newModel.setStringToFind(text); FindUtil.findAllAndShow(project, editor, newModel); }
20. IDEHelperImpl#findOpenProject()
View license@NotNull private static Project findOpenProject(@NotNull ProjectDescriptor projectDescriptor) throws AzureCmdException { Project project = null; for (Project openProject : ProjectManager.getInstance().getOpenProjects()) { if (projectDescriptor.getName().equals(openProject.getName()) && projectDescriptor.getPath().equals(openProject.getBasePath())) { project = openProject; break; } } if (project == null) { throw new AzureCmdException("Unable to find an open project with the specified description."); } return project; }
21. FileManagerImpl#findFile()
View license@RequiredReadAction @Override @Nullable public PsiFile findFile(@NotNull VirtualFile vFile) { if (vFile.isDirectory()) return null; final Project project = myManager.getProject(); if (project.isDefault()) return null; ApplicationManager.getApplication().assertReadAccessAllowed(); if (!vFile.isValid()) { LOG.error("Invalid file: " + vFile); return null; } dispatchPendingEvents(); final FileViewProvider viewProvider = findViewProvider(vFile); return viewProvider.getPsi(viewProvider.getBaseLanguage()); }
22. CoverageDataManagerImpl#processGatheredCoverage()
View licensepublic static void processGatheredCoverage(RunConfigurationBase configuration) { final Project project = configuration.getProject(); if (project.isDisposed()) return; final CoverageDataManager coverageDataManager = CoverageDataManager.getInstance(project); final CoverageEnabledConfiguration coverageEnabledConfiguration = CoverageEnabledConfiguration.getOrCreate(configuration); //noinspection ConstantConditions final CoverageSuite coverageSuite = coverageEnabledConfiguration.getCurrentCoverageSuite(); if (coverageSuite != null) { ((BaseCoverageSuite) coverageSuite).setConfiguration(configuration); coverageDataManager.coverageGathered(coverageSuite); } }
23. CustomizableActionsPanel#setCustomizationSchemaForCurrentProjects()
View licenseprivate static void setCustomizationSchemaForCurrentProjects() { final Project[] openProjects = ProjectManager.getInstance().getOpenProjects(); for (Project project : openProjects) { final IdeFrameImpl frame = WindowManagerEx.getInstanceEx().getFrame(project); if (frame != null) { frame.updateView(); } //final FavoritesManager favoritesView = FavoritesManager.getInstance(project); //final String[] availableFavoritesLists = favoritesView.getAvailableFavoritesLists(); //for (String favoritesList : availableFavoritesLists) { // favoritesView.getFavoritesTreeViewPanel(favoritesList).updateTreePopupHandler(); //} } final IdeFrameImpl frame = WindowManagerEx.getInstanceEx().getFrame(null); if (frame != null) { frame.updateView(); } }
24. LafManagerImpl#fireUpdate()
View licenseprivate static void fireUpdate() { UISettings.getInstance().fireUISettingsChanged(); EditorFactory.getInstance().refreshAllEditors(); Project[] openProjects = ProjectManager.getInstance().getOpenProjects(); for (Project openProject : openProjects) { FileStatusManager.getInstance(openProject).fileStatusesChanged(); DaemonCodeAnalyzer.getInstance(openProject).restart(); } for (IdeFrame frame : WindowManagerEx.getInstanceEx().getAllProjectFrames()) { if (frame instanceof IdeFrameImpl) { ((IdeFrameImpl) frame).updateView(); } } ActionToolbarImpl.updateAllToolbarsImmediately(); }
25. ApplicationImpl#canExit()
View licenseprivate boolean canExit() { for (ApplicationListener applicationListener : myDispatcher.getListeners()) { if (!applicationListener.canExitApplication()) { return false; } } ProjectManagerEx projectManager = (ProjectManagerEx) ProjectManager.getInstance(); Project[] projects = projectManager.getOpenProjects(); for (Project project : projects) { if (!projectManager.canClose(project)) { return false; } } return true; }
26. ApplicationImpl#saveAll()
View license@Override public void saveAll() { if (myDoNotSave) return; FileDocumentManager.getInstance().saveAllDocuments(); Project[] openProjects = ProjectManager.getInstance().getOpenProjects(); for (Project openProject : openProjects) { ProjectEx project = (ProjectEx) openProject; project.save(); } saveSettings(); }
27. LvcsHelper#addLabel()
View licensepublic static void addLabel(final TestFrameworkRunningModel model) { String label; int color; if (model.getRoot().isDefect()) { color = RED.getRGB(); label = ExecutionBundle.message("junit.runing.info.tests.failed.label"); } else { color = GREEN.getRGB(); label = ExecutionBundle.message("junit.runing.info.tests.passed.label"); } final TestConsoleProperties consoleProperties = model.getProperties(); String name = label + " " + consoleProperties.getConfiguration().getName(); Project project = consoleProperties.getProject(); if (project.isDisposed()) return; LocalHistory.getInstance().putSystemLabel(project, name, color); }
28. IdeaModifiableModelsProvider#getLibraryTableModifiableModel()
View license@Override public LibraryTable.ModifiableModel getLibraryTableModifiableModel() { final Project[] projects = ProjectManager.getInstance().getOpenProjects(); for (Project project : projects) { if (!project.isInitialized()) { continue; } StructureConfigurableContext context = getProjectStructureContext(project); LibraryTableModifiableModelProvider provider = context != null ? context.createModifiableModelProvider(LibraryTablesRegistrar.APPLICATION_LEVEL) : null; final LibraryTable.ModifiableModel modifiableModel = provider != null ? provider.getModifiableModel() : null; if (modifiableModel != null) { return modifiableModel; } } return LibraryTablesRegistrar.getInstance().getLibraryTable().getModifiableModel(); }
29. IdeaGateway#isVersioned()
View licensepublic boolean isVersioned(@NotNull VirtualFile f, boolean shouldBeInContent) { if (!f.isInLocalFileSystem()) return false; if (!f.isDirectory() && StringUtil.endsWith(f.getNameSequence(), ".class")) return false; Project[] openProjects = ProjectManager.getInstance().getOpenProjects(); boolean isInContent = false; for (Project each : openProjects) { if (each.isDefault()) continue; if (!each.isInitialized()) continue; if (Comparing.equal(each.getWorkspaceFile(), f)) return false; ProjectFileIndex index = ProjectRootManager.getInstance(each).getFileIndex(); if (index.isExcluded(f)) return false; isInContent |= index.isInContent(f); } if (shouldBeInContent && !isInContent) return false; // optimisation: FileTypeManager.isFileIgnored(f) already checked inside ProjectFileIndex.isIgnored() return openProjects.length != 0 || !FileTypeManager.getInstance().isFileIgnored(f); }
30. HgQRenameCommand#performPatchRename()
View licensepublic static void performPatchRename(@NotNull final HgRepository repository, @NotNull final String oldName, @NotNull final String newName) { if (oldName.equals(newName)) return; final Project project = repository.getProject(); new HgCommandExecutor(project).execute(repository.getRoot(), "qrename", Arrays.asList(oldName, newName), new HgCommandResultHandler() { @Override public void process(@Nullable HgCommandResult result) { if (HgErrorUtil.hasErrorsInCommandExecution(result)) { new HgCommandResultNotifier(project).notifyError(result, "Qrename command failed", "Could not rename patch " + oldName + " to " + newName); } repository.update(); } }); }
31. StudyEditInputAction#update()
View license@Override public void update(final AnActionEvent e) { EduUtils.enableAction(e, false); final Project project = e.getProject(); if (project != null) { StudyEditor studyEditor = StudyUtils.getSelectedStudyEditor(project); if (studyEditor != null) { final List<UserTest> userTests = StudyTaskManager.getInstance(project).getUserTests(studyEditor.getTaskFile().getTask()); if (!userTests.isEmpty()) { EduUtils.enableAction(e, true); } } } }
32. HgRepositoryImpl#update()
View license@Override public void update() { HgRepoInfo currentInfo = readRepoInfo(); // update only if something changed!!! if update every time - new log will be refreshed every time, too. // Then blinking and do not work properly; final Project project = getProject(); if (!project.isDisposed() && !currentInfo.equals(myInfo)) { myInfo = currentInfo; HgCommandResult branchCommandResult = new HgBranchesCommand(project, getRoot()).collectBranches(); if (branchCommandResult == null || branchCommandResult.getExitValue() != 0) { // hg executable is not valid LOG.warn("Could not collect hg opened branches."); myOpenedBranches = myInfo.getBranches().keySet(); } else { myOpenedBranches = HgBranchesCommand.collectNames(branchCommandResult); } HgUtil.executeOnPooledThread(new Runnable() { public void run() { project.getMessageBus().syncPublisher(HgVcs.STATUS_TOPIC).update(project, getRoot()); } }, project); } }
33. ImportUtils#hasDefaultImportConflict()
View licenseprivate static boolean hasDefaultImportConflict(String fqName, PsiJavaFile file) { final String shortName = ClassUtil.extractClassName(fqName); final String packageName = ClassUtil.extractPackageName(fqName); final String filePackageName = file.getPackageName(); if (filePackageName.equals(packageName)) { return false; } final Project project = file.getProject(); final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); final PsiPackage filePackage = psiFacade.findPackage(filePackageName); if (filePackage == null) { return false; } return filePackage.containsClassNamed(shortName); }
34. ImportUtils#hasJavaLangImportConflict()
View licenseprivate static boolean hasJavaLangImportConflict(String fqName, PsiJavaFile file) { final String shortName = ClassUtil.extractClassName(fqName); final String packageName = ClassUtil.extractPackageName(fqName); if (HardcodedMethodConstants.JAVA_LANG.equals(packageName)) { return false; } final Project project = file.getProject(); final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); final PsiPackage javaLangPackage = psiFacade.findPackage(HardcodedMethodConstants.JAVA_LANG); if (javaLangPackage == null) { return false; } return javaLangPackage.containsClassNamed(shortName); }
35. VariableSearchUtils#variableNameResolvesToTarget()
View licensepublic static boolean variableNameResolvesToTarget(@NotNull String variableName, @NotNull PsiVariable target, @NotNull PsiElement context) { final Project project = context.getProject(); final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); final PsiResolveHelper resolveHelper = psiFacade.getResolveHelper(); final PsiVariable variable = resolveHelper.resolveAccessibleReferencedVariable(variableName, context); return target.equals(variable); }
36. WeakestTypeFinder#getVisibleInheritor()
View license@Nullable private static PsiClass getVisibleInheritor(@NotNull PsiClass superClass, PsiClass upperBound, PsiElement context) { final Query<PsiClass> search = DirectClassInheritorsSearch.search(superClass, context.getResolveScope()); final Project project = superClass.getProject(); for (PsiClass aClass : search) { if (aClass.isInheritor(superClass, true) && upperBound.isInheritor(aClass, true)) { if (PsiUtil.isAccessible(project, aClass, context, null)) { return aClass; } else { return getVisibleInheritor(aClass, upperBound, context); } } } return null; }
37. ForCanBeForeachInspection#createNewVariableName()
View licensestatic String createNewVariableName(@NotNull PsiElement scope, PsiType type, @Nullable String containerName) { final Project project = scope.getProject(); final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); @NonNls String baseName; if (containerName != null) { baseName = StringUtils.createSingularFromName(containerName); } else { final SuggestedNameInfo suggestions = codeStyleManager.suggestVariableName(VariableKind.LOCAL_VARIABLE, null, null, type); final String[] names = suggestions.names; if (names != null && names.length > 0) { baseName = names[0]; } else { baseName = "value"; } } if (baseName == null || baseName.isEmpty()) { baseName = "value"; } return codeStyleManager.suggestUniqueVariableName(baseName, scope, true); }
38. JavaLanguageInjectionSupport#removeInjectionInPlace()
View licensepublic boolean removeInjectionInPlace(final PsiLanguageInjectionHost psiElement) { if (!isMine(psiElement)) return false; final HashMap<BaseInjection, Pair<PsiMethod, Integer>> injectionsMap = new HashMap<BaseInjection, Pair<PsiMethod, Integer>>(); final ArrayList<PsiElement> annotations = new ArrayList<PsiElement>(); final PsiLiteralExpression host = (PsiLiteralExpression) psiElement; final Project project = host.getProject(); final Configuration configuration = Configuration.getProjectInstance(project); collectInjections(host, configuration, this, injectionsMap, annotations); if (injectionsMap.isEmpty() && annotations.isEmpty()) return false; final ArrayList<BaseInjection> originalInjections = new ArrayList<BaseInjection>(injectionsMap.keySet()); final List<BaseInjection> newInjections = ContainerUtil.mapNotNull(originalInjections, (NullableFunction<BaseInjection, BaseInjection>) injection -> { final Pair<PsiMethod, Integer> pair = injectionsMap.get(injection); final String placeText = getPatternStringForJavaPlace(pair.first, pair.second); final BaseInjection newInjection = injection.copy(); newInjection.setPlaceEnabled(placeText, false); return InjectorUtils.canBeRemoved(newInjection) ? null : newInjection; }); configuration.replaceInjectionsWithUndo(project, newInjections, originalInjections, annotations); return true; }
39. JavaLanguageInjectionSupport#editInjectionInPlace()
View licensepublic boolean editInjectionInPlace(final PsiLanguageInjectionHost psiElement) { if (!isMine(psiElement)) return false; final HashMap<BaseInjection, Pair<PsiMethod, Integer>> injectionsMap = new HashMap<BaseInjection, Pair<PsiMethod, Integer>>(); final ArrayList<PsiElement> annotations = new ArrayList<PsiElement>(); final PsiLiteralExpression host = (PsiLiteralExpression) psiElement; final Project project = host.getProject(); final Configuration configuration = Configuration.getProjectInstance(project); collectInjections(host, configuration, this, injectionsMap, annotations); if (injectionsMap.isEmpty() || !annotations.isEmpty()) return false; final BaseInjection originalInjection = injectionsMap.keySet().iterator().next(); final MethodParameterInjection methodParameterInjection = createFrom(psiElement.getProject(), originalInjection, injectionsMap.get(originalInjection).first, false); final MethodParameterInjection copy = methodParameterInjection.copy(); final BaseInjection newInjection = showInjectionUI(project, methodParameterInjection); if (newInjection != null) { newInjection.mergeOriginalPlacesFrom(copy, false); newInjection.mergeOriginalPlacesFrom(originalInjection, true); configuration.replaceInjectionsWithUndo(project, Collections.singletonList(newInjection), Collections.singletonList(originalInjection), Collections.<PsiAnnotation>emptyList()); } return true; }
40. XmlLanguageInjectionSupport#removeInjection()
View license@Override public boolean removeInjection(PsiElement host) { final Project project = host.getProject(); final Configuration configuration = Configuration.getProjectInstance(project); final ArrayList<BaseInjection> injections = collectInjections(host, configuration); if (injections.isEmpty()) return false; final ArrayList<BaseInjection> newInjections = new ArrayList<BaseInjection>(); for (BaseInjection injection : injections) { final BaseInjection newInjection = injection.copy(); newInjection.setPlaceEnabled(null, false); if (InjectorUtils.canBeRemoved(newInjection)) continue; newInjections.add(newInjection); } configuration.replaceInjectionsWithUndo(project, newInjections, injections, Collections.<PsiElement>emptyList()); return true; }
41. XmlLanguageInjectionSupport#editInjectionInPlace()
View licensepublic boolean editInjectionInPlace(final PsiLanguageInjectionHost host) { if (!isMine(host)) return false; final Project project = host.getProject(); final Configuration configuration = Configuration.getProjectInstance(project); final ArrayList<BaseInjection> injections = collectInjections(host, configuration); if (injections.isEmpty()) return false; final BaseInjection originalInjection = injections.get(0); final BaseInjection xmlInjection = createFrom(originalInjection); final BaseInjection newInjection = xmlInjection == null ? showDefaultInjectionUI(project, originalInjection.copy()) : showInjectionUI(project, xmlInjection); if (newInjection != null) { configuration.replaceInjectionsWithUndo(project, Collections.singletonList(newInjection), Collections.singletonList(originalInjection), Collections.<PsiElement>emptyList()); } return true; }
42. AdapterToListenerIntention#implementMethodInClass()
View licenseprivate static void implementMethodInClass(@NotNull PsiMethod method, @NotNull PsiClass aClass) { final PsiMethod newMethod = (PsiMethod) aClass.add(method); final PsiDocComment comment = newMethod.getDocComment(); if (comment != null) { comment.delete(); } final PsiModifierList modifierList = newMethod.getModifierList(); modifierList.setModifierProperty(PsiModifier.ABSTRACT, false); final Project project = aClass.getProject(); final CodeStyleSettings codeStyleSettings = CodeStyleSettingsManager.getSettings(project); if (codeStyleSettings.INSERT_OVERRIDE_ANNOTATION && PsiUtil.isLanguageLevel6OrHigher(aClass)) { modifierList.addAnnotation("java.lang.Override"); } final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); final PsiCodeBlock codeBlock = factory.createCodeBlock(); newMethod.add(codeBlock); }
43. Intention#replaceExpressionWithNegatedExpressionString()
View licenseprotected static void replaceExpressionWithNegatedExpressionString(@NotNull String newExpression, @NotNull PsiExpression expression) { final Project project = expression.getProject(); final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); final PsiElementFactory factory = psiFacade.getElementFactory(); PsiExpression expressionToReplace = expression; final String expString; if (BoolUtils.isNegated(expression)) { expressionToReplace = BoolUtils.findNegation(expressionToReplace); expString = newExpression; } else { PsiElement parent = expressionToReplace.getParent(); while (parent instanceof PsiParenthesizedExpression) { expressionToReplace = (PsiExpression) parent; parent = parent.getParent(); } expString = "!(" + newExpression + ')'; } final PsiExpression newCall = factory.createExpressionFromText(expString, expression); assert expressionToReplace != null; final PsiElement insertedElement = expressionToReplace.replace(newCall); final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project); codeStyleManager.reformat(insertedElement); }
44. MoveDeclarationIntention#highlightElement()
View licenseprivate static void highlightElement(@NotNull PsiElement element) { final Project project = element.getProject(); final FileEditorManager editorManager = FileEditorManager.getInstance(project); final HighlightManager highlightManager = HighlightManager.getInstance(project); final EditorColorsManager editorColorsManager = EditorColorsManager.getInstance(); final Editor editor = editorManager.getSelectedTextEditor(); final EditorColorsScheme globalScheme = editorColorsManager.getGlobalScheme(); final TextAttributes textattributes = globalScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES); final PsiElement[] elements = new PsiElement[] { element }; highlightManager.addOccurrenceHighlights(editor, elements, textattributes, true, null); StatusBar.Info.set(IntentionPowerPackBundle.message("status.bar.escape.highlighting.message"), project); }
45. FlipSetterCallIntention#processIntention()
View licenseprotected void processIntention(@NotNull PsiElement element) throws IncorrectOperationException { final Project project = element.getProject(); final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor(); if (editor != null) { final List<PsiMethodCallExpression> methodCalls = PsiSelectionSearcher.searchElementsInSelection(editor, project, PsiMethodCallExpression.class, false); if (methodCalls.size() > 0) { for (PsiMethodCallExpression call : methodCalls) { flipCall(call); } editor.getSelectionModel().removeSelection(); return; } } if (element instanceof PsiMethodCallExpression) { flipCall((PsiMethodCallExpression) element); } }
46. ReplaceForEachLoopWithIndexedForLoopIntention#createVariable()
View licenseprivate static String createVariable(String variableNameRoot, PsiExpression iteratedValue, PsiElement context) { final String variableName = createVariableName(variableNameRoot, iteratedValue); final Project project = context.getProject(); final PsiType iteratedValueType = iteratedValue.getType(); assert iteratedValueType != null; final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project); final PsiDeclarationStatement declarationStatement = elementFactory.createVariableDeclarationStatement(variableName, iteratedValueType, iteratedValue); final PsiElement newElement = context.getParent().addBefore(declarationStatement, context); JavaCodeStyleManager.getInstance(project).shortenClassReferences(newElement); return variableName; }
47. ReplaceForEachLoopWithIndexedForLoopIntention#createVariableName()
View licensepublic static String createVariableName(@Nullable String baseName, @NotNull PsiExpression assignedExpression) { final Project project = assignedExpression.getProject(); final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); final SuggestedNameInfo names = codeStyleManager.suggestVariableName(VariableKind.LOCAL_VARIABLE, baseName, assignedExpression, null); if (names.names.length == 0) { return codeStyleManager.suggestUniqueVariableName(baseName, assignedExpression, true); } return codeStyleManager.suggestUniqueVariableName(names.names[0], assignedExpression, true); }
48. ReplaceForEachLoopWithIndexedForLoopIntention#createVariableName()
View licensepublic static String createVariableName(@Nullable String baseName, @NotNull PsiType type, @NotNull PsiElement context) { final Project project = context.getProject(); final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); final SuggestedNameInfo names = codeStyleManager.suggestVariableName(VariableKind.LOCAL_VARIABLE, baseName, null, type); if (names.names.length == 0) { return codeStyleManager.suggestUniqueVariableName(baseName, context, true); } return codeStyleManager.suggestUniqueVariableName(names.names[0], context, true); }
49. ConvertInterfaceToClassIntention#moveSubClassImplementsToExtends()
View licenseprivate static boolean moveSubClassImplementsToExtends(PsiClass oldInterface) throws IncorrectOperationException { final Project project = oldInterface.getProject(); final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); final PsiElementFactory elementFactory = psiFacade.getElementFactory(); final PsiJavaCodeReferenceElement oldInterfaceReference = elementFactory.createClassReferenceElement(oldInterface); final SearchScope searchScope = oldInterface.getUseScope(); final Query<PsiClass> query = ClassInheritorsSearch.search(oldInterface, searchScope, false); final Collection<PsiClass> inheritors = query.findAll(); final boolean success = CommonRefactoringUtil.checkReadOnlyStatusRecursively(project, inheritors, false); if (!success) { return false; } for (PsiClass inheritor : inheritors) { final PsiReferenceList implementsList = inheritor.getImplementsList(); final PsiReferenceList extendsList = inheritor.getExtendsList(); if (implementsList != null) { moveReference(implementsList, extendsList, oldInterfaceReference); } } return true; }
50. DataPointHolderConversionIntention#convertToField()
View licenseprivate static PsiField convertToField(final PsiMethod method) { final Project project = method.getProject(); final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project); final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); final String fieldName = codeStyleManager.propertyNameToVariableName(method.getName(), VariableKind.STATIC_FIELD); final PsiType returnType = method.getReturnType(); assert returnType != null; final PsiField field = elementFactory.createField(fieldName, returnType); final PsiStatement returnStatement = PsiTreeUtil.findChildOfType(method, PsiStatement.class); if (returnStatement != null) { field.setInitializer(((PsiReturnStatement) returnStatement).getReturnValue()); } return field; }
51. DataPointHolderConversionIntention#convertToMethod()
View licenseprivate static PsiMethod convertToMethod(final PsiField field) { final Project project = field.getProject(); final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project); final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); final PsiExpression fieldInitializer = field.getInitializer(); final PsiMethod method = elementFactory.createMethod(codeStyleManager.variableNameToPropertyName(field.getName(), VariableKind.STATIC_FIELD), field.getType()); PsiCodeBlock body = method.getBody(); assert body != null; final PsiStatement methodCode = elementFactory.createStatementFromText(PsiKeyword.RETURN + " " + fieldInitializer.getText() + ";", null); body.add(methodCode); return method; }
52. ConvertToNestedIfIntention#processIntention()
View license@Override public void processIntention(@NotNull PsiElement element) { final PsiReturnStatement returnStatement = (PsiReturnStatement) element; final PsiExpression returnValue = returnStatement.getReturnValue(); if (returnValue == null || ErrorUtil.containsDeepError(returnValue)) { return; } final String newStatementText = buildIf(returnValue, true, new StringBuilder()).toString(); final Project project = returnStatement.getProject(); final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory(); final PsiBlockStatement blockStatement = (PsiBlockStatement) elementFactory.createStatementFromText("{" + newStatementText + "}", returnStatement); final PsiElement parent = returnStatement.getParent(); for (PsiStatement st : blockStatement.getCodeBlock().getStatements()) { CodeStyleManager.getInstance(project).reformat(parent.addBefore(st, returnStatement)); } PsiReplacementUtil.replaceStatement(returnStatement, "return false;"); }
53. I18nizeAction#actionPerformed()
View license@Override public void actionPerformed(AnActionEvent e) { final Editor editor = getEditor(e); final Project project = editor.getProject(); assert project != null; final PsiFile psiFile = CommonDataKeys.PSI_FILE.getData(e.getDataContext()); if (psiFile == null) return; final I18nQuickFixHandler handler = getHandler(e); if (handler == null) return; doI18nSelectedString(project, editor, psiFile, handler); }
54. I18nizeQuickFix#performI18nization()
View license@Override public void performI18nization(final PsiFile psiFile, final Editor editor, PsiLiteralExpression literalExpression, Collection<PropertiesFile> propertiesFiles, String key, String value, String i18nizedText, PsiExpression[] parameters, final PropertyCreationHandler propertyCreationHandler) throws IncorrectOperationException { Project project = psiFile.getProject(); propertyCreationHandler.createProperty(project, propertiesFiles, key, value, parameters); try { final PsiElement newExpression = doReplacementInJava(psiFile, editor, literalExpression, i18nizedText); reformatAndCorrectReferences(newExpression); } catch (IncorrectOperationException e) { Messages.showErrorDialog(project, CodeInsightBundle.message("inspection.i18n.expression.is.invalid.error.message"), CodeInsightBundle.message("inspection.error.dialog.title")); } }
55. JavaI18nizeQuickFixDialog#isAvailable()
View licensepublic static boolean isAvailable(PsiFile file) { final Project project = file.getProject(); final String title = CodeInsightBundle.message("i18nize.dialog.error.jdk.title"); try { return ResourceBundleManager.getManager(file) != null; } catch (ResourceBundleManager.ResourceBundleNotFoundException e) { final IntentionAction fix = e.getFix(); if (fix != null) { if (Messages.showOkCancelDialog(project, e.getMessage(), title, Messages.getErrorIcon()) == Messages.OK) { try { fix.invoke(project, null, file); return false; } catch (IncorrectOperationException e1) { LOG.error(e1); } } } Messages.showErrorDialog(project, e.getMessage(), title); return false; } }
56. ResourceBundleManager#getManager()
View license@Nullable public static ResourceBundleManager getManager(PsiFile context) throws ResourceBundleNotFoundException { final Project project = context.getProject(); final ResourceBundleManager[] managers = project.getExtensions(RESOURCE_BUNDLE_MANAGER); for (ResourceBundleManager manager : managers) { if (manager.isActive(context)) { return manager; } } final DefaultResourceBundleManager manager = new DefaultResourceBundleManager(project); return manager.isActive(context) ? manager : null; }
57. JavaFxGetterSetterPrototypeProvider#generateGetters()
View license@Override public PsiMethod[] generateGetters(PsiField field) { final Project project = field.getProject(); final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); final PsiMethod getter = GenerateMembersUtil.generateSimpleGetterPrototype(field); final PsiType wrappedType = JavaFxPsiUtil.getWrappedPropertyType(field, project, JavaFxCommonNames.ourReadOnlyMap); getter.setName(PropertyUtil.suggestGetterName(PropertyUtil.suggestPropertyName(field), wrappedType)); final PsiTypeElement returnTypeElement = getter.getReturnTypeElement(); LOG.assertTrue(returnTypeElement != null); returnTypeElement.replace(factory.createTypeElement(wrappedType)); final PsiCodeBlock getterBody = getter.getBody(); LOG.assertTrue(getterBody != null); final String fieldName = field.getName(); getterBody.getStatements()[0].replace(factory.createStatementFromText("return " + fieldName + ".get();", field)); final PsiMethod propertyGetter = PropertyUtil.generateGetterPrototype(field); if (propertyGetter != null && fieldName != null) { propertyGetter.setName(JavaCodeStyleManager.getInstance(project).variableNameToPropertyName(fieldName, VariableKind.FIELD) + JavaFxCommonNames.PROPERTY_METHOD_SUFFIX); } return new PsiMethod[] { getter, GenerateMembersUtil.annotateOnOverrideImplement(field.getContainingClass(), propertyGetter) }; }
58. JavaFxGetterSetterPrototypeProvider#generateSetters()
View license@Override public PsiMethod[] generateSetters(PsiField field) { final PsiMethod setter = GenerateMembersUtil.generateSimpleSetterPrototype(field); final Project project = field.getProject(); final PsiType wrappedType = JavaFxPsiUtil.getWrappedPropertyType(field, project, JavaFxCommonNames.ourWritableMap); final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project); final PsiTypeElement newTypeElement = elementFactory.createTypeElement(wrappedType); final PsiParameter[] parameters = setter.getParameterList().getParameters(); LOG.assertTrue(parameters.length == 1); final PsiParameter parameter = parameters[0]; final PsiTypeElement typeElement = parameter.getTypeElement(); LOG.assertTrue(typeElement != null); typeElement.replace(newTypeElement); final PsiCodeBlock body = setter.getBody(); LOG.assertTrue(body != null); body.getStatements()[0].replace(elementFactory.createStatementFromText("this." + field.getName() + ".set(" + parameter.getName() + ");", field)); return new PsiMethod[] { setter }; }
59. JavaFxImplicitUsageProvider#isFxmlUsage()
View licenseprivate static boolean isFxmlUsage(PsiMember member, GlobalSearchScope scope) { final String name = member.getName(); if (name == null) return false; final Project project = member.getProject(); final PsiSearchHelper searchHelper = PsiSearchHelper.SERVICE.getInstance(project); final PsiSearchHelper.SearchCostResult searchCost = RefResolveService.getInstance(project).isUpToDate() ? PsiSearchHelper.SearchCostResult.FEW_OCCURRENCES : searchHelper.isCheapEnoughToSearch(name, scope, null, null); if (searchCost == PsiSearchHelper.SearchCostResult.FEW_OCCURRENCES) { final Query<PsiReference> query = ReferencesSearch.search(member, scope); return query.findFirst() != null; } return false; }
60. JavaFxScopeEnlarger#isControllerClass()
View licensepublic boolean isControllerClass(PsiClass psiClass) { final Project project = psiClass.getProject(); final GlobalSearchScope resolveScope = psiClass.getResolveScope(); if (isControllerClassName(project, psiClass.getQualifiedName(), resolveScope)) { return true; } final Ref<Boolean> refFound = new Ref<>(false); ClassInheritorsSearch.search(psiClass, resolveScope, true, true, false).forEach(( aClass) -> { if (isControllerClassName(project, aClass.getQualifiedName(), resolveScope)) { refFound.set(true); return false; } return true; }); return refFound.get(); }
61. AbstractAllInDirectoryConfigurationProducer#setupConfigurationFromContext()
View license@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; }
62. TestMethods#createJavaParameters()
View license@Override protected JavaParameters createJavaParameters() throws ExecutionException { final JavaParameters javaParameters = super.createDefaultJavaParameters(); final JUnitConfiguration.Data data = getConfiguration().getPersistentData(); RunConfigurationModule module = getConfiguration().getConfigurationModule(); final Project project = module.getProject(); final SourceScope scope = getSourceScope(); final GlobalSearchScope searchScope = scope != null ? scope.getGlobalSearchScope() : GlobalSearchScope.allScope(project); addClassesListToJavaParameters(myFailedTests, testInfo -> testInfo != null ? getTestPresentation(testInfo, project, searchScope) : null, data.getPackageName(), true, javaParameters); return javaParameters; }
63. JUnitRerunFailedTestsTest#testIgnoreRenamedMethodInRerunFailed()
View licensepublic void testIgnoreRenamedMethodInRerunFailed() throws Exception { final PsiClass baseClass = myFixture.addClass("abstract class ATest extends junit.framework.TestCase {" + " public void testMe() {}\n" + "}"); myFixture.addClass("public class ChildTest extends ATest {}"); final SMTestProxy testProxy = new SMTestProxy("testMe", false, "java:test://ChildTest.testMe"); final Project project = getProject(); final GlobalSearchScope searchScope = GlobalSearchScope.projectScope(project); testProxy.setLocator(JavaTestLocator.INSTANCE); final String presentation = TestMethods.getTestPresentation(testProxy, project, searchScope); assertEquals("ChildTest,testMe", presentation); WriteCommandAction.runWriteCommandAction(project, () -> { baseClass.getMethods()[0].setName("testName2"); }); assertNull(TestMethods.getTestPresentation(testProxy, project, searchScope)); }
64. JUnitRerunFailedTestsTest#testInnerClass()
View licensepublic void testInnerClass() throws Exception { myFixture.addClass("public class TestClass {\n" + " public static class Tests extends junit.framework.TestCase {\n" + " public void testFoo() throws Exception {}\n" + " }\n" + "}"); final SMTestProxy testProxy = new SMTestProxy("testFoo", false, "java:test://TestClass$Tests.testFoo"); final Project project = getProject(); final GlobalSearchScope searchScope = GlobalSearchScope.projectScope(project); testProxy.setLocator(JavaTestLocator.INSTANCE); Location location = testProxy.getLocation(project, searchScope); assertNotNull(location); PsiElement element = location.getPsiElement(); assertTrue(element instanceof PsiMethod); String name = ((PsiMethod) element).getName(); assertEquals(name, "testFoo"); }
65. MavenPluginCustomParameterValueConverter#getConverter()
View license@Override public Converter getConverter(@NotNull GenericDomValue domElement) { Project project = domElement.getManager().getProject(); JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); PsiClass psiClass = psiFacade.findClass(myType, GlobalSearchScope.allScope(project)); if (psiClass != null) { GenericDomValueConvertersRegistry convertersRegistry = MavenDomConvertersRegistry.getInstance().getConvertersRegistry(); return convertersRegistry.getConverter(domElement, psiFacade.getElementFactory().createType(psiClass)); } return null; }
66. BaseRefactorAction#actionPerformed()
View licensepublic void actionPerformed(AnActionEvent e) { final Project project = PlatformDataKeys.PROJECT.getData(e.getDataContext()); final BaseRefactorHandler handler = initHandler(project, e.getDataContext()); boolean processChooser = handler.processChooser(); if (processChooser) { final Editor editor = getEditor(e); CommandProcessor.getInstance().executeCommand(project, new Runnable() { @Override public void run() { ApplicationManager.getApplication().runWriteAction(handler); } }, getClass().getName() + "-Commandname", DocCommandGroupId.noneGroupId(editor.getDocument())); } }
67. BaseLombokHandler#addAnnotation()
View licenseprivate void addAnnotation(@NotNull PsiModifierListOwner targetElement, @NotNull PsiAnnotation newPsiAnnotation, @NotNull Class<? extends Annotation> annotationClass) { final PsiAnnotation presentAnnotation = PsiAnnotationSearchUtil.findAnnotation(targetElement, annotationClass); final Project project = targetElement.getProject(); final JavaCodeStyleManager javaCodeStyleManager = JavaCodeStyleManager.getInstance(project); javaCodeStyleManager.shortenClassReferences(newPsiAnnotation); if (null == presentAnnotation) { PsiModifierList modifierList = targetElement.getModifierList(); if (null != modifierList) { modifierList.addAfter(newPsiAnnotation, null); } } else { presentAnnotation.setDeclaredAttributeValue(PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME, newPsiAnnotation.findDeclaredAttributeValue(PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME)); } }
68. AbstractLogProcessor#createLoggerField()
View licenseprivate LombokLightFieldBuilder createLoggerField(@NotNull PsiClass psiClass, @NotNull PsiAnnotation psiAnnotation) { final Project project = psiClass.getProject(); final PsiManager manager = psiClass.getContainingFile().getManager(); final PsiElementFactory psiElementFactory = JavaPsiFacade.getElementFactory(project); PsiType psiLoggerType = psiElementFactory.createTypeFromText(loggerType, psiClass); LombokLightFieldBuilder loggerField = new LombokLightFieldBuilder(manager, getLoggerName(psiClass), psiLoggerType).withContainingClass(psiClass).withModifier(PsiModifier.FINAL).withModifier(PsiModifier.PRIVATE).withNavigationElement(psiAnnotation); if (isLoggerStatic(psiClass)) { loggerField.withModifier(PsiModifier.STATIC); } final String loggerInitializerParameter = createLoggerInitializeParameter(psiClass, psiAnnotation); final PsiExpression initializer = psiElementFactory.createExpressionFromText(String.format(loggerInitializer, loggerInitializerParameter), psiClass); loggerField.setInitializer(initializer); return loggerField; }
69. BuilderHandler#createBuilderClass()
View license@NotNull private LombokLightClassBuilder createBuilderClass(@NotNull PsiClass psiClass, @NotNull PsiTypeParameterListOwner psiTypeParameterListOwner, @NotNull String builderClassName, final boolean isStatic, @NotNull PsiAnnotation psiAnnotation) { final String builderClassQualifiedName = psiClass.getQualifiedName() + "." + builderClassName; final Project project = psiClass.getProject(); final LombokLightClassBuilder classBuilder = new LombokLightClassBuilder(project, builderClassName, builderClassQualifiedName).withContainingClass(psiClass).withNavigationElement(psiAnnotation).withParameterTypes(psiTypeParameterListOwner.getTypeParameterList()).withModifier(PsiModifier.PUBLIC); if (isStatic) { classBuilder.withModifier(PsiModifier.STATIC); } return classBuilder; }
70. SingularMapHandler#addBuilderField()
View licensepublic void addBuilderField(@NotNull List<PsiField> fields, @NotNull PsiVariable psiVariable, @NotNull PsiClass innerClass, @NotNull AccessorsInfo accessorsInfo) { final String fieldName = accessorsInfo.removePrefix(psiVariable.getName()); final Project project = psiVariable.getProject(); final PsiManager psiManager = psiVariable.getManager(); final PsiType psiFieldType = psiVariable.getType(); final PsiType keyType = PsiTypeUtil.extractOneElementType(psiFieldType, psiManager, CommonClassNames.JAVA_UTIL_MAP, 0); final PsiType valueType = PsiTypeUtil.extractOneElementType(psiFieldType, psiManager, CommonClassNames.JAVA_UTIL_MAP, 1); final PsiType builderFieldKeyType = getBuilderFieldType(keyType, project); fields.add(new LombokLightFieldBuilder(psiManager, fieldName + LOMBOK_KEY, builderFieldKeyType).withModifier(PsiModifier.PRIVATE).withNavigationElement(psiVariable).withContainingClass(innerClass)); final PsiType builderFieldValueType = getBuilderFieldType(valueType, project); fields.add(new LombokLightFieldBuilder(psiManager, fieldName + LOMBOK_VALUE, builderFieldValueType).withModifier(PsiModifier.PRIVATE).withNavigationElement(psiVariable).withContainingClass(innerClass)); }
71. MongoConsoleAction#update()
View license@Override public void update(AnActionEvent e) { final Project project = e.getData(PlatformDataKeys.PROJECT); boolean enabled = project != null; if (!enabled) { return; } MongoConfiguration configuration = MongoConfiguration.getInstance(project); e.getPresentation().setVisible(configuration != null && StringUtils.isNotBlank(configuration.getShellPath()) && mongoExplorerPanel.getConfiguration() != null && mongoExplorerPanel.getConfiguration().isSingleServer()); e.getPresentation().setEnabled(mongoExplorerPanel.getSelectedDatabase() != null); }
72. PackageAction#actionPerformed()
View licensepublic void actionPerformed(AnActionEvent event) { Project project = event.getData(com.intellij.openapi.actionSystem.CommonDataKeys.PROJECT); if (checkSdk()) { AzureWizardModel model = new AzureWizardModel(project, createWaProjMgr()); AzureWizardDialog wizard = new AzureWizardDialog(model); final String title = AzureBundle.message("pWizWindowTitle"); wizard.setTitle(title); wizard.show(); if (wizard.isOK()) { // FileContentUtil.reparseFiles(); } } }
73. RolesConfigurable#buildConfigurables()
View license@Override protected Configurable[] buildConfigurables() { Project project = module.getProject(); return new Configurable[] { new CachingPanel(module, waProjManager, windowsAzureRole), new CertificatesPanel(module, waProjManager, windowsAzureRole), new ComponentsPanel(project, waProjManager, windowsAzureRole), new DebuggingPanel(project, waProjManager, windowsAzureRole), new RoleEndpointsPanel(module, waProjManager, windowsAzureRole), new EnvVarsPanel(module, waProjManager, windowsAzureRole), new LoadBalancingPanel(waProjManager, windowsAzureRole), new LocalStoragePanel(module, waProjManager, windowsAzureRole), new ServerConfigurationConfigurable(module, waProjManager, windowsAzureRole), new SSLOffloadingPanel(module, waProjManager, windowsAzureRole) }; }
74. CreatePullRequestAction#doUpdate()
View license@Override public void doUpdate(AnActionEvent anActionEvent) { final Project project = anActionEvent.getData(CommonDataKeys.PROJECT); final GitRepository gitRepository = TfGitHelper.getTfGitRepository(project); if (project == null || project.isDefault() || gitRepository == null) { anActionEvent.getPresentation().setVisible(false); anActionEvent.getPresentation().setEnabled(false); } else { anActionEvent.getPresentation().setVisible(true); anActionEvent.getPresentation().setEnabled(true); } }
75. ImportAction#doUpdate()
View license@Override public void doUpdate(final AnActionEvent anActionEvent) { final Project project = anActionEvent.getData(CommonDataKeys.PROJECT); if (project == null || project.isDefault()) { anActionEvent.getPresentation().setVisible(false); anActionEvent.getPresentation().setEnabled(false); return; } anActionEvent.getPresentation().setVisible(true); anActionEvent.getPresentation().setEnabled(true); }
76. ImportAction#doActionPerformed()
View license@Override public void doActionPerformed(final AnActionEvent anActionEvent) { final Project project = anActionEvent.getData(CommonDataKeys.PROJECT); if (project == null || project.isDisposed()) { return; } BasicAction.saveAll(); try { final ImportController controller = new ImportController(project); controller.showModalDialog(); } catch (Throwable t) { logger.warn("ImportAction doActionPerformed failed unexpected error", t); VcsNotifier.getInstance(project).notifyError(TfPluginBundle.message(TfPluginBundle.KEY_ACTIONS_IMPORT), TfPluginBundle.message(TfPluginBundle.KEY_IMPORT_ERRORS_UNEXPECTED, t.getMessage())); } }
77. SelectWorkItemsAction#doUpdate()
View license@Override public void doUpdate(AnActionEvent anActionEvent) { anActionEvent.getPresentation().setVisible(true); // only enable button if the repo is TFS final Project project = CommonDataKeys.PROJECT.getData(anActionEvent.getDataContext()); if ((TfGitHelper.getTfGitRepository(project) == null)) { anActionEvent.getPresentation().setEnabled(false); // change hover text to explain why button is disabled anActionEvent.getPresentation().setText(TfPluginBundle.message(TfPluginBundle.KEY_ERRORS_NOT_TFS_REPO, TfPluginBundle.message(TfPluginBundle.KEY_ACTIONS_SELECT_WORK_ITEMS_ACTION))); } else { anActionEvent.getPresentation().setEnabled(true); } }
78. SimpleCheckoutStarter#processCommand()
View license/** * Kicks off the SimpleCheckout workflow with the Git Url passed */ public void processCommand() { final Project project = DefaultProjectFactory.getInstance().getDefaultProject(); final CheckoutProvider.Listener listener = new CompositeCheckoutListener(project); try { launchApplicationWindow(); final SimpleCheckoutController controller = new SimpleCheckoutController(project, listener, gitUrl, ref); controller.showModalDialog(); } catch (Throwable t) { logger.warn("VSTS commandline checkout failed due to an unexpected error", t); VcsNotifier.getInstance(project).notifyError(TfPluginBundle.message(TfPluginBundle.KEY_CHECKOUT_DIALOG_TITLE), TfPluginBundle.message(TfPluginBundle.KEY_CHECKOUT_ERRORS_UNEXPECTED, t.getMessage())); } }
79. MavenDomProjectProcessorUtils#processParentProjects()
View licensepublic static void processParentProjects(@NotNull final MavenDomProjectModel projectDom, @NotNull final Processor<MavenDomProjectModel> processor) { Set<MavenDomProjectModel> processed = new HashSet<MavenDomProjectModel>(); Project project = projectDom.getManager().getProject(); MavenDomProjectModel parent = findParent(projectDom, project); while (parent != null) { if (processed.contains(parent)) break; processed.add(parent); if (processor.process(parent)) break; parent = findParent(parent, project); } }
80. MavenDomProjectProcessorUtils#searchDependencyUsages()
View license@NotNull public static Set<MavenDomDependency> searchDependencyUsages(@NotNull final MavenDomProjectModel model, @NotNull final DependencyConflictId dependencyId, @NotNull final Set<MavenDomDependency> excludes) { Project project = model.getManager().getProject(); final Set<MavenDomDependency> usages = new HashSet<MavenDomDependency>(); Processor<MavenDomProjectModel> collectProcessor = mavenDomProjectModel -> { for (MavenDomDependency domDependency : mavenDomProjectModel.getDependencies().getDependencies()) { if (excludes.contains(domDependency)) continue; if (dependencyId.equals(DependencyConflictId.create(domDependency))) { usages.add(domDependency); } } return false; }; processChildrenRecursively(model, collectProcessor, project, new HashSet<MavenDomProjectModel>(), true); return usages; }
81. MavenDomProjectProcessorUtils#searchManagedPluginUsages()
View license@NotNull public static Collection<MavenDomPlugin> searchManagedPluginUsages(@NotNull final MavenDomProjectModel model, @Nullable final String groupId, @NotNull final String artifactId) { Project project = model.getManager().getProject(); final Set<MavenDomPlugin> usages = new HashSet<MavenDomPlugin>(); Processor<MavenDomProjectModel> collectProcessor = mavenDomProjectModel -> { for (MavenDomPlugin domPlugin : mavenDomProjectModel.getBuild().getPlugins().getPlugins()) { if (MavenPluginDomUtil.isPlugin(domPlugin, groupId, artifactId)) { usages.add(domPlugin); } } return false; }; processChildrenRecursively(model, collectProcessor, project, new HashSet<MavenDomProjectModel>(), true); return usages; }
82. MavenDomUtil#findContainingMavenizedModule()
View license@Nullable public static Module findContainingMavenizedModule(@NotNull PsiFile psiFile) { VirtualFile file = psiFile.getVirtualFile(); if (file == null) return null; Project project = psiFile.getProject(); MavenProjectsManager manager = MavenProjectsManager.getInstance(project); if (!manager.isMavenizedProject()) return null; ProjectFileIndex index = ProjectRootManager.getInstance(project).getFileIndex(); Module module = index.getModuleForFile(file); if (module == null || !manager.isMavenizedModule(module)) return null; return module; }
83. MavenDomUtil#updateMavenParent()
View licensepublic static MavenDomParent updateMavenParent(MavenDomProjectModel mavenModel, MavenProject parentProject) { MavenDomParent result = mavenModel.getMavenParent(); VirtualFile pomFile = DomUtil.getFile(mavenModel).getVirtualFile(); Project project = mavenModel.getXmlElement().getProject(); MavenId parentId = parentProject.getMavenId(); result.getGroupId().setStringValue(parentId.getGroupId()); result.getArtifactId().setStringValue(parentId.getArtifactId()); result.getVersion().setStringValue(parentId.getVersion()); if (!Comparing.equal(pomFile.getParent().getParent(), parentProject.getDirectoryFile())) { result.getRelativePath().setValue(PsiManager.getInstance(project).findFile(parentProject.getFile())); } return result; }
84. MavenPluginDomUtil#getMavenPluginModel()
View license@Nullable public static MavenDomPluginModel getMavenPluginModel(DomElement element) { Project project = element.getManager().getProject(); MavenDomPlugin pluginElement = element.getParentOfType(MavenDomPlugin.class, false); if (pluginElement == null) return null; String groupId = pluginElement.getGroupId().getStringValue(); String artifactId = pluginElement.getArtifactId().getStringValue(); String version = pluginElement.getVersion().getStringValue(); return getMavenPluginModel(project, groupId, artifactId, version); }
85. MavenPropertyCompletionContributor#fillCompletionVariants()
View license@Override public void fillCompletionVariants(@NotNull CompletionParameters parameters, @NotNull CompletionResultSet result) { PsiFile psiFile = parameters.getOriginalFile(); Project project = psiFile.getProject(); MavenProjectsManager manager = MavenProjectsManager.getInstance(project); if (!manager.isMavenizedProject()) return; MavenProject projectFile = MavenDomUtil.findContainingProject(psiFile); if (projectFile == null) return; if (!MavenDomUtil.isMavenFile(psiFile) && !MavenDomUtil.isFilteredResourceFile(psiFile)) return; String text = psiFile.getText(); int offset = parameters.getOffset(); int braceOffset = findOpenBrace(text, offset); if (braceOffset == -1) return; TextRange range = TextRange.create(braceOffset, offset); String prefix = range.substring(text); MavenFilteredPropertyPsiReference ref = new MavenFilteredPropertyPsiReference(projectFile, psiFile, prefix, range); addVariants(Arrays.asList(ref.getVariants()), result.withPrefixMatcher(prefix)); }
86. EditMavenRunConfigurationAction#actionPerformed()
View license@Override public void actionPerformed(@NotNull AnActionEvent e) { Project project = e.getProject(); RunnerAndConfigurationSettings settings = MavenDataKeys.RUN_CONFIGURATION.getData(e.getDataContext()); assert settings != null && project != null; RunManager.getInstance(project).setSelectedConfiguration(settings); EditConfigurationsDialog dialog = new EditConfigurationsDialog(project); dialog.show(); }
87. ResourceFileReference#resolve()
View license@Nullable public PsiElement resolve() { final Project project = myFile.getProject(); final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); final VirtualFile formVirtualFile = myFile.getVirtualFile(); if (formVirtualFile == null) { return null; } final Module module = fileIndex.getModuleForFile(formVirtualFile); if (module == null) { return null; } final VirtualFile formFile = ResourceFileUtil.findResourceFileInDependents(module, getRangeText()); if (formFile == null) { return null; } return PsiManager.getInstance(project).findFile(formFile); }
88. XsltHighlightingTest#runHighlighting()
View licenseprivate long runHighlighting() { final Project project = myFixture.getProject(); PsiDocumentManager.getInstance(project).commitAllDocuments(); return ApplicationManager.getApplication().runReadAction(new Computable<Long>() { @Override public Long compute() { final long l = System.currentTimeMillis(); CodeInsightTestFixtureImpl.instantiateAndRun(myFixture.getFile(), myFixture.getEditor(), ArrayUtil.EMPTY_INT_ARRAY, false); return System.currentTimeMillis() - l; } }); }
89. BindingProperty#findBoundField()
View license@Nullable public static PsiField findBoundField(@NotNull final RadRootContainer root, final String fieldName) { final Project project = root.getProject(); final String classToBind = root.getClassToBind(); if (classToBind != null) { final PsiManager manager = PsiManager.getInstance(project); PsiClass aClass = JavaPsiFacade.getInstance(manager.getProject()).findClass(classToBind, GlobalSearchScope.allScope(project)); if (aClass != null) { final PsiField oldBindingField = aClass.findFieldByName(fieldName, false); if (oldBindingField != null) { return oldBindingField; } } } return null; }
90. DeleteGroupAction#actionPerformed()
View licensepublic void actionPerformed(AnActionEvent e) { Project project = e.getData(CommonDataKeys.PROJECT); GroupItem groupToBeRemoved = e.getData(GroupItem.DATA_KEY); if (groupToBeRemoved == null || project == null) return; if (!Palette.isRemovable(groupToBeRemoved)) { Messages.showInfoMessage(project, UIDesignerBundle.message("error.cannot.remove.default.group"), CommonBundle.getErrorTitle()); return; } Palette palette = Palette.getInstance(project); ArrayList<GroupItem> groups = new ArrayList<GroupItem>(palette.getGroups()); groups.remove(groupToBeRemoved); palette.setGroups(groups); }
91. DeleteComponentAction#actionPerformed()
View licensepublic void actionPerformed(AnActionEvent e) { Project project = e.getData(CommonDataKeys.PROJECT); ComponentItem selectedItem = e.getData(ComponentItem.DATA_KEY); GroupItem groupItem = e.getData(GroupItem.DATA_KEY); if (project == null || selectedItem == null || groupItem == null) return; if (!selectedItem.isRemovable()) { Messages.showInfoMessage(project, UIDesignerBundle.message("error.cannot.remove.default.palette"), CommonBundle.getErrorTitle()); return; } int rc = Messages.showYesNoDialog(project, UIDesignerBundle.message("delete.component.prompt", selectedItem.getClassShortName()), UIDesignerBundle.message("delete.component.title"), Messages.getQuestionIcon()); if (rc != Messages.YES) return; final Palette palette = Palette.getInstance(project); palette.removeItem(groupItem, selectedItem); palette.fireGroupsChanged(); }
92. AddComponentAction#update()
View license@Override public void update(AnActionEvent e) { Project project = e.getData(CommonDataKeys.PROJECT); if (e.getData(GroupItem.DATA_KEY) != null || e.getData(ComponentItem.DATA_KEY) != null) { e.getPresentation().setVisible(true); GroupItem groupItem = e.getData(GroupItem.DATA_KEY); e.getPresentation().setEnabled(project != null && (groupItem == null || !groupItem.isReadOnly())); } else { PsiFile psiFile = e.getData(CommonDataKeys.PSI_FILE); e.getPresentation().setVisible(psiFile != null && findElementToAdd(psiFile) != null); } }
93. FormEditingUtil#getActiveEditor()
View license@Nullable public static GuiEditor getActiveEditor(final DataContext context) { Project project = CommonDataKeys.PROJECT.getData(context); if (project == null) { return null; } final DesignerToolWindowManager toolWindowManager = DesignerToolWindowManager.getInstance(project); if (toolWindowManager == null) { return null; } return toolWindowManager.getActiveFormEditor(); }
94. FormReferencesSearcher#processReferencesInUIForms()
View licenseprivate static boolean processReferencesInUIForms(final Processor<PsiReference> processor, PsiManager psiManager, final PropertiesFile propFile, final GlobalSearchScope globalSearchScope, final LocalSearchScope filterScope) { final Project project = psiManager.getProject(); GlobalSearchScope scope = GlobalSearchScope.projectScope(project).intersectWith(globalSearchScope); final String baseName = ApplicationManager.getApplication().runReadAction(new Computable<String>() { @Override public String compute() { return propFile.getResourceBundle().getBaseName(); } }); PsiFile containingFile = ApplicationManager.getApplication().runReadAction(new Computable<PsiFile>() { @Override public PsiFile compute() { return propFile.getContainingFile(); } }); List<PsiFile> files = Arrays.asList(CacheManager.SERVICE.getInstance(project).getFilesWithWord(baseName, UsageSearchContext.IN_PLAIN_TEXT, scope, true)); return processReferencesInFiles(files, psiManager, baseName, containingFile, filterScope, processor); }
95. ConfigurationsTest#testCreateFromContext()
View license@Test public void testCreateFromContext() { final Project project = myProjectFixture.getProject(); final PsiClass psiClass = findTestClass(project); final TestNGInClassConfigurationProducer producer = new TestNGInClassConfigurationProducer(); final MapDataContext dataContext = new MapDataContext(); dataContext.put(CommonDataKeys.PROJECT, project); dataContext.put(LangDataKeys.MODULE, ModuleUtil.findModuleForPsiElement(psiClass)); dataContext.put(Location.DATA_KEY, PsiLocation.fromPsiElement(psiClass)); final ConfigurationFromContext fromContext = producer.createConfigurationFromContext(ConfigurationContext.getFromContext(dataContext)); assert fromContext != null; final RunnerAndConfigurationSettings config = fromContext.getConfigurationSettings(); final RunConfiguration runConfiguration = config.getConfiguration(); Assert.assertTrue(runConfiguration instanceof TestNGConfiguration); TestNGConfigurationType t = (TestNGConfigurationType) runConfiguration.getType(); Assert.assertTrue(t.isConfigurationByLocation(runConfiguration, new PsiLocation(project, psiClass))); }
96. AbstractCreateFormAction#update()
View licensepublic void update(final AnActionEvent e) { super.update(e); final Project project = e.getData(CommonDataKeys.PROJECT); final Presentation presentation = e.getPresentation(); if (presentation.isEnabled()) { final IdeView view = e.getData(LangDataKeys.IDE_VIEW); if (view != null) { final ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex(); final PsiDirectory[] dirs = view.getDirectories(); for (final PsiDirectory dir : dirs) { if (projectFileIndex.isUnderSourceRootOfType(dir.getVirtualFile(), JavaModuleSourceRootTypes.SOURCES) && JavaDirectoryService.getInstance().getPackage(dir) != null) { return; } } } presentation.setEnabled(false); presentation.setVisible(false); } }
97. GenerateMainAction#isActionEnabled()
View licenseprivate static boolean isActionEnabled(final AnActionEvent e) { Project project = e.getData(CommonDataKeys.PROJECT); if (project == null) return false; Editor editor = e.getData(CommonDataKeys.EDITOR); if (editor == null) return false; int offset = editor.getCaretModel().getOffset(); PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (file == null) return false; PsiElement element = file.findElementAt(offset); if (element == null) return false; PsiClass psiClass = PsiTreeUtil.getParentOfType(element, PsiClass.class); if (psiClass == null) return false; if (PsiMethodUtil.findMainMethod(psiClass) != null) return false; if (FormClassIndex.findFormsBoundToClass(project, psiClass).isEmpty()) return false; return true; }
98. XPathEvalAction#showUsageView()
View licenseprivate void showUsageView(final Editor editor, final XPath xPath, final XmlElement contextNode, final List<?> result) { final Project project = editor.getProject(); //noinspection unchecked final List<?> _result = new ArrayList(result); final Factory<UsageSearcher> searcherFactory = () -> new MyUsageSearcher(_result, xPath, contextNode); final MyUsageTarget usageTarget = new MyUsageTarget(xPath.toString(), contextNode); showUsageView(project, usageTarget, searcherFactory, new EditExpressionAction() { final Config config = XPathAppComponent.getInstance().getConfig(); @Override protected void execute() { XPathEvalAction.this.execute(editor); } }); }
99. ResourceBundleFileReference#resolve()
View licensepublic PsiElement resolve() { final Project project = myFile.getProject(); final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); final VirtualFile formVirtualFile = myFile.getVirtualFile(); if (formVirtualFile == null) { return null; } final Module module = fileIndex.getModuleForFile(formVirtualFile); if (module == null) { return null; } PropertiesFile propertiesFile = PropertiesUtilBase.getPropertiesFile(getRangeText(), module, null); return propertiesFile == null ? null : propertiesFile.getContainingFile(); }
100. ResourceBundleKeyReference#resolve()
View licensepublic PsiElement resolve() { final Project project = myFile.getProject(); final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); final VirtualFile formVirtualFile = myFile.getVirtualFile(); if (formVirtualFile == null) { return null; } final Module module = fileIndex.getModuleForFile(formVirtualFile); if (module == null) { return null; } final PropertiesFile propertiesFile = PropertiesUtilBase.getPropertiesFile(myBundleName, module, null); if (propertiesFile == null) { return null; } IProperty property = propertiesFile.findPropertyByKey(getRangeText()); return property == null ? null : property.getPsiElement(); }