JAL-4059 Tidy getting the namespace, and save the namespace in the Jalview instance...
[jalview.git] / src / jalview / util / IdUtils.java
1 package jalview.util;
2
3 import java.util.HashMap;
4 import java.util.HashSet;
5 import java.util.Map;
6 import java.util.Set;
7
8 import jalview.bin.Console;
9
10 public class IdUtils
11 {
12   /**
13    * id generating tools avoiding Random.nextLong() for JalviewJS. Avoids
14    * collisions.
15    */
16
17   public static enum IdType
18   {
19     GENERAL, PROGRESS;
20   }
21
22   private static int count = 0;
23
24   private static Map<IdType, Set<Long>> typeMap = new HashMap<>();
25
26   static
27   {
28     for (IdType t : IdType.values())
29     {
30       typeMap.put(t, new HashSet<>());
31     }
32   }
33
34   public static long newId()
35   {
36     return newId(IdType.GENERAL, null);
37   }
38
39   public static long newId(IdType t)
40   {
41     return newId(t, null);
42   }
43
44   public static long newId(IdType t, Object o)
45   {
46     Set<Long> idSet = typeMap.get(t);
47     long newId = 0;
48     if (o == null)
49     {
50       // get a new hashCode -- not tied to an object.
51       // Adding Integer.MAX_VALUE should avoid collisions with object generated
52       // Ids.
53       newId = Integer.MAX_VALUE + t.hashCode() + System.currentTimeMillis()
54               + count;
55       while (idSet.contains(newId))
56       {
57         newId += count;
58       }
59     }
60     else
61     {
62       // generate the hashcode tied to this object for this type
63       newId = t.hashCode() + o.hashCode();
64       if (idSet.contains(newId))
65       {
66         Console.debug("Using an existing id for Type " + t.name()
67                 + " and object " + o.toString() + ": '" + newId + "'");
68       }
69       else
70       {
71         idSet.add(newId);
72       }
73     }
74     count++;
75     return newId;
76   }
77
78   public static void NOTremoveId(IdType t, Object o)
79   {
80     if (o == null)
81     {
82       return;
83     }
84     Set<Long> idSet = typeMap.get(t);
85     long id = t.hashCode() + o.hashCode();
86     idSet.remove(id);
87   }
88
89   public static void NOTremoveId(IdType t, long id)
90   {
91     Set<Long> idSet = typeMap.get(t);
92     idSet.remove(id);
93   }
94
95 }