1   package ixa.kaflib;
2   
3   import java.util.regex.Matcher;
4   import java.util.regex.Pattern;
5   
6   /**
7    * Created with IntelliJ IDEA.
8    * User: alessio
9    * Date: 07/08/14
10   * Time: 21:41
11   * To change this template use File | Settings | File Templates.
12   */
13  
14  public class GenericId {
15  	private String prefix;
16  	private int counter = 0;
17  	private boolean inconsistent = false;
18  
19  	public String getNext() {
20  		if (inconsistent) {
21  			throw new IllegalStateException("Inconsistent WF IDs. Can't create new WF IDs.");
22  		}
23  		return prefix + Integer.toString(++counter);
24  	}
25  
26  	public void update(String id) {
27  		try {
28  			Integer idNum = extractCounterFromId(id);
29  			if (counter < idNum) {
30  				counter = idNum;
31  			}
32  		} catch (IllegalStateException e) {
33  			inconsistent = true;
34  		}
35  	}
36  
37  	GenericId(String prefix) {
38  		this.prefix = prefix;
39  	}
40  
41  	private static int extractCounterFromId(String id) {
42  		Matcher matcher = Pattern.compile("\\d+$").matcher(id);
43  		if (!matcher.find()) {
44  			throw new IllegalStateException("GenericId doesn't recognise the given id's (" + id + ") format.");
45  		}
46  		return Integer.valueOf(matcher.group(0));
47  	}
48  
49  	public String getPrefix() {
50  		return prefix;
51  	}
52  }