Reduced graph handles and thread locals
diff --git a/src/main/java/net/floodlightcontroller/core/INetMapTopologyObjects.java b/src/main/java/net/floodlightcontroller/core/INetMapTopologyObjects.java
index 2c19f68..e58b19f 100644
--- a/src/main/java/net/floodlightcontroller/core/INetMapTopologyObjects.java
+++ b/src/main/java/net/floodlightcontroller/core/INetMapTopologyObjects.java
@@ -62,10 +62,23 @@
 		@Property("number")
 		public Short getNumber();
 		
+		@Property("number")
+		public void setNumber(Short n);
+		
 		@JsonProperty("desc")
 		@Property("desc")
 		public String getDesc();
 		
+		@Property("desc")
+		public void setDesc(String s);
+		
+		@JsonIgnore
+		@Property("port_sate")
+		public Integer getPortState();
+		
+		@Property("port_state")
+		public void setPortState(Integer s);
+		
 		@JsonIgnore
 		@Incidence(label="on",direction = Direction.IN)
 		public ISwitchObject getSwitch();
diff --git a/src/main/java/net/floodlightcontroller/core/INetMapTopologyService.java b/src/main/java/net/floodlightcontroller/core/INetMapTopologyService.java
index 6cfc974..ecf217e 100644
--- a/src/main/java/net/floodlightcontroller/core/INetMapTopologyService.java
+++ b/src/main/java/net/floodlightcontroller/core/INetMapTopologyService.java
@@ -19,12 +19,14 @@
 		Iterable<ISwitchObject> getInactiveSwitches();
 		Iterable<IPortObject> getPortsOnSwitch(String dpid);
 		IPortObject getPortOnSwitch(String dpid, short port_num);
