/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (the "License").  You may not use this file except 
 * in compliance with the License.
 * 
 * You can obtain a copy of the license at 
 * glassfish/bootstrap/legal/CDDLv1.0.txt or 
 * https://glassfish.dev.java.net/public/CDDLv1.0.html. 
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * HEADER in each file and include the License file at 
 * glassfish/bootstrap/legal/CDDLv1.0.txt.  If applicable, 
 * add the following below this CDDL HEADER, with the 
 * fields enclosed by brackets "[]" replaced with your 
 * own identifying information: Portions Copyright [yyyy] 
 * [name of copyright owner]
 */
// Copyright (c) 1998, 2005, Oracle. All rights reserved.  
package oracle.toplink.essentials.internal.sequencing;

import java.util.Vector;
import java.util.Hashtable;

class PreallocationHandler implements SequencingLogInOut {
    protected Hashtable preallocatedSequences;

    public PreallocationHandler() {
        super();
    }

    /**
    * PROTECTED:
    * return a vector from the global sequences based on
    * seqName.  If there is not one, put it there.
    */
    protected Vector getPreallocatedSequences(String seqName) {
        Vector sequencesForName;
        synchronized (preallocatedSequences) {
            sequencesForName = (Vector)preallocatedSequences.get(seqName);
            if (sequencesForName == null) {
                sequencesForName = new Vector();
                preallocatedSequences.put(seqName, sequencesForName);
            }
        }
        return sequencesForName;
    }

    // SequencingLogInOut
    public void onConnect() {
        initializePreallocated();
    }

    public void onDisconnect() {
        preallocatedSequences = null;
    }

    public boolean isConnected() {
        return preallocatedSequences != null;
    }

    // removes all preallocated objects.
    // a dangerous method to use in multithreaded environment method,
    // but so handy for testing
    public void initializePreallocated() {
        preallocatedSequences = new Hashtable(20);
    }

    // removes all preallocated objects for the specified seqName.
    // a dangerous method to use in multithreaded environment method,
    // but so handy for testing
    public void initializePreallocated(String seqName) {
        preallocatedSequences.remove(seqName);
    }

    public Vector getPreallocated(String seqName) {
        return getPreallocatedSequences(seqName);
    }

    public void setPreallocated(String seqName, Vector sequences) {
        getPreallocatedSequences(seqName).addAll(sequences);
    }
}
