Java Code Examples for com.intellij.openapi.components.ServiceManager

The following examples show how to use com.intellij.openapi.components.ServiceManager. These examples are extracted from open source projects. 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 Project: consulo   Source File: ExternalSystemExecuteTaskTask.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected void doExecute() throws Exception {
  final ExternalSystemFacadeManager manager = ServiceManager.getService(ExternalSystemFacadeManager.class);
  ExternalSystemExecutionSettings settings = ExternalSystemApiUtil.getExecutionSettings(getIdeProject(),
                                                                                        getExternalProjectPath(),
                                                                                        getExternalSystemId());
  RemoteExternalSystemFacade facade = manager.getFacade(getIdeProject(), getExternalProjectPath(), getExternalSystemId());
  RemoteExternalSystemTaskManager taskManager = facade.getTaskManager();
  List<String> taskNames = ContainerUtilRt.map2List(myTasksToExecute, MAPPER);

  final List<String> vmOptions = parseCmdParameters(myVmOptions);
  final List<String> scriptParametersList = parseCmdParameters(myScriptParameters);

  taskManager.executeTasks(getId(), taskNames, getExternalProjectPath(), settings, vmOptions, scriptParametersList, myDebuggerSetup);
}
 
Example 2
Source Project: consulo   Source File: RefreshAllExternalProjectsAction.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void update(AnActionEvent e) {
  final Project project = e.getDataContext().getData(CommonDataKeys.PROJECT);
  if (project == null) {
    e.getPresentation().setEnabled(false);
    return;
  }

  final List<ProjectSystemId> systemIds = getSystemIds(e);
  if (systemIds.isEmpty()) {
    e.getPresentation().setEnabled(false);
    return;
  }

  final String name = StringUtil.join(systemIds, new Function<ProjectSystemId, String>() {
    @Override
    public String fun(ProjectSystemId projectSystemId) {
      return projectSystemId.getReadableName();
    }
  }, ",");
  e.getPresentation().setText(ExternalSystemBundle.message("action.refresh.all.projects.text", name));
  e.getPresentation().setDescription(ExternalSystemBundle.message("action.refresh.all.projects.description", name));

  ExternalSystemProcessingManager processingManager = ServiceManager.getService(ExternalSystemProcessingManager.class);
  e.getPresentation().setEnabled(!processingManager.hasTaskOfTypeInProgress(ExternalSystemTaskType.RESOLVE_PROJECT, project));
}
 
Example 3
public void testAddLegacyPackaging() throws IOException {
    CamelService service = ServiceManager.getService(myProject, CamelService.class);
    assertEquals(0, service.getLibraries().size());

    VirtualFile camelCoreVirtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(createTestArchive("camel-core-2.22.0.jar"));
    VirtualFile legacyJarPackagingFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(createTestArchive("legacy-custom-file-0.12.snapshot.jar"));

    final LibraryTable projectLibraryTable = LibraryTablesRegistrar.getInstance().getLibraryTable(myProject);

    addLibraryToModule(camelCoreVirtualFile, projectLibraryTable, "Maven: org.apache.camel:camel-core:2.22.0-snapshot");
    addLibraryToModule(legacyJarPackagingFile, projectLibraryTable, "c:\\test\\libs\\legacy-custom-file-0.12.snapshot.jar");

    UIUtil.dispatchAllInvocationEvents();
    assertEquals(1, service.getLibraries().size());
    assertEquals(true, service.getLibraries().contains("camel-core"));
}
 
Example 4
Source Project: consulo   Source File: VcsRootIterator.java    License: Apache License 2.0 6 votes vote down vote up
private MyRootIterator(final Project project,
                       final VirtualFile root,
                       @Nullable final Processor<FilePath> pathProcessor,
                       @javax.annotation.Nullable final Processor<VirtualFile> fileProcessor,
                       @Nullable VirtualFileFilter directoryFilter) {
  myProject = project;
  myPathProcessor = pathProcessor;
  myFileProcessor = fileProcessor;
  myDirectoryFilter = directoryFilter;
  myRoot = root;

  final ProjectLevelVcsManager plVcsManager = ProjectLevelVcsManager.getInstance(project);
  final AbstractVcs vcs = plVcsManager.getVcsFor(root);
  myRootPresentFilter = (vcs == null) ? null : new MyRootFilter(root, vcs.getName());
  if (myRootPresentFilter != null) {
    myRootPresentFilter.init(ProjectLevelVcsManager.getInstance(myProject).getAllVcsRoots());
  }
  myExcludedFileIndex = ServiceManager.getService(project, FileIndexFacade.class);
}
 
