3 * Copyright (C) 2009-2021 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.ce.task.projectanalysis.metric;
22 import java.util.List;
24 import java.util.Optional;
25 import java.util.stream.Collectors;
26 import javax.annotation.CheckForNull;
27 import org.picocontainer.Startable;
28 import org.sonar.db.DbClient;
29 import org.sonar.db.DbSession;
30 import org.sonar.db.metric.MetricDto;
32 import static java.util.Objects.requireNonNull;
34 public class MetricRepositoryImpl implements MetricRepository, Startable {
36 private final DbClient dbClient;
38 private Map<String, Metric> metricsByKey;
40 private Map<String, Metric> metricsByUuid;
42 public MetricRepositoryImpl(DbClient dbClient) {
43 this.dbClient = dbClient;
48 try (DbSession dbSession = dbClient.openSession(false)) {
49 List<MetricDto> metricList = dbClient.metricDao().selectEnabled(dbSession);
50 this.metricsByKey = metricList.stream().map(MetricDtoToMetric.INSTANCE).collect(Collectors.toMap(Metric::getKey, x -> x));
51 this.metricsByUuid = metricList.stream().map(MetricDtoToMetric.INSTANCE).collect(Collectors.toMap(Metric::getUuid, x -> x));
57 // nothing to do when stopping
61 public Metric getByKey(String key) {
63 verifyMetricsInitialized();
65 Metric res = this.metricsByKey.get(key);
67 throw new IllegalStateException(String.format("Metric with key '%s' does not exist", key));
73 public Metric getByUuid(String uuid) {
74 return getOptionalByUuid(uuid)
75 .orElseThrow(() -> new IllegalStateException(String.format("Metric with uuid '%s' does not exist", uuid)));
79 public Optional<Metric> getOptionalByUuid(String uuid) {
80 verifyMetricsInitialized();
82 return Optional.ofNullable(this.metricsByUuid.get(uuid));
86 public Iterable<Metric> getAll() {
87 return metricsByKey.values();
90 private void verifyMetricsInitialized() {
91 if (this.metricsByKey == null) {
92 throw new IllegalStateException("Metric cache has not been initialized");