001/*
002 * Copyright 2009-2024 Ping Identity Corporation
003 * All Rights Reserved.
004 */
005/*
006 * Copyright 2009-2024 Ping Identity Corporation
007 *
008 * Licensed under the Apache License, Version 2.0 (the "License");
009 * you may not use this file except in compliance with the License.
010 * You may obtain a copy of the License at
011 *
012 *    http://www.apache.org/licenses/LICENSE-2.0
013 *
014 * Unless required by applicable law or agreed to in writing, software
015 * distributed under the License is distributed on an "AS IS" BASIS,
016 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
017 * See the License for the specific language governing permissions and
018 * limitations under the License.
019 */
020/*
021 * Copyright (C) 2009-2024 Ping Identity Corporation
022 *
023 * This program is free software; you can redistribute it and/or modify
024 * it under the terms of the GNU General Public License (GPLv2 only)
025 * or the terms of the GNU Lesser General Public License (LGPLv2.1 only)
026 * as published by the Free Software Foundation.
027 *
028 * This program is distributed in the hope that it will be useful,
029 * but WITHOUT ANY WARRANTY; without even the implied warranty of
030 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
031 * GNU General Public License for more details.
032 *
033 * You should have received a copy of the GNU General Public License
034 * along with this program; if not, see <http://www.gnu.org/licenses>.
035 */
036package com.unboundid.util;
037
038
039
040import java.io.Serializable;
041import java.util.ArrayList;
042import java.util.Collections;
043import java.util.List;
044import java.util.Map;
045import java.util.TreeMap;
046import java.util.concurrent.ConcurrentHashMap;
047import java.util.concurrent.atomic.AtomicLong;
048import java.util.concurrent.atomic.AtomicReference;
049
050import com.unboundid.ldap.sdk.ResultCode;
051
052
053
054/**
055 * This class provides a utility that may be used to count operation results and
056 * categorize them based on the total number of results of each type.  It also
057 * provides a method for retrieving result code counts, sorted by the number of
058 * occurrences for each.
059 */
060@Mutable()
061@ThreadSafety(level=ThreadSafetyLevel.COMPLETELY_THREADSAFE)
062public final class ResultCodeCounter
063       implements Serializable
064{
065  /**
066   * The serial version UID for this serializable class.
067   */
068  private static final long serialVersionUID = -2280620218815022241L;
069
070
071
072  // The reference to the current map used to hold result code counts.
073  @NotNull private final
074       AtomicReference<ConcurrentHashMap<ResultCode,AtomicLong>> rcMap;
075
076
077
078  /**
079   * Creates a new instance of this result code counter.
080   */
081  public ResultCodeCounter()
082  {
083    rcMap = new AtomicReference<>();
084    rcMap.set(new ConcurrentHashMap<ResultCode,AtomicLong>(
085         StaticUtils.computeMapCapacity(ResultCode.values().length)));
086  }
087
088
089
090  /**
091   * Increments the count for the provided result code.
092   *
093   * @param  resultCode  The result code for which to increment the count.
094   */
095  public void increment(@NotNull final ResultCode resultCode)
096  {
097    increment(resultCode, 1);
098  }
099
100
101
102  /**
103   * Increments the count for the provided result code by the specified amount.
104   *
105   * @param  resultCode  The result code for which to increment the count.
106   * @param  amount      The amount by which to increment the count.
107   */
108  public void increment(@NotNull final ResultCode resultCode, final int amount)
109  {
110    final ConcurrentHashMap<ResultCode,AtomicLong> m = rcMap.get();
111
112    AtomicLong l = m.get(resultCode);
113    if (l == null)
114    {
115      l = new AtomicLong(0L);
116      final AtomicLong l2 = m.putIfAbsent(resultCode, l);
117      if (l2 != null)
118      {
119        l = l2;
120      }
121    }
122
123    l.addAndGet(amount);
124  }
125
126
127
128  /**
129   * Clears all collected data from the result code counter.  Any
130   * previously-collected data will be lost.
131   */
132  public void reset()
133  {
134    rcMap.set(new ConcurrentHashMap<ResultCode,AtomicLong>(
135         StaticUtils.computeMapCapacity(ResultCode.values().length)));
136  }
137
138
139
140  /**
141   * Retrieves a list of the result codes of each type along with their
142   * respective counts.  The returned list will be sorted by number of
143   * occurrences, from most frequent to least frequent.
144   *
145   * @param  reset  Indicates whether to clear the results after obtaining
146   *                them.
147   *
148   * @return  A list of the result codes of each type along with their
149   *          respective counts.
150   */
151  @NotNull()
152  public List<ObjectPair<ResultCode,Long>> getCounts(final boolean reset)
153  {
154    final ConcurrentHashMap<ResultCode,AtomicLong> m;
155    if (reset)
156    {
157      m = rcMap.getAndSet(new ConcurrentHashMap<ResultCode,AtomicLong>(
158           StaticUtils.computeMapCapacity(ResultCode.values().length)));
159    }
160    else
161    {
162      m = new ConcurrentHashMap<>(rcMap.get());
163    }
164
165
166    if (m.isEmpty())
167    {
168      return Collections.emptyList();
169    }
170
171
172    final TreeMap<Long,TreeMap<Integer,ResultCode>> sortedMap =
173         new TreeMap<>(new ReverseComparator<Long>());
174    for (final Map.Entry<ResultCode,AtomicLong> e : m.entrySet())
175    {
176      final long l = e.getValue().longValue();
177      TreeMap<Integer,ResultCode> rcByValue = sortedMap.get(l);
178      if (rcByValue == null)
179      {
180        rcByValue = new TreeMap<>();
181        sortedMap.put(l, rcByValue);
182      }
183
184      final ResultCode rc = e.getKey();
185      rcByValue.put(rc.intValue(), rc);
186    }
187
188
189    final ArrayList<ObjectPair<ResultCode,Long>> rcCounts =
190         new ArrayList<>(2*sortedMap.size());
191    for (final Map.Entry<Long,TreeMap<Integer,ResultCode>> e :
192         sortedMap.entrySet())
193    {
194      final long count = e.getKey();
195      for (final ResultCode rc : e.getValue().values())
196      {
197        rcCounts.add(new ObjectPair<>(rc, count));
198      }
199    }
200
201    return Collections.unmodifiableList(rcCounts);
202  }
203}