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