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.hc.client5.http.impl.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 import java.util.concurrent.locks.ReentrantLock;
36
37
38
39
40 class BasicIdGenerator {
41
42 private final String hostname;
43 private final SecureRandom rnd;
44
45 private long count;
46
47 private final ReentrantLock lock;
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 this.lock = new ReentrantLock();
65 }
66
67 public void generate(final StringBuilder buffer) {
68 lock.lock();
69 try {
70 this.count++;
71 final int rndnum = this.rnd.nextInt();
72 buffer.append(System.currentTimeMillis());
73 buffer.append('.');
74 try (Formatter formatter = new Formatter(buffer, Locale.ROOT)) {
75 formatter.format("%1$016x-%2$08x", this.count, rndnum);
76 }
77 buffer.append('.');
78 buffer.append(this.hostname);
79 } finally {
80 lock.unlock();
81 }
82 }
83
84 public String generate() {
85 final StringBuilder buffer = new StringBuilder();
86 generate(buffer);
87 return buffer.toString();
88 }
89
90 }