001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.rest.server.stats;
018
019import static org.apache.juneau.commons.utils.CollectionUtils.*;
020import static org.apache.juneau.commons.utils.Shorts.*;
021
022import java.time.*;
023import java.util.*;
024import java.util.concurrent.atomic.*;
025
026import org.apache.juneau.commons.bean.*;
027import org.apache.juneau.commons.collections.*;
028import org.apache.juneau.commons.inject.*;
029
030/**
031 * Represents an entry in {@link ThrownStore}.
032 *
033 * <p>
034 * The first message and stack trace are available to Java callers but are not part of the serialized bean, so
035 * statistics output carries only the class name, counts and timestamps.
036 *
037 * <h2 class='section'>See Also:</h2><ul>
038 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/ExecutionStatistics">REST method execution statistics</a>
039 * </ul>
040 */
041@SuppressWarnings({
042   "java:S1192" // Duplicated literals (argument/property names) read more clearly inline than as constants
043})
044public class ThrownStats {
045
046   /**
047    * Builder class.
048    */
049   public static class Builder {
050
051      final BeanStore beanStore;
052      Throwable throwable;
053      long hash;
054      List<String> stackTrace;
055      ThrownStats causedBy;
056      Clock clock = Clock.systemUTC();
057
058      private Class<? extends ThrownStats> implType;
059
060      /**
061       * Constructor.
062       *
063       * @param beanStore The bean store to use for creating beans.
064       */
065      protected Builder(BeanStore beanStore) {
066         this.beanStore = beanStore;
067      }
068
069      /**
070       * Create a new {@link ThrownStats} using this builder.
071       *
072       * @return A new {@link ThrownStats}
073       */
074      public ThrownStats build() {
075         var t = or(implType, ThrownStats.class);
076         return BeanInstantiator.of(ThrownStats.class, beanStore)
077            .type(t)
078            .noBuilder()
079            .addBean(Builder.class, this)
080            .run();
081      }
082
083      /**
084       * Specifies the caused-by exception.
085       *
086       * @param value The new value for this setting.
087       * @return This object.
088       */
089      public Builder causedBy(ThrownStats value) {
090         causedBy = value;
091         return this;
092      }
093
094      /**
095       * Specifies the clock used to stamp the first and last occurrence times.
096       *
097       * <p>
098       * Defaults to {@link Clock#systemUTC()}.  Tests can pass {@link Clock#fixed(Instant, ZoneId)} to make the
099       * reported occurrence times deterministic.
100       *
101       * @param value The new value for this setting.  Must not be <jk>null</jk>.
102       * @return This object.
103       */
104      public Builder clock(Clock value) {
105         clock = reqnn("value", value);
106         return this;
107      }
108
109      /**
110       * Specifies the calculated hash.
111       *
112       * @param value The new value for this setting.
113       * @return This object.
114       */
115      public Builder hash(long value) {
116         hash = value;
117         return this;
118      }
119
120      /**
121       * Specifies the normalized stacktrace.
122       *
123       * @param value The new value for this setting.
124       * @return This object.
125       */
126      public Builder stackTrace(List<String> value) {
127         stackTrace = value;
128         return this;
129      }
130
131      /**
132       * Specifies the thrown exception.
133       *
134       * @param value The new value for this setting.
135       * @return This object.
136       */
137      public Builder throwable(Throwable value) {
138         throwable = value;
139         return this;
140      }
141
142      /**
143       * Specifies a subclass of {@link ThrownStats} to create when the {@link #build()} method is called.
144       *
145       * @param value The new value for this setting. Can be <jk>null</jk> (defaults to {@link ThrownStats}).
146       * @return This object.
147       */
148      public Builder type(Class<? extends ThrownStats> value) {
149         implType = o(value).isPresent() ? value : ThrownStats.class;
150         return this;
151      }
152   }
153
154   /**
155    * Static creator.
156    *
157    * @param beanStore The bean store to use for creating beans.
158    * @return A new builder for this object.
159    */
160   public static Builder create(BeanStore beanStore) {
161      return new Builder(beanStore);
162   }
163
164   private final long guid;
165   private final long hash;
166   private final Class<?> thrownClass;
167   private final String firstMessage;
168   private final List<String> stackTrace;
169   private final Optional<ThrownStats> causedBy;
170
171   private final Clock clock;
172   private final AtomicInteger count;
173   private final AtomicLong firstOccurrence;
174   private final AtomicLong lastOccurrence;
175
176   /**
177    * Copy constructor.
178    */
179   private ThrownStats(ThrownStats x) {
180      this.guid = x.guid;
181      this.thrownClass = x.thrownClass;
182      this.firstMessage = x.firstMessage;
183      this.stackTrace = u(cp(x.stackTrace));
184      this.causedBy = o(ThrownStats.copyOrNull(x.causedBy.orElse(null)));
185      this.hash = x.hash;
186      this.clock = x.clock;
187      this.count = new AtomicInteger(x.count.get());
188      this.firstOccurrence = new AtomicLong(x.firstOccurrence.get());
189      this.lastOccurrence = new AtomicLong(x.lastOccurrence.get());
190   }
191
192   /**
193    * Null-safe copy: returns a deep copy of the specified value, or <jk>null</jk> if the value is <jk>null</jk>.
194    *
195    * @param value The value to copy.  Can be <jk>null</jk>, in which case <jk>null</jk> is returned.
196    * @return A copy of the value, or <jk>null</jk> if the value was <jk>null</jk>.
197    */
198   public static ThrownStats copyOrNull(ThrownStats value) {
199      return value == null ? null : new ThrownStats(value);
200   }
201
202   /**
203    * Constructor.
204    *
205    * @param builder The builder for this object. Must not be <jk>null</jk>.
206    */
207   protected ThrownStats(Builder builder) {
208      this.guid = new Random().nextLong();
209      this.thrownClass = builder.throwable.getClass();
210      this.firstMessage = builder.throwable.getMessage();
211      this.stackTrace = u(cp(builder.stackTrace));
212      this.causedBy = o(builder.causedBy);
213      this.hash = builder.hash;
214      this.clock = builder.clock;
215      this.count = new AtomicInteger(0);
216      long ct = clock.millis();
217      this.firstOccurrence = new AtomicLong(ct);
218      this.lastOccurrence = new AtomicLong(ct);
219   }
220
221
222   /**
223    * Returns the stats on the caused-by exception.
224    *
225    * @return The stats on the caused-by exception, never <jk>null</jk>.
226    */
227   public Optional<ThrownStats> getCausedBy() { return causedBy; }
228
229   /**
230    * Returns the number of times this exception occurred at a specific location in code.
231    *
232    * @return The number of times this exception occurred at a specific location in code.
233    */
234   public int getCount() { return count.intValue(); }
235
236   /**
237    * Returns the message of the first exception at a specific location in code.
238    *
239    * @return The message of the first exception at a specific location in code, or <jk>null</jk> if the exception had no message.
240    */
241   @BeanIgnore
242   public String getFirstMessage() { return firstMessage; }
243
244   /**
245    * Returns the UTC time of the first occurrence of this exception at a specific location in code.
246    *
247    * @return The UTC time of the first occurrence of this exception at a specific location in code.
248    */
249   public long getFirstOccurrence() { return firstOccurrence.longValue(); }
250
251   /**
252    * Returns a globally unique ID for this object.
253    *
254    * <p>
255    * A random long generated during the creation of this object.
256    * Allows this object to be differentiated from other similar objects in multi-node environments so that
257    * statistics can be reliably stored in a centralized location.
258    *
259    * @return The globally unique ID for this object.
260    */
261   public long getGuid() { return guid; }
262
263   /**
264    * Returns a hash of this exception that can typically be used to uniquely identify it.
265    *
266    * @return A hash of this exception.
267    */
268   public long getHash() { return hash; }
269
270   /**
271    * Returns the UTC time of the last occurrence of this exception at a specific location in code.
272    *
273    * @return The UTC time of the last occurrence of this exception at a specific location in code.
274    */
275   public long getLastOccurrence() { return lastOccurrence.longValue(); }
276
277   /**
278    * Returns the stack trace of the first exception at a specific location in code.
279    *
280    * @return The stack trace of the first exception at a specific location in code.
281    */
282   @BeanIgnore
283   public List<String> getStackTrace() { return stackTrace; }
284
285   /**
286    * Returns the exception class.
287    *
288    * @return The exception class.
289    */
290   public Class<?> getThrownClass() { return thrownClass; }
291
292   /**
293    * Increments the occurrence count of this exception.
294    *
295    * @return This object.
296    */
297   public ThrownStats increment() {
298      count.incrementAndGet();
299      lastOccurrence.set(clock.millis());
300      causedBy.ifPresent(ThrownStats::increment);
301      return this;
302   }
303
304   protected FluentMap<String,Object> properties() {
305      // @formatter:off
306      return filteredBeanPropertyMap()
307         .a("causedBy", causedBy.orElse(null))
308         .a("count", getCount())
309         .a("firstMessage", firstMessage)
310         .a("firstOccurrence", getFirstOccurrence())
311         .a("guid", guid)
312         .a("hash", hash)
313         .a("lastOccurrence", getLastOccurrence())
314         .a("stackTrace", stackTrace)
315         .a("thrownClass", thrownClass);
316      // @formatter:on
317   }
318
319   @Override /* Overridden from Object */
320   public String toString() {
321      return r(properties());
322   }
323}