/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.activeblaze.cluster;

import org.apache.activeblaze.BaseService;
import org.apache.activeblaze.BlazeRuntimeException;
import org.apache.activeblaze.group.Member;
import org.apache.activeblaze.group.MemberChangedListener;
import org.apache.activeblaze.wire.MemberImpl;
import org.apache.activeblaze.wire.StateKey;
import org.apache.activeblaze.wire.StateValue;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.Serializable;
import java.util.*;
import java.util.concurrent.*;

/**
 * <p/>
 * A <CODE>ClusterState</CODE> is a distributed collaboration implementation
 * that is used to shared state and process messages amongst a distributed group
 * of other <CODE>Group</CODE> instances. Membership of a group is handled
 * automatically using discovery.
 */
public class ClusterState extends BaseService implements Map<String, Object>, MemberChangedListener {
    final static Log LOG = LogFactory.getLog(ClusterState.class);
    private boolean alwaysLock = true;
    private boolean removeOwnedObjectsOnExit;
    private boolean releaseLockOnExit = true;
    private int timeToLive;
    private int lockTimeToLive;
    private int requestTimeout = 5000;
    final BlazeClusterGroupChannelImpl channel;
    private final List<ClusterStateChangedListener> clusterStateChangedListeners = new CopyOnWriteArrayList<ClusterStateChangedListener>();
    private final Map<String, StateValue> localMap = new ConcurrentHashMap<String, StateValue>();
    private ExecutorService stateChangedExecutor;
    private Timer expirationTimer;
    private int maxDispatchQueueSize = 10000;
    private LinkedBlockingQueue<StateValue> dispatchQueue;
    private Thread dispatchQueueThread;

    protected ClusterState(BlazeClusterGroupChannelImpl channel) {
        this.channel = channel;
    }

    /**
     * Test to see if we own the key
     *
     * @return true if the owner of the key
     */
    public boolean isOwner(String key) {
        boolean result = false;
        StateValue value = this.localMap.get(key);
        if (value != null) {
            result = value.getKey().getOwner().equals(this.channel.getLocalMember());
        }
        return result;
    }

    /**
     * Get the owner of a Key
     *
     * @return the owner or null if the key doesnn't exist
     */
    public Member getOwner(String key) {
        StateValue value = this.localMap.get(key);
        if (value != null) {
            return value.getKey().getOwner();
        }
        return null;
    }

    /**
     * Unlock a key
     */
    public void unlock(String key) throws Exception {
        StateKey stateKey = new StateKey(this.channel.getLocalMember(), key);
        stateKey.setLocked(false);
        stateKey.setRemoveOnExit(isRemoveOwnedObjectsOnExit());
        stateKey.setReleaseLockOnExit(isReleaseLockOnExit());
        stateKey.setTimeToLive(getTimeToLive());
        StateValue state = new StateValue();
        state.setKey(stateKey);
        state.setLockWrite(true);
        sendMasterRequest(state);
    }

    /**
     * Lock a Key
     */
    public void lock(String key) throws Exception {
        lock(key, getLockTimeToLive());
    }

    /**
     * Lock a Key
     */
    public void lock(String key, long leaseTime) throws Exception {
        checkStatus();
        StateKey stateKey = new StateKey(this.channel.getLocalMember(), key);
        stateKey.setLocked(true);
        stateKey.setRemoveOnExit(isRemoveOwnedObjectsOnExit());
        stateKey.setReleaseLockOnExit(isReleaseLockOnExit());
        stateKey.setTimeToLive(getTimeToLive());
        stateKey.setLockLeaseTime(leaseTime);
        StateValue state = new StateValue();
        state.setKey(stateKey);
        state.setLockWrite(true);
        sendMasterRequest(state);
    }

    /**
     * @see java.util.Map#clear()
     */
    public void clear() {
        checkStatus();
        if (this.localMap != null && !this.localMap.isEmpty()) {
            Set<String> keys = null;
            keys = new HashSet<String>(this.localMap.keySet());
            for (String key : keys) {
                remove(key);
            }
        }
        this.localMap.clear();
    }

    /**
     * @return true if it contains the key
     * @see java.util.Map#containsKey(java.lang.Object)
     */
    public boolean containsKey(java.lang.Object key) {
        return this.localMap.containsKey(key);
    }

