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