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
36
37
38
39 class BasicIdGenerator {
40
41 private final String hostname;
42 private final SecureRandom rnd;
43
44 private long count;
45
46 public BasicIdGenerator() {
47 super();
48 String hostname;
49 try {
50 hostname = InetAddress.getLocalHost().getHostName();
51 } catch (final UnknownHostException ex) {
52 hostname = "localhost";
53 }
54 this.hostname = hostname;
55 try {
56 this.rnd = SecureRandom.getInstance("SHA1PRNG");
57 } catch (final NoSuchAlgorithmException ex) {
58 throw new Error(ex);
59 }
60 this.rnd.setSeed(System.currentTimeMillis());
61 }
62
63 public synchronized void generate(final StringBuilder buffer) {
64 this.count++;
65 final int rndnum = this.rnd.nextInt();
66 buffer.append(System.currentTimeMillis());
67 buffer.append('.');
68 try (Formatter formatter = new Formatter(buffer, Locale.ROOT)) {
69 formatter.format("%1$016x-%2$08x", this.count, rndnum);
70 }
71 buffer.append('.');
72 buffer.append(this.hostname);
73 }
74
75 public String generate() {
76 final StringBuilder buffer = new StringBuilder();
77 generate(buffer);
78 return buffer.toString();
79 }
80
81 }