Subversion Repositories SmartDukaan

Rev

Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
10 shop2020 1
/**
2
 * 
3
 */
4
package in.shop2020.metamodel.util;
5
 
6
import java.io.Serializable;
22 naveen 7
import java.util.Arrays;
10 shop2020 8
 
9
/**
49 naveen 10
 * Utility class to generate unique numbers
11
 * 
10 shop2020 12
 * @author naveen
13
 * 
49 naveen 14
 * 
10 shop2020 15
 */
16
public class SequenceGenerator implements Serializable {
17
 
18
	/**
19
	 * 
20
	 */
21
	private static final long serialVersionUID = 1L;
49 naveen 22
 
23
	/**
51 naveen 24
	 * Entity object's starting sequence number
49 naveen 25
	 */
21 naveen 26
	public static final int ENTITY = 0;
10 shop2020 27
 
28
	/**
51 naveen 29
	 * Singleton instance that is de-serialized from file on the disk
10 shop2020 30
	 * 
21 naveen 31
	 * @return 	SequenceGenerator 	instance of SequenceGenerator
32
	 * @throws Exception 
10 shop2020 33
	 */
21 naveen 34
	public static final SequenceGenerator getInstance() throws Exception {
35
		// De-serialize
36
		String dbFile = CN.CONTENT_DB_PATH + "sequence" + ".ser";
37
 
38
		SequenceGenerator sequenceGenerator = 
39
			(SequenceGenerator) DBUtils.read(dbFile);
40
 
41
		if(sequenceGenerator == null) {
42
			sequenceGenerator = new SequenceGenerator();
43
		}
44
 
10 shop2020 45
		return sequenceGenerator;
46
	}
47
 
48
	/**
51 naveen 49
	 * Instance memeber that records all current counts
10 shop2020 50
	 */
21 naveen 51
	private long[] currentCounts = null;
10 shop2020 52
 
53
	/**
51 naveen 54
	 * A private Constructor prevents any other class from instantiating. All 
55
	 * objects that need dynamic sequence generation need to provide starting 
56
	 * number here.
10 shop2020 57
	 */
58
	private SequenceGenerator() {
59
		this.currentCounts = new long[1];
60
 
61
		// Set initial values
21 naveen 62
		this.currentCounts[ENTITY] = 1000000;
10 shop2020 63
	}
64
 
65
	/**
51 naveen 66
	 * Client of the class call this method to get new sequence number. 
67
	 * Once a sequence number if fetched it cannot be undone.
10 shop2020 68
	 * 
69
	 * @param index
70
	 * @return currentCount
21 naveen 71
	 * @throws Exception 
10 shop2020 72
	 */
21 naveen 73
	public long getNextSequence(int index) throws Exception {
74
		// Increment
75
		this.currentCounts[index]++;
76
 
77
		// Store back
78
		String dbFile = CN.CONTENT_DB_PATH + "sequence" + ".ser";
79
		DBUtils.store(this, dbFile);
80
 
81
		return this.currentCounts[index];
10 shop2020 82
	}
22 naveen 83
 
84
	/* (non-Javadoc)
85
	 * @see java.lang.Object#toString()
86
	 */
87
	@Override
88
	public String toString() {
89
		return "SequenceGenerator [currentCounts="
90
				+ Arrays.toString(currentCounts) + "]";
91
	}
92
 
10 shop2020 93
}