+		void close();
 
 	}
 	
 	public interface ITopoLinkService {
 		List<Link> getActiveLinks();
 		List<Link> getLinksOnSwitch(String dpid);
+		void close();
 	}
 	public interface ITopoDeviceService {
 		Iterable<IDeviceObject> getActiveDevices();
diff --git a/src/main/java/net/floodlightcontroller/core/ISwitchStorage.java b/src/main/java/net/floodlightcontroller/core/ISwitchStorage.java
index 3646e15..1219aac 100644
--- a/src/main/java/net/floodlightcontroller/core/ISwitchStorage.java
+++ b/src/main/java/net/floodlightcontroller/core/ISwitchStorage.java
@@ -50,9 +50,6 @@
 	 */
 	public void deletePort(String dpid, String portName);
 	
-	public Iterable<ISwitchObject> getActiveSwitches();
-	public Iterable<ISwitchObject> getAllSwitches();
-	public Iterable<ISwitchObject> getInactiveSwitches();
 	
 	/*
 	 * Initialize
diff --git a/src/main/java/net/floodlightcontroller/core/internal/Controller.java b/src/main/java/net/floodlightcontroller/core/internal/Controller.java
index c3d2b03..1a9a9c5 100644
--- a/src/main/java/net/floodlightcontroller/core/internal/Controller.java
+++ b/src/main/java/net/floodlightcontroller/core/internal/Controller.java
@@ -146,18 +146,8 @@
  */
 public class Controller implements IFloodlightProviderService, 
             IStorageSourceListener {
-   
-	ThreadLocal<SwitchStorageImpl> store = new ThreadLocal<SwitchStorageImpl>() {
-		@Override
-		protected SwitchStorageImpl initialValue() {
-			SwitchStorageImpl swStore = new SwitchStorageImpl();
-			//TODO: Get the file path from global properties
-			swStore.init("/tmp/cassandra.titan");
-			return swStore;
-		}
-	};
-	
-	protected SwitchStorageImpl swStore = store.get();
+   	
+	protected SwitchStorageImpl swStore;;
 	
     protected static Logger log = LoggerFactory.getLogger(Controller.class);
 
@@ -2217,11 +2207,20 @@
         this.updates = new LinkedBlockingQueue<IUpdate>();
         this.factory = new BasicFactory();
         this.providerMap = new HashMap<String, List<IInfoProvider>>();
+        
         setConfigParams(configParams);
         //this.role = getInitialRole(configParams);
         //Set the controller's role to MASTER so it always tries to do role requests.
         this.role = Role.MASTER;
         this.roleChanger = new RoleChanger();
+        
+		String conf = configParams.get("dbconf");
+		if (conf == null) {
+			conf = "/tmp/cassandra.titan";
+		}
+		this.swStore = new SwitchStorageImpl();
+		this.swStore.init(conf);
+		
         initVendorMessages();
         this.systemStartTime = System.currentTimeMillis();
     }
diff --git a/src/main/java/net/floodlightcontroller/core/internal/SwitchStorageImpl.java b/src/main/java/net/floodlightcontroller/core/internal/SwitchStorageImpl.java
index 7e049b6..a068586 100644
--- a/src/main/java/net/floodlightcontroller/core/internal/SwitchStorageImpl.java
+++ b/src/main/java/net/floodlightcontroller/core/internal/SwitchStorageImpl.java
@@ -1,31 +1,21 @@
 package net.floodlightcontroller.core.internal;
 
-import java.util.ArrayList;
 import java.util.Collection;
-import java.util.List;
-import java.util.Set;
 
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import net.floodlightcontroller.core.INetMapTopologyObjects.IPortObject;
+import net.floodlightcontroller.core.INetMapTopologyObjects.ISwitchObject;
+import net.floodlightcontroller.core.ISwitchStorage;
+import net.onrc.onos.util.GraphDBConnection;
+import net.onrc.onos.util.GraphDBConnection.Transaction;
 
 import org.openflow.protocol.OFPhysicalPort;
 import org.openflow.protocol.OFPhysicalPort.OFPortConfig;
 import org.openflow.protocol.OFPhysicalPort.OFPortState;
-
-import com.thinkaurelius.titan.core.TitanException;
-import com.thinkaurelius.titan.core.TitanFactory;
-import com.thinkaurelius.titan.core.TitanGraph;
-import com.tinkerpop.blueprints.Direction;
-import com.tinkerpop.blueprints.TransactionalGraph;
-import com.tinkerpop.blueprints.TransactionalGraph.Conclusion;
-import com.tinkerpop.blueprints.Edge;
-import com.tinkerpop.blueprints.Vertex;
-import com.tinkerpop.frames.FramedGraph;
-import net.floodlightcontroller.core.INetMapTopologyObjects.ISwitchObject;
-import net.floodlightcontroller.core.ISwitchStorage;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 public class SwitchStorageImpl implements ISwitchStorage {
-	public TitanGraph graph;
+	public GraphDBConnection conn;
 	protected static Logger log = LoggerFactory.getLogger(SwitchStorageImpl.class);
 
 	@Override
@@ -50,26 +40,20 @@
 	}
 
 	private void setStatus(String dpid, SwitchState state) {
-		Vertex sw;
-		try {
-            if ((sw = graph.getVertices("dpid",dpid).iterator().next()) != null) {
-            	sw.setProperty("state",state.toString());
-            	graph.stopTransaction(Conclusion.SUCCESS);
-            	log.info("SwitchStorage:setStatus dpid:{} state: {} done", dpid, state);
-            }
-		} catch (TitanException e) {
-             // TODO: handle exceptions
-			graph.stopTransaction(Conclusion.FAILURE);
+		ISwitchObject sw = conn.utils().searchSwitch(conn, dpid);
+		if (sw != null) {
+			sw.setState(state.toString());
+			conn.endTx(Transaction.COMMIT);
+			log.info("SwitchStorage:setStatus dpid:{} state: {} done", dpid, state);
+		} 	else {
+			conn.endTx(Transaction.ROLLBACK);
 			log.info("SwitchStorage:setStatus dpid:{} state: {} failed", dpid, state);
 		}
-            	
-		
 	}
 
 	@Override
 	public void addPort(String dpid, OFPhysicalPort port) {
 		// TODO Auto-generated method stub
-		Vertex sw;
 		
         boolean portDown = ((OFPortConfig.OFPPC_PORT_DOWN.getValue() & port.getConfig()) > 0) ||
         		((OFPortState.OFPPS_LINK_DOWN.getValue() & port.getState()) > 0);
@@ -77,30 +61,31 @@
              deletePort(dpid, port.getPortNumber());
              return;
        }
+             
 		try {
-            if ((sw = graph.getVertices("dpid",dpid).iterator().next()) != null) {
+			ISwitchObject sw = conn.utils().searchSwitch(conn, dpid);
+
+            if (sw != null) {
+            	IPortObject p = conn.utils().searchPort(conn, dpid, port.getPortNumber());
             	log.info("SwitchStorage:addPort dpid:{} port:{}", dpid, port.getPortNumber());
-            	// TODO: Check if port exists
-            	if (sw.query().direction(Direction.OUT).labels("on").has("number",port.getPortNumber()).vertices().iterator().hasNext()) {
-            		//TODO: Do nothing for now
+            	if (p != null) {
             		log.error("SwitchStorage:addPort dpid:{} port:{} exists", dpid, port.getPortNumber());
             	} else {
-            		Vertex p = graph.addVertex(null);
-            		p.setProperty("type","port");
-            		p.setProperty("number",port.getPortNumber());
-            		p.setProperty("state", "ACTIVE");
-            		p.setProperty("port_state",port.getState());
-            		p.setProperty("desc",port.getName());
-            		Edge e = graph.addEdge(null, sw, p, "on");
-            		e.setProperty("state","ACTIVE");
-            		e.setProperty("number", port.getPortNumber());
-                     	
-            		graph.stopTransaction(Conclusion.SUCCESS);
+            		p = conn.utils().newPort(conn);
+
+            		p.setType("port");
+            		p.setNumber(port.getPortNumber());
+            		p.setState("ACTIVE");
+            		p.setPortState(port.getState());
+            		p.setDesc(port.getName());
+            		sw.addPort(p);
+            		conn.endTx(Transaction.COMMIT);
+  
             	}
             }
-		} catch (TitanException e) {
+		} catch (Exception e) {
              // TODO: handle exceptions
-			graph.stopTransaction(Conclusion.FAILURE);
+			conn.endTx(Transaction.ROLLBACK);
 			log.error("SwitchStorage:addPort dpid:{} port:{} failed", dpid, port.getPortNumber());
 		}	
 
@@ -130,29 +115,29 @@
 		log.info("SwitchStorage:addSwitch(): dpid {} ", dpid);
 		
         try {
-            if (graph.getVertices("dpid",dpid).iterator().hasNext()) {
+        	ISwitchObject sw = conn.utils().searchSwitch(conn, dpid);
+            if (sw != null) {
                     /*
                      *  Do nothing or throw exception?
                      */
-            		Vertex sw = graph.getVertices("dpid",dpid).iterator().next();
             	
             		log.info("SwitchStorage:addSwitch dpid:{} already exists", dpid);
-            		sw.setProperty("state",SwitchState.ACTIVE.toString());
-            		graph.stopTransaction(Conclusion.SUCCESS);
+            		sw.setState(SwitchState.ACTIVE.toString());
+            		conn.endTx(Transaction.COMMIT);
             } else {
-                    Vertex sw = graph.addVertex(null);
+                    sw = conn.utils().newSwitch(conn);
 
-                    sw.setProperty("type","switch");
-                    sw.setProperty("dpid", dpid);
-                    sw.setProperty("state",SwitchState.ACTIVE.toString());
-                    graph.stopTransaction(Conclusion.SUCCESS);
+                    sw.setType("switch");
+                    sw.setDPID(dpid);
+                    sw.setState(SwitchState.ACTIVE.toString());
+                    conn.endTx(Transaction.COMMIT);
                     log.info("SwitchStorage:addSwitch dpid:{} added", dpid);
             }
-    } catch (TitanException e) {
+    } catch (Exception e) {
             /*
-             * retry till we succeed?
+             * retry?
              */
-    	graph.stopTransaction(Conclusion.FAILURE);
+    	conn.endTx(Transaction.ROLLBACK);
     	log.info("SwitchStorage:addSwitch dpid:{} failed", dpid);
     }
 
@@ -162,17 +147,19 @@
 	@Override
 	public void deleteSwitch(String dpid) {
 		// TODO Setting inactive but we need to eventually remove data
-		Vertex sw;
+
 		try {
-			
-            if ((sw = graph.getVertices("dpid",dpid).iterator().next()) != null) {
-            	graph.removeVertex(sw);
-            	graph.stopTransaction(Conclusion.SUCCESS);
+
+			ISwitchObject sw = conn.utils().searchSwitch(conn, dpid);
+            if (sw  != null) {
+            	conn.utils().removeSwitch(conn, sw);
+ 
+            	conn.endTx(Transaction.COMMIT);
             	log.info("SwitchStorage:DeleteSwitch dpid:{} done", dpid);
             }
-		} catch (TitanException e) {
+		} catch (Exception e) {
              // TODO: handle exceptions
-			graph.stopTransaction(Conclusion.FAILURE);
+			conn.endTx(Transaction.ROLLBACK);			
 			log.error("SwitchStorage:deleteSwitch {} failed", dpid);
 		}
 
@@ -181,21 +168,21 @@
 	@Override
 	public void deletePort(String dpid, short port) {
 		// TODO Auto-generated method stub
-		Vertex sw;
 		try {
-            if ((sw = graph.getVertices("dpid",dpid).iterator().next()) != null) {
-            	// TODO: Check if port exists
-            	log.info("SwitchStorage:deletePort dpid:{} port:{}", dpid, port);
-            	if (sw.query().direction(Direction.OUT).labels("on").has("number",port).vertices().iterator().hasNext()) {
-            		Vertex p = sw.query().direction(Direction.OUT).labels("on").has("number",port).vertices().iterator().next();
+			ISwitchObject sw = conn.utils().searchSwitch(conn, dpid);
+
+            if (sw != null) {
+            	IPortObject p = conn.utils().searchPort(conn, dpid, port);
+                if (p != null) {
             		log.info("SwitchStorage:deletePort dpid:{} port:{} found and deleted", dpid, port);
-            		graph.removeVertex(p);
-            		graph.stopTransaction(Conclusion.SUCCESS);
+            		sw.removePort(p);
+            		conn.utils().removePort(conn, p);
+            		conn.endTx(Transaction.COMMIT);
             	}
             }
-		} catch (TitanException e) {
+		} catch (Exception e) {
              // TODO: handle exceptions
-			graph.stopTransaction(Conclusion.FAILURE);
+			conn.endTx(Transaction.ROLLBACK);
 			log.info("SwitchStorage:deletePort dpid:{} port:{} failed", dpid, port);
 		}	
 	}
@@ -206,74 +193,24 @@
 
 	}
 
-	@Override
-	public Iterable<ISwitchObject> getActiveSwitches() {
-		// TODO Add unit test
-		FramedGraph<TitanGraph> fg = new FramedGraph<TitanGraph>(graph);
-		Iterable<ISwitchObject> switches =  fg.getVertices("type","switch",ISwitchObject.class);
-		List<ISwitchObject> activeSwitches = new ArrayList<ISwitchObject>();
 
-		for (ISwitchObject sw: switches) {
-			if(sw.getState().equals(SwitchState.ACTIVE.toString())) {
-				activeSwitches.add(sw);
-			}
-		}
-
-		return activeSwitches;		
-	}
 
 	@Override
 	public void init(String conf) {
 
-        graph = TitanFactory.open(conf);
+		conn = GraphDBConnection.getInstance(conf);
         
-        // FIXME: Creation on Indexes should be done only once
-        Set<String> s = graph.getIndexedKeys(Vertex.class);
-        if (!s.contains("dpid")) {
-           graph.createKeyIndex("dpid", Vertex.class);
-           graph.stopTransaction(Conclusion.SUCCESS);
-        }
-        if (!s.contains("type")) {
-        	graph.createKeyIndex("type", Vertex.class);
-        	graph.stopTransaction(Conclusion.SUCCESS);
-        }
 	}
 
-	@Override
-	public Iterable<ISwitchObject> getAllSwitches() {
-		// TODO Auto-generated method stub
-		FramedGraph<TitanGraph> fg = new FramedGraph<TitanGraph>(graph);
-		Iterable<ISwitchObject> switches =  fg.getVertices("type","switch",ISwitchObject.class);
 
 
-		return switches;
-	}
-
-	@Override
-	public Iterable<ISwitchObject> getInactiveSwitches() {
-		// TODO Auto-generated method stub
-		FramedGraph<TitanGraph> fg = new FramedGraph<TitanGraph>(graph);
-		Iterable<ISwitchObject> switches =  fg.getVertices("type","switch",ISwitchObject.class);
-
-		List<ISwitchObject> inactiveSwitches = new ArrayList<ISwitchObject>();
-		
-		for (ISwitchObject sw: switches) {
-			if(sw.getState().equals(SwitchState.INACTIVE.toString())) {
-				inactiveSwitches.add(sw);
-			}
-		}
-		return inactiveSwitches;
-	}
-
 	public void finalize() {
 		close();
 	}
 	
 	@Override
 	public void close() {
-		// TODO Auto-generated method stub
-		graph.shutdown();
-		
+		conn.close();		
 	}
 
 	
diff --git a/src/main/java/net/floodlightcontroller/core/internal/TopoSwitchServiceImpl.java b/src/main/java/net/floodlightcontroller/core/internal/TopoSwitchServiceImpl.java
index e8b1bf8..b3c31ec 100644
--- a/src/main/java/net/floodlightcontroller/core/internal/TopoSwitchServiceImpl.java
+++ b/src/main/java/net/floodlightcontroller/core/internal/TopoSwitchServiceImpl.java
@@ -1,39 +1,49 @@
 package net.floodlightcontroller.core.internal;
 
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 import net.floodlightcontroller.core.INetMapTopologyObjects.IPortObject;
 import net.floodlightcontroller.core.INetMapTopologyObjects.ISwitchObject;
 import net.floodlightcontroller.core.INetMapTopologyService.ITopoSwitchService;
+import net.onrc.onos.util.GraphDBConnection;
+import net.onrc.onos.util.GraphDBConnection.Transaction;
 
 public class TopoSwitchServiceImpl implements ITopoSwitchService {
 	
-	ThreadLocal<SwitchStorageImpl> store = new ThreadLocal<SwitchStorageImpl>() {
-		@Override
-		protected SwitchStorageImpl initialValue() {
-			SwitchStorageImpl swStore = new SwitchStorageImpl();
-			//TODO: Get the file path from global properties
-			swStore.init("/tmp/cassandra.titan");
-			return swStore;
-		}
-	};
+	private GraphDBConnection conn;
+	protected static Logger log = LoggerFactory.getLogger(TopoSwitchServiceImpl.class);
+
+
+	public void finalize() {
+		close();
+	}
 	
-	SwitchStorageImpl swStore = store.get();
+	@Override
+	public void close() {
+		conn.endTx(Transaction.COMMIT);
+		conn.close();
+	}
 	
 	@Override
 	public Iterable<ISwitchObject> getActiveSwitches() {
 		// TODO Auto-generated method stub
-		return swStore.getActiveSwitches();
+		conn = GraphDBConnection.getInstance("");
+		return conn.utils().getActiveSwitches(conn);
 	}
 
 	@Override
 	public Iterable<ISwitchObject> getAllSwitches() {
-		// TODO Auto-generated method stub		
-		return swStore.getAllSwitches();
+		// TODO Auto-generated method stub
+		conn = GraphDBConnection.getInstance("");
+		return conn.utils().getAllSwitches(conn);
 	}
 
 	@Override
 	public Iterable<ISwitchObject> getInactiveSwitches() {
 		// TODO Auto-generated method stub
-		return swStore.getInactiveSwitches();
+		conn = GraphDBConnection.getInstance("");
+		return conn.utils().getInactiveSwitches(conn);
 	}
 
 	@Override