1 package com.ontotext.ordi.wsmo4rdf.remote.server;
2
3 import java.util.HashMap;
4 import java.util.Map;
5
6 import com.ontotext.ordi.wsmo4rdf.remote.server.exception.RegistryFullException;
7
8 public class Registry<EntityType> {
9 private Map<Integer, EntityType> index;
10
11 /**
12 * how many entities a register can handle
13 */
14 protected static int maxEntities;
15
16 public Registry(final int maxEntities) {
17 Registry.maxEntities = maxEntities;
18 index = new HashMap<Integer, EntityType>(maxEntities);
19 }
20
21 /**
22 * Verifies if an identifier is in the legal range according to this register limits.
23 * @param id identifier to be verified
24 * @return <code>true</code> if valid, <code>false</code> otherwise
25 */
26 public static boolean isValid(final int id) {
27 if (id >= -1 && id < maxEntities) {
28 return true;
29 } else {
30 return false;
31 }
32 }
33
34 /**
35 * Finds a unique ID for an entity and puts it in registry index
36 *
37 * @param registryEntity
38 * EntityType instance to be registered
39 * @return integer ID of the registered object
40 * @throws RegistryFullException
41 * if there is no available space for connections
42 */
43 public int register(final EntityType registryEntity)
44 throws RegistryFullException {
45 int id = getUniqueId();
46 if (id == -1)
47 throw new RegistryFullException();
48
49 index.put(id, registryEntity);
50 return id;
51 }
52
53 /**
54 * Removes entity from this register
55 *
56 * @param id
57 * Integer ID of the RegistryEntity to be removed
58 * @return EntityType reference if entity exists or <code>null</code> otherwise
59 */
60 public EntityType unregister(final int id) {
61 return this.index.remove(id);
62 }
63
64 /**
65 * Unregisters all WsmoConnections. If a connection cannot be closed, this method continues with the next connection.
66 */
67 public void clear() {
68 for (int i = 0; i<maxEntities; i++) {
69 unregister(i);
70 }
71 }
72
73 /**
74 * Finds unoccupied ID starting from the beginning
75 *
76 * @return ID of a free slot in the register, or -1 if all slots are
77 * occupied
78 */
79 private int getUniqueId() {
80 for (int id = 0; id < maxEntities; id++) {
81 if (!index.containsKey(Integer.valueOf(id))) {
82 return id;
83 }
84 }
85 return -1;
86 }
87
88 /**
89 *
90 * @return Integer for number of the mapped entities in this registry
91 */
92 int getIndexSize() {
93 return this.index.size();
94 }
95
96 /**
97 * Return an entity ID as per register index
98 * @param entityId Integer ID of looked up entity
99 * @return EntityType instance if entity is in this register or null otherwise
100 */
101 public EntityType getById(final int entityId) {
102 return this.index.get(entityId);
103 }
104 }