Renamed datagrid and datastore packages

net.onrc.onos.datagrid.* => net.onrc.onos.core.datagrid.*
net.onrc.onos.datastore.* => net.onrc.onos.core.datastore.*

Change-Id: Ibe1894a6fabae08ea7cfcbf6595f0c91b05ef497
diff --git a/src/main/java/net/onrc/onos/core/datastore/topology/KVDevice.java b/src/main/java/net/onrc/onos/core/datastore/topology/KVDevice.java
new file mode 100644
index 0000000..96411a9
--- /dev/null
+++ b/src/main/java/net/onrc/onos/core/datastore/topology/KVDevice.java
@@ -0,0 +1,222 @@
+package net.onrc.onos.core.datastore.topology;
+
+import java.nio.ByteBuffer;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+
+import net.onrc.onos.core.datastore.DataStoreClient;
+import net.onrc.onos.core.datastore.IKVTable.IKVEntry;
+import net.onrc.onos.core.datastore.topology.KVLink.STATUS;
+import net.onrc.onos.core.datastore.utils.ByteArrayComparator;
+import net.onrc.onos.core.datastore.utils.ByteArrayUtil;
+import net.onrc.onos.core.datastore.utils.KVObject;
+import net.onrc.onos.ofcontroller.networkgraph.DeviceEvent;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.esotericsoftware.kryo.Kryo;
+
+/**
+ * Device object.
+ *
+ * TODO switch to ProtoBuf, etc.
+ */
+public class KVDevice extends KVObject {
+    private static final Logger log = LoggerFactory.getLogger(KVDevice.class);
+
+    private static final ThreadLocal<Kryo> deviceKryo = new ThreadLocal<Kryo>() {
+        @Override
+        protected Kryo initialValue() {
+            Kryo kryo = new Kryo();
+            kryo.setRegistrationRequired(true);
+            kryo.setReferences(false);
+            kryo.register(byte[].class);
+            kryo.register(byte[][].class);
+            kryo.register(HashMap.class);
+            // TODO check if we should explicitly specify EnumSerializer
+            kryo.register(STATUS.class);
+            return kryo;
+        }
+    };
+
+    public static final String GLOBAL_DEVICE_TABLE_NAME = "G:Device";
+
+    // FIXME these should be Enum or some number, not String
+    private static final String PROP_MAC = "mac";
+    private static final String PROP_PORT_IDS = "port-ids";
+
+    private final byte[] mac;
+    private TreeSet<byte[]> portIds;
+    private transient boolean isPortIdsModified;
+    
+    // Assume there is only one ip on a device now.
+    private int ip;
+    private long lastSeenTime;
+
+    // Assuming mac is unique cluster-wide
+    public static byte[] getDeviceID(final byte[] mac) {
+        return DeviceEvent.getDeviceID(mac).array();
+    }
+
+    public static byte[] getMacFromKey(final byte[] key) {
+        ByteBuffer keyBuf = ByteBuffer.wrap(key);
+        if (keyBuf.getChar() != 'D') {
+            throw new IllegalArgumentException("Invalid Device key");
+        }
+        byte[] mac = new byte[keyBuf.remaining()];
+        keyBuf.get(mac);
+        return mac;
+    }
+
+    public KVDevice(final byte[] mac) {
+        super(DataStoreClient.getClient().getTable(GLOBAL_DEVICE_TABLE_NAME), getDeviceID(mac));
+
+        this.mac = mac;
+        this.portIds = new TreeSet<>(ByteArrayComparator.BYTEARRAY_COMPARATOR);
+        this.isPortIdsModified = true;
+    }
+
+    /**
+     * Get an instance from Key.
+     *
+     * @note You need to call `read()` to get the DB content.
+     * @param key
+     * @return
+     */
+    public static KVDevice createFromKey(final byte[] key) {
+        return new KVDevice(getMacFromKey(key));
+    }
+
+    public static Iterable<KVDevice> getAllDevices() {
+        return new DeviceEnumerator();
+    }
+
+    public static class DeviceEnumerator implements Iterable<KVDevice> {
+
+        @Override
+        public Iterator<KVDevice> iterator() {
+            return new DeviceIterator();
+        }
+    }
+
+    public static class DeviceIterator extends AbstractObjectIterator<KVDevice> {
+
+        public DeviceIterator() {
+            super(DataStoreClient.getClient().getTable(GLOBAL_DEVICE_TABLE_NAME));
+        }
+
+        @Override
+        public KVDevice next() {
+            IKVEntry o = enumerator.next();
+            KVDevice e = KVDevice.createFromKey(o.getKey());
+            e.deserialize(o.getValue(), o.getVersion());
+            return e;
+        }
+    }
+
+    public byte[] getMac() {
+        // TODO may need to clone() to be sure this object will be immutable.
+        return mac;
+    }
+
+    public byte[] getId() {
+        return getKey();
+    }
+
+    public void addPortId(final byte[] portId) {
+        // TODO: Should we copy portId, or reference is OK.
+        isPortIdsModified |= portIds.add(portId);
+    }
+
+    public void removePortId(final byte[] portId) {
+        isPortIdsModified |= portIds.remove(portId);
+    }
+
+    public void emptyPortIds() {
+        portIds.clear();
+        this.isPortIdsModified = true;
+    }
+
+    public void addAllToPortIds(final Collection<byte[]> portIds) {
+        // TODO: Should we copy portId, or reference is OK.
+        isPortIdsModified |= this.portIds.addAll(portIds);
+    }
+
+    /**
+     *
+     * @return Unmodifiable Set view of all the PortIds;
+     */
+    public Set<byte[]> getAllPortIds() {
+        return Collections.unmodifiableSet(portIds);
+    }
+
+    @Override
+    public byte[] serialize() {
+        Map<Object, Object> map = getPropertyMap();
+
+        map.put(PROP_MAC, mac);
+        if (isPortIdsModified) {
+            byte[][] portIdArray = new byte[portIds.size()][];
+            map.put(PROP_PORT_IDS, portIds.toArray(portIdArray));
+            isPortIdsModified = false;
+        }
+
+        return serializePropertyMap(deviceKryo.get(), map);
+    }
+
+    @Override
+    protected boolean deserialize(final byte[] bytes) {
+        boolean success = deserializePropertyMap(deviceKryo.get(), bytes);
+        if (!success) {
+            log.error("Deserializing Link: " + this + " failed.");
+            return false;
+        }
+        Map<Object, Object> map = this.getPropertyMap();
+
+        if (this.portIds == null) {
+            this.portIds = new TreeSet<>(
+                    ByteArrayComparator.BYTEARRAY_COMPARATOR);
+        }
+        byte[][] portIdArray = (byte[][]) map.get(PROP_PORT_IDS);
+        if (portIdArray != null) {
+            this.portIds.clear();
+            this.portIds.addAll(Arrays.asList(portIdArray));
+            isPortIdsModified = false;
+        } else {
+            // trigger write on next serialize
+            isPortIdsModified = true;
+        }
+
+        return success;
+    }
+
+    @Override
+    public String toString() {
+        // TODO output all properties?
+        return "[" + this.getClass().getSimpleName()
+                + " " + ByteArrayUtil.toHexStringBuffer(mac, ":") + "]";
+    }
+    
+	public int getIp() {
+		return ip;
+	}
+
+	public void setIp(int ip) {
+		this.ip = ip;
+	}
+
+	public long getLastSeenTime() {
+		return lastSeenTime;
+	}
+
+	public void setLastSeenTime(long lastSeenTime) {
+		this.lastSeenTime = lastSeenTime;
+	}
+}
diff --git a/src/main/java/net/onrc/onos/core/datastore/topology/KVLink.java b/src/main/java/net/onrc/onos/core/datastore/topology/KVLink.java
new file mode 100644
index 0000000..971cb6d
--- /dev/null
+++ b/src/main/java/net/onrc/onos/core/datastore/topology/KVLink.java
@@ -0,0 +1,217 @@
+package net.onrc.onos.core.datastore.topology;
+
+import java.nio.ByteBuffer;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import net.onrc.onos.core.datastore.DataStoreClient;
+import net.onrc.onos.core.datastore.IKVTable.IKVEntry;
+import net.onrc.onos.core.datastore.RCProtos.LinkProperty;
+import net.onrc.onos.core.datastore.utils.KVObject;
+import net.onrc.onos.ofcontroller.networkgraph.LinkEvent;
+import net.onrc.onos.ofcontroller.networkgraph.PortEvent;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.esotericsoftware.kryo.Kryo;
+import com.google.protobuf.ByteString;
+import com.google.protobuf.InvalidProtocolBufferException;
+
+/**
+ * Link object in data store.
+ */
+public class KVLink extends KVObject {
+    private static final Logger log = LoggerFactory.getLogger(KVLink.class);
+
+    private static final ThreadLocal<Kryo> linkKryo = new ThreadLocal<Kryo>() {
+        @Override
+        protected Kryo initialValue() {
+            Kryo kryo = new Kryo();
+            kryo.setRegistrationRequired(true);
+            kryo.setReferences(false);
+            kryo.register(byte[].class);
+            kryo.register(byte[][].class);
+            kryo.register(HashMap.class);
+            // TODO check if we should explicitly specify EnumSerializer
+            kryo.register(STATUS.class);
+            return kryo;
+        }
+    };
+
+    public static class SwitchPort {
+        public final Long dpid;
+        public final Long number;
+
+        public SwitchPort(final Long dpid, final Long number) {
+            this.dpid = dpid;
+            this.number = number;
+        }
+
+        public byte[] getPortID() {
+            return KVPort.getPortID(dpid, number);
+        }
+
+        public byte[] getSwitchID() {
+            return KVSwitch.getSwitchID(dpid);
+        }
+
+        @Override
+        public String toString() {
+            return "(" + Long.toHexString(dpid) + "@" + number + ")";
+        }
+
+    }
+
+    public static final String GLOBAL_LINK_TABLE_NAME = "G:Link";
+
+    // must not re-order enum members, ordinal will be sent over wire
+    public enum STATUS {
+        INACTIVE, ACTIVE;
+    }
+
+    private final SwitchPort src;
+    private final SwitchPort dst;
+    private STATUS status;
+
+    public static byte[] getLinkID(final Long src_dpid, final Long src_port_no,
+            final Long dst_dpid, final Long dst_port_no) {
+        return LinkEvent.getLinkID(src_dpid, src_port_no, dst_dpid,
+                dst_port_no).array();
+    }
+
+    public static long[] getLinkTupleFromKey(final byte[] key) {
+        return getLinkTupleFromKey(ByteBuffer.wrap(key));
+    }
+
+    public static long[] getLinkTupleFromKey(final ByteBuffer keyBuf) {
+        if (keyBuf.getChar() != 'L') {
+            throw new IllegalArgumentException("Invalid Link key");
+        }
+        final long[] srcPortPair = KVPort.getPortPairFromKey(keyBuf.slice());
+        keyBuf.position(2 + PortEvent.PORTID_BYTES);
+        final long[] dstPortPair = KVPort.getPortPairFromKey(keyBuf.slice());
+
+        long[] tuple = new long[4];
+        tuple[0] = srcPortPair[0];
+        tuple[1] = srcPortPair[1];
+        tuple[2] = dstPortPair[0];
+        tuple[3] = dstPortPair[1];
+
+        return tuple;
+    }
+
+    public KVLink(final Long src_dpid, final Long src_port_no,
+            final Long dst_dpid, final Long dst_port_no) {
+        super(DataStoreClient.getClient().getTable(GLOBAL_LINK_TABLE_NAME), getLinkID(src_dpid,
+                src_port_no, dst_dpid, dst_port_no));
+
+        src = new SwitchPort(src_dpid, src_port_no);
+        dst = new SwitchPort(dst_dpid, dst_port_no);
+        status = STATUS.INACTIVE;
+    }
+
+    /**
+     * Get an instance from Key.
+     *
+     * @note You need to call `read()` to get the DB content.
+     * @param key
+     * @return KVLink instance
+     */
+    public static KVLink createFromKey(final byte[] key) {
+        long[] linkTuple = getLinkTupleFromKey(key);
+        return new KVLink(linkTuple[0], linkTuple[1], linkTuple[2],
+                linkTuple[3]);
+    }
+
+    public static Iterable<KVLink> getAllLinks() {
+        return new LinkEnumerator();
+    }
+
+    public static class LinkEnumerator implements Iterable<KVLink> {
+
+        @Override
+        public Iterator<KVLink> iterator() {
+            return new LinkIterator();
+        }
+    }
+
+    public static class LinkIterator extends AbstractObjectIterator<KVLink> {
+
+        public LinkIterator() {
+            super(DataStoreClient.getClient().getTable(GLOBAL_LINK_TABLE_NAME));
+        }
+
+        @Override
+        public KVLink next() {
+            IKVEntry o = enumerator.next();
+            KVLink e = KVLink.createFromKey(o.getKey());
+            e.deserialize(o.getValue(), o.getVersion());
+            return e;
+        }
+    }
+
+    public STATUS getStatus() {
+        return status;
+    }
+
+    public void setStatus(final STATUS status) {
+        this.status = status;
+    }
+
+    public SwitchPort getSrc() {
+        return src;
+    }
+
+    public SwitchPort getDst() {
+        return dst;
+    }
+
+    public byte[] getId() {
+        return getKey();
+    }
+
+    @Override
+    public byte[] serialize() {
+        Map<Object, Object> map = getPropertyMap();
+
+        LinkProperty.Builder link = LinkProperty.newBuilder();
+        link.setSrcSwId(ByteString.copyFrom(src.getSwitchID()));
+        link.setSrcPortId(ByteString.copyFrom(src.getPortID()));
+        link.setDstSwId(ByteString.copyFrom(dst.getSwitchID()));
+        link.setDstPortId(ByteString.copyFrom(dst.getPortID()));
+        link.setStatus(status.ordinal());
+
+        if (!map.isEmpty()) {
+            byte[] propMaps = serializePropertyMap(linkKryo.get(), map);
+            link.setValue(ByteString.copyFrom(propMaps));
+        }
+
+        return link.build().toByteArray();
+    }
+
+    @Override
+    protected boolean deserialize(final byte[] bytes) {
+        try {
+            boolean success = true;
+
+            LinkProperty link = LinkProperty.parseFrom(bytes);
+            byte[] props = link.getValue().toByteArray();
+            success &= deserializePropertyMap(linkKryo.get(), props);
+            this.status = STATUS.values()[link.getStatus()];
+
+            return success;
+        } catch (InvalidProtocolBufferException e) {
+            log.error("Deserializing Link: " + this + " failed.", e);
+            return false;
+        }
+    }
+
+    @Override
+    public String toString() {
+        // TODO output all properties?
+        return "[" + this.getClass().getSimpleName()
+                + " " + src + "->" + dst + " STATUS:" + status + "]";
+    }
+}
diff --git a/src/main/java/net/onrc/onos/core/datastore/topology/KVPort.java b/src/main/java/net/onrc/onos/core/datastore/topology/KVPort.java
new file mode 100644
index 0000000..9ab2d2a
--- /dev/null
+++ b/src/main/java/net/onrc/onos/core/datastore/topology/KVPort.java
@@ -0,0 +1,205 @@
+package net.onrc.onos.core.datastore.topology;
+
+import java.nio.ByteBuffer;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import net.onrc.onos.core.datastore.DataStoreClient;
+import net.onrc.onos.core.datastore.IKVTable.IKVEntry;
+import net.onrc.onos.core.datastore.RCProtos.PortProperty;
+import net.onrc.onos.core.datastore.utils.ByteArrayUtil;
+import net.onrc.onos.core.datastore.utils.KVObject;
+import net.onrc.onos.ofcontroller.networkgraph.PortEvent;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.esotericsoftware.kryo.Kryo;
+import com.google.protobuf.ByteString;
+import com.google.protobuf.InvalidProtocolBufferException;
+
+/**
+ * Port object in data store.
+ *
+ * Note: This class will not maintain invariants.
+ *       e.g., It will NOT automatically remove Links or Devices on Port,
+ *       when deleting a Port.
+ */
+public class KVPort extends KVObject {
+    private static final Logger log = LoggerFactory.getLogger(KVPort.class);
+
+    private static final ThreadLocal<Kryo> portKryo = new ThreadLocal<Kryo>() {
+        @Override
+        protected Kryo initialValue() {
+            Kryo kryo = new Kryo();
+            kryo.setRegistrationRequired(true);
+            kryo.setReferences(false);
+            kryo.register(byte[].class);
+            kryo.register(byte[][].class);
+            kryo.register(HashMap.class);
+            // TODO check if we should explicitly specify EnumSerializer
+            kryo.register(STATUS.class);
+            return kryo;
+        }
+    };
+
+    public static final String GLOBAL_PORT_TABLE_NAME = "G:Port";
+
+    // must not re-order enum members, ordinal will be sent over wire
+    public enum STATUS {
+        INACTIVE, ACTIVE;
+    }
+
+    private final Long dpid;
+    private final Long number;
+
+    private STATUS status;
+
+    public static byte[] getPortID(final Long dpid, final Long number) {
+        return PortEvent.getPortID(dpid, number).array();
+    }
+
+    public static long[] getPortPairFromKey(final byte[] key) {
+        return getPortPairFromKey(ByteBuffer.wrap(key));
+    }
+
+    public static long[] getPortPairFromKey(final ByteBuffer keyBuf) {
+        if (keyBuf.getChar() != 'S') {
+            throw new IllegalArgumentException("Invalid Port key:" + keyBuf
+                    + " "
+                    + ByteArrayUtil.toHexStringBuffer(keyBuf.array(), ":"));
+        }
+        long[] pair = new long[2];
+        pair[0] = keyBuf.getLong();
+        if (keyBuf.getChar() != 'P') {
+            throw new IllegalArgumentException("Invalid Port key:" + keyBuf
+                    + " "
+                    + ByteArrayUtil.toHexStringBuffer(keyBuf.array(), ":"));
+        }
+        pair[1] = keyBuf.getLong();
+        return pair;
+
+    }
+
+    public static long getDpidFromKey(final byte[] key) {
+        return getPortPairFromKey(key)[0];
+    }
+
+    public static long getNumberFromKey(final byte[] key) {
+        return getPortPairFromKey(key)[1];
+    }
+
+    // FIXME specify DPID,number here, or Should caller specify the key it self?
+    // In other words, should layer above have the control of the ID?
+    public KVPort(final Long dpid, final Long number) {
+        super(DataStoreClient.getClient().getTable(GLOBAL_PORT_TABLE_NAME), getPortID(dpid, number));
+
+        // TODO Auto-generated constructor stub
+
+        this.dpid = dpid;
+        this.number = number;
+        this.status = STATUS.INACTIVE;
+    }
+
+    /**
+     * Get an instance from Key.
+     *
+     * @note You need to call `read()` to get the DB content.
+     * @param key
+     * @return KVPort instance
+     */
+    public static KVPort createFromKey(final byte[] key) {
+        long[] pair = getPortPairFromKey(key);
+        return new KVPort(pair[0], pair[1]);
+    }
+
+    public static Iterable<KVPort> getAllPorts() {
+        return new PortEnumerator();
+    }
+
+    public static class PortEnumerator implements Iterable<KVPort> {
+
+        @Override
+        public Iterator<KVPort> iterator() {
+            return new PortIterator();
+        }
+    }
+
+    public static class PortIterator extends AbstractObjectIterator<KVPort> {
+
+        public PortIterator() {
+            super(DataStoreClient.getClient().getTable(GLOBAL_PORT_TABLE_NAME));
+        }
+
+        @Override
+        public KVPort next() {
+            IKVEntry o = enumerator.next();
+            KVPort e = KVPort.createFromKey(o.getKey());
+            e.deserialize(o.getValue(), o.getVersion());
+            return e;
+        }
+    }
+
+    public STATUS getStatus() {
+        return status;
+    }
+
+    public void setStatus(final STATUS status) {
+        this.status = status;
+    }
+
+    public Long getDpid() {
+        return dpid;
+    }
+
+    public Long getNumber() {
+        return number;
+    }
+
+    public byte[] getId() {
+        return getKey();
+    }
+
+    @Override
+    public byte[] serialize() {
+        Map<Object, Object> map = getPropertyMap();
+
+        PortProperty.Builder port = PortProperty.newBuilder();
+        port.setDpid(dpid);
+        port.setNumber(number);
+        port.setStatus(status.ordinal());
+
+        if (!map.isEmpty()) {
+            byte[] propMaps = serializePropertyMap(portKryo.get(), map);
+            port.setValue(ByteString.copyFrom(propMaps));
+        }
+
+        return port.build().toByteArray();
+    }
+
+    @Override
+    protected boolean deserialize(final byte[] bytes) {
+        try {
+            boolean success = true;
+
+            PortProperty port = PortProperty.parseFrom(bytes);
+            byte[] props = port.getValue().toByteArray();
+            success &= deserializePropertyMap(portKryo.get(), props);
+            this.status = STATUS.values()[port.getStatus()];
+
+            return success;
+        } catch (InvalidProtocolBufferException e) {
+            log.error("Deserializing Port: " + this + " failed.", e);
+            return false;
+        }
+    }
+
+    @Override
+    public String toString() {
+        // TODO output all properties?
+        return "[" + this.getClass().getSimpleName()
+                + " 0x" + Long.toHexString(dpid) + "@" + number
+                + " STATUS:" + status + "]";
+    }
+}
diff --git a/src/main/java/net/onrc/onos/core/datastore/topology/KVSwitch.java b/src/main/java/net/onrc/onos/core/datastore/topology/KVSwitch.java
new file mode 100644
index 0000000..eb27f7a
--- /dev/null
+++ b/src/main/java/net/onrc/onos/core/datastore/topology/KVSwitch.java
@@ -0,0 +1,174 @@
+package net.onrc.onos.core.datastore.topology;
+
+import java.nio.ByteBuffer;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import net.onrc.onos.core.datastore.DataStoreClient;
+import net.onrc.onos.core.datastore.IKVTable.IKVEntry;
+import net.onrc.onos.core.datastore.RCProtos.SwitchProperty;
+import net.onrc.onos.core.datastore.utils.KVObject;
+import net.onrc.onos.ofcontroller.networkgraph.SwitchEvent;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.esotericsoftware.kryo.Kryo;
+import com.google.protobuf.ByteString;
+import com.google.protobuf.InvalidProtocolBufferException;
+
+/**
+ * Switch object in data store.
+ *
+ * Note: This class will not maintain invariants.
+ *       e.g., It will NOT automatically remove Ports on Switch,
+ *       when deleting a Switch.
+ */
+public class KVSwitch extends KVObject {
+    private static final Logger log = LoggerFactory.getLogger(KVSwitch.class);
+
+    private static final ThreadLocal<Kryo> switchKryo = new ThreadLocal<Kryo>() {
+        @Override
+        protected Kryo initialValue() {
+            Kryo kryo = new Kryo();
+            kryo.setRegistrationRequired(true);
+            kryo.setReferences(false);
+            kryo.register(byte[].class);
+            kryo.register(byte[][].class);
+            kryo.register(HashMap.class);
+            // TODO check if we should explicitly specify EnumSerializer
+            kryo.register(STATUS.class);
+            return kryo;
+        }
+    };
+
+    public static final String GLOBAL_SWITCH_TABLE_NAME = "G:Switch";
+
+    // must not re-order enum members, ordinal will be sent over wire
+    public enum STATUS {
+        INACTIVE, ACTIVE;
+    }
+
+    private final Long dpid;
+    private STATUS status;
+
+    public static byte[] getSwitchID(final Long dpid) {
+        return SwitchEvent.getSwitchID(dpid).array();
+    }
+
+    public static long getDpidFromKey(final byte[] key) {
+        return getDpidFromKey(ByteBuffer.wrap(key));
+    }
+
+    public static long getDpidFromKey(final ByteBuffer keyBuf) {
+        if (keyBuf.getChar() != 'S') {
+            throw new IllegalArgumentException("Invalid Switch key");
+        }
+        return keyBuf.getLong();
+    }
+
+    // FIXME specify DPID here, or Should caller specify the key it self?
+    // In other words, should layer above have the control of the ID?
+    public KVSwitch(final Long dpid) {
+        super(DataStoreClient.getClient().getTable(GLOBAL_SWITCH_TABLE_NAME), getSwitchID(dpid));
+
+        this.dpid = dpid;
+        this.status = STATUS.INACTIVE;
+    }
+
+    /**
+     * Get an instance from Key.
+     *
+     * @note You need to call `read()` to get the DB content.
+     * @param key
+     * @return KVSwitch instance
+     */
+    public static KVSwitch createFromKey(final byte[] key) {
+        return new KVSwitch(getDpidFromKey(key));
+    }
+
+    public static Iterable<KVSwitch> getAllSwitches() {
+        return new SwitchEnumerator();
+    }
+
+    public static class SwitchEnumerator implements Iterable<KVSwitch> {
+
+        @Override
+        public Iterator<KVSwitch> iterator() {
+            return new SwitchIterator();
+        }
+    }
+
+    public static class SwitchIterator extends AbstractObjectIterator<KVSwitch> {
+
+        public SwitchIterator() {
+            super(DataStoreClient.getClient().getTable(GLOBAL_SWITCH_TABLE_NAME));
+        }
+
+        @Override
+        public KVSwitch next() {
+            IKVEntry o = enumerator.next();
+            KVSwitch e = KVSwitch.createFromKey(o.getKey());
+            e.deserialize(o.getValue(), o.getVersion());
+            return e;
+        }
+    }
+
+    public STATUS getStatus() {
+        return status;
+    }
+
+    public void setStatus(final STATUS status) {
+        this.status = status;
+    }
+
+    public Long getDpid() {
+        return dpid;
+    }
+
+    public byte[] getId() {
+        return getKey();
+    }
+
+    @Override
+    public byte[] serialize() {
+        Map<Object, Object> map = getPropertyMap();
+
+        SwitchProperty.Builder sw = SwitchProperty.newBuilder();
+        sw.setDpid(dpid);
+        sw.setStatus(status.ordinal());
+
+        if (!map.isEmpty()) {
+            byte[] propMaps = serializePropertyMap(switchKryo.get(), map);
+            sw.setValue(ByteString.copyFrom(propMaps));
+        }
+
+        return sw.build().toByteArray();
+    }
+
+    @Override
+    protected boolean deserialize(final byte[] bytes) {
+        try {
+            boolean success = true;
+
+            SwitchProperty sw = SwitchProperty.parseFrom(bytes);
+            byte[] props = sw.getValue().toByteArray();
+            success &= deserializePropertyMap(switchKryo.get(), props);
+            this.status = STATUS.values()[sw.getStatus()];
+
+            return success;
+        } catch (InvalidProtocolBufferException e) {
+            log.error("Deserializing Switch: " + this + " failed.", e);
+            return false;
+        }
+    }
+
+    @Override
+    public String toString() {
+        // TODO output all properties?
+        return "[" + this.getClass().getSimpleName()
+                + " 0x" + Long.toHexString(dpid) + " STATUS:" + status + "]";
+    }
+
+}