View Javadoc
1   package org.djutils.logger;
2   
3   import java.util.Random;
4   
5   /**
6    * LogCategory for the CategoryLogger.
7    * <p>
8    * Copyright (c) 2018-2019 Delft University of Technology, Jaffalaan 5, 2628 BX Delft, the Netherlands. All rights reserved. See
9    * for project information <a href="https://djutils.org" target="_blank"> https://djutils.org</a>. The DJUTILS project is
10   * distributed under a three-clause BSD-style license, which can be found at
11   * <a href="https://djutils.org/docs/license.html" target="_blank"> https://djutils.org/docs/license.html</a>.
12   * </p>
13   */
14  public class LogCategory
15  {
16      /** The category name; can be blank. */
17      private final String name;
18  
19      /** Cached hashcode for very quick retrieval. */
20      private final int hashCode;
21  
22      /** Random number to generate fast hashCode. */
23      private static Random random = new Random(1L);
24  
25      /** The category to indicate that ALL messages need to be logged. */
26      public static final LogCategory ALL = new LogCategory("ALL");
27  
28      /**
29       * @param name the category name; can be blank
30       */
31      public LogCategory(final String name)
32      {
33          this.name = name == null ? "" : name;
34          this.hashCode = calcHashCode();
35      }
36  
37      /** {@inheritDoc} */
38      @Override
39      public int hashCode()
40      {
41          return this.hashCode;
42      }
43  
44      /**
45       * Calculate the hashCode. In case of a blank name, use a reproducible random number (so NOT the memory address of
46       * the LogCategory object)
47       * @return the calculated hash code
48       */
49      private int calcHashCode()
50      {
51          final int prime = 31;
52          int result = 1;
53          result = (this.name == null || this.name.length() == 0) ? random.nextInt() : prime + this.name.hashCode();
54          return result;
55      }
56  
57      /** {@inheritDoc} */
58      @Override
59      @SuppressWarnings("checkstyle:needbraces")
60      public boolean equals(final Object obj)
61      {
62          if (this == obj)
63              return true;
64          if (obj == null)
65              return false;
66          if (getClass() != obj.getClass())
67              return false;
68          LogCategory other = (LogCategory) obj;
69          if (this.hashCode != other.hashCode)
70              return false;
71          return true;
72      }
73  
74      /** {@inheritDoc} */
75      @Override
76      public String toString()
77      {
78          return "LogCategory." + this.name;
79      }
80  
81  }