3 * Copyright (C) 2009-2023 SonarSource SA
4 * mailto:info AT sonarsource DOT com
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 3 of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 package org.sonar.server.management;
22 import com.google.common.collect.MoreCollectors;
24 import java.util.Optional;
26 import javax.annotation.Priority;
27 import org.sonar.api.server.ServerSide;
28 import org.sonar.db.DbSession;
30 import static java.util.function.Function.identity;
31 import static java.util.stream.Collectors.toMap;
32 import static java.util.stream.Collectors.toSet;
33 import static org.sonar.api.utils.Preconditions.checkState;
36 @Priority(ManagedInstanceService.DELEGATING_INSTANCE_PRIORITY)
37 public class DelegatingManagedInstanceService implements ManagedInstanceService {
39 private final Set<ManagedInstanceService> delegates;
41 public DelegatingManagedInstanceService(Set<ManagedInstanceService> delegates) {
42 this.delegates = delegates;
45 public final boolean isInstanceExternallyManaged() {
46 return delegates.stream().anyMatch(ManagedInstanceService::isInstanceExternallyManaged);
50 public Map<String, Boolean> getUserUuidToManaged(DbSession dbSession, Set<String> userUuids) {
51 return findManagedInstanceService()
52 .map(managedInstanceService -> managedInstanceService.getUserUuidToManaged(dbSession, userUuids))
53 .orElse(returnNonManagedForAllGroups(userUuids));
57 public Map<String, Boolean> getGroupUuidToManaged(DbSession dbSession, Set<String> groupUuids) {
58 return findManagedInstanceService()
59 .map(managedInstanceService -> managedInstanceService.getGroupUuidToManaged(dbSession, groupUuids))
60 .orElse(returnNonManagedForAllGroups(groupUuids));
63 private Optional<ManagedInstanceService> findManagedInstanceService() {
64 Set<ManagedInstanceService> managedInstanceServices = delegates.stream()
65 .filter(ManagedInstanceService::isInstanceExternallyManaged)
68 checkState(managedInstanceServices.size() < 2,
69 "The instance can't be managed by more than one identity provider and %s were found.", managedInstanceServices.size());
70 return managedInstanceServices.stream().collect(MoreCollectors.toOptional());
73 private static Map<String, Boolean> returnNonManagedForAllGroups(Set<String> resourcesUuid) {
74 return resourcesUuid.stream().collect(toMap(identity(), any -> false));