1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package com.isenshi.util;
17
18 import java.util.HashMap;
19 import java.util.Map;
20
21 public class UniqueNameGenerator {
22
23 private Map versionMap = new HashMap();
24
25 public void putName(String name){
26 putName(name, 0);
27 }
28
29 public String nextUniqueName(String name) {
30 synchronized (versionMap) {
31 Integer version = (Integer) versionMap.get(name);
32 if (version == null) {
33 putName(name, 0);
34 } else {
35 int currentVersion = version.intValue();
36 int nextVersion = nextVersion(name, ++currentVersion);
37 putName(name, nextVersion);
38 name = generateName(name, nextVersion);
39 }
40 putName(name, 0);
41 }
42 return name;
43 }
44
45 private void putName(String name, int version){
46 versionMap.put(name, new Integer(version));
47 }
48
49 private int nextVersion(String name, int version) {
50 String generatedName = generateName(name, version);
51 if (versionMap.get(generatedName) == null) {
52 return version;
53 }
54 return nextVersion(name, ++version);
55 }
56
57 private String generateName(String name, int version) {
58 return name + "_" + version;
59 }
60 }