From 5e46ecd76d756e17881b11774d8d1230fda83930 Mon Sep 17 00:00:00 2001 From: Kirill Knize Date: Mon, 20 Jan 2025 11:21:13 +0100 Subject: [PATCH] PR feedback --- ...piProvider.java => ConnectionManager.java} | 22 ++++------ .../sonarlint/core/ConnectionService.java | 18 ++++---- .../sonarlint/core/OrganizationsCache.java | 10 ++--- .../sonarlint/core/SonarProjectsCache.java | 10 ++--- .../core/VersionSoonUnsupportedHelper.java | 8 ++-- .../core/connection/ConnectionManager.java | 42 ------------------- .../server/ShowHotspotRequestHandler.java | 10 ++--- .../server/ShowIssueRequestHandler.java | 12 +++--- .../core/file/ServerFilePathsProvider.java | 12 +++--- .../core/hotspot/HotspotService.java | 12 +++--- .../sonarlint/core/issue/IssueService.java | 24 +++++------ .../sonarlint/core/rules/RulesService.java | 24 +++++------ .../server/event/ServerEventsService.java | 10 ++--- .../server/event/SonarQubeEventStream.java | 10 ++--- .../SmartNotifications.java | 10 ++--- .../core/spring/SonarLintSpringAppConfig.java | 4 +- .../sync/HotspotSynchronizationService.java | 12 +++--- .../sync/IssueSynchronizationService.java | 12 +++--- ...ProjectBranchesSynchronizationService.java | 12 +++--- .../core/sync/SynchronizationService.java | 12 +++--- .../sync/TaintSynchronizationService.java | 12 +++--- .../core/usertoken/UserTokenService.java | 10 ++--- ...Tests.java => ConnectionManagerTests.java} | 27 +++++++++++- .../core/SonarProjectsCacheTests.java | 8 ++-- .../VersionSoonUnsupportedHelperTests.java | 18 ++++---- .../file/ServerFilePathsProviderTest.java | 18 ++++---- .../src/test/java/testutils/TestUtils.java | 6 +-- 27 files changed, 180 insertions(+), 205 deletions(-) rename backend/core/src/main/java/org/sonarsource/sonarlint/core/{ServerApiProvider.java => ConnectionManager.java} (94%) delete mode 100644 backend/core/src/main/java/org/sonarsource/sonarlint/core/connection/ConnectionManager.java rename backend/core/src/test/java/org/sonarsource/sonarlint/core/{ServerApiProviderTests.java => ConnectionManagerTests.java} (85%) diff --git a/backend/core/src/main/java/org/sonarsource/sonarlint/core/ServerApiProvider.java b/backend/core/src/main/java/org/sonarsource/sonarlint/core/ConnectionManager.java similarity index 94% rename from backend/core/src/main/java/org/sonarsource/sonarlint/core/ServerApiProvider.java rename to backend/core/src/main/java/org/sonarsource/sonarlint/core/ConnectionManager.java index 3032ba5141..c2bc552016 100644 --- a/backend/core/src/main/java/org/sonarsource/sonarlint/core/ServerApiProvider.java +++ b/backend/core/src/main/java/org/sonarsource/sonarlint/core/ConnectionManager.java @@ -19,7 +19,6 @@ */ package org.sonarsource.sonarlint.core; -import com.google.common.annotations.VisibleForTesting; import java.net.URI; import java.util.Optional; import java.util.function.Consumer; @@ -30,7 +29,6 @@ import org.eclipse.lsp4j.jsonrpc.ResponseErrorException; import org.eclipse.lsp4j.jsonrpc.messages.ResponseError; import org.sonarsource.sonarlint.core.commons.log.SonarLintLogger; -import org.sonarsource.sonarlint.core.connection.ConnectionManager; import org.sonarsource.sonarlint.core.connection.ServerConnection; import org.sonarsource.sonarlint.core.commons.progress.SonarLintCancelMonitor; import org.sonarsource.sonarlint.core.http.ConnectionAwareHttpClientProvider; @@ -53,7 +51,7 @@ @Named @Singleton -public class ServerApiProvider implements ConnectionManager { +public class ConnectionManager { private static final SonarLintLogger LOG = SonarLintLogger.get(); private final ConnectionConfigurationRepository connectionRepository; @@ -62,8 +60,8 @@ public class ServerApiProvider implements ConnectionManager { private final SonarLintRpcClient client; private final URI sonarCloudUri; - public ServerApiProvider(ConnectionConfigurationRepository connectionRepository, ConnectionAwareHttpClientProvider awareHttpClientProvider, HttpClientProvider httpClientProvider, - SonarCloudActiveEnvironment sonarCloudActiveEnvironment, SonarLintRpcClient client) { + public ConnectionManager(ConnectionConfigurationRepository connectionRepository, ConnectionAwareHttpClientProvider awareHttpClientProvider, HttpClientProvider httpClientProvider, + SonarCloudActiveEnvironment sonarCloudActiveEnvironment, SonarLintRpcClient client) { this.connectionRepository = connectionRepository; this.awareHttpClientProvider = awareHttpClientProvider; this.httpClientProvider = httpClientProvider; @@ -145,7 +143,6 @@ private HttpClient getClientFor(EndpointParams params, Either httpClientProvider.getHttpClientWithPreemptiveAuth(userPass.getUsername(), userPass.getPassword())); } - @Override public ServerConnection getConnectionOrThrow(String connectionId) { var serverApi = getServerApiOrThrow(connectionId); return new ServerConnection(connectionId, serverApi, client); @@ -161,28 +158,27 @@ public Optional tryGetConnectionWithoutCredentials(String conn .map(serverApi -> new ServerConnection(connectionId, serverApi, client)); } - @Override public ServerApi getTransientConnection(String token,@Nullable String organization, String baseUrl) { return getServerApi(baseUrl, organization, token); } - @Override public void withValidConnection(String connectionId, Consumer serverApiConsumer) { getValidConnection(connectionId).ifPresent(connection -> connection.withClientApi(serverApiConsumer)); } - @Override public Optional withValidConnectionAndReturn(String connectionId, Function serverApiConsumer) { return getValidConnection(connectionId).map(connection -> connection.withClientApiAndReturn(serverApiConsumer)); } - @Override public Optional withValidConnectionFlatMapOptionalAndReturn(String connectionId, Function> serverApiConsumer) { return getValidConnection(connectionId).map(connection -> connection.withClientApiAndReturn(serverApiConsumer)).flatMap(Function.identity()); } - @VisibleForTesting - public Optional getValidConnection(String connectionId) { - return tryGetConnection(connectionId).filter(ServerConnection::isValid); + private Optional getValidConnection(String connectionId) { + return tryGetConnection(connectionId).filter(ServerConnection::isValid) + .or(() -> { + LOG.debug("Connection '{}' is invalid", connectionId); + return Optional.empty(); + }); } } diff --git a/backend/core/src/main/java/org/sonarsource/sonarlint/core/ConnectionService.java b/backend/core/src/main/java/org/sonarsource/sonarlint/core/ConnectionService.java index 94fb9dd4af..1410c5d577 100644 --- a/backend/core/src/main/java/org/sonarsource/sonarlint/core/ConnectionService.java +++ b/backend/core/src/main/java/org/sonarsource/sonarlint/core/ConnectionService.java @@ -63,23 +63,23 @@ public class ConnectionService { private final ApplicationEventPublisher applicationEventPublisher; private final ConnectionConfigurationRepository repository; private final URI sonarCloudUri; - private final ServerApiProvider serverApiProvider; + private final ConnectionManager connectionManager; private final TokenGeneratorHelper tokenGeneratorHelper; @Inject public ConnectionService(ApplicationEventPublisher applicationEventPublisher, ConnectionConfigurationRepository repository, InitializeParams params, - SonarCloudActiveEnvironment sonarCloudActiveEnvironment, TokenGeneratorHelper tokenGeneratorHelper, ServerApiProvider serverApiProvider) { - this(applicationEventPublisher, repository, params.getSonarQubeConnections(), params.getSonarCloudConnections(), sonarCloudActiveEnvironment, serverApiProvider, + SonarCloudActiveEnvironment sonarCloudActiveEnvironment, TokenGeneratorHelper tokenGeneratorHelper, ConnectionManager connectionManager) { + this(applicationEventPublisher, repository, params.getSonarQubeConnections(), params.getSonarCloudConnections(), sonarCloudActiveEnvironment, connectionManager, tokenGeneratorHelper); } ConnectionService(ApplicationEventPublisher applicationEventPublisher, ConnectionConfigurationRepository repository, @Nullable List initSonarQubeConnections, @Nullable List initSonarCloudConnections, - SonarCloudActiveEnvironment sonarCloudActiveEnvironment, ServerApiProvider serverApiProvider, TokenGeneratorHelper tokenGeneratorHelper) { + SonarCloudActiveEnvironment sonarCloudActiveEnvironment, ConnectionManager connectionManager, TokenGeneratorHelper tokenGeneratorHelper) { this.applicationEventPublisher = applicationEventPublisher; this.repository = repository; this.sonarCloudUri = sonarCloudActiveEnvironment.getUri(); - this.serverApiProvider = serverApiProvider; + this.connectionManager = connectionManager; this.tokenGeneratorHelper = tokenGeneratorHelper; if (initSonarQubeConnections != null) { initSonarQubeConnections.forEach(c -> repository.addOrReplace(adapt(c))); @@ -157,7 +157,7 @@ private void updateConnection(AbstractConnectionConfiguration connectionConfigur public ValidateConnectionResponse validateConnection(Either transientConnection, SonarLintCancelMonitor cancelMonitor) { - var serverApi = serverApiProvider.getForTransientConnection(transientConnection); + var serverApi = connectionManager.getForTransientConnection(transientConnection); var serverChecker = new ServerVersionAndStatusChecker(serverApi); try { serverChecker.checkVersionAndStatus(cancelMonitor); @@ -179,7 +179,7 @@ public ValidateConnectionResponse validateConnection(Either transientConnection, SonarLintCancelMonitor cancelMonitor) { - var serverApi = serverApiProvider.getForTransientConnection(transientConnection); + var serverApi = connectionManager.getForTransientConnection(transientConnection); var developersApi = serverApi.developers(); return developersApi.isSupported(cancelMonitor); } @@ -189,7 +189,7 @@ public HelpGenerateUserTokenResponse helpGenerateUserToken(String serverUrl, Son } public List getAllProjects(Either transientConnection, SonarLintCancelMonitor cancelMonitor) { - var serverApi = serverApiProvider.getForTransientConnection(transientConnection); + var serverApi = connectionManager.getForTransientConnection(transientConnection); return serverApi.component().getAllProjects(cancelMonitor) .stream().map(serverProject -> new SonarProjectDto(serverProject.getKey(), serverProject.getName())) .collect(Collectors.toList()); @@ -197,7 +197,7 @@ public List getAllProjects(Either getProjectNamesByKey(Either transientConnection, List projectKeys, SonarLintCancelMonitor cancelMonitor) { - var serverApi = serverApiProvider.getForTransientConnection(transientConnection); + var serverApi = connectionManager.getForTransientConnection(transientConnection); var projectNamesByKey = new HashMap(); projectKeys.forEach(key -> { var projectName = serverApi.component().getProject(key, cancelMonitor).map(ServerProject::getName).orElse(null); diff --git a/backend/core/src/main/java/org/sonarsource/sonarlint/core/OrganizationsCache.java b/backend/core/src/main/java/org/sonarsource/sonarlint/core/OrganizationsCache.java index 0f6113546a..487d008e9f 100644 --- a/backend/core/src/main/java/org/sonarsource/sonarlint/core/OrganizationsCache.java +++ b/backend/core/src/main/java/org/sonarsource/sonarlint/core/OrganizationsCache.java @@ -47,14 +47,14 @@ public class OrganizationsCache { private static final SonarLintLogger LOG = SonarLintLogger.get(); - private final ServerApiProvider serverApiProvider; + private final ConnectionManager connectionManager; private final Cache, TextSearchIndex> textSearchIndexCacheByCredentials = CacheBuilder.newBuilder() .expireAfterWrite(5, TimeUnit.MINUTES) .build(); - public OrganizationsCache(ServerApiProvider serverApiProvider) { - this.serverApiProvider = serverApiProvider; + public OrganizationsCache(ConnectionManager connectionManager) { + this.connectionManager = connectionManager; } public List fuzzySearchOrganizations(Either credentials, String searchText, SonarLintCancelMonitor cancelMonitor) { @@ -74,7 +74,7 @@ public TextSearchIndex getTextSearchIndex(Either orgs; try { - var serverApi = serverApiProvider.getForSonarCloudNoOrg(credentials); + var serverApi = connectionManager.getForSonarCloudNoOrg(credentials); var serverOrganizations = serverApi.organization().listUserOrganizations(cancelMonitor); orgs = serverOrganizations.stream().map(o -> new OrganizationDto(o.getKey(), o.getName(), o.getDescription())).collect(Collectors.toList()); } catch (Exception e) { @@ -103,7 +103,7 @@ public List listUserOrganizations(Either credentials, String organizationKey, SonarLintCancelMonitor cancelMonitor) { - var helper = serverApiProvider.getForSonarCloudNoOrg(credentials); + var helper = connectionManager.getForSonarCloudNoOrg(credentials); var serverOrganization = helper.organization().getOrganization(organizationKey, cancelMonitor); return serverOrganization.map(o -> new OrganizationDto(o.getKey(), o.getName(), o.getDescription())).orElse(null); } diff --git a/backend/core/src/main/java/org/sonarsource/sonarlint/core/SonarProjectsCache.java b/backend/core/src/main/java/org/sonarsource/sonarlint/core/SonarProjectsCache.java index e0e8171f69..e18b7d91e7 100644 --- a/backend/core/src/main/java/org/sonarsource/sonarlint/core/SonarProjectsCache.java +++ b/backend/core/src/main/java/org/sonarsource/sonarlint/core/SonarProjectsCache.java @@ -46,7 +46,7 @@ public class SonarProjectsCache { private static final SonarLintLogger LOG = SonarLintLogger.get(); - private final ServerApiProvider serverApiProvider; + private final ConnectionManager connectionManager; private final Cache> textSearchIndexCacheByConnectionId = CacheBuilder.newBuilder() .expireAfterWrite(1, TimeUnit.HOURS) @@ -94,8 +94,8 @@ public int hashCode() { } } - public SonarProjectsCache(ServerApiProvider serverApiProvider) { - this.serverApiProvider = serverApiProvider; + public SonarProjectsCache(ConnectionManager connectionManager) { + this.connectionManager = connectionManager; } @EventListener @@ -120,7 +120,7 @@ public Optional getSonarProject(String connectionId, String sonar return singleProjectsCache.get(new SonarProjectKey(connectionId, sonarProjectKey), () -> { LOG.debug("Query project '{}' on connection '{}'...", sonarProjectKey, connectionId); try { - return serverApiProvider.withValidConnectionAndReturn(connectionId, + return connectionManager.withValidConnectionAndReturn(connectionId, s -> s.component().getProject(sonarProjectKey, cancelMonitor)).orElse(Optional.empty()); } catch (Exception e) { LOG.error("Error while querying project '{}' from connection '{}'", sonarProjectKey, connectionId, e); @@ -138,7 +138,7 @@ public TextSearchIndex getTextSearchIndex(String connectionId, So LOG.debug("Load projects from connection '{}'...", connectionId); List projects; try { - projects = serverApiProvider.withValidConnectionAndReturn(connectionId, + projects = connectionManager.withValidConnectionAndReturn(connectionId, s -> s.component().getAllProjects(cancelMonitor)) .orElse(List.of()); } catch (Exception e) { diff --git a/backend/core/src/main/java/org/sonarsource/sonarlint/core/VersionSoonUnsupportedHelper.java b/backend/core/src/main/java/org/sonarsource/sonarlint/core/VersionSoonUnsupportedHelper.java index d237cd70d9..533db9b929 100644 --- a/backend/core/src/main/java/org/sonarsource/sonarlint/core/VersionSoonUnsupportedHelper.java +++ b/backend/core/src/main/java/org/sonarsource/sonarlint/core/VersionSoonUnsupportedHelper.java @@ -56,17 +56,17 @@ public class VersionSoonUnsupportedHelper { private final SonarLintRpcClient client; private final ConfigurationRepository configRepository; private final ConnectionConfigurationRepository connectionRepository; - private final ServerApiProvider serverApiProvider; + private final ConnectionManager connectionManager; private final SynchronizationService synchronizationService; private final Map cacheConnectionIdPerVersion = new ConcurrentHashMap<>(); private final ExecutorServiceShutdownWatchable executorService; - public VersionSoonUnsupportedHelper(SonarLintRpcClient client, ConfigurationRepository configRepository, ServerApiProvider serverApiProvider, + public VersionSoonUnsupportedHelper(SonarLintRpcClient client, ConfigurationRepository configRepository, ConnectionManager connectionManager, ConnectionConfigurationRepository connectionRepository, SynchronizationService synchronizationService) { this.client = client; this.configRepository = configRepository; this.connectionRepository = connectionRepository; - this.serverApiProvider = serverApiProvider; + this.connectionManager = connectionManager; this.synchronizationService = synchronizationService; this.executorService = new ExecutorServiceShutdownWatchable<>(new ThreadPoolExecutor(0, 1, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), r -> new Thread(r, "Version Soon Unsupported Helper"))); @@ -107,7 +107,7 @@ private void queueCheckIfSoonUnsupported(String connectionId, String configScope try { var connection = connectionRepository.getConnectionById(connectionId); if (connection != null && connection.getKind() == ConnectionKind.SONARQUBE) { - serverApiProvider.tryGetConnectionWithoutCredentials(connectionId) + connectionManager.tryGetConnectionWithoutCredentials(connectionId) .ifPresent(serverConnection -> serverConnection.withClientApi(serverApi -> { var version = synchronizationService.readOrSynchronizeServerVersion(connectionId, serverApi, cancelMonitor); var isCached = cacheConnectionIdPerVersion.containsKey(connectionId) && cacheConnectionIdPerVersion.get(connectionId).compareTo(version) == 0; diff --git a/backend/core/src/main/java/org/sonarsource/sonarlint/core/connection/ConnectionManager.java b/backend/core/src/main/java/org/sonarsource/sonarlint/core/connection/ConnectionManager.java deleted file mode 100644 index 144b5ba5db..0000000000 --- a/backend/core/src/main/java/org/sonarsource/sonarlint/core/connection/ConnectionManager.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * SonarLint Core - Implementation - * Copyright (C) 2016-2025 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonarsource.sonarlint.core.connection; - -import java.util.Optional; -import java.util.function.Consumer; -import java.util.function.Function; -import javax.annotation.Nullable; -import org.sonarsource.sonarlint.core.serverapi.ServerApi; - -public interface ConnectionManager { - ServerConnection getConnectionOrThrow(String connectionId); - /** - * Having dedicated TransientConnection class makes sense only if we handle the connection errors from there. - * Which brings up the problem of managing global state for notifications because we don't know the connection ID.

- * On other hand providing ServerApis directly, all Web API calls from transient ServerApi are not protected by checks for connection state. - * So we still can spam server with unprotected requests. - * It's not a big problem because we don't use such requests during scheduled sync. - * They are mostly related to setting up the connection or other user-triggered actions. - */ - ServerApi getTransientConnection(String token, @Nullable String organization, String baseUrl); - void withValidConnection(String connectionId, Consumer serverApiConsumer); - Optional withValidConnectionAndReturn(String connectionId, Function serverApiConsumer); - Optional withValidConnectionFlatMapOptionalAndReturn(String connectionId, Function> serverApiConsumer); -} diff --git a/backend/core/src/main/java/org/sonarsource/sonarlint/core/embedded/server/ShowHotspotRequestHandler.java b/backend/core/src/main/java/org/sonarsource/sonarlint/core/embedded/server/ShowHotspotRequestHandler.java index 17f711a190..6ac4c6fab3 100644 --- a/backend/core/src/main/java/org/sonarsource/sonarlint/core/embedded/server/ShowHotspotRequestHandler.java +++ b/backend/core/src/main/java/org/sonarsource/sonarlint/core/embedded/server/ShowHotspotRequestHandler.java @@ -35,7 +35,7 @@ import org.apache.hc.core5.http.io.entity.StringEntity; import org.apache.hc.core5.http.protocol.HttpContext; import org.apache.hc.core5.net.URIBuilder; -import org.sonarsource.sonarlint.core.ServerApiProvider; +import org.sonarsource.sonarlint.core.ConnectionManager; import org.sonarsource.sonarlint.core.commons.api.TextRange; import org.sonarsource.sonarlint.core.commons.progress.SonarLintCancelMonitor; import org.sonarsource.sonarlint.core.file.FilePathTranslation; @@ -57,15 +57,15 @@ @Singleton public class ShowHotspotRequestHandler implements HttpRequestHandler { private final SonarLintRpcClient client; - private final ServerApiProvider serverApiProvider; + private final ConnectionManager connectionManager; private final TelemetryService telemetryService; private final RequestHandlerBindingAssistant requestHandlerBindingAssistant; private final PathTranslationService pathTranslationService; - public ShowHotspotRequestHandler(SonarLintRpcClient client, ServerApiProvider serverApiProvider, TelemetryService telemetryService, + public ShowHotspotRequestHandler(SonarLintRpcClient client, ConnectionManager connectionManager, TelemetryService telemetryService, RequestHandlerBindingAssistant requestHandlerBindingAssistant, PathTranslationService pathTranslationService) { this.client = client; - this.serverApiProvider = serverApiProvider; + this.connectionManager = connectionManager; this.telemetryService = telemetryService; this.requestHandlerBindingAssistant = requestHandlerBindingAssistant; this.pathTranslationService = pathTranslationService; @@ -105,7 +105,7 @@ private void showHotspotForScope(String connectionId, String configurationScopeI } private Optional tryFetchHotspot(String connectionId, String hotspotKey, SonarLintCancelMonitor cancelMonitor) { - return serverApiProvider.withValidConnectionFlatMapOptionalAndReturn(connectionId,api -> api.hotspot().fetch(hotspotKey, cancelMonitor)); + return connectionManager.withValidConnectionFlatMapOptionalAndReturn(connectionId, api -> api.hotspot().fetch(hotspotKey, cancelMonitor)); } private static HotspotDetailsDto adapt(String hotspotKey, ServerHotspotDetails hotspot, FilePathTranslation translation) { diff --git a/backend/core/src/main/java/org/sonarsource/sonarlint/core/embedded/server/ShowIssueRequestHandler.java b/backend/core/src/main/java/org/sonarsource/sonarlint/core/embedded/server/ShowIssueRequestHandler.java index 2fb9d6976e..4ce8e2f468 100644 --- a/backend/core/src/main/java/org/sonarsource/sonarlint/core/embedded/server/ShowIssueRequestHandler.java +++ b/backend/core/src/main/java/org/sonarsource/sonarlint/core/embedded/server/ShowIssueRequestHandler.java @@ -41,7 +41,7 @@ import org.apache.hc.core5.http.io.entity.StringEntity; import org.apache.hc.core5.http.protocol.HttpContext; import org.apache.hc.core5.net.URIBuilder; -import org.sonarsource.sonarlint.core.ServerApiProvider; +import org.sonarsource.sonarlint.core.ConnectionManager; import org.sonarsource.sonarlint.core.SonarCloudActiveEnvironment; import org.sonarsource.sonarlint.core.commons.progress.SonarLintCancelMonitor; import org.sonarsource.sonarlint.core.file.FilePathTranslation; @@ -73,18 +73,18 @@ public class ShowIssueRequestHandler implements HttpRequestHandler { private final SonarLintRpcClient client; - private final ServerApiProvider serverApiProvider; + private final ConnectionManager connectionManager; private final TelemetryService telemetryService; private final RequestHandlerBindingAssistant requestHandlerBindingAssistant; private final PathTranslationService pathTranslationService; private final String sonarCloudUrl; private final SonarProjectBranchesSynchronizationService sonarProjectBranchesSynchronizationService; - public ShowIssueRequestHandler(SonarLintRpcClient client, ServerApiProvider serverApiProvider, TelemetryService telemetryService, + public ShowIssueRequestHandler(SonarLintRpcClient client, ConnectionManager connectionManager, TelemetryService telemetryService, RequestHandlerBindingAssistant requestHandlerBindingAssistant, PathTranslationService pathTranslationService, SonarCloudActiveEnvironment sonarCloudActiveEnvironment, SonarProjectBranchesSynchronizationService sonarProjectBranchesSynchronizationService) { this.client = client; - this.serverApiProvider = serverApiProvider; + this.connectionManager = connectionManager; this.telemetryService = telemetryService; this.requestHandlerBindingAssistant = requestHandlerBindingAssistant; this.pathTranslationService = pathTranslationService; @@ -188,13 +188,13 @@ static boolean isIssueTaint(String ruleKey) { private Optional tryFetchIssue(String connectionId, String issueKey, String projectKey, String branch, @Nullable String pullRequest, SonarLintCancelMonitor cancelMonitor) { - return serverApiProvider.withValidConnectionFlatMapOptionalAndReturn(connectionId, + return connectionManager.withValidConnectionFlatMapOptionalAndReturn(connectionId, serverApi -> serverApi.issue().fetchServerIssue(issueKey, projectKey, branch, pullRequest, cancelMonitor)); } private Optional tryFetchCodeSnippet(String connectionId, String fileKey, Common.TextRange textRange, String branch, @Nullable String pullRequest, SonarLintCancelMonitor cancelMonitor) { - return serverApiProvider.withValidConnectionFlatMapOptionalAndReturn(connectionId, + return connectionManager.withValidConnectionFlatMapOptionalAndReturn(connectionId, api -> api.issue().getCodeSnippet(fileKey, textRange, branch, pullRequest, cancelMonitor)); } diff --git a/backend/core/src/main/java/org/sonarsource/sonarlint/core/file/ServerFilePathsProvider.java b/backend/core/src/main/java/org/sonarsource/sonarlint/core/file/ServerFilePathsProvider.java index 11ebe91b19..49fbcae7bb 100644 --- a/backend/core/src/main/java/org/sonarsource/sonarlint/core/file/ServerFilePathsProvider.java +++ b/backend/core/src/main/java/org/sonarsource/sonarlint/core/file/ServerFilePathsProvider.java @@ -44,7 +44,7 @@ import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.sonarsource.sonarlint.core.ServerApiProvider; +import org.sonarsource.sonarlint.core.ConnectionManager; import org.sonarsource.sonarlint.core.commons.Binding; import org.sonarsource.sonarlint.core.commons.progress.SonarLintCancelMonitor; import org.sonarsource.sonarlint.core.serverapi.ServerApi; @@ -56,13 +56,13 @@ public class ServerFilePathsProvider { private static final Logger LOG = LoggerFactory.getLogger(ServerFilePathsProvider.class); - private final ServerApiProvider serverApiProvider; + private final ConnectionManager connectionManager; private final Map cachedResponseFilePathByBinding = new HashMap<>(); private final Path cacheDirectoryPath; private final Cache> temporaryInMemoryFilePathCacheByBinding; - public ServerFilePathsProvider(ServerApiProvider serverApiProvider, Path storageRoot) { - this.serverApiProvider = serverApiProvider; + public ServerFilePathsProvider(ConnectionManager connectionManager, Path storageRoot) { + this.connectionManager = connectionManager; this.cacheDirectoryPath = storageRoot.resolve("cache"); this.temporaryInMemoryFilePathCacheByBinding = CacheBuilder.newBuilder() .expireAfterWrite(Duration.of(1, ChronoUnit.MINUTES)) @@ -104,13 +104,13 @@ private Optional> getPathsFromFileCache(Binding binding) { } private Optional> fetchPathsFromServer(Binding binding, SonarLintCancelMonitor cancelMonitor) { - var connectionOpt = serverApiProvider.tryGetConnection(binding.getConnectionId()); + var connectionOpt = connectionManager.tryGetConnection(binding.getConnectionId()); if (connectionOpt.isEmpty()) { LOG.debug("Connection '{}' does not exist", binding.getConnectionId()); return Optional.empty(); } try { - return serverApiProvider.withValidConnectionFlatMapOptionalAndReturn(binding.getConnectionId(), serverApi -> { + return connectionManager.withValidConnectionFlatMapOptionalAndReturn(binding.getConnectionId(), serverApi -> { List paths = fetchPathsFromServer(serverApi, binding.getSonarProjectKey(), cancelMonitor); cacheServerPaths(binding, paths); return Optional.of(paths); diff --git a/backend/core/src/main/java/org/sonarsource/sonarlint/core/hotspot/HotspotService.java b/backend/core/src/main/java/org/sonarsource/sonarlint/core/hotspot/HotspotService.java index b5bb7dc3ae..51ffc3306e 100644 --- a/backend/core/src/main/java/org/sonarsource/sonarlint/core/hotspot/HotspotService.java +++ b/backend/core/src/main/java/org/sonarsource/sonarlint/core/hotspot/HotspotService.java @@ -25,7 +25,7 @@ import javax.inject.Singleton; import org.eclipse.lsp4j.jsonrpc.ResponseErrorException; import org.eclipse.lsp4j.jsonrpc.messages.ResponseError; -import org.sonarsource.sonarlint.core.ServerApiProvider; +import org.sonarsource.sonarlint.core.ConnectionManager; import org.sonarsource.sonarlint.core.branch.SonarProjectBranchTrackingService; import org.sonarsource.sonarlint.core.commons.Binding; import org.sonarsource.sonarlint.core.commons.HotspotReviewStatus; @@ -57,19 +57,19 @@ public class HotspotService { private final ConfigurationRepository configurationRepository; private final ConnectionConfigurationRepository connectionRepository; - private final ServerApiProvider serverApiProvider; + private final ConnectionManager connectionManager; private final TelemetryService telemetryService; private final SonarProjectBranchTrackingService branchTrackingService; private final StorageService storageService; public HotspotService(SonarLintRpcClient client, StorageService storageService, ConfigurationRepository configurationRepository, - ConnectionConfigurationRepository connectionRepository, ServerApiProvider serverApiProvider, TelemetryService telemetryService, + ConnectionConfigurationRepository connectionRepository, ConnectionManager connectionManager, TelemetryService telemetryService, SonarProjectBranchTrackingService branchTrackingService) { this.client = client; this.storageService = storageService; this.configurationRepository = configurationRepository; this.connectionRepository = connectionRepository; - this.serverApiProvider = serverApiProvider; + this.connectionManager = connectionManager; this.telemetryService = telemetryService; this.branchTrackingService = branchTrackingService; } @@ -117,7 +117,7 @@ public CheckLocalDetectionSupportedResponse checkLocalDetectionSupported(String public CheckStatusChangePermittedResponse checkStatusChangePermitted(String connectionId, String hotspotKey, SonarLintCancelMonitor cancelMonitor) { // fixme add getConnectionByIdOrThrow var connection = connectionRepository.getConnectionById(connectionId); - var r = serverApiProvider.getConnectionOrThrow(connectionId) + var r = connectionManager.getConnectionOrThrow(connectionId) .withClientApiAndReturn(serverApi -> serverApi.hotspot().show(hotspotKey, cancelMonitor)); var allowedStatuses = HotspotReviewStatus.allowedStatusesOn(connection.getKind()); // canChangeStatus is false when the 'Administer Hotspots' permission is missing @@ -140,7 +140,7 @@ public void changeStatus(String configurationScopeId, String hotspotKey, Hotspot LOG.debug("No binding for config scope {}", configurationScopeId); return; } - serverApiProvider.withValidConnection(effectiveBindingOpt.get().getConnectionId(), serverApi -> { + connectionManager.withValidConnection(effectiveBindingOpt.get().getConnectionId(), serverApi -> { serverApi.hotspot().changeStatus(hotspotKey, newStatus, cancelMonitor); saveStatusInStorage(effectiveBindingOpt.get(), hotspotKey, newStatus); telemetryService.hotspotStatusChanged(); diff --git a/backend/core/src/main/java/org/sonarsource/sonarlint/core/issue/IssueService.java b/backend/core/src/main/java/org/sonarsource/sonarlint/core/issue/IssueService.java index 53470525b3..3ac82bf5f0 100644 --- a/backend/core/src/main/java/org/sonarsource/sonarlint/core/issue/IssueService.java +++ b/backend/core/src/main/java/org/sonarsource/sonarlint/core/issue/IssueService.java @@ -35,7 +35,7 @@ import javax.inject.Singleton; import org.eclipse.lsp4j.jsonrpc.ResponseErrorException; import org.eclipse.lsp4j.jsonrpc.messages.ResponseError; -import org.sonarsource.sonarlint.core.ServerApiProvider; +import org.sonarsource.sonarlint.core.ConnectionManager; import org.sonarsource.sonarlint.core.commons.Binding; import org.sonarsource.sonarlint.core.commons.ImpactSeverity; import org.sonarsource.sonarlint.core.commons.LocalOnlyIssue; @@ -100,7 +100,7 @@ public class IssueService { ); private final ConfigurationRepository configurationRepository; - private final ServerApiProvider serverApiProvider; + private final ConnectionManager connectionManager; private final StorageService storageService; private final LocalOnlyIssueStorageService localOnlyIssueStorageService; private final LocalOnlyIssueRepository localOnlyIssueRepository; @@ -111,12 +111,12 @@ public class IssueService { private final RulesService rulesService; private final TaintVulnerabilityTrackingService taintVulnerabilityTrackingService; - public IssueService(ConfigurationRepository configurationRepository, ServerApiProvider serverApiProvider, StorageService storageService, + public IssueService(ConfigurationRepository configurationRepository, ConnectionManager connectionManager, StorageService storageService, LocalOnlyIssueStorageService localOnlyIssueStorageService, LocalOnlyIssueRepository localOnlyIssueRepository, ApplicationEventPublisher eventPublisher, FindingReportingService findingReportingService, SeverityModeService severityModeService, NewCodeService newCodeService, RulesService rulesService, TaintVulnerabilityTrackingService taintVulnerabilityTrackingService) { this.configurationRepository = configurationRepository; - this.serverApiProvider = serverApiProvider; + this.connectionManager = connectionManager; this.storageService = storageService; this.localOnlyIssueStorageService = localOnlyIssueStorageService; this.localOnlyIssueRepository = localOnlyIssueRepository; @@ -130,7 +130,7 @@ public IssueService(ConfigurationRepository configurationRepository, ServerApiPr public void changeStatus(String configurationScopeId, String issueKey, ResolutionStatus newStatus, boolean isTaintIssue, SonarLintCancelMonitor cancelMonitor) { var binding = configurationRepository.getEffectiveBindingOrThrow(configurationScopeId); - var serverConnection = serverApiProvider.getConnectionOrThrow(binding.getConnectionId()); + var serverConnection = connectionManager.getConnectionOrThrow(binding.getConnectionId()); var reviewStatus = transitionByResolutionStatus.get(newStatus); var projectServerIssueStore = storageService.binding(binding).findings(); boolean isServerIssue = projectServerIssueStore.containsIssue(issueKey); @@ -168,7 +168,7 @@ private static List subtract(List allIssues, Lis public boolean checkAnticipatedStatusChangeSupported(String configScopeId) { var binding = configurationRepository.getEffectiveBindingOrThrow(configScopeId); var connectionId = binding.getConnectionId(); - return serverApiProvider.getConnectionOrThrow(binding.getConnectionId()) + return connectionManager.getConnectionOrThrow(binding.getConnectionId()) .withClientApiAndReturn(serverApi -> checkAnticipatedStatusChangeSupported(serverApi, connectionId)); } @@ -186,7 +186,7 @@ private boolean checkAnticipatedStatusChangeSupported(ServerApi api, String conn } public CheckStatusChangePermittedResponse checkStatusChangePermitted(String connectionId, String issueKey, SonarLintCancelMonitor cancelMonitor) { - return serverApiProvider.getConnectionOrThrow(connectionId).withClientApiAndReturn(serverApi -> asUUID(issueKey) + return connectionManager.getConnectionOrThrow(connectionId).withClientApiAndReturn(serverApi -> asUUID(issueKey) .flatMap(localOnlyIssueRepository::findByKey) .map(r -> { // For anticipated issues we currently don't get the information from SonarQube (as there is no web API @@ -264,7 +264,7 @@ public boolean reopenIssue(String configurationScopeId, String issueId, boolean var projectServerIssueStore = storageService.binding(binding).findings(); boolean isServerIssue = projectServerIssueStore.containsIssue(issueId); if (isServerIssue) { - return serverApiProvider.getConnectionOrThrow(binding.getConnectionId()) + return connectionManager.getConnectionOrThrow(binding.getConnectionId()) .withClientApiAndReturn(serverApi -> reopenServerIssue(serverApi, binding, issueId, projectServerIssueStore, isTaintIssue, cancelMonitor)); } else { return reopenLocalIssue(issueId, configurationScopeId, cancelMonitor); @@ -285,7 +285,7 @@ private void removeAllIssuesForFile(XodusLocalOnlyIssueStore localOnlyIssueStore var issuesForFile = localOnlyIssueStore.loadForFile(configurationScopeId, filePath); var issuesToSync = subtract(allIssues, issuesForFile); var binding = configurationRepository.getEffectiveBindingOrThrow(configurationScopeId); - serverApiProvider.getConnectionOrThrow(binding.getConnectionId()) + connectionManager.getConnectionOrThrow(binding.getConnectionId()) .withClientApi(serverApi -> serverApi.issue().anticipatedTransitions(binding.getSonarProjectKey(), issuesToSync, cancelMonitor)); } @@ -294,7 +294,7 @@ private void removeIssueOnServer(XodusLocalOnlyIssueStore localOnlyIssueStore, var allIssues = localOnlyIssueStore.loadAll(configurationScopeId); var issuesToSync = allIssues.stream().filter(it -> !it.getId().equals(issueId)).collect(Collectors.toList()); var binding = configurationRepository.getEffectiveBindingOrThrow(configurationScopeId); - serverApiProvider.getConnectionOrThrow(binding.getConnectionId()) + connectionManager.getConnectionOrThrow(binding.getConnectionId()) .withClientApi(serverApi -> serverApi.issue().anticipatedTransitions(binding.getSonarProjectKey(), issuesToSync, cancelMonitor)); } @@ -309,7 +309,7 @@ private void setCommentOnLocalOnlyIssue(String configurationScopeId, UUID issueI var issuesToSync = localOnlyIssueStore.loadAll(configurationScopeId); issuesToSync.replaceAll(issue -> issue.getId().equals(issueId) ? commentedIssue : issue); var binding = configurationRepository.getEffectiveBindingOrThrow(configurationScopeId); - serverApiProvider.getConnectionOrThrow(binding.getConnectionId()) + connectionManager.getConnectionOrThrow(binding.getConnectionId()) .withClientApi(serverApi -> serverApi.issue().anticipatedTransitions(binding.getSonarProjectKey(), issuesToSync, cancelMonitor)); localOnlyIssueStore.storeLocalOnlyIssue(configurationScopeId, commentedIssue); } @@ -325,7 +325,7 @@ private static ResponseErrorException issueNotFoundException(String issueId) { private void addCommentOnServerIssue(String configurationScopeId, String issueKey, String comment, SonarLintCancelMonitor cancelMonitor) { var binding = configurationRepository.getEffectiveBindingOrThrow(configurationScopeId); - serverApiProvider.getConnectionOrThrow(binding.getConnectionId()) + connectionManager.getConnectionOrThrow(binding.getConnectionId()) .withClientApi(serverApi -> serverApi.issue().addComment(issueKey, comment, cancelMonitor)); } diff --git a/backend/core/src/main/java/org/sonarsource/sonarlint/core/rules/RulesService.java b/backend/core/src/main/java/org/sonarsource/sonarlint/core/rules/RulesService.java index 9be573c341..7578c12875 100644 --- a/backend/core/src/main/java/org/sonarsource/sonarlint/core/rules/RulesService.java +++ b/backend/core/src/main/java/org/sonarsource/sonarlint/core/rules/RulesService.java @@ -38,7 +38,7 @@ import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.sonarsource.sonarlint.core.ServerApiProvider; +import org.sonarsource.sonarlint.core.ConnectionManager; import org.sonarsource.sonarlint.core.analysis.RuleDetailsForAnalysis; import org.sonarsource.sonarlint.core.commons.Binding; import org.sonarsource.sonarlint.core.commons.BoundScope; @@ -84,7 +84,7 @@ public class RulesService { private static final Logger LOG = LoggerFactory.getLogger(RulesService.class); public static final String IN_EMBEDDED_RULES = "' in embedded rules"; - private final ServerApiProvider serverApiProvider; + private final ConnectionManager connectionManager; private final ConfigurationRepository configurationRepository; private final RulesRepository rulesRepository; private final StorageService storageService; @@ -95,17 +95,17 @@ public class RulesService { private final SeverityModeService severityModeService; @Inject - public RulesService(ServerApiProvider serverApiProvider, ConfigurationRepository configurationRepository, RulesRepository rulesRepository, - StorageService storageService, InitializeParams params, ApplicationEventPublisher eventPublisher, - SeverityModeService severityModeService) { - this(serverApiProvider, configurationRepository, rulesRepository, storageService, eventPublisher, + public RulesService(ConnectionManager connectionManager, ConfigurationRepository configurationRepository, RulesRepository rulesRepository, + StorageService storageService, InitializeParams params, ApplicationEventPublisher eventPublisher, + SeverityModeService severityModeService) { + this(connectionManager, configurationRepository, rulesRepository, storageService, eventPublisher, params.getStandaloneRuleConfigByKey(), severityModeService); } - RulesService(ServerApiProvider serverApiProvider, ConfigurationRepository configurationRepository, RulesRepository rulesRepository, - StorageService storageService, ApplicationEventPublisher eventPublisher, - @Nullable Map standaloneRuleConfigByKey, SeverityModeService severityModeService) { - this.serverApiProvider = serverApiProvider; + RulesService(ConnectionManager connectionManager, ConfigurationRepository configurationRepository, RulesRepository rulesRepository, + StorageService storageService, ApplicationEventPublisher eventPublisher, + @Nullable Map standaloneRuleConfigByKey, SeverityModeService severityModeService) { + this.connectionManager = connectionManager; this.configurationRepository = configurationRepository; this.rulesRepository = rulesRepository; this.storageService = storageService; @@ -139,7 +139,7 @@ public RuleDetails getRuleDetails(String configurationScopeId, String ruleKey, S public RuleDetails getActiveRuleForBinding(String ruleKey, Binding binding, SonarLintCancelMonitor cancelMonitor) { var connectionId = binding.getConnectionId(); - serverApiProvider.getConnectionOrThrow(connectionId); + connectionManager.getConnectionOrThrow(connectionId); var serverUsesStandardSeverityMode = !severityModeService.isMQRModeForConnection(connectionId); @@ -168,7 +168,7 @@ private Optional findServerActiveRuleInStorage(Binding binding private RuleDetails hydrateDetailsWithServer(String connectionId, ServerActiveRule activeRuleFromStorage, boolean skipCleanCodeTaxonomy, SonarLintCancelMonitor cancelMonitor) { var ruleKey = activeRuleFromStorage.getRuleKey(); var templateKey = activeRuleFromStorage.getTemplateKey(); - var serverConnection = serverApiProvider.getConnectionOrThrow(connectionId); + var serverConnection = connectionManager.getConnectionOrThrow(connectionId); if (StringUtils.isNotBlank(templateKey)) { var templateRule = rulesRepository.getRule(connectionId, templateKey); if (templateRule.isEmpty()) { diff --git a/backend/core/src/main/java/org/sonarsource/sonarlint/core/server/event/ServerEventsService.java b/backend/core/src/main/java/org/sonarsource/sonarlint/core/server/event/ServerEventsService.java index 33348ce342..b28488a1f5 100644 --- a/backend/core/src/main/java/org/sonarsource/sonarlint/core/server/event/ServerEventsService.java +++ b/backend/core/src/main/java/org/sonarsource/sonarlint/core/server/event/ServerEventsService.java @@ -30,7 +30,7 @@ import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import javax.annotation.PreDestroy; -import org.sonarsource.sonarlint.core.ServerApiProvider; +import org.sonarsource.sonarlint.core.ConnectionManager; import org.sonarsource.sonarlint.core.commons.Binding; import org.sonarsource.sonarlint.core.commons.ConnectionKind; import org.sonarsource.sonarlint.core.commons.log.SonarLintLogger; @@ -58,7 +58,7 @@ public class ServerEventsService { private static final SonarLintLogger LOG = SonarLintLogger.get(); private final ConfigurationRepository configurationRepository; private final ConnectionConfigurationRepository connectionConfigurationRepository; - private final ServerApiProvider serverApiProvider; + private final ConnectionManager connectionManager; private final LanguageSupportRepository languageSupportRepository; private final boolean shouldManageServerSentEvents; private final ApplicationEventPublisher eventPublisher; @@ -66,10 +66,10 @@ public class ServerEventsService { private final ExecutorService executorService = Executors.newSingleThreadExecutor(r -> new Thread(r, "sonarlint-server-sent-events-subscriber")); public ServerEventsService(ConfigurationRepository configurationRepository, ConnectionConfigurationRepository connectionConfigurationRepository, - ServerApiProvider serverApiProvider, LanguageSupportRepository languageSupportRepository, InitializeParams initializeParams, ApplicationEventPublisher eventPublisher) { + ConnectionManager connectionManager, LanguageSupportRepository languageSupportRepository, InitializeParams initializeParams, ApplicationEventPublisher eventPublisher) { this.configurationRepository = configurationRepository; this.connectionConfigurationRepository = connectionConfigurationRepository; - this.serverApiProvider = serverApiProvider; + this.connectionManager = connectionManager; this.languageSupportRepository = languageSupportRepository; this.shouldManageServerSentEvents = initializeParams.getFeatureFlags().shouldManageServerSentEvents(); this.eventPublisher = eventPublisher; @@ -178,7 +178,7 @@ private void subscribe(String connectionId, Set possiblyNewProjectKeys) } private SonarQubeEventStream openStream(String connectionId) { - return new SonarQubeEventStream(languageSupportRepository.getEnabledLanguagesInConnectedMode(), connectionId, serverApiProvider, + return new SonarQubeEventStream(languageSupportRepository.getEnabledLanguagesInConnectedMode(), connectionId, connectionManager, e -> eventPublisher.publishEvent(new SonarServerEventReceivedEvent(connectionId, e))); } diff --git a/backend/core/src/main/java/org/sonarsource/sonarlint/core/server/event/SonarQubeEventStream.java b/backend/core/src/main/java/org/sonarsource/sonarlint/core/server/event/SonarQubeEventStream.java index cfbc8eb625..ec58e52549 100644 --- a/backend/core/src/main/java/org/sonarsource/sonarlint/core/server/event/SonarQubeEventStream.java +++ b/backend/core/src/main/java/org/sonarsource/sonarlint/core/server/event/SonarQubeEventStream.java @@ -22,7 +22,7 @@ import java.util.LinkedHashSet; import java.util.Set; import java.util.function.Consumer; -import org.sonarsource.sonarlint.core.ServerApiProvider; +import org.sonarsource.sonarlint.core.ConnectionManager; import org.sonarsource.sonarlint.core.commons.api.SonarLanguage; import org.sonarsource.sonarlint.core.serverapi.push.SonarServerEvent; import org.sonarsource.sonarlint.core.serverapi.stream.EventStream; @@ -32,13 +32,13 @@ public class SonarQubeEventStream { private final Set subscribedProjectKeys = new LinkedHashSet<>(); private final Set enabledLanguages; private final String connectionId; - private final ServerApiProvider serverApiProvider; + private final ConnectionManager connectionManager; private final Consumer eventConsumer; - public SonarQubeEventStream(Set enabledLanguages, String connectionId, ServerApiProvider serverApiProvider, Consumer eventConsumer) { + public SonarQubeEventStream(Set enabledLanguages, String connectionId, ConnectionManager connectionManager, Consumer eventConsumer) { this.enabledLanguages = enabledLanguages; this.connectionId = connectionId; - this.serverApiProvider = serverApiProvider; + this.connectionManager = connectionManager; this.eventConsumer = eventConsumer; } @@ -67,7 +67,7 @@ public synchronized void unsubscribe(String projectKey) { private void attemptSubscription(Set projectKeys) { if (!enabledLanguages.isEmpty()) { - serverApiProvider.getServerApi(connectionId) + connectionManager.getServerApi(connectionId) .ifPresent(serverApi -> eventStream = serverApi.push().subscribe(projectKeys, enabledLanguages, e -> notifyHandlers(e, eventConsumer))); } } diff --git a/backend/core/src/main/java/org/sonarsource/sonarlint/core/smartnotifications/SmartNotifications.java b/backend/core/src/main/java/org/sonarsource/sonarlint/core/smartnotifications/SmartNotifications.java index a2b1590566..067c3f2277 100644 --- a/backend/core/src/main/java/org/sonarsource/sonarlint/core/smartnotifications/SmartNotifications.java +++ b/backend/core/src/main/java/org/sonarsource/sonarlint/core/smartnotifications/SmartNotifications.java @@ -34,7 +34,7 @@ import javax.annotation.PreDestroy; import javax.inject.Named; import javax.inject.Singleton; -import org.sonarsource.sonarlint.core.ServerApiProvider; +import org.sonarsource.sonarlint.core.ConnectionManager; import org.sonarsource.sonarlint.core.commons.BoundScope; import org.sonarsource.sonarlint.core.commons.ConnectionKind; import org.sonarsource.sonarlint.core.commons.log.SonarLintLogger; @@ -63,7 +63,7 @@ public class SmartNotifications { private final ConfigurationRepository configurationRepository; private final ConnectionConfigurationRepository connectionRepository; - private final ServerApiProvider serverApiProvider; + private final ConnectionManager connectionManager; private final SonarLintRpcClient client; private final TelemetryService telemetryService; private final WebSocketService webSocketService; @@ -72,11 +72,11 @@ public class SmartNotifications { private final LastEventPolling lastEventPollingService; private ExecutorServiceShutdownWatchable smartNotificationsPolling; - public SmartNotifications(ConfigurationRepository configurationRepository, ConnectionConfigurationRepository connectionRepository, ServerApiProvider serverApiProvider, + public SmartNotifications(ConfigurationRepository configurationRepository, ConnectionConfigurationRepository connectionRepository, ConnectionManager connectionManager, SonarLintRpcClient client, StorageService storageService, TelemetryService telemetryService, WebSocketService webSocketService, InitializeParams params) { this.configurationRepository = configurationRepository; this.connectionRepository = connectionRepository; - this.serverApiProvider = serverApiProvider; + this.connectionManager = connectionManager; this.client = client; this.telemetryService = telemetryService; this.webSocketService = webSocketService; @@ -101,7 +101,7 @@ private void poll(SonarLintCancelMonitor cancelMonitor) { boundScopeByConnectionAndSonarProject.forEach((connectionId, boundScopesByProject) -> { var connection = connectionRepository.getConnectionById(connectionId); if (connection != null && !connection.isDisableNotifications() && !shouldSkipPolling(connection)) { - serverApiProvider.withValidConnection(connectionId, + connectionManager.withValidConnection(connectionId, serverApi -> manageNotificationsForConnection(serverApi, boundScopesByProject, connection, cancelMonitor)); } }); diff --git a/backend/core/src/main/java/org/sonarsource/sonarlint/core/spring/SonarLintSpringAppConfig.java b/backend/core/src/main/java/org/sonarsource/sonarlint/core/spring/SonarLintSpringAppConfig.java index faa7b2311f..e1b08cebcf 100644 --- a/backend/core/src/main/java/org/sonarsource/sonarlint/core/spring/SonarLintSpringAppConfig.java +++ b/backend/core/src/main/java/org/sonarsource/sonarlint/core/spring/SonarLintSpringAppConfig.java @@ -38,7 +38,7 @@ import org.sonarsource.sonarlint.core.ConnectionService; import org.sonarsource.sonarlint.core.ConnectionSuggestionProvider; import org.sonarsource.sonarlint.core.OrganizationsCache; -import org.sonarsource.sonarlint.core.ServerApiProvider; +import org.sonarsource.sonarlint.core.ConnectionManager; import org.sonarsource.sonarlint.core.SharedConnectedModeSettingsProvider; import org.sonarsource.sonarlint.core.SonarCloudActiveEnvironment; import org.sonarsource.sonarlint.core.SonarProjectsCache; @@ -133,7 +133,7 @@ ConfigurationService.class, ConfigurationRepository.class, RulesService.class, - ServerApiProvider.class, + ConnectionManager.class, ConnectionConfigurationRepository.class, RulesRepository.class, RulesExtractionHelper.class, diff --git a/backend/core/src/main/java/org/sonarsource/sonarlint/core/sync/HotspotSynchronizationService.java b/backend/core/src/main/java/org/sonarsource/sonarlint/core/sync/HotspotSynchronizationService.java index 636c81f1b9..df3a9ed3b5 100644 --- a/backend/core/src/main/java/org/sonarsource/sonarlint/core/sync/HotspotSynchronizationService.java +++ b/backend/core/src/main/java/org/sonarsource/sonarlint/core/sync/HotspotSynchronizationService.java @@ -24,7 +24,7 @@ import java.util.stream.Collectors; import javax.inject.Named; import javax.inject.Singleton; -import org.sonarsource.sonarlint.core.ServerApiProvider; +import org.sonarsource.sonarlint.core.ConnectionManager; import org.sonarsource.sonarlint.core.commons.Binding; import org.sonarsource.sonarlint.core.commons.Version; import org.sonarsource.sonarlint.core.commons.api.SonarLanguage; @@ -45,12 +45,12 @@ public class HotspotSynchronizationService { private static final SonarLintLogger LOG = SonarLintLogger.get(); private final StorageService storageService; private final LanguageSupportRepository languageSupportRepository; - private final ServerApiProvider serverApiProvider; + private final ConnectionManager connectionManager; - public HotspotSynchronizationService(StorageService storageService, LanguageSupportRepository languageSupportRepository, ServerApiProvider serverApiProvider) { + public HotspotSynchronizationService(StorageService storageService, LanguageSupportRepository languageSupportRepository, ConnectionManager connectionManager) { this.storageService = storageService; this.languageSupportRepository = languageSupportRepository; - this.serverApiProvider = serverApiProvider; + this.connectionManager = connectionManager; } public void syncServerHotspotsForProject(ServerApi serverApi, String connectionId, String projectKey, String branchName, SonarLintCancelMonitor cancelMonitor) { @@ -73,7 +73,7 @@ private static Version getSonarServerVersion(ServerApi serverApi, ConnectionStor } public void fetchProjectHotspots(Binding binding, String activeBranch, SonarLintCancelMonitor cancelMonitor) { - serverApiProvider.withValidConnection(binding.getConnectionId(), serverApi -> + connectionManager.withValidConnection(binding.getConnectionId(), serverApi -> downloadAllServerHotspots(binding.getConnectionId(), serverApi, binding.getSonarProjectKey(), activeBranch, cancelMonitor)); } @@ -87,7 +87,7 @@ private void downloadAllServerHotspots(String connectionId, ServerApi serverApi, } public void fetchFileHotspots(Binding binding, String activeBranch, Path serverFilePath, SonarLintCancelMonitor cancelMonitor) { - serverApiProvider.withValidConnection(binding.getConnectionId(), serverApi -> + connectionManager.withValidConnection(binding.getConnectionId(), serverApi -> downloadAllServerHotspotsForFile(binding.getConnectionId(), serverApi, binding.getSonarProjectKey(), serverFilePath, activeBranch, cancelMonitor)); } diff --git a/backend/core/src/main/java/org/sonarsource/sonarlint/core/sync/IssueSynchronizationService.java b/backend/core/src/main/java/org/sonarsource/sonarlint/core/sync/IssueSynchronizationService.java index dd897db526..78c5001031 100644 --- a/backend/core/src/main/java/org/sonarsource/sonarlint/core/sync/IssueSynchronizationService.java +++ b/backend/core/src/main/java/org/sonarsource/sonarlint/core/sync/IssueSynchronizationService.java @@ -24,7 +24,7 @@ import java.util.stream.Collectors; import javax.inject.Named; import javax.inject.Singleton; -import org.sonarsource.sonarlint.core.ServerApiProvider; +import org.sonarsource.sonarlint.core.ConnectionManager; import org.sonarsource.sonarlint.core.commons.Binding; import org.sonarsource.sonarlint.core.commons.api.SonarLanguage; import org.sonarsource.sonarlint.core.commons.log.SonarLintLogger; @@ -42,13 +42,13 @@ public class IssueSynchronizationService { private static final SonarLintLogger LOG = SonarLintLogger.get(); private final StorageService storageService; private final LanguageSupportRepository languageSupportRepository; - private final ServerApiProvider serverApiProvider; + private final ConnectionManager connectionManager; public IssueSynchronizationService(StorageService storageService, LanguageSupportRepository languageSupportRepository, - ServerApiProvider serverApiProvider) { + ConnectionManager connectionManager) { this.storageService = storageService; this.languageSupportRepository = languageSupportRepository; - this.serverApiProvider = serverApiProvider; + this.connectionManager = connectionManager; } public void syncServerIssuesForProject(ServerApi serverApi, String connectionId, String projectKey, String branchName, SonarLintCancelMonitor cancelMonitor) { @@ -65,7 +65,7 @@ public void syncServerIssuesForProject(ServerApi serverApi, String connectionId, } public void fetchProjectIssues(Binding binding, String activeBranch, SonarLintCancelMonitor cancelMonitor) { - serverApiProvider.withValidConnection(binding.getConnectionId(), serverApi -> + connectionManager.withValidConnection(binding.getConnectionId(), serverApi -> downloadServerIssuesForProject(binding.getConnectionId(), serverApi, binding.getSonarProjectKey(), activeBranch, cancelMonitor)); } @@ -78,7 +78,7 @@ private void downloadServerIssuesForProject(String connectionId, ServerApi serve } public void fetchFileIssues(Binding binding, Path serverFileRelativePath, String activeBranch, SonarLintCancelMonitor cancelMonitor) { - serverApiProvider.withValidConnection(binding.getConnectionId(), serverApi -> + connectionManager.withValidConnection(binding.getConnectionId(), serverApi -> downloadServerIssuesForFile(binding.getConnectionId(), serverApi, binding.getSonarProjectKey(), serverFileRelativePath, activeBranch, cancelMonitor)); } diff --git a/backend/core/src/main/java/org/sonarsource/sonarlint/core/sync/SonarProjectBranchesSynchronizationService.java b/backend/core/src/main/java/org/sonarsource/sonarlint/core/sync/SonarProjectBranchesSynchronizationService.java index 2177630f53..90b17e9cd5 100644 --- a/backend/core/src/main/java/org/sonarsource/sonarlint/core/sync/SonarProjectBranchesSynchronizationService.java +++ b/backend/core/src/main/java/org/sonarsource/sonarlint/core/sync/SonarProjectBranchesSynchronizationService.java @@ -22,7 +22,7 @@ import java.util.Optional; import javax.inject.Named; import javax.inject.Singleton; -import org.sonarsource.sonarlint.core.ServerApiProvider; +import org.sonarsource.sonarlint.core.ConnectionManager; import org.sonarsource.sonarlint.core.commons.Binding; import org.sonarsource.sonarlint.core.commons.log.SonarLintLogger; import org.sonarsource.sonarlint.core.commons.progress.SonarLintCancelMonitor; @@ -42,17 +42,17 @@ public class SonarProjectBranchesSynchronizationService { private static final SonarLintLogger LOG = SonarLintLogger.get(); private final StorageService storageService; - private final ServerApiProvider serverApiProvider; + private final ConnectionManager connectionManager; private final ApplicationEventPublisher eventPublisher; - public SonarProjectBranchesSynchronizationService(StorageService storageService, ServerApiProvider serverApiProvider, ApplicationEventPublisher eventPublisher) { + public SonarProjectBranchesSynchronizationService(StorageService storageService, ConnectionManager connectionManager, ApplicationEventPublisher eventPublisher) { this.storageService = storageService; - this.serverApiProvider = serverApiProvider; + this.connectionManager = connectionManager; this.eventPublisher = eventPublisher; } public void sync(String connectionId, String sonarProjectKey, SonarLintCancelMonitor cancelMonitor) { - serverApiProvider.withValidConnection(connectionId, serverApi -> { + connectionManager.withValidConnection(connectionId, serverApi -> { var branchesStorage = storageService.getStorageFacade().connection(connectionId).project(sonarProjectKey).branches(); Optional oldBranches = Optional.empty(); if (branchesStorage.exists()) { @@ -81,7 +81,7 @@ public String findMainBranch(String connectionId, String projectKey, SonarLintCa var storedBranches = branchesStorage.read(); return storedBranches.getMainBranchName(); } else { - return serverApiProvider.withValidConnectionAndReturn(connectionId, + return connectionManager.withValidConnectionAndReturn(connectionId, serverApi -> getProjectBranches(serverApi, projectKey, cancelMonitor)) .map(ProjectBranches::getMainBranchName).orElseThrow(); } diff --git a/backend/core/src/main/java/org/sonarsource/sonarlint/core/sync/SynchronizationService.java b/backend/core/src/main/java/org/sonarsource/sonarlint/core/sync/SynchronizationService.java index beacfc13a4..ae8ed7dc3a 100644 --- a/backend/core/src/main/java/org/sonarsource/sonarlint/core/sync/SynchronizationService.java +++ b/backend/core/src/main/java/org/sonarsource/sonarlint/core/sync/SynchronizationService.java @@ -39,7 +39,7 @@ import javax.annotation.PreDestroy; import javax.inject.Named; import javax.inject.Singleton; -import org.sonarsource.sonarlint.core.ServerApiProvider; +import org.sonarsource.sonarlint.core.ConnectionManager; import org.sonarsource.sonarlint.core.branch.MatchedSonarProjectBranchChangedEvent; import org.sonarsource.sonarlint.core.branch.SonarProjectBranchTrackingService; import org.sonarsource.sonarlint.core.commons.Binding; @@ -86,7 +86,7 @@ public class SynchronizationService { private final SonarLintRpcClient client; private final ConfigurationRepository configurationRepository; private final LanguageSupportRepository languageSupportRepository; - private final ServerApiProvider serverApiProvider; + private final ConnectionManager connectionManager; private final TaskManager taskManager; private final StorageService storageService; private final Set connectedModeEmbeddedPluginKeys; @@ -107,14 +107,14 @@ public class SynchronizationService { private final Set ignoreBranchEventForScopes = ConcurrentHashMap.newKeySet(); public SynchronizationService(SonarLintRpcClient client, ConfigurationRepository configurationRepository, LanguageSupportRepository languageSupportRepository, - ServerApiProvider serverApiProvider, StorageService storageService, InitializeParams params, TaintSynchronizationService taintSynchronizationService, + ConnectionManager connectionManager, StorageService storageService, InitializeParams params, TaintSynchronizationService taintSynchronizationService, IssueSynchronizationService issueSynchronizationService, HotspotSynchronizationService hotspotSynchronizationService, SonarProjectBranchesSynchronizationService sonarProjectBranchesSynchronizationService, SonarProjectBranchTrackingService sonarProjectBranchTrackingService, PluginsRepository pluginsRepository, ApplicationEventPublisher applicationEventPublisher) { this.client = client; this.configurationRepository = configurationRepository; this.languageSupportRepository = languageSupportRepository; - this.serverApiProvider = serverApiProvider; + this.connectionManager = connectionManager; this.taskManager = new TaskManager(client); this.storageService = storageService; this.connectedModeEmbeddedPluginKeys = params.getConnectedModeEmbeddedPluginPathsByKey().keySet(); @@ -184,7 +184,7 @@ private void synchronizeProjectsOfTheSameConnection(String connectionId, Map { + connectionManager.withValidConnection(connectionId, serverApi -> { var subProgressGap = progressGap / boundScopeBySonarProject.size(); var subProgress = progress; for (var entry : boundScopeBySonarProject.entrySet()) { @@ -296,7 +296,7 @@ public void onConnectionCredentialsChanged(ConnectionCredentialsChangedEvent eve private void synchronizeConnectionAndProjectsIfNeededAsync(String connectionId, Collection boundScopes) { var cancelMonitor = new SonarLintCancelMonitor(); cancelMonitor.watchForShutdown(scheduledSynchronizer); - scheduledSynchronizer.submit(() -> serverApiProvider.withValidConnection(connectionId, serverApi -> + scheduledSynchronizer.submit(() -> connectionManager.withValidConnection(connectionId, serverApi -> synchronizeConnectionAndProjectsIfNeededSync(connectionId, serverApi, boundScopes, cancelMonitor))); } diff --git a/backend/core/src/main/java/org/sonarsource/sonarlint/core/sync/TaintSynchronizationService.java b/backend/core/src/main/java/org/sonarsource/sonarlint/core/sync/TaintSynchronizationService.java index 4a82bb1d79..e63b129441 100644 --- a/backend/core/src/main/java/org/sonarsource/sonarlint/core/sync/TaintSynchronizationService.java +++ b/backend/core/src/main/java/org/sonarsource/sonarlint/core/sync/TaintSynchronizationService.java @@ -23,7 +23,7 @@ import java.util.stream.Collectors; import javax.inject.Named; import javax.inject.Singleton; -import org.sonarsource.sonarlint.core.ServerApiProvider; +import org.sonarsource.sonarlint.core.ConnectionManager; import org.sonarsource.sonarlint.core.branch.SonarProjectBranchTrackingService; import org.sonarsource.sonarlint.core.commons.api.SonarLanguage; import org.sonarsource.sonarlint.core.commons.log.SonarLintLogger; @@ -51,22 +51,22 @@ public class TaintSynchronizationService { private final SonarProjectBranchTrackingService branchTrackingService; private final StorageService storageService; private final LanguageSupportRepository languageSupportRepository; - private final ServerApiProvider serverApiProvider; + private final ConnectionManager connectionManager; private final ApplicationEventPublisher eventPublisher; public TaintSynchronizationService(ConfigurationRepository configurationRepository, SonarProjectBranchTrackingService branchTrackingService, - StorageService storageService, LanguageSupportRepository languageSupportRepository, - ServerApiProvider serverApiProvider, ApplicationEventPublisher eventPublisher) { + StorageService storageService, LanguageSupportRepository languageSupportRepository, + ConnectionManager connectionManager, ApplicationEventPublisher eventPublisher) { this.configurationRepository = configurationRepository; this.branchTrackingService = branchTrackingService; this.storageService = storageService; this.languageSupportRepository = languageSupportRepository; - this.serverApiProvider = serverApiProvider; + this.connectionManager = connectionManager; this.eventPublisher = eventPublisher; } public void synchronizeTaintVulnerabilities(String connectionId, String projectKey, SonarLintCancelMonitor cancelMonitor) { - serverApiProvider.withValidConnection(connectionId, serverApi -> { + connectionManager.withValidConnection(connectionId, serverApi -> { var allScopes = configurationRepository.getBoundScopesToConnectionAndSonarProject(connectionId, projectKey); var allScopesByOptBranch = allScopes.stream() .collect(groupingBy(b -> branchTrackingService.awaitEffectiveSonarProjectBranch(b.getConfigScopeId()))); diff --git a/backend/core/src/main/java/org/sonarsource/sonarlint/core/usertoken/UserTokenService.java b/backend/core/src/main/java/org/sonarsource/sonarlint/core/usertoken/UserTokenService.java index b957d2c4d6..34d0c77d8a 100644 --- a/backend/core/src/main/java/org/sonarsource/sonarlint/core/usertoken/UserTokenService.java +++ b/backend/core/src/main/java/org/sonarsource/sonarlint/core/usertoken/UserTokenService.java @@ -21,7 +21,7 @@ import javax.inject.Named; import javax.inject.Singleton; -import org.sonarsource.sonarlint.core.ServerApiProvider; +import org.sonarsource.sonarlint.core.ConnectionManager; import org.sonarsource.sonarlint.core.commons.log.SonarLintLogger; import org.sonarsource.sonarlint.core.commons.progress.SonarLintCancelMonitor; import org.sonarsource.sonarlint.core.rpc.protocol.backend.connection.auth.RevokeTokenParams; @@ -32,15 +32,15 @@ public class UserTokenService { private static final SonarLintLogger LOG = SonarLintLogger.get(); - private final ServerApiProvider serverApiProvider; + private final ConnectionManager connectionManager; - public UserTokenService(ServerApiProvider serverApiProvider) { - this.serverApiProvider = serverApiProvider; + public UserTokenService(ConnectionManager connectionManager) { + this.connectionManager = connectionManager; } public void revokeToken(RevokeTokenParams params, SonarLintCancelMonitor cancelMonitor) { LOG.debug(String.format("Revoking token '%s'", params.getTokenName())); - serverApiProvider.getServerApi(params.getBaseUrl(), null, params.getTokenValue()) + connectionManager.getServerApi(params.getBaseUrl(), null, params.getTokenValue()) .userTokens() .revoke(params.getTokenName(), cancelMonitor); } diff --git a/backend/core/src/test/java/org/sonarsource/sonarlint/core/ServerApiProviderTests.java b/backend/core/src/test/java/org/sonarsource/sonarlint/core/ConnectionManagerTests.java similarity index 85% rename from backend/core/src/test/java/org/sonarsource/sonarlint/core/ServerApiProviderTests.java rename to backend/core/src/test/java/org/sonarsource/sonarlint/core/ConnectionManagerTests.java index 792c4e2c2a..6fb9315331 100644 --- a/backend/core/src/test/java/org/sonarsource/sonarlint/core/ServerApiProviderTests.java +++ b/backend/core/src/test/java/org/sonarsource/sonarlint/core/ConnectionManagerTests.java @@ -25,6 +25,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.sonarsource.sonarlint.core.commons.log.SonarLintLogTester; +import org.sonarsource.sonarlint.core.connection.ServerConnection; import org.sonarsource.sonarlint.core.http.ConnectionAwareHttpClientProvider; import org.sonarsource.sonarlint.core.http.HttpClient; import org.sonarsource.sonarlint.core.http.HttpClientProvider; @@ -32,12 +33,16 @@ import org.sonarsource.sonarlint.core.repository.connection.SonarCloudConnectionConfiguration; import org.sonarsource.sonarlint.core.rpc.protocol.SonarLintRpcClient; import org.sonarsource.sonarlint.core.serverapi.EndpointParams; +import org.sonarsource.sonarlint.core.serverapi.ServerApi; +import org.sonarsource.sonarlint.core.serverapi.exception.ForbiddenException; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; -class ServerApiProviderTests { +class ConnectionManagerTests { @RegisterExtension private static final SonarLintLogTester logTester = new SonarLintLogTester(); @@ -45,7 +50,7 @@ class ServerApiProviderTests { private final ConnectionAwareHttpClientProvider awareHttpClientProvider = mock(ConnectionAwareHttpClientProvider.class); private final HttpClientProvider httpClientProvider = mock(HttpClientProvider.class); private final SonarLintRpcClient client = mock(SonarLintRpcClient.class); - private final ServerApiProvider underTest = new ServerApiProvider(connectionRepository, awareHttpClientProvider, httpClientProvider, + private final ConnectionManager underTest = new ConnectionManager(connectionRepository, awareHttpClientProvider, httpClientProvider, SonarCloudActiveEnvironment.prod(), client); @Test @@ -136,4 +141,22 @@ void getServerApi_returns_empty_if_client_cant_provide_httpclient() { assertThat(serverApi).isEmpty(); } + + @Test + void should_log_invalid_connection() { + var connectionId = "connectionId"; + ConnectionManager spy = spy(underTest); + var serverApi = mock(ServerApi.class); + var serverConnection = new ServerConnection(connectionId, serverApi, client); + doReturn(Optional.of(serverConnection)).when(spy).tryGetConnection(connectionId); + + // switch connection to invalid state + spy.withValidConnection(connectionId, api -> { + throw new ForbiddenException("401"); + }); + // attempt to get connection + spy.withValidConnection(connectionId, api -> {}); + + assertThat(logTester.logs()).contains("Connection 'connectionId' is invalid"); + } } diff --git a/backend/core/src/test/java/org/sonarsource/sonarlint/core/SonarProjectsCacheTests.java b/backend/core/src/test/java/org/sonarsource/sonarlint/core/SonarProjectsCacheTests.java index a98271aeb6..82b505a069 100644 --- a/backend/core/src/test/java/org/sonarsource/sonarlint/core/SonarProjectsCacheTests.java +++ b/backend/core/src/test/java/org/sonarsource/sonarlint/core/SonarProjectsCacheTests.java @@ -85,15 +85,15 @@ public String getName() { return PROJECT_NAME_2; } }; - private final ServerApiProvider serverApiProvider = mockServerApiProvider(); + private final ConnectionManager connectionManager = mockServerApiProvider(); private final ServerApi serverApi = mock(ServerApi.class, Mockito.RETURNS_DEEP_STUBS); - private final SonarProjectsCache underTest = new SonarProjectsCache(serverApiProvider); + private final SonarProjectsCache underTest = new SonarProjectsCache(connectionManager); @BeforeEach public void setup() { - doReturn(Optional.of(serverApi)).when(serverApiProvider).getServerApi(SQ_1); + doReturn(Optional.of(serverApi)).when(connectionManager).getServerApi(SQ_1); var serverConnection = new ServerConnection(SQ_1, serverApi, null); - doReturn(Optional.of(serverConnection)).when(serverApiProvider).tryGetConnection(SQ_1); + doReturn(Optional.of(serverConnection)).when(connectionManager).tryGetConnection(SQ_1); } @Test diff --git a/backend/core/src/test/java/org/sonarsource/sonarlint/core/VersionSoonUnsupportedHelperTests.java b/backend/core/src/test/java/org/sonarsource/sonarlint/core/VersionSoonUnsupportedHelperTests.java index 62b7a70339..70c0e57485 100644 --- a/backend/core/src/test/java/org/sonarsource/sonarlint/core/VersionSoonUnsupportedHelperTests.java +++ b/backend/core/src/test/java/org/sonarsource/sonarlint/core/VersionSoonUnsupportedHelperTests.java @@ -66,7 +66,7 @@ class VersionSoonUnsupportedHelperTests { private static final SonarCloudConnectionConfiguration SC_CONNECTION = new SonarCloudConnectionConfiguration(SonarCloudActiveEnvironment.PRODUCTION_URI, SC_CONNECTION_ID, "https://sonarcloud.com", true); private final SonarLintRpcClient client = mock(SonarLintRpcClient.class); - private final ServerApiProvider serverApiProvider = mock(ServerApiProvider.class); + private final ConnectionManager connectionManager = mock(ConnectionManager.class); private final SynchronizationService synchronizationService = mock(SynchronizationService.class); private ConfigurationRepository configRepository; @@ -77,7 +77,7 @@ class VersionSoonUnsupportedHelperTests { void init() { configRepository = new ConfigurationRepository(); connectionRepository = new ConnectionConfigurationRepository(); - underTest = new VersionSoonUnsupportedHelper(client, configRepository, serverApiProvider, connectionRepository, synchronizationService); + underTest = new VersionSoonUnsupportedHelper(client, configRepository, connectionManager, connectionRepository, synchronizationService); } @Test @@ -87,7 +87,7 @@ void should_trigger_notification_when_new_binding_to_previous_lts_detected_on_co configRepository.addOrReplace(new ConfigurationScope(CONFIG_SCOPE_ID_2, null, false, ""), bindingConfiguration); connectionRepository.addOrReplace(SQ_CONNECTION); var serverApi = mock(ServerApi.class); - when(serverApiProvider.tryGetConnection(SQ_CONNECTION_ID)).thenReturn(Optional.of(new ServerConnection(SQ_CONNECTION_ID, serverApi, null))); + when(connectionManager.tryGetConnection(SQ_CONNECTION_ID)).thenReturn(Optional.of(new ServerConnection(SQ_CONNECTION_ID, serverApi, null))); when(synchronizationService.readOrSynchronizeServerVersion(eq(SQ_CONNECTION_ID), eq(serverApi), any(SonarLintCancelMonitor.class))).thenReturn(VersionUtils.getMinimalSupportedVersion()); @@ -107,8 +107,8 @@ void should_trigger_multiple_notification_when_new_bindings_to_previous_lts_dete connectionRepository.addOrReplace(SQ_CONNECTION_2); var serverApi = mock(ServerApi.class); var serverApi2 = mock(ServerApi.class); - when(serverApiProvider.tryGetConnection(SQ_CONNECTION_ID)).thenReturn(Optional.of(new ServerConnection(SQ_CONNECTION_ID, serverApi, null))); - when(serverApiProvider.tryGetConnection(CONFIG_SCOPE_ID_2)).thenReturn(Optional.of(new ServerConnection(CONFIG_SCOPE_ID_2, serverApi2, null))); + when(connectionManager.tryGetConnection(SQ_CONNECTION_ID)).thenReturn(Optional.of(new ServerConnection(SQ_CONNECTION_ID, serverApi, null))); + when(connectionManager.tryGetConnection(CONFIG_SCOPE_ID_2)).thenReturn(Optional.of(new ServerConnection(CONFIG_SCOPE_ID_2, serverApi2, null))); when(synchronizationService.readOrSynchronizeServerVersion(eq(SQ_CONNECTION_ID), eq(serverApi), any(SonarLintCancelMonitor.class))).thenReturn(VersionUtils.getMinimalSupportedVersion()); when(synchronizationService.readOrSynchronizeServerVersion(eq(SQ_CONNECTION_ID_2), eq(serverApi2), any(SonarLintCancelMonitor.class))).thenReturn(Version.create(VersionUtils.getMinimalSupportedVersion() + ".9")); @@ -132,7 +132,7 @@ void should_not_trigger_notification_when_config_scope_has_no_effective_binding( void should_trigger_notification_when_new_binding_to_previous_lts_detected() { connectionRepository.addOrReplace(SQ_CONNECTION); var serverApi = mock(ServerApi.class); - when(serverApiProvider.tryGetConnection(SQ_CONNECTION_ID)).thenReturn(Optional.of(new ServerConnection(SQ_CONNECTION_ID, serverApi, null))); + when(connectionManager.tryGetConnection(SQ_CONNECTION_ID)).thenReturn(Optional.of(new ServerConnection(SQ_CONNECTION_ID, serverApi, null))); when(synchronizationService.readOrSynchronizeServerVersion(eq(SQ_CONNECTION_ID), eq(serverApi), any(SonarLintCancelMonitor.class))) .thenReturn(VersionUtils.getMinimalSupportedVersion()); @@ -147,7 +147,7 @@ void should_trigger_notification_when_new_binding_to_previous_lts_detected() { void should_trigger_once_when_same_binding_to_previous_lts_detected_twice() { connectionRepository.addOrReplace(SQ_CONNECTION); var serverApi = mock(ServerApi.class); - when(serverApiProvider.tryGetConnection(SQ_CONNECTION_ID)).thenReturn(Optional.of(new ServerConnection(SQ_CONNECTION_ID, serverApi, null))); + when(connectionManager.tryGetConnection(SQ_CONNECTION_ID)).thenReturn(Optional.of(new ServerConnection(SQ_CONNECTION_ID, serverApi, null))); when(synchronizationService.readOrSynchronizeServerVersion(eq(SQ_CONNECTION_ID), eq(serverApi), any(SonarLintCancelMonitor.class))).thenReturn(VersionUtils.getMinimalSupportedVersion()); underTest.bindingConfigChanged(new BindingConfigChangedEvent(CONFIG_SCOPE_ID, null, @@ -163,7 +163,7 @@ void should_trigger_once_when_same_binding_to_previous_lts_detected_twice() { void should_trigger_notification_when_new_binding_to_in_between_lts_detected() { connectionRepository.addOrReplace(SQ_CONNECTION); var serverApi = mock(ServerApi.class); - when(serverApiProvider.tryGetConnection(SQ_CONNECTION_ID)).thenReturn(Optional.of(new ServerConnection(SQ_CONNECTION_ID, serverApi, null))); + when(connectionManager.tryGetConnection(SQ_CONNECTION_ID)).thenReturn(Optional.of(new ServerConnection(SQ_CONNECTION_ID, serverApi, null))); when(synchronizationService.readOrSynchronizeServerVersion(eq(SQ_CONNECTION_ID), eq(serverApi), any(SonarLintCancelMonitor.class))).thenReturn(Version.create(VersionUtils.getMinimalSupportedVersion().getName() + ".9")); underTest.bindingConfigChanged(new BindingConfigChangedEvent(CONFIG_SCOPE_ID, null, @@ -177,7 +177,7 @@ void should_trigger_notification_when_new_binding_to_in_between_lts_detected() { void should_not_trigger_notification_when_new_binding_to_current_lts_detected() { connectionRepository.addOrReplace(SQ_CONNECTION); var serverApi = mock(ServerApi.class); - when(serverApiProvider.tryGetConnection(SQ_CONNECTION_ID)).thenReturn(Optional.of(new ServerConnection(SQ_CONNECTION_ID, serverApi, null))); + when(connectionManager.tryGetConnection(SQ_CONNECTION_ID)).thenReturn(Optional.of(new ServerConnection(SQ_CONNECTION_ID, serverApi, null))); when(synchronizationService.readOrSynchronizeServerVersion(eq(SQ_CONNECTION_ID), eq(serverApi), any(SonarLintCancelMonitor.class))).thenReturn(VersionUtils.getCurrentLts()); underTest.bindingConfigChanged(new BindingConfigChangedEvent(CONFIG_SCOPE_ID, null, diff --git a/backend/core/src/test/java/org/sonarsource/sonarlint/core/file/ServerFilePathsProviderTest.java b/backend/core/src/test/java/org/sonarsource/sonarlint/core/file/ServerFilePathsProviderTest.java index ffb12b01cd..8373a4ed2b 100644 --- a/backend/core/src/test/java/org/sonarsource/sonarlint/core/file/ServerFilePathsProviderTest.java +++ b/backend/core/src/test/java/org/sonarsource/sonarlint/core/file/ServerFilePathsProviderTest.java @@ -37,7 +37,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.api.io.TempDir; -import org.sonarsource.sonarlint.core.ServerApiProvider; +import org.sonarsource.sonarlint.core.ConnectionManager; import org.sonarsource.sonarlint.core.commons.Binding; import org.sonarsource.sonarlint.core.commons.log.SonarLintLogTester; import org.sonarsource.sonarlint.core.commons.progress.SonarLintCancelMonitor; @@ -64,7 +64,7 @@ class ServerFilePathsProviderTest { public static final String PROJECT_KEY = "projectKey"; private Path cacheDirectory; - private final ServerApiProvider serverApiProvider = mockServerApiProvider(); + private final ConnectionManager connectionManager = mockServerApiProvider(); private final ServerApi serverApi_A = mock(ServerApi.class); private final ServerApi serverApi_B = mock(ServerApi.class); private final SonarLintCancelMonitor cancelMonitor =mock(SonarLintCancelMonitor.class); @@ -77,20 +77,18 @@ void before(@TempDir Path storageDir) throws IOException { cacheDirectory = storageDir.resolve("cache"); Files.createDirectories(cacheDirectory); - when(serverApiProvider.getServerApi(CONNECTION_A)).thenReturn(Optional.of(serverApi_A)); - when(serverApiProvider.getServerApi(CONNECTION_B)).thenReturn(Optional.of(serverApi_B)); + when(connectionManager.getServerApi(CONNECTION_A)).thenReturn(Optional.of(serverApi_A)); + when(connectionManager.getServerApi(CONNECTION_B)).thenReturn(Optional.of(serverApi_B)); var serverConnectionA = new ServerConnection(CONNECTION_A, serverApi_A, null); var serverConnectionB = new ServerConnection(CONNECTION_B, serverApi_B, null); - doReturn(Optional.of(serverConnectionA)).when(serverApiProvider).getValidConnection(CONNECTION_A); - doReturn(Optional.of(serverConnectionB)).when(serverApiProvider).getValidConnection(CONNECTION_B); - doReturn(Optional.of(serverConnectionA)).when(serverApiProvider).tryGetConnection(CONNECTION_A); - doReturn(Optional.of(serverConnectionB)).when(serverApiProvider).tryGetConnection(CONNECTION_B); + doReturn(Optional.of(serverConnectionA)).when(connectionManager).tryGetConnection(CONNECTION_A); + doReturn(Optional.of(serverConnectionB)).when(connectionManager).tryGetConnection(CONNECTION_B); when(serverApi_A.component()).thenReturn(componentApi_A); when(serverApi_B.component()).thenReturn(componentApi_B); mockServerFilePaths(componentApi_A, "pathA", "pathB"); mockServerFilePaths(componentApi_B, "pathC", "pathD"); - underTest = new ServerFilePathsProvider(serverApiProvider, storageDir); + underTest = new ServerFilePathsProvider(connectionManager, storageDir); cacheDirectory = storageDir.resolve("cache"); } @@ -108,7 +106,7 @@ void clear_cache_directory_after_initialization(@TempDir Path storageDir) throws @Test void log_when_connection_not_exist() { - when(serverApiProvider.getServerApi(anyString())).thenReturn(Optional.empty()); + when(connectionManager.getServerApi(anyString())).thenReturn(Optional.empty()); underTest.getServerPaths(new Binding("conId", null), cancelMonitor); diff --git a/backend/core/src/test/java/testutils/TestUtils.java b/backend/core/src/test/java/testutils/TestUtils.java index 15efc5d74b..b98e4127ce 100644 --- a/backend/core/src/test/java/testutils/TestUtils.java +++ b/backend/core/src/test/java/testutils/TestUtils.java @@ -20,7 +20,7 @@ package testutils; import java.lang.management.ManagementFactory; -import org.sonarsource.sonarlint.core.ServerApiProvider; +import org.sonarsource.sonarlint.core.ConnectionManager; import org.sonarsource.sonarlint.core.SonarCloudActiveEnvironment; import org.sonarsource.sonarlint.core.http.ConnectionAwareHttpClientProvider; import org.sonarsource.sonarlint.core.http.HttpClientProvider; @@ -57,13 +57,13 @@ public static void printThreadDump() { System.out.println(generateThreadDump()); } - public static ServerApiProvider mockServerApiProvider() { + public static ConnectionManager mockServerApiProvider() { var connectionRepository = mock(ConnectionConfigurationRepository.class); var awareHttpClientProvider = mock(ConnectionAwareHttpClientProvider.class); var httpClientProvider = mock(HttpClientProvider.class); var sonarCloudActiveEnvironment = mock(SonarCloudActiveEnvironment.class); var client = mock(SonarLintRpcClient.class); - var obj = new ServerApiProvider(connectionRepository, awareHttpClientProvider, httpClientProvider, + var obj = new ConnectionManager(connectionRepository, awareHttpClientProvider, httpClientProvider, sonarCloudActiveEnvironment, client); return spy(obj); }