1 public class RandomIdGenerator implements IdGenerator {
2 private static final Logger logger = LoggerFactory.getLogger(RandomIdGenerator.class);
3
4 @Override
5 public String generate() {
6 String substrOfHostName = getLastFiledOfHostName();
7 long currentTimeMillis = System.currentTimeMillis();
8 String randomString = generateRandomAlphameric(8);
9 String id = String.format("%s-%d-%s",
10 substrOfHostName, currentTimeMillis, randomString);
11 return id;
12 }
13
14 private String getLastFiledOfHostName() {
15 String substrOfHostName = null;
16 try {
17 String hostName = InetAddress.getLocalHost().getHostName();
18 substrOfHostName = getLastSubstrSplittedByDot(hostName);
19 } catch (UnknownHostException e) {
20 logger.warn("Failed to get the host name.", e);
21 }
22 return substrOfHostName;
23 }
24
25 @VisibleForTesting
26 protected String getLastSubstrSplittedByDot(String hostName) {
27 String[] tokens = hostName.split("\\.");
28 String substrOfHostName = tokens[tokens.length - 1];
29 return substrOfHostName;
30 }
31
32 @VisibleForTesting
33 protected String generateRandomAlphameric(int length) {
34 char[] randomChars = new char[length];
35 int count = 0;
36 Random random = new Random();
37 while (count < length) {
38 int maxAscii = 'z';
39 int randomAscii = random.nextInt(maxAscii);
40 boolean isDigit= randomAscii >= '0' && randomAscii <= '9';
41 boolean isUppercase= randomAscii >= 'A' && randomAscii <= 'Z';
42 boolean isLowercase= randomAscii >= 'a' && randomAscii <= 'z';
43 if (isDigit|| isUppercase || isLowercase) {
44 randomChars[count] = (char) (randomAscii);
45 ++count;
46 }
47 }
48 return new String(randomChars);
49 }
50 }