1 19 package org.netbeans.mdr.persistence.memoryimpl; 20 21 import java.util.*; 22 import org.netbeans.mdr.persistence.*; 23 24 public class TransactionLog { 25 26 private static final byte OP_NONE = 0; 28 private static final byte OP_ADD = 1; 29 private static final byte OP_REMOVE = 2; 30 private static final byte OP_REPLACE = 3; 31 32 private HashMap log = new HashMap (); 33 private SinglevaluedIndex index; 34 private boolean rollingBack = false; 35 36 38 public TransactionLog (SinglevaluedIndex index) { 39 this.index = index; 40 } 41 42 44 47 public void clear () { 48 log.clear (); 49 } 50 51 54 public void logAdd (Object key) { 55 if (rollingBack) 56 return; 57 Record rec = (Record) log.get(key); 58 if (rec == null) { 59 rec = new Record (OP_REMOVE, null); 60 log.put (key, rec); 61 } else { 62 rec.opCode = OP_REPLACE; 63 } 64 } 65 66 69 public void logRemove (Object key, Object value) { 70 if (rollingBack) 71 return; 72 Record rec = (Record) log.get(key); 73 if (rec == null) { 74 rec = new Record (OP_ADD, value); 75 log.put (key, rec); 76 } else { 77 log.remove (key); 78 } 79 } 80 81 84 public void logReplace (Object key, Object oldValue) { 85 if (rollingBack) 86 return; 87 Record rec = (Record) log.get(key); 88 if (rec == null) { 89 rec = new Record (OP_REPLACE, oldValue); 90 log.put (key, rec); 91 } 92 } 93 94 public void logValue (Object key, Object value) { 95 if (rollingBack) 96 return; 97 log.put (key, new Record (OP_NONE, value)); 98 } 99 100 public boolean isLogged (Object key) { 101 return log.get (key) != null; 102 } 103 104 public void setDirty (Object key) { 105 if (rollingBack) 106 return; 107 Record rec = (Record) log.get(key); 108 if (rec.opCode == OP_NONE) 109 rec.opCode = OP_REPLACE; 110 } 111 112 115 public void rollBack () throws StorageException { 116 rollingBack = true; 117 Iterator iter = log.keySet().iterator(); 118 while(iter.hasNext()) { 119 Object key = iter.next(); 120 Record rec = (Record) log.get(key); 121 if (rec.opCode == OP_NONE) 122 continue; 123 Object value; 124 if (rec.value instanceof ValueLog) { 125 value = ((ValueLog) rec.value).resolveOriginalValue (); 126 } else { 127 value = rec.value; 128 } 129 switch (rec.opCode) { 130 case OP_ADD: 131 index.add (key, value); 132 break; 133 case OP_REMOVE: 134 index.remove (key); 135 break; 136 case OP_REPLACE: 137 index.replace (key, value); 138 break; 139 } } 141 rollingBack = false; 142 } 143 144 146 public interface ValueLog { 147 148 public Object resolveOriginalValue () throws StorageException; 149 150 } 152 154 private static class Record { 155 156 byte opCode; Object value; 158 159 public Record (byte opCode, Object value) { 160 this.opCode = opCode; 161 this.value = value; 162 } 163 164 } 166 } 167 | Popular Tags |