001/*
002 * Copyright 2009-2020 Ping Identity Corporation
003 * All Rights Reserved.
004 */
005/*
006 * Copyright 2009-2020 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-2020 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  private final AtomicReference<ConcurrentHashMap<ResultCode,AtomicLong>> rcMap;
074
075
076
077  /**
078   * Creates a new instance of this result code counter.
079   */
080  public ResultCodeCounter()
081  {
082    rcMap = new AtomicReference<>();
083    rcMap.set(new ConcurrentHashMap<ResultCode,AtomicLong>(
084         StaticUtils.computeMapCapacity(ResultCode.values().length)));
085  }
086
087
088
089  /**
090   * Increments the count for the provided result code.
091   *
092   * @param  resultCode  The result code for which to increment the count.
093   */
094  public void increment(final ResultCode resultCode)
095  {
096    increment(resultCode, 1);
097  }
098
099
100
101  /**
102   * Increments the count for the provided result code by the specified amount.
103   *
104   * @param  resultCode  The result code for which to increment the count.
105   * @param  amount      The amount by which to increment the count.
106   */
107  public void increment(final ResultCode resultCode, final int amount)
108  {
109    final ConcurrentHashMap<ResultCode,AtomicLong> m = rcMap.get();
110
111    AtomicLong l = m.get(resultCode);
112    if (l == null)
113    {
114      l = new AtomicLong(0L);
115      final AtomicLong l2 = m.putIfAbsent(resultCode, l);
116      if (l2 != null)
117      {
118        l = l2;
119      }
120    }
121
122    l.addAndGet(amount);
123  }
124
125
126
127  /**
128   * Clears all collected data from the result code counter.  Any
129   * previously-collected data will be lost.
130   */
131  public void reset()
132  {
133    rcMap.set(new ConcurrentHashMap<ResultCode,AtomicLong>(
134         StaticUtils.computeMapCapacity(ResultCode.values().length)));
135  }
136
137
138
139  /**
140   * Retrieves a list of the result codes of each type along with their
141   * respective counts.  The returned list will be sorted by number of
142   * occurrences, from most frequent to least frequent.
143   *
144   * @param  reset  Indicates whether to clear the results after obtaining
145   *                them.
146   *
147   * @return  A list of the result codes of each type along with their
148   *          respective counts.
149   */
150  public List<ObjectPair<ResultCode,Long>> getCounts(final boolean reset)
151  {
152    final ConcurrentHashMap<ResultCode,AtomicLong> m;
153    if (reset)
154    {
155      m = rcMap.getAndSet(new ConcurrentHashMap<ResultCode,AtomicLong>(
156           StaticUtils.computeMapCapacity(ResultCode.values().length)));
157    }
158    else
159    {
160      m = new ConcurrentHashMap<>(rcMap.get());
161    }
162
163
164    if (m.isEmpty())
165    {
166      return Collections.emptyList();
167    }
168
169
170    final TreeMap<Long,TreeMap<Integer,ResultCode>> sortedMap =
171         new TreeMap<>(new ReverseComparator<Long>());
172    for (final Map.Entry<ResultCode,AtomicLong> e : m.entrySet())
173    {
174      final long l = e.getValue().longValue();
175      TreeMap<Integer,ResultCode> rcByValue = sortedMap.get(l);
176      if (rcByValue == null)
177      {
178        rcByValue = new TreeMap<>();
179        sortedMap.put(l, rcByValue);
180      }
181
182      final ResultCode rc = e.getKey();
183      rcByValue.put(rc.intValue(), rc);
184    }
185
186
187    final ArrayList<ObjectPair<ResultCode,Long>> rcCounts =
188         new ArrayList<>(2*sortedMap.size());
189    for (final Map.Entry<Long,TreeMap<Integer,ResultCode>> e :
190         sortedMap.entrySet())
191    {
192      final long count = e.getKey();
193      for (final ResultCode rc : e.getValue().values())
194      {
195        rcCounts.add(new ObjectPair<>(rc, count));
196      }
197    }
198
199    return Collections.unmodifiableList(rcCounts);
200  }
201}