Subversion Repositories SmartDukaan

Rev

Rev 726 | Blame | Compare with Previous | Last modification | View Log | RSS feed

/**
 * 
 */
package in.shop2020.metamodel.util;

import in.shop2020.util.DBUtils;
import in.shop2020.util.Utils;

import java.io.File;
import java.io.Serializable;
import java.util.Arrays;

/**
 * Utility class to generate unique numbers
 * 
 * @author naveen
 * 
 * 
 */
public class SequenceGenerator implements Serializable {

        /**
         * 
         */
        private static final long serialVersionUID = 1L;
        
        /**
         * Entity object's starting sequence number
         */
        public static final int ENTITY = 0;

        /**
         * Singleton instance that is de-serialized from file on the disk
         * 
         * @return      SequenceGenerator       instance of SequenceGenerator
         * @throws Exception 
         */
        public static final SequenceGenerator getInstance() throws Exception {
                // De-serialize
                String dbFile = Utils.CONTENT_DB_PATH + "entities" + File.separator + "sequence.ser";
                
                SequenceGenerator sequenceGenerator = 
                        (SequenceGenerator) DBUtils.read(dbFile);
                
                if(sequenceGenerator == null) {
                        sequenceGenerator = new SequenceGenerator();
                }
                
                return sequenceGenerator;
        }
        
        /**
         * Instance member that records all current counts
         */
        private long[] currentCounts = null;

        /**
         * A private Constructor prevents any other class from instantiating. All 
         * objects that need dynamic sequence generation need to provide starting 
         * number here.
         */
        private SequenceGenerator() {
                this.currentCounts = new long[1];
                
                // Set initial values
                this.currentCounts[ENTITY] = 1000000;
        }
        
        /**
         * Client of the class call this method to get new sequence number. 
         * Once a sequence number if fetched it cannot be undone.
         * 
         * @param index
         * @return currentCount
         * @throws Exception 
         */
        public long getNextSequence(int index) throws Exception {
                // Increment
                this.currentCounts[index]++;
                
                // Store back
                String dbFile = Utils.CONTENT_DB_PATH + "entities" + File.separator + "sequence.ser";
                DBUtils.store(this, dbFile);
                
                return this.currentCounts[index];
        }

        /* (non-Javadoc)
         * @see java.lang.Object#toString()
         */
        @Override
        public String toString() {
                return "SequenceGenerator [currentCounts="
                                + Arrays.toString(currentCounts) + "]";
        }

}