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.counter;
22 import java.util.Optional;
23 import javax.annotation.CheckForNull;
24 import javax.annotation.Nullable;
25 import org.sonar.ce.task.projectanalysis.formula.CounterInitializationContext;
26 import org.sonar.ce.task.projectanalysis.measure.Measure;
28 import static java.util.Objects.requireNonNull;
31 * Simple counter that do the sum of an integer measure
33 public class IntSumCounter implements SumCounter<Integer, IntSumCounter> {
35 private final String metricKey;
37 private final Integer defaultInputValue;
39 private int value = 0;
40 private boolean initialized = false;
42 public IntSumCounter(String metricKey) {
43 this(metricKey, null);
46 public IntSumCounter(String metricKey, @Nullable Integer defaultInputValue) {
47 this.metricKey = requireNonNull(metricKey, "metricKey can not be null");
48 this.defaultInputValue = defaultInputValue;
52 public void aggregate(IntSumCounter counter) {
53 if (counter.getValue().isPresent()) {
54 addValue(counter.getValue().get());
59 public void initialize(CounterInitializationContext context) {
60 Optional<Measure> measureOptional = context.getMeasure(metricKey);
61 if (measureOptional.isPresent()) {
62 addValue(measureOptional.get().getIntValue());
63 } else if (defaultInputValue != null) {
64 addValue(defaultInputValue);
68 private void addValue(int newValue) {
74 public Optional<Integer> getValue() {
76 return Optional.of(value);
78 return Optional.empty();