Example 5
Source Project: consulo   Source File: ExecutionHelper.java    License: Apache License 2.0 6 votes vote down vote up
private static void removeContents(@Nullable final Content notToRemove, @Nonnull final Project myProject, @Nonnull final String tabDisplayName) {
  MessageView messageView = ServiceManager.getService(myProject, MessageView.class);
  Content[] contents = messageView.getContentManager().getContents();
  for (Content content : contents) {
    LOG.assertTrue(content != null);
    if (content.isPinned()) continue;
    if (tabDisplayName.equals(content.getDisplayName()) && content != notToRemove) {
      ErrorTreeView listErrorView = (ErrorTreeView)content.getComponent();
      if (listErrorView != null) {
        if (messageView.getContentManager().removeContent(content, true)) {
          content.release();
        }
      }
    }
  }
}
 
Example 6
Source Project: azure-devops-intellij   Source File: TFSRollbackEnvironmentTest.java    License: MIT License 6 votes vote down vote up
@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
    PowerMockito.mockStatic(CommandUtils.class, LocalFileSystem.class, ServiceManager.class, TfsFileUtil.class);

    when(mockTFSVcs.getServerContext(anyBoolean())).thenReturn(mockServerContext);
    when(ServiceManager.getService(eq(mockProject), any())).thenReturn(new ClassicTfvcClient(mockProject));
    when(LocalFileSystem.getInstance()).thenReturn(mockLocalFileSystem);
    when(TfsFileUtil.createLocalPath(any(String.class))).thenCallRealMethod();
    when(TfsFileUtil.createLocalPath(any(FilePath.class))).thenCallRealMethod();
    when(TfsFileUtil.getPathItem(any(TfsPath.class))).thenCallRealMethod();
    when(filePath1.getPath()).thenReturn("/path/to/file1");
    when(filePath2.getPath()).thenReturn("/path/to/file2");
    when(filePath3.getPath()).thenReturn("/path/to/file3");
    exceptions = new ArrayList<>();

    rollbackEnvironment = new TFSRollbackEnvironment(mockTFSVcs, mockProject);
}
 
Example 7
Source Project: consulo   Source File: TodoCheckinHandler.java    License: Apache License 2.0 6 votes vote down vote up
private void showTodo(TodoCheckinHandlerWorker worker) {
  String title = "For commit (" + DateFormatUtil.formatDateTime(System.currentTimeMillis()) + ")";
  ServiceManager.getService(myProject, TodoView.class).addCustomTodoView(new TodoTreeBuilderFactory() {
    @Override
    public TodoTreeBuilder createTreeBuilder(JTree tree, Project project) {
      return new CustomChangelistTodosTreeBuilder(tree, myProject, title, worker.inOneList());
    }
  }, title, new TodoPanelSettings(myConfiguration.myTodoPanelSettings));

  ApplicationManager.getApplication().invokeLater(() -> {
    ToolWindowManager manager = ToolWindowManager.getInstance(myProject);
    if (manager != null) {
      ToolWindow window = manager.getToolWindow("TODO");
      if (window != null) {
        window.show(() -> {
          ContentManager cm = window.getContentManager();
          Content[] contents = cm.getContents();
          if (contents.length > 0) {
            cm.setSelectedContent(contents[contents.length - 1], true);
          }
        });
      }
    }
  }, ModalityState.NON_MODAL, myProject.getDisposed());
}
 
