more updates
[iotcloud.git] / src / java / iotcloud / Table.java
index c2adbc93fe9a67e84b6f669e52177760ff9d760a..c31aed86851d4e273eb950b0656f3223a54a7698 100644 (file)
@@ -21,10 +21,18 @@ final public class Table {
        public Table(String baseurl, String password, long _localmachineid) {
                localmachineid=_localmachineid;
                buffer = new SlotBuffer();
+               numslots = buffer.capacity();
                sequencenumber = 1;
                initCloud(baseurl, password);
        }
 
+       public Table(CloudComm _cloud, long _localmachineid) {
+               localmachineid=_localmachineid;
+               buffer = new SlotBuffer();
+               sequencenumber = 1;
+               cloud=_cloud;
+       }
+       
        private void initCloud(String baseurl, String password) {
                try {
                        SecretKeySpec secret=getKey(password);
@@ -64,21 +72,37 @@ final public class Table {
                        return null;
        }
 
+       public void initTable() {
+               Slot s=new Slot(1, localmachineid);
+               TableStatus status=new TableStatus(s, numslots);
+               s.addEntry(status);
+    Slot[] array=cloud.putSlot(s, numslots);
+    if (array == null) {
+      array = new Slot[] {s};
+                       validateandupdate(array); // update data structure
+               } else {
+                       throw new Error("Error on initialization");
+               }
+       }
+       
        public IoTString put(IoTString key, IoTString value) {
     while(true) {
       KeyValue oldvalue=table.get(key);
-      if (tryput(key, value)) {
+      if (tryput(key, value, false)) {
         return oldvalue.getValue();
       }
     }
   }
 
-  private boolean tryput(IoTString key, IoTString value) {
-    Slot s=new Slot(sequencenumber+1, localmachineid, buffer.getSlot(sequencenumber).getHMAC());
-    boolean forcedresize = false;
-
+  private boolean tryput(IoTString key, IoTString value, boolean forcedresize) {
+               Slot s=new Slot(sequencenumber+1, localmachineid, buffer.getSlot(sequencenumber).getHMAC());
     long seqn = buffer.getOldestSeqNum();
-    
+
+               if (forcedresize) {
+                       TableStatus status=new TableStatus(s, FORCED_RESIZE_INCREMENT + numslots);
+                       s.addEntry(status);
+               }
+               
     if ((numslots - buffer.size()) < FREE_SLOTS) {
       //have to check whether we have enough free slots
       seqn = buffer.getNewestSeqNum() + 1 - numslots;
@@ -93,9 +117,10 @@ final public class Table {
           else if (i==0) {
             if (s.canFit(liveentry))
               s.addEntry(liveentry);
-            else
-              forcedresize = true;
-          }
+            else if (!forcedresize) {
+              return tryput(key, value, true);
+                                               }
+                                       }
         }
       }
     }