View Javadoc

1   /*
2    * Copyright 2004-2006 the Seasar Foundation and the Others.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
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) { // check
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  }