e7b56d4ac7dbef057d29ccfaa7b59c6a69c369ce
[debian/openrocket] / src / net / sf / openrocket / util / UniqueID.java
1 package net.sf.openrocket.util;
2
3 import java.security.MessageDigest;
4 import java.security.NoSuchAlgorithmException;
5 import java.util.UUID;
6 import java.util.concurrent.atomic.AtomicInteger;
7
8 import net.sf.openrocket.gui.main.ExceptionHandler;
9
10 public class UniqueID {
11         
12         private static AtomicInteger nextId = new AtomicInteger(1);
13         
14         /**
15          * Return a positive integer ID unique during this program execution.  
16          * The values are taken as sequential numbers, and will re-occur in 
17          * later executions of the program.
18          * <p>
19          * This method is thread-safe and fast.
20          * 
21          * @return      a positive integer ID unique in this program execution.
22          */
23         public static int next() {
24                 return nextId.getAndIncrement();
25         }
26
27         
28         /**
29          * Return a new universally unique ID string.
30          * 
31          * @return      a unique identifier string.
32          */
33         public static String uuid() {
34                 return UUID.randomUUID().toString();
35         }
36         
37         
38         /**
39          * Return a hashed unique ID that contains no information whatsoever of the
40          * originating computer.
41          * 
42          * @return      a unique identifier string that contains no information about the computer.
43          */
44         public static String generateHashedID() {
45                 String id = UUID.randomUUID().toString();
46                 
47                 try {
48                         MessageDigest algorithm = MessageDigest.getInstance("MD5");
49                         algorithm.reset();
50                         algorithm.update(id.getBytes());
51                         byte[] digest = algorithm.digest();
52                         
53                         StringBuilder sb = new StringBuilder();
54                         for (byte b: digest) {
55                                 sb.append(String.format("%02X", 0xFF & b));
56                         }
57                         id = sb.toString();
58                         
59                 } catch (NoSuchAlgorithmException e) {
60                         ExceptionHandler.handleErrorCondition(e);
61                         id = "" + id.hashCode();
62                 }
63                 
64                 return id;
65         }
66         
67 }