View Javadoc

1   package com.atlassian.scheduler.util;
2   
3   import com.atlassian.annotations.Internal;
4   import com.google.common.collect.ImmutableMap;
5   
6   import javax.annotation.Nonnull;
7   import javax.annotation.Nullable;
8   import java.io.Serializable;
9   import java.util.Collections;
10  import java.util.Date;
11  import java.util.HashMap;
12  import java.util.Map;
13  
14  /**
15   * Static utility methods for things like {@code null}-testing and defensive copies.
16   *
17   * @since v1.0
18   */
19  @Internal
20  public final class Safe {
21      /**
22       * Make a defensive copy of a mutable {@link Date}.
23       */
24      @Nullable
25      public static Date copy(@Nullable Date date) {
26          return (date != null) ? (Date) date.clone() : null;
27      }
28  
29      /**
30       * Make a defensive copy of a byte array.
31       */
32      @Nullable
33      public static byte[] copy(@Nullable final byte[] bytes) {
34          return (bytes != null) ? bytes.clone() : null;
35      }
36  
37      /**
38       * Make a defensive copy of a possibly mutable map.  An empty map is substituted
39       * for {@code null}.
40       */
41      @Nonnull
42      public static Map<String, Serializable> copy(@Nullable final Map<String, Serializable> map) {
43          final Map<String, Serializable> copy;
44          if (map == null) {
45              copy = ImmutableMap.of();
46          } else if (map instanceof ImmutableMap) {
47              copy = map;
48          } else {
49              copy = Collections.unmodifiableMap(new HashMap<String, Serializable>(map));
50          }
51          return copy;
52      }
53  
54      private Safe() {
55          throw new Error("I am static-only.");
56      }
57  }