1 package org.sourceforge.jemm.database.persistent.berkeley;
2
3 import java.util.Map;
4 import java.util.concurrent.ConcurrentHashMap;
5
6 import com.sleepycat.je.DatabaseException;
7 import com.sleepycat.persist.EntityCursor;
8 import com.sleepycat.persist.EntityStore;
9 import com.sleepycat.persist.PrimaryIndex;
10
11 import org.apache.log4j.Logger;
12
13 import org.sourceforge.jemm.database.ClassId;
14 import org.sourceforge.jemm.database.EnumId;
15 import org.sourceforge.jemm.types.ID;
16
17 public class IDManager {
18 private static final Logger LOG = Logger.getLogger(IDManager.class);
19
20
21
22 private static final String CLASS_ID_KEY = new String("class");
23 private static final String ENUM_ID_KEY = new String("enum");
24 private static final String ID_KEY = new String("id");
25
26 private final PrimaryIndex<String, IDEntry> pIdx;
27 private final Map<String,IDEntry> entries = new ConcurrentHashMap<String, IDEntry>();
28
29 public IDManager(EntityStore store) {
30 try {
31 pIdx = store.getPrimaryIndex(String.class, IDEntry.class);
32 EntityCursor<IDEntry> cursor = pIdx.entities();
33 for (IDEntry idEntry : cursor) {
34 entries.put(idEntry.typeName, idEntry);
35 }
36 cursor.close();
37 } catch (DatabaseException e) {
38 throw new RuntimeException("Error initialising index " ,e);
39 }
40 }
41
42 private long getNextKeyValue(String key) {
43 synchronized(key) {
44 try {
45 IDEntry idEntry = entries.get(key);
46 if(idEntry == null) {
47 idEntry = new IDEntry(key);
48 pIdx.put(idEntry);
49 entries.put(key, idEntry);
50 }
51
52 long result = idEntry.getAndIncrement();
53 pIdx.put(idEntry);
54 return result;
55 }catch(DatabaseException de){
56 LOG.error("Error whilst getting next key value for " + key,de);
57 throw new RuntimeException("Error getting next key value for " + key,de);
58 }
59 }
60 }
61
62 public ClassId getNextClassId() {
63 return new ClassId(getNextKeyValue(CLASS_ID_KEY));
64 }
65
66 public EnumId getNextEnumId() {
67 return new EnumId(getNextKeyValue(ENUM_ID_KEY));
68 }
69
70 public ID getNextId() {
71 return new ID(getNextKeyValue(ID_KEY));
72 }
73 }