Example 8
@Override
protected void addCompletions(final CompletionParameters completionParameters,
        final ProcessingContext processingContext, final CompletionResultSet resultSet) {

    final PsiElement element = completionParameters.getPosition();
    if (!LeafPsiElement.class.isInstance(element)) {
        return; // ignore comment
    }

    final Project project = element.getProject();
    final Module module = findModule(element);
    final SuggestionService service = ServiceManager.getService(project, SuggestionService.class);
    if ((module == null || !service.isSupported(completionParameters))) { // limit suggestion to Messages
        return;
    }

    if (PropertyValueImpl.class.isInstance(element)) {
        ofNullable(PropertyValueImpl.class.cast(element).getPrevSibling())
                .map(PsiElement::getPrevSibling)
                .map(PsiElement::getText)
                .ifPresent(text -> resultSet.addAllElements(service.computeValueSuggestions(text)));
    } else if (PropertyKeyImpl.class.isInstance(element)) {
        final List<String> containerElements = PropertiesFileImpl.class
                .cast(element.getContainingFile())
                .getProperties()
                .stream()
                .filter(p -> !Objects.equals(p.getKey(), element.getText()))
                .map(IProperty::getKey)
                .collect(toList());
        resultSet
                .addAllElements(service
                        .computeKeySuggestions(project, module, getPropertiesPackage(module, completionParameters),
                                containerElements, truncateIdeaDummyIdentifier(element)));
    }
}
 
Example 9
public PsalmValidatorConfigurationManager(@Nullable Project project) {
    super(project);
    if (project != null) {
        this.myProjectManager = ServiceManager.getService(project, ProjectPsalmValidatorConfigurationBaseManager.class);
    }

    this.myApplicationManager = ServiceManager.getService(AppPsalmValidatorConfigurationBaseManager.class);
}
 
Example 10
@NotNull
protected List<PhpStanValidatorConfiguration> getDefaultProjectSettings() {
    ProjectPhpStanValidatorConfigurationBaseManager service = ServiceManager.getService(
        ProjectManager.getInstance().getDefaultProject(),
        ProjectPhpStanValidatorConfigurationBaseManager.class
    );

    return service.getSettings();
}
 
Example 11
Source Project: intellij-haskforce   Source File: HaskellBuildSettings.java    License: Apache License 2.0 5 votes vote down vote up
@NotNull
public static HaskellBuildSettings getInstance(@NotNull Project project) {
    HaskellBuildSettings settings = ServiceManager.getService(project, HaskellBuildSettings.class);
    if (settings == null) settings = new HaskellBuildSettings();
    settings.updatePaths();
    return settings;
}
 
Example 12
Source Project: tmc-intellij   Source File: LoginDialog.java    License: MIT License 5 votes vote down vote up
private void onOK() {
    final PersistentTmcSettings saveSettings =
            ServiceManager.getService(PersistentTmcSettings.class);

    settingsTmc.setUsername(usernameField.getText());

    saveSettings.setSettingsTmc(settingsTmc);

    LoginManager loginManager = new LoginManager();

    if (loginManager.login(passwordField.getText())) {
        dispose();
        addressNormalizer = getAddressNormalizer();
        addressNormalizer.selectOrganizationAndCourse();
        try {
            if (!settingsTmc.getOrganization().isPresent()) {
                OrganizationListWindow.display();
            } else if (!settingsTmc.getCurrentCourse().isPresent()
                    || (previousOrganization != settingsTmc.getOrganization().get()
                && previousCourse == settingsTmc.getCurrentCourse().get())) {
                // Show courselistwindow if current course isn't selected OR if user's
                // organization has
                // changed and current course hasn't.
                // Because then the current course probably isn't the right organization's
                // course.
                CourseListWindow.display();
            } else {
                ProjectListManagerHolder.get().refreshAllCourses();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
Example 13
protected void withCypherMetadataProvider(CompletionParameters parameters, ProjectRunnable runnable) {
    Project project = parameters.getEditor().getProject();
    if (project != null) {
        CypherMetadataProviderService provider = ServiceManager.getService(project, CypherMetadataProviderService.class);
        runnable.run(provider);
    }
}
 
Example 14
Source Project: litho   Source File: LithoTemplateActionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void postProcess_generateCreatedLayoutSpec() throws IOException {
  final PsiFile specCls = testHelper.configure("LayoutSpec.java");
  ApplicationManager.getApplication()
      .invokeAndWait(
          () -> {
            new TestTemplateAction().postProcess(specCls, "Any", Collections.emptyMap());
            final PsiClass generatedForSpecCls =
                ServiceManager.getService(
                        testHelper.getFixture().getProject(), ComponentsCacheService.class)
                    .getComponent("Layout");
            assertThat(generatedForSpecCls).isNotNull();
          });
}
 
Example 15
public static EditorTextField create(Project project, DataProvider dataProvider) {
    List<EditorCustomization> customizations =
            Arrays.<EditorCustomization>asList(SoftWrapsEditorCustomization.ENABLED, SpellCheckingEditorCustomization.DISABLED);
    EditorTextField editorField = ServiceManager.getService(project, EditorTextFieldProvider.class)
            .getEditorField(FileTypes.PLAIN_TEXT.getLanguage(), project, customizations);
    new CommaSeparatedTextFieldCompletion(dataProvider).apply(editorField);
    return editorField;

}
 
Example 16
@Override
public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException {
     // filter libraries to only be Camel libraries
    Set<String> artifacts = ServiceManager.getService(project, CamelService.class).getLibraries();

    // find the camel component from those libraries
    boolean consumerOnly = getCamelIdeaUtils().isConsumerEndpoint(element);
    List<String> names = findCamelComponentNamesInArtifact(artifacts, consumerOnly, project);

    // no camel endpoints then exit
    if (names.isEmpty()) {
        return;
    }

    // show popup to chose the component
    JBList list = new JBList(names.toArray(new Object[names.size()]));
    PopupChooserBuilder builder = JBPopupFactory.getInstance().createListPopupBuilder(list);
    builder.setAdText(names.size() + " components");
    builder.setTitle("Add Camel Endpoint");
    builder.setItemChoosenCallback(() -> {
        String line = (String) list.getSelectedValue();
        int pos = editor.getCaretModel().getCurrentCaret().getOffset();
        if (pos > 0) {
            // must run this as write action because we change the source code
            new WriteCommandAction(project, element.getContainingFile()) {
                @Override
                protected void run(@NotNull Result result) throws Throwable {
                    String text = line + ":";
                    editor.getDocument().insertString(pos, text);
                    editor.getCaretModel().moveToOffset(pos + text.length());
                }
            }.execute();
        }
    });

    JBPopup popup = builder.createPopup();
    popup.showInBestPositionFor(editor);
}
 
Example 17
Source Project: azure-devops-intellij   Source File: TFSFileSystemListenerTest.java    License: MIT License 5 votes vote down vote up
@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
    PowerMockito.mockStatic(
            CommandUtils.class,
            LocalFileSystem.class,
            ServiceManager.class,
            TFSVcs.class,
            TFVCUtil.class,
            VcsHelper.class,
            VersionControlPath.class
    );

    when(ServiceManager.getService(eq(mockProject), any())).thenReturn(new ClassicTfvcClient(mockProject));
    when(mockTFSVcs.getProject()).thenReturn(mockProject);
    when(mockVcsShowConfirmationOption.getValue()).thenReturn(VcsShowConfirmationOption.Value.DO_ACTION_SILENTLY);
    when(mockTFSVcs.getDeleteConfirmation()).thenReturn(mockVcsShowConfirmationOption);
    when(VcsHelper.getTFSVcsByPath(mockVirtualFile)).thenReturn(mockTFSVcs);
    when(LocalFileSystem.getInstance()).thenReturn(mockLocalFileSystem);
    when(mockVirtualFile.getPath()).thenReturn(CURRENT_FILE_PATH);
    when(mockVirtualFile.getName()).thenReturn(CURRENT_FILE_NAME);
    when(mockVirtualParent.getPath()).thenReturn(PARENT_PATH);
    when(mockVirtualFile.getParent()).thenReturn(mockVirtualParent);
    when(mockNewDirectory.getPath()).thenReturn(NEW_DIRECTORY_PATH);
    when(mockTFSVcs.getServerContext(anyBoolean())).thenReturn(mockServerContext);
    when(TFSVcs.getInstance(mockProject)).thenReturn(mockTFSVcs);
    when(TFVCUtil.isInvalidTFVCPath(eq(mockTFSVcs), any(FilePath.class))).thenReturn(false);
    when(
            CommandUtils.deleteFiles(
                    any(ServerContext.class), anyListOf(String.class), any(String.class), any(Boolean.class)))
            .thenReturn(new TfvcDeleteResult());

    FilePath mockFilePath = mock(FilePath.class);
    when(VersionControlPath.getFilePath(CURRENT_FILE_PATH, false)).thenReturn(mockFilePath);
    when(mockPendingChange.getLocalItem()).thenReturn(CURRENT_FILE_PATH);
    when(mockPendingChange.getVersion()).thenReturn("5");

    tfsFileSystemListener = new TFSFileSystemListener(mockProject);
}
 
Example 18
Source Project: reasonml-idea-plugin   Source File: InsightManagerImpl.java    License: MIT License 5 votes vote down vote up
@Nullable
public String getRincewindFilenameExcludingVersion(@NotNull VirtualFile sourceFile, @NotNull String excludedVersion) {
    String ocamlVersion = ServiceManager.getService(m_project, BsProcess.class).getOCamlVersion(sourceFile);
    String rincewindVersion = getRincewindVersion(ocamlVersion);

    if (ocamlVersion != null && !rincewindVersion.equals(excludedVersion)) {
        return "rincewind_" + getOsPrefix() + ocamlVersion + "-" + rincewindVersion + ".exe";
    }

    return null;
}
 
Example 19
Source Project: consulo   Source File: VcsRootIterator.java    License: Apache License 2.0 5 votes vote down vote up
public VcsRootIterator(final Project project, final AbstractVcs vcs) {
  final ProjectLevelVcsManager plVcsManager = ProjectLevelVcsManager.getInstance(project);
  myOtherVcsFolders = new HashMap<String, MyRootFilter>();
  myExcludedFileIndex = ServiceManager.getService(project, FileIndexFacade.class);

  final VcsRoot[] allRoots = plVcsManager.getAllVcsRoots();
  final VirtualFile[] roots = plVcsManager.getRootsUnderVcs(vcs);
  for (VirtualFile root : roots) {
    final MyRootFilter rootPresentFilter = new MyRootFilter(root, vcs.getName());
    rootPresentFilter.init(allRoots);
    myOtherVcsFolders.put(root.getUrl(), rootPresentFilter);
  }
}
 
Example 20
Source Project: react-templates-plugin   Source File: RTFileListener.java    License: MIT License 5 votes vote down vote up
public static void stop(@NotNull Project project) {
    RTFileListener listener = ServiceManager.getService(project, RTFileListener.class);
    if (listener == null) {
        LOG.warn("failed to stop RTFileListener");
    } else {
        listener.stopListener();
    }
}
 
Example 21
public void testWithExcludeFile() {
    ServiceManager.getService(CamelPreferenceService.class).setExcludePropertyFiles(Collections.singletonList("**/CompleteExclude*"));
    myFixture.configureByFiles("CompleteYmlPropertyTestData.java", "CompleteJavaPropertyTestData.properties", "CompleteExcludePropertyTestData.properties");
    myFixture.complete(CompletionType.BASIC, 1);
    List<String> strings = myFixture.getLookupElementStrings();
    assertTrue(strings.containsAll(Arrays.asList("ftp.client}}", "ftp.server}}")));
    assertEquals(2, strings.size());
}
 
Example 22
public void testCamelGutter() {
    myFixture.configureByFiles("XmlCamelRouteLineMarkerProviderTestData.xml");
    List<GutterMark> gutters = myFixture.findAllGutters();
    assertNotNull(gutters);

    assertEquals("Does not contain the expected amount of Camel gutters", 3, gutters.size());

    Icon defaultIcon = ServiceManager.getService(CamelPreferenceService.class).getCamelIcon();
    gutters.forEach(gutterMark -> {
        assertSame("Gutter should have the Camel icon", defaultIcon, gutterMark.getIcon());
        assertEquals("Camel route", gutterMark.getTooltipText());
    });

    LineMarkerInfo.LineMarkerGutterIconRenderer firstGutter = (LineMarkerInfo.LineMarkerGutterIconRenderer) gutters.get(1);

    assertTrue(firstGutter.getLineMarkerInfo().getElement() instanceof XmlToken);
    assertEquals("The navigation start element doesn't match", "file:inbox",
            PsiTreeUtil.getParentOfType(firstGutter.getLineMarkerInfo().getElement(), XmlTag.class).getAttribute("uri").getValue());

    List<GotoRelatedItem> firstGutterTargets = GutterTestUtil.getGutterNavigationDestinationElements(firstGutter);
    assertEquals("Navigation should have one target", 1, firstGutterTargets.size());
    assertEquals("The navigation target route doesn't match", "file:inbox", firstGutterTargets.get(0).getElement().getText());
    assertEquals("The navigation target tag name doesn't match", "to",
            GutterTestUtil.getGuttersWithXMLTarget(firstGutterTargets).get(0).getLocalName());

    LineMarkerInfo.LineMarkerGutterIconRenderer secondGutter = (LineMarkerInfo.LineMarkerGutterIconRenderer) gutters.get(2);

    assertTrue(secondGutter.getLineMarkerInfo().getElement() instanceof XmlToken);
    assertEquals("The navigation start element doesn't match", "file:outbox",
            PsiTreeUtil.getParentOfType(secondGutter.getLineMarkerInfo().getElement(), XmlTag.class).getAttribute("uri").getValue());

    List<GotoRelatedItem> secondGutterTargets = GutterTestUtil.getGutterNavigationDestinationElements(secondGutter);
    assertEquals("Navigation should have one target", 1, secondGutterTargets.size());
    assertEquals("The navigation target route doesn't match", "file:outbox", secondGutterTargets.get(0).getElement().getText());
    assertEquals("The navigation target tag name doesn't match", "to",
            GutterTestUtil.getGuttersWithXMLTarget(secondGutterTargets).get(0).getLocalName());
}
 
Example 23
Source Project: camel-idea-plugin   Source File: CamelEndpointAnnotator.java    License: Apache License 2.0 4 votes vote down vote up
private CamelIdeaUtils getCamelIdeaUtils() {
    return ServiceManager.getService(CamelIdeaUtils.class);
}
 
Example 24
public static PsalmValidatorProjectConfiguration getInstance(Project project) {
    return ServiceManager.getService(project, PsalmValidatorProjectConfiguration.class);
}
 
Example 25
Source Project: consulo   Source File: AllVcses.java    License: Apache License 2.0 4 votes vote down vote up
public static AllVcsesI getInstance(final Project project) {
  return ServiceManager.getService(project, AllVcsesI.class);
}
 
Example 26
public static PsalmValidatorConfigurationManager getInstance(@NotNull Project project) {
    return ServiceManager.getService(project, PsalmValidatorConfigurationManager.class);
}
 
Example 27
Source Project: consulo   Source File: FrameWrapper.java    License: Apache License 2.0 4 votes vote down vote up
protected JFrame createJFrame(IdeFrame parent) {
  FrameWrapperPeerFactory service = ServiceManager.getService(FrameWrapperPeerFactory.class);
  return service.createJFrame(this, parent);
}
 
Example 28
Source Project: intellij   Source File: JarCache.java    License: Apache License 2.0 4 votes vote down vote up
public static JarCache getInstance(Project project) {
  return ServiceManager.getService(project, JarCache.class);
}
 
Example 29
Source Project: GitLink   Source File: Preferences.java    License: MIT License 4 votes vote down vote up
public static Preferences getInstance(Project project)
{
    return ServiceManager.getService(project, Preferences.class);
}
 
Example 30
private BuilderHandler getBuilderHandler() {
  return ServiceManager.getService(BuilderHandler.class);
}