blob: 7d3cfdc1d1559ff6194b8d4b5832646da8a2189c [file] [log] [blame]
Jonathan Hartc41227c2020-01-28 16:56:49 -08001/*
2 * Copyright 2018-present Open Networking Foundation
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.opencord.aaa;
18
19import com.google.common.base.MoreObjects;
20import com.google.common.collect.ImmutableMap;
21
22/**
23 * Immutable snapshot of AAA statistics.
24 */
25public class AaaStatisticsSnapshot {
26
27 private final ImmutableMap<String, Long> counters;
28
29 /**
30 * Gets the value of a counter.
31 *
32 * @param counterName name of the counter
33 * @return counter value, or 0 if it doesn't exist
34 */
35 public long get(String counterName) {
36 return counters.getOrDefault(counterName, 0L);
37 }
38
39 /**
40 * Creates a new empty snapshot with all counters initialized to 0.
41 */
42 public AaaStatisticsSnapshot() {
43 ImmutableMap.Builder<String, Long> builder = ImmutableMap.builder();
44
45 for (String name : AaaStatistics.COUNTER_NAMES) {
46 builder.put(name, 0L);
47 }
48
49 counters = builder.build();
50 }
51
52 /**
53 * Creates a new snapshot with the given counter values.
54 *
55 * @param counters counter values
56 */
57 public AaaStatisticsSnapshot(ImmutableMap<String, Long> counters) {
58 this.counters = counters;
59 }
60
61 /**
62 * Adds the given snapshot to this snapshot and returns a new snapshot with the aggregate values.
63 *
64 * @param other other snapshot to add to this one
65 * @return new aggregate snapshot
66 */
67 public AaaStatisticsSnapshot add(AaaStatisticsSnapshot other) {
68 ImmutableMap.Builder<String, Long> builder = ImmutableMap.builder();
69
70 counters.forEach((name, value) -> builder.put(name, value + other.counters.get(name)));
71
72 return new AaaStatisticsSnapshot(builder.build());
73 }
74
75 public String toString() {
76 MoreObjects.ToStringHelper helper = MoreObjects.toStringHelper(this.getClass());
77 counters.forEach(helper::add);
78 return helper.toString();
79 }
80
81}