3 * Copyright (C) 2009-2024 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.formula;
22 import java.util.Optional;
23 import org.sonar.ce.task.projectanalysis.measure.Measure;
24 import org.sonar.server.measure.ImpactMeasureBuilder;
26 import static java.util.Objects.requireNonNull;
28 public class ImpactSumFormula implements Formula<ImpactSumFormula.ImpactCounter> {
30 private final String metricKey;
33 private ImpactSumFormula(String metricKey) {
34 this.metricKey = requireNonNull(metricKey, "Metric key cannot be null");
38 public ImpactSumFormula.ImpactCounter createNewCounter() {
39 return new ImpactSumFormula.ImpactCounter();
42 public static ImpactSumFormula createImpactSumFormula(String metricKey) {
43 return new ImpactSumFormula(metricKey);
47 public Optional<Measure> createMeasure(ImpactCounter counter, CreateMeasureContext context) {
48 return counter.getValue().map(v -> Measure.newMeasureBuilder().create(v));
52 public String[] getOutputMetricKeys() {
53 return new String[]{metricKey};
56 class ImpactCounter implements Counter<ImpactSumFormula.ImpactCounter> {
58 private boolean initialized = false;
59 private boolean hasEmptyValue = false;
60 private final ImpactMeasureBuilder measureImpactBuilder = ImpactMeasureBuilder.createEmpty();
63 public void aggregate(ImpactSumFormula.ImpactCounter counter) {
64 Optional<String> value = counter.getValue();
65 if (value.isPresent()) {
67 measureImpactBuilder.add(ImpactMeasureBuilder.fromString(value.get()));
74 public void initialize(CounterInitializationContext context) {
75 Optional<Measure> measureOptional = context.getMeasure(metricKey);
76 String data = measureOptional.map(Measure::getData).orElse(null);
79 measureImpactBuilder.add(ImpactMeasureBuilder.fromString(data));
85 public Optional<String> getValue() {
86 if (initialized && !hasEmptyValue) {
87 return Optional.ofNullable(measureImpactBuilder.buildAsString());
89 return Optional.empty();