    /**
     * @return true if it contains the value
     * @see java.util.Map#containsValue(java.lang.Object)
     */
    public boolean containsValue(java.lang.Object value) {
        StateValue sv = new StateValue(null, value);
        return this.localMap.containsValue(sv);
    }

    /**
     * @return a Set
     * @see java.util.Map#entrySet()
     */
    public Set<java.util.Map.Entry<String, Object>> entrySet() {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            for (StateValue entry : this.localMap.values()) {
                String key = entry.getKey().getKey();
                Object value = entry.getValue();
                result.put(key, value);
            }
        } catch (Exception e) {
            throw new BlazeRuntimeException(e);
        }
        return result.entrySet();
    }

    /**
     * @see java.util.Map#get(java.lang.Object)
     */
    public Object get(java.lang.Object key) {
        StateValue v = this.localMap.get(key);
        try {
            return v != null ? v.getValue() : null;
        } catch (Exception e) {
            throw new BlazeRuntimeException(e);
        }
    }

    /**
     * @see java.util.Map#isEmpty()
     */
    public boolean isEmpty() {
        return this.localMap.isEmpty();
    }

    /**
     * @see java.util.Map#keySet()
     */
    public Set<String> keySet() {
        return this.localMap.keySet();
    }

    /**
     * @see java.util.Map#put(java.lang.Object, java.lang.Object)
     */
    public Object put(String key, Object value) {
        return put(key, value, isAlwaysLock(), isRemoveOwnedObjectsOnExit(), isReleaseLockOnExit(), getTimeToLive(),
                getLockTimeToLive());
    }

    /**
     * @return the old value
     */
    public Object put(String key, Object value, boolean lock, boolean removeOnExit, boolean releaseLockOnExit,
                      long timeToLive, long leaseTime) throws BlazeRuntimeException {
        checkStatus();
        StateValue resultValue = null;
        try {
            StateKey stateKey = new StateKey(this.channel.getLocalMember(), key);
            stateKey.setLocked(lock);
            stateKey.setRemoveOnExit(removeOnExit);
            stateKey.setReleaseLockOnExit(releaseLockOnExit);
            stateKey.setTimeToLive(timeToLive);
            stateKey.setLockLeaseTime(leaseTime);
            StateValue state = new StateValue();
            state.setKey(stateKey);
            state.setType(StateValue.StateType.INSERT);
            state.setMapWrite(true);
            state.setValue(value);
            resultValue = sendMasterRequest(state);
        } catch (Exception e) {
            if (e instanceof ClusterUpdateException) {
                throw (ClusterUpdateException) e;
            }
            throw new ClusterUpdateException(e);
        }
        return resultValue != null ? resultValue.getOldValue() : null;
    }

    /**
     * @see java.util.Map#putAll(java.util.Map)
     */
    public void putAll(Map<? extends String, ? extends Object> t) {
        putAll(t, isAlwaysLock(), isRemoveOwnedObjectsOnExit(), isReleaseLockOnExit(), getTimeToLive(),
                getLockTimeToLive());
    }

    /**
     * put all
     */
    public void putAll(Map<? extends String, ? extends Object> t, boolean lock, boolean removeOnExit,
                       boolean releaseLockOnExit, long timeToLive, long lockTimeToLive) {
        for (java.util.Map.Entry<? extends String, ? extends Object> entry : t.entrySet()) {
            put(entry.getKey(), entry.getValue(), lock, removeOnExit, releaseLockOnExit, timeToLive, lockTimeToLive);
        }
    }

    /**
     * @return the old object
     * @see java.util.Map#remove(java.lang.Object)
     */
    public Object remove(java.lang.Object key) {
        checkStatus();
        StateKey stateKey = new StateKey(this.channel.getLocalMember(), key.toString());
        StateValue state = new StateValue();
        state.setKey(stateKey);
        state.setMapWrite(true);
        state.setType(StateValue.StateType.DELETE);
        try {
            return this.channel.sendRequest((MemberImpl) this.channel.getMaster(), state, getRequestTimeout());
        } catch (Exception e) {
            throw new BlazeRuntimeException(e);
        }
    }

    /**
     * @see java.util.Map#size()
     */
    public int size() {
        return this.localMap.size();
    }

    /**
     * @see java.util.Map#values()
     */
    public Collection<Object> values() {
        List<Object> result = new ArrayList<Object>();
        try {
            for (StateValue v : this.localMap.values()) {
                result.add(v.getValue());
            }
        } catch (Exception e) {
            throw new BlazeRuntimeException(e);
        }
        return result;
    }

    /**
     * @return the alwaysLock
     */
    public boolean isAlwaysLock() {
        return this.alwaysLock;
    }

    /**
     * @param alwaysLock the alwaysLock to set
     */
    public void setAlwaysLock(boolean alwaysLock) {
        this.alwaysLock = alwaysLock;
    }

    /**
     * @return the removeOwnedObjectsOnExit
     */
    public boolean isRemoveOwnedObjectsOnExit() {
        return this.removeOwnedObjectsOnExit;
    }

    /**
     * @param removeOwnedObjectsOnExit the removeOwnedObjectsOnExit to set
     */
    public void setRemoveOwnedObjectsOnExit(boolean removeOwnedObjectsOnExit) {
        this.removeOwnedObjectsOnExit = removeOwnedObjectsOnExit;
    }

    /**
     * @return the releaseLockOnExit
     */
    public boolean isReleaseLockOnExit() {
        return this.releaseLockOnExit;
    }

    /**
     * @param releaseLockOnExit the releaseLockOnExit to set
     */
    public void setReleaseLockOnExit(boolean releaseLockOnExit) {
        this.releaseLockOnExit = releaseLockOnExit;
    }

    /**
     * @return the timeToLive
     */
    public int getTimeToLive() {
        return this.timeToLive;
    }

    /**
     * @param timeToLive the timeToLive to set
     */
    public void setTimeToLive(int timeToLive) {
        this.timeToLive = timeToLive;
    }

    /**
     * @return the lockTimeToLive
     */
    public int getLockTimeToLive() {
        return this.lockTimeToLive;
    }

    /**
     * @param lockTimeToLive the lockTimeToLive to set
     */
    public void setLockTimeToLive(int lockTimeToLive) {
        this.lockTimeToLive = lockTimeToLive;
    }

    /**
     * @return the requestTimeout
     */
    public int getRequestTimeout() {
        return this.requestTimeout;
    }

    /**
     * @param requestTimeout the requestTimeout to set
     */
    public void setRequestTimeout(int requestTimeout) {
        this.requestTimeout = requestTimeout;
    }

    @Override
    public void doInit() throws Exception {
        this.channel.addMemberChangedListener(this);
        this.dispatchQueue = new LinkedBlockingQueue<StateValue>(getMaxDispatchQueueSize());
    }

    @Override
    public void doShutDown() throws Exception {
        this.channel.removeMemberChangedListener(this);
    }

    @Override
    public void doStart() throws Exception {
        this.stateChangedExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
            public Thread newThread(Runnable runnable) {
                Thread thread = new Thread(runnable, "Cluster State{" + ClusterState.this.channel.getLocalMember()
                        + "}");
                thread.setDaemon(true);
                return thread;
            }
        });
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                try {
                    expirationSweep();
                } catch (Exception e) {
                    ClusterState.LOG.error("Failed to do expiration sweep", e);
                }
            }
        };
        this.expirationTimer = new Timer(true);
        this.expirationTimer.scheduleAtFixedRate(task, 500, 500);
        Runnable runable = new Runnable() {
            public void run() {
                while (isStarted()) {
                    dequeuePackets();
                }
            }
        };
        this.dispatchQueueThread = new Thread(runable, toString() + "-DispatchQueue");
        this.dispatchQueueThread.setDaemon(true);
        this.dispatchQueueThread.start();
    }

    @Override
    public void doStop() throws Exception {
        if (this.dispatchQueueThread != null) {
            this.dispatchQueueThread.interrupt();
            try {
                this.dispatchQueueThread.join(100);
            } catch (InterruptedException e) {
            }
        }
        this.stateChangedExecutor.shutdown();
        this.expirationTimer.cancel();
    }

    protected void stopInternal() {
        try {
            stop();
        } catch (Throwable e) {
            LOG.error("Caught an exception stopping", e);
        }
    }

    /**
     * Add a <Code>ClusterStateChangedListener</Code>
     */
    public void addClusterStateChangedListener(ClusterStateChangedListener l) {
        this.clusterStateChangedListeners.add(l);
    }

    /**
     * Add a <Code>ClusterStateChangedListener</Code>
     */
    public void removeClusterStateChangedListener(ClusterStateChangedListener l) {
        this.clusterStateChangedListeners.remove(l);
    }

    /**
     * @return the maxDispatchQueueSize
     */
    public int getMaxDispatchQueueSize() {
        return this.maxDispatchQueueSize;
    }

    /**
     * @param maxDispatchQueueSize the maxDispatchQueueSize to set
     */
    public void setMaxDispatchQueueSize(int maxDispatchQueueSize) {
        this.maxDispatchQueueSize = maxDispatchQueueSize;
    }

    /**
     * Implementation of org.apache.activeblaze.group.MemberChangedListener for
     * listening to membership changes
     *
     * @see org.apache.activeblaze.group.MemberChangedListener#memberStarted(org.apache.activeblaze.group.Member)
     */
    public void memberStarted(Member member) {
        try {
            if (this.channel.isMaster()) {
                // this.channel.waitForElection(0);
                // even though we may no longer be the master - we
                // was the master before the new node started - so
                // we take responsibility for updating the new node
                for (StateValue state : this.localMap.values()) {
                    state = state.clone();
                    state.setMapWrite(false);
                    state.setMapUpdate(true);
                    state.setType(StateValue.StateType.SYNC);
                    broadcastStateUpdate(state, "");
                }
            }
        } catch (Exception e) {
            LOG.error("Failed to sync up new group member: " + member);
        }
    }

    /**
     * Implementation of org.apache.activeblaze.group.MemberChangedListener for
     * listening to membership changes
     *
     * @see org.apache.activeblaze.group.MemberChangedListener#memberStopped(org.apache.activeblaze.group.Member)
     */
    public void memberStopped(Member member) {
        if (isStarted()) {
            // remove any values held by this member
            List<StateKey> list = new ArrayList<StateKey>();
            for (StateValue stateValue : this.localMap.values()) {
                StateKey key = stateValue.getKey();
                if (key.getOwner().equals(member)) {
                    if (key.isReleaseLockOnExit()) {
                        key.setLocked(false);
                    }
                    if (key.isRemoveOnExit()) {
                        list.add(key);
                    }
                }
            }
            for (StateKey key : list) {
                StateValue value = this.localMap.remove(key.getKey());
                if (value != null) {
                    try {
                        fireMapChanged(member, key.getKey(), value.getValue(), null, false);
                    } catch (Exception e) {
                        LOG.warn("Failed to fireMapChanged for key " + key.getKey(), e);
                    }
                }
            }
        }
    }

    protected void processState(StateValue state) throws Exception {
        if (!isStopped()) {
            this.dispatchQueue.put(state);
        }
    }

    protected void dequeuePackets() {
        StateValue state = null;
        try {
            state = this.dispatchQueue.take();
            if (state != null) {
                doProcessState(state);
            }
        } catch (InterruptedException e1) {
            // we've stopped
        } catch (Exception e) {
            LOG.error("Caught an exception processing a packet: " + state, e);
            stopInternal();
        }
    }

    private void doProcessState(StateValue state) throws Exception {
        String correlationId = state.getId();
        if (!state.isError()) {
            if (state.isMapUpdate()) {
                processMapUpdate(state);
            } else if (state.isLockUpdate()) {
                processLockUpdate(state, correlationId);
            } else if (state.isLockWrite()) {
                processLockWrite(state, correlationId);
            } else if (state.isMapWrite()) {
                processMapOperations(state, correlationId);
            } else {
                LOG.error("Don't know how to process " + state);
            }
        }
    }

    protected void processLockWrite(StateValue stateValue, String correlationId) throws Exception {
        // reset values for when we broadcast an update
        boolean newLock = stateValue.getKey().isLocked();
        stateValue = stateValue.clone();
        if (this.channel.waitForElection(0)) {
            stateValue.setLockUpdate(true);
            stateValue.setLockWrite(false);
            MemberImpl newOwner = stateValue.getKey().getOwner().clone();
            long newLockExpiration = newLock ? stateValue.getKey().getLockExpiration() : 0l;
            if (this.channel.isMaster()) {
                StateKey originalKey = getKey(stateValue.getKey().getKey());
                if (originalKey != null) {
                    if (originalKey.isLocked()) {
                        if (!originalKey.getOwner().equals(stateValue.getKey().getOwner())) {
                            StateValue stateReply = stateValue.clone();
                            Serializable reply = new ClusterUpdateException("Owned by " + originalKey.getOwner());
                            stateReply.setError(true);
                            stateReply.setValue(reply);
                            this.channel.sendReply(stateReply.getKey().getOwner(), stateReply,
                                    correlationId);
                        } else {
                            originalKey.setLocked(newLock);
                            originalKey.setOwner(newOwner);
                            originalKey.setLockExpiration(newLockExpiration);
                            broadcastStateUpdate(stateValue, correlationId);
                        }
                    } else {
                        originalKey.setLocked(newLock);
                        originalKey.setOwner(newOwner);
                        originalKey.setLockExpiration(newLockExpiration);
                        broadcastStateUpdate(stateValue, correlationId);
                    }
                }
            } else {
                StateValue stateReply = stateValue.clone();
                stateReply.setType(StateValue.StateType.NOT_SET);
                Serializable reply = new ClusterNotMasterException(this.channel.getLocalMember() + " Not Master");
                stateReply.setError(true);
                stateReply.setValue(reply);
                this.channel.sendReply(stateReply.getKey().getOwner(), stateReply, correlationId);
            }
        }
    }

    protected void processLockUpdate(StateValue state, String correlationId) throws Exception {
        if (this.channel.waitForElection(0)) {
            StateValue stateValue = state.clone();
            boolean newLock = stateValue.getKey().isLocked();
            MemberImpl newOwner = stateValue.getKey().getOwner().clone();
            long newLockExpiration = newLock ? stateValue.getKey().getLockExpiration() : 0l;
            if (!this.channel.isMaster()) {
                StateKey originalKey = getKey(stateValue.getKey().getKey());
                if (originalKey != null) {
                    originalKey.setLocked(newLock);
                    originalKey.setOwner(newOwner);
                    originalKey.setLockExpiration(newLockExpiration);
                }
            }
        }
    }

    protected void processMapOperations(StateValue state, String correlationId) throws Exception {
        StateValue stateValue = state.clone();
        StateKey key = stateValue.getKey();
        StateValue.StateType stateType = stateValue.getType();
        if (stateType != null) {
            boolean insert = stateType.equals(StateValue.StateType.INSERT)
                    || stateType.equals(StateValue.StateType.SYNC);
            boolean containsKey = this.localMap.containsKey(key.getKey());
            if (this.channel.waitForElection(0)) {
                if (this.channel.isMaster()) {
                    if (containsKey) {
                        StateKey originalKey = getKey(key.getKey());
                        if (originalKey.getOwner().equals(key.getOwner()) || !originalKey.isLocked()) {
                            StateValue old = null;
                            if (insert) {
                                old = this.localMap.put(key.getKey(), stateValue);
                            } else {
                                old = this.localMap.remove(key.getKey());
                            }
                            StateValue newStateData = state.clone();
                            newStateData.setOldValue(null);
                            if (old != null && old.getValue() != null) {
                                newStateData.setOldValue(old.getValue());
                            }
                            newStateData.setMapWrite(false);
                            newStateData.setMapUpdate(true);
                            broadcastStateUpdate(newStateData, correlationId);
                            fireMapChanged(key.getOwner(), key.getKey(), old == null ? null : old.getValue(),
                                    stateValue.getValue(), false);
                        } else {
                            StateValue stateReply = stateValue.clone();
                            Serializable reply = new ClusterUpdateException("Owned by " + originalKey.getOwner());
                            stateReply.setValue(reply);
                            stateReply.setError(true);
                            this.channel.sendReply(stateReply.getKey().getOwner(), stateReply,
                                    correlationId);
                        }
                    } else {
                        if (insert) {
                            this.localMap.put(key.getKey(), stateValue);
                            StateValue newStateData = state.clone();
                            newStateData.setMapWrite(false);
                            newStateData.setMapUpdate(true);
                            broadcastStateUpdate(newStateData, correlationId);
                            fireMapChanged(key.getOwner(), key.getKey(), null, stateValue.getValue(), false);
                        } else {
                            // this shouldn't happen - as we are trying to
                            // remove
                            // a non-existent key
                            LOG
                                    .warn("Cluster State in inconsistent state - master trying to remove a non-existent key: "
                                            + key.getKey() + " from " + key.getOwner());
                        }
                    }
                } else {
                    StateValue stateReply = stateValue.clone();
                    stateReply.setType(StateValue.StateType.NOT_SET);
                    Serializable reply = new ClusterNotMasterException(this.channel.getLocalMember() + " Not Master");
                    stateReply.setError(true);
                    stateReply.setValue(reply);
                    this.channel.sendReply(stateReply.getKey().getOwner(), stateReply, correlationId);
                }
            }
        }
    }

    protected void processMapUpdate(StateValue state) throws Exception {
        StateKey key = state.getKey().clone();
        StateValue stateValue = state.clone();
        boolean containsKey = this.localMap.containsKey(key.getKey());
        if (this.channel.waitForElection(0)) {
            boolean insert = state.getType().equals(StateValue.StateType.SYNC)
                    || state.getType().equals(StateValue.StateType.INSERT);
            if (!this.channel.isMaster() || state.getType().equals(StateValue.StateType.SYNC)) {
                if (containsKey) {
                    if (key.isLockExpired()) {
                        StateValue old = this.localMap.get(key.getKey());
                        if (old != null) {
                            old.getKey().setLocked(false);
                        }
                    } else {
                        StateValue old = null;
                        if (insert) {
                            old = this.localMap.put(key.getKey(), stateValue);
                        } else {
                            old = this.localMap.remove(key.getKey());
                            StateValue copy = state.clone();
                            copy.setValue(null);
                            copy.setOldValue(null);
                            stateValue = copy;
                        }
                        fireMapChanged(key.getOwner(), key.getKey(), old.getValue(), stateValue.getValue(), stateValue
                                .isExpired());
                    }
                } else {
                    if (insert) {
                        this.localMap.put(key.getKey(), stateValue);
                        fireMapChanged(key.getOwner(), key.getKey(), null, stateValue.getValue(), false);
                    }
                }
            }
        }
    }

    protected void checkStatus() throws RuntimeException {
        if (!isStarted()) {
            throw new IllegalStateException("ClusterState " + this.channel.getName() + " not started");
        }
        boolean result = false;
        BlazeClusterGroupConfiguration config = this.channel.getConfiguration();
        try {
            // We need to wait longer than the ElectionService (which calls an
            // election)
            // to determine if the election has finished
            result = this.channel.waitForElection(0);
        } catch (Exception e) {
            if (e instanceof RuntimeException) {
                throw (RuntimeException) e;
            }
            throw new BlazeRuntimeException(e);
        }
        if (!result) {
            int memberCount = 0;
            try {
                memberCount = this.channel.getMembers().size();
                System.err.println("Member count = " + memberCount + " are we master ? " + this.channel.isMaster());
            } catch (Exception e) {
            }
            throw new BlazeRuntimeException("Cluster not established - need " + config.getMinimumGroupSize()
                    + " but only " + memberCount + " members");
        }
    }

    protected void expirationSweep() throws Exception {
        if (this.channel.waitForElection(0)) {
            if (this.channel.isMaster() && isStarted()) {
                List<String> expiredMessages = null;
                List<StateValue> expiredLocks = null;
                long currentTime = System.currentTimeMillis();
                for (StateValue value : this.localMap.values()) {
                    StateKey key = value.getKey();
                    if (key.isExpired(currentTime)) {
                        if (expiredMessages == null) {
                            expiredMessages = new ArrayList<String>();
                        }
                        expiredMessages.add(key.getKey());
                    } else if (key.isLockExpired(currentTime)) {
                        key.setLocked(false);
                        if (expiredLocks == null) {
                            expiredLocks = new ArrayList<StateValue>();
                        }
                        expiredLocks.add(value);
                    }
                }
                // do the actual removal of entries in a separate thread
                if (expiredMessages != null) {
                    final List<String> expire = expiredMessages;
                    this.stateChangedExecutor.execute(new Runnable() {
                        public void run() {
                            try {
                                doMessageExpiration(expire);
                            } catch (Exception e) {
                                LOG.error("Message expiration failed", e);
                            }
                        }
                    });
                }
                if (expiredLocks != null) {
                    final List<StateValue> expire = expiredLocks;
                    this.stateChangedExecutor.execute(new Runnable() {
                        public void run() {
                            try {
                                doLockExpiration(expire);
                            } catch (Exception e) {
                                LOG.error("Lock expiration failed", e);
                            }
                        }
                    });
                }
            }
        }
    }

    protected void doMessageExpiration(List<String> list) throws Exception {
        if (isStarted() && this.channel.isElectionFinished() && this.channel.isMaster()) {
            for (String k : list) {
                StateValue old = this.localMap.remove(k);
                if (old != null) {
                    StateValue value = old.clone();
                    value.setType(StateValue.StateType.DELETE);
                    value.setExpired(true);
                    value.setMapWrite(false);
                    value.setMapUpdate(true);
                    broadcastStateUpdate(value, "");
                    fireMapChanged(value.getKey().getOwner().clone(), k, old.getValue(), null, true);
                }
            }
        }
    }

    protected StateKey getKey(String key) {
        StateValue stateValue = this.localMap != null ? this.localMap.get(key) : null;
        return stateValue != null ? stateValue.getKey() : null;
    }

    protected void doLockExpiration(List<StateValue> list) throws Exception {
        if (isStarted() && this.channel.isElectionFinished() && this.channel.isMaster()) {
            for (StateValue value : list) {
                StateValue copy = value.clone();
                copy.setType(StateValue.StateType.DELETE);
                copy.setLockExpired(true);
                broadcastStateUpdate(copy, "");
            }
        }
    }

    protected void fireMapChanged(final Member owner, final String key, final Object oldValue, final Object newValue,
                                  final boolean expired) {
        if (isStarted() && this.stateChangedExecutor != null && !this.stateChangedExecutor.isShutdown()) {
            this.stateChangedExecutor.execute(new Runnable() {
                public void run() {
                    doFireMapChanged(owner, key, oldValue, newValue, expired);
                }
            });
        }
    }

    protected void doFireMapChanged(Member owner, String key, Object oldValue, Object newValue, boolean expired) {
        if (isStarted()) {
            for (ClusterStateChangedListener l : this.clusterStateChangedListeners) {
                if (oldValue == null) {
                    l.mapInsert(owner, key, newValue);
                } else if (newValue == null) {
                    l.mapRemove(owner, key, oldValue, expired);
                } else {
                    l.mapUpdate(owner, key, oldValue, newValue);
                }
            }
        }
    }

    protected void broadcastStateUpdate(StateValue value, String correlationId) {
        if (isStarted()) {
            try {
                value.setMapUpdate(true);
                this.channel.broadcastManagementMessage(value, correlationId);
            } catch (Exception e) {
                if (isStarted()) {
                    LOG.error("Failed to send StateData " + value, e);
                }
            }
        }
    }

    protected StateValue sendMasterRequest(StateValue state) throws Exception {
        int retryCount = 0;
        StateValue result = null;
        MemberImpl master = null;
        while (retryCount < 5) {
            this.channel.waitForElection(0);
            master = (MemberImpl) this.channel.getMaster();
            result = (StateValue) this.channel.sendRequest(master, state, getRequestTimeout());
            retryCount++;
            if (result != null) {
                if (result.getValue() instanceof ClusterNotMasterException) {
                    LOG.warn(this.getLocal().getName() + " Request sent to an old master " + master
                            + "  - resending to new master: " + this.channel.getMaster());
                    Thread.sleep(1000);
                    continue;
                }
                if (result.getValue() instanceof ClusterUpdateException) {
                    throw (ClusterUpdateException) result.getValue();
                }
                return result;
            }
        }
        throw new ClusterUpdateException(getLocal() + " Request timed out to " + master);
    }

    protected MemberImpl getLocal() {
        return this.channel.getLocalMember();
    }

    protected String getName() {
        return getLocal().getName();
    }
}