1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 package org.apache.http.impl.client.cache;
28
29 import java.net.InetAddress;
30 import java.net.UnknownHostException;
31 import java.security.NoSuchAlgorithmException;
32 import java.security.SecureRandom;
33 import java.util.Formatter;
34 import java.util.Locale;
35
36 import org.apache.http.annotation.Contract;
37 import org.apache.http.annotation.ThreadingBehavior;
38
39
40
41
42 @Contract(threading = ThreadingBehavior.SAFE)
43 class BasicIdGenerator {
44
45 private final String hostname;
46 private final SecureRandom rnd;
47 private long count;
48
49 public BasicIdGenerator() {
50 super();
51 String hostname;
52 try {
53 hostname = InetAddress.getLocalHost().getHostName();
54 } catch (final UnknownHostException ex) {
55 hostname = "localhost";
56 }
57 this.hostname = hostname;
58 try {
59 this.rnd = SecureRandom.getInstance("SHA1PRNG");
60 } catch (final NoSuchAlgorithmException ex) {
61 throw new Error(ex);
62 }
63 this.rnd.setSeed(System.currentTimeMillis());
64 }
65
66 public synchronized void generate(final StringBuilder buffer) {
67 this.count++;
68 final int rndnum = this.rnd.nextInt();
69 buffer.append(System.currentTimeMillis());
70 buffer.append('.');
71 final Formatter formatter = new Formatter(buffer, Locale.US);
72 formatter.format("%1$016x-%2$08x", Long.valueOf(this.count), Integer.valueOf(rndnum));
73 formatter.close();
74 buffer.append('.');
75 buffer.append(this.hostname);
76 }
77
78 public String generate() {
79 final StringBuilder buffer = new StringBuilder();
80 generate(buffer);
81 return buffer.toString();
82 }
83
84 }