summaryrefslogtreecommitdiff
path: root/source/com/c2kernel/persistency/RemoteMap.java
blob: ca9cbc486ad14690c968a787ec2f5abc0bed7085 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
package com.c2kernel.persistency;

import java.util.AbstractSet;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;

import com.c2kernel.common.ObjectNotFoundException;
import com.c2kernel.entity.C2KLocalObject;
import com.c2kernel.entity.proxy.*;
import com.c2kernel.entity.proxy.EntityProxyObserver;
import com.c2kernel.lookup.EntityPath;
import com.c2kernel.process.Gateway;
import com.c2kernel.utils.Logger;

/**
 * Maps a storage cluster onto a java.util.Map
 * 
 * @author Andrew Branson
 * $Revision: 1.22 $
 * $Date: 2006/03/03 13:52:21 $
 *
 * Copyright (C) 2003 CERN - European Organization for Nuclear Research
 * All rights reserved.
 */
public class RemoteMap implements C2KLocalObject, Map {
	
    protected static final boolean KEYS = false;
	protected static final boolean VALUES = true;

	private int mID=-1;
	private String mName;
	protected int mSysKey;
	private String mPath = "";
	protected String[] keys = null;
    Object keyLock = new Object();
	protected C2KLocalObject[] values = null;
	TransactionManager storage;
    EntityProxyObserver listener;
    EntityProxy source;
	Object mLocker; // if this remote map will participate in a transaction  
	
	public RemoteMap(int sysKey, String path, Object locker) {
		mSysKey = sysKey;
		mLocker = locker;

		// split the path into path/name
		int lastSlash = path.lastIndexOf("/");
		mName = path.substring(lastSlash+1);
		if (lastSlash>0) mPath = path.substring(0,lastSlash);

		// see if the name is also a suitable id
		try {
			mID = Integer.parseInt(mName);
		} catch (NumberFormatException e) {}
		storage = Gateway.getStorage();
        
        listener = new EntityProxyObserver() {
            public void add(C2KLocalObject obj) {
                synchronized (keyLock) {
                    if (keys == null) return;
                    boolean found = false;
                    for (int i=0; i<keys.length; i++) {
                        if (keys[i].equals(obj.getName())) { //replaced
                            values[i] = obj;
                            found = true;
                            break;
                        }
                    }
        
                    if (found == false) { // new
                        String[] newKeys = new String[keys.length+1];
                        C2KLocalObject[] newValues = new C2KLocalObject[keys.length+1];
                        System.arraycopy(keys, 0, newKeys, 0, keys.length);
                        if (values!=null) System.arraycopy(values, 0, newValues, 0, keys.length);
                        newKeys[newKeys.length-1] = obj.getName();
                        newValues[newValues.length-1] = obj;
                        keys = newKeys;
                        values = newValues;
                    }
                }        
            }

            public void remove(String id) {
                synchronized (keyLock) {
                    if (keys == null) return;
                    boolean found = false;
                    for (int i=0; i<keys.length; i++) {
                        if (keys[i].equals(id)) { //replaced
                            String[] newKeys = new String[keys.length-1];
                            C2KLocalObject[] newValues = new C2KLocalObject[keys.length-1];
                            int pos = 0;
                            for (int j=0; j<keys.length;j++) {
                                if (i!=j) {
                                    newKeys[pos] = keys[j];
                                    newValues[pos++] = values[j];
                                }
                            }
                            keys = newKeys;
                            values = newValues;
                            break;
                        }
                    }
                }
            }
        };

        try {
            source = Gateway.getProxyManager().getProxy(new EntityPath(sysKey));
            source.subscribe(listener, path, false);
        } catch (Exception ex) {
            Logger.error("Error subscribing to remote map. Changes will not be received");
            Logger.error(ex);
        }
	}
    
	protected void loadKeys() throws ClusterStorageException {
        synchronized(keyLock) {
    		keys = storage.getClusterContents(mSysKey, mPath+mName);
	       	values = new C2KLocalObject[keys.length];
        }
	}
	
	protected String[] getKeys() {
		try {
			if (keys == null) loadKeys();
		} catch (ClusterStorageException e) { 
			Logger.error(e);
			keys = new String[0];
		}
		return keys;
	}
    
    public synchronized int getLastId() {
    
        synchronized (this) {
            int lastID = -1;

            String[] allIds = getKeys();
            
            for (int i = 0; i < allIds.length; i++) {
                try {
                    int thisID = Integer.parseInt(allIds[i]);
                    if (thisID > lastID) lastID = thisID;
                } catch (NumberFormatException e) {
                    Logger.warning("RemoteMap.getLastID() - Cluster contained invalid id: "+allIds[i]);
                }
            }
            Logger.msg(7, "RemoteMap.getLastID() - last id in "+mPath+mName+" of "+mSysKey+" is "+lastID);
            return lastID;
        }
    }    
	

	// c2kLocalObject methods
	public void setID(int id) { mID = id; }

	public int getID() { return mID; }

	public void setName(String name) { mName = name; }

	public String getName() { return mName; }

	/**
	 * Cannot be stored
	 */
	public String getClusterType() {
		return null;
	}
	/**
	 * @see java.util.Map#clear()
	 */
	public synchronized void clear() {
		keys = null;	
	}
    


	/**
	 * @see java.util.Map#containsKey(Object)
	 */
	public synchronized boolean containsKey(Object key) {
		getKeys();
		for (int i = 0; i < keys.length; i++) {
				if (key.equals(keys[i]))
					return true;
			}
		return false;
	}

	/**
	 * This must retrieve all the values until a match is made.
	 * Very expensive, but if you must, you must.
	 * @see java.util.Map#containsValue(Object)
	 */
	public synchronized boolean containsValue(Object value) {
		getKeys();
        synchronized(keyLock) {
    		if (values == null) values = new C2KLocalObject[keys.length];
    		for (int i = 0; i < keys.length; i++) {
    			try {
    				if (values[i] == null) values[i] = storage.get(mSysKey, mPath+mName+"/"+keys[i], mLocker);
    				if (value.equals(values[i])) return true;
    			} catch (ClusterStorageException ex) {
    				Logger.error(ex);
    			} catch (ObjectNotFoundException e) {
                    Logger.error(e);
                }
    		}
        }
		return false;
	}

	/**
	 * @see java.util.Map#entrySet()
	 */
	public synchronized Set entrySet() {
		return new RemoteMap.RemoteSet(this, KEYS);
	}

	/**
	 * @see java.util.Map#get(Object)
	 */
	public synchronized Object get(Object key) {
		getKeys();
        synchronized(keyLock) {
    		if (values == null) values = new C2KLocalObject[keys.length];
    		try {
    			for (int i = 0; i < keys.length; i++) {
    				if (key.equals(keys[i])) {
    					if (values[i] == null)
    						values[i] = storage.get(mSysKey, mPath+mName+"/"+keys[i], mLocker);
    					return values[i];
    				}
    			}
    		} catch (ClusterStorageException e) {
    				Logger.error(e);
    		} catch (ObjectNotFoundException e) {
                Logger.error(e);
            }
        }
		return null;
	}

	/**
	 * @see java.util.Map#isEmpty()
	 */
	public synchronized boolean isEmpty() {
		return getKeys().length==0;
	}

	/**
	 * @see java.util.Map#keySet()
	 */
	public synchronized Set keySet() {
		return new RemoteMap.RemoteSet(this, KEYS);
	}

	/**
	 * Inserts the given object into the storage
	 * the key is ignored - it can be fetched from the value.
	 * @see java.util.Map#put(Object, Object)
	 */
	public synchronized Object put(Object key, Object value) {
		try {
			C2KLocalObject newValue = (C2KLocalObject)value;
            synchronized(keyLock) {
                storage.put(mSysKey, newValue, mLocker);
			    keys = null; values = null;
            }
		} catch (ClusterStorageException e) {
			Logger.error(e);
			return null;
		} catch (ClassCastException e) {
			Logger.error("RemoteMap.put() - value was not a localobject, it was a "+value.getClass().getName());
			return null;
		}
		return value;
	}

	/**
	 * @see java.util.Map#putAll(Map)
	 */
	public synchronized void putAll(Map t) {
		for (Iterator iter = t.keySet().iterator(); iter.hasNext();) {
			Object key = iter.next();
			put(key, t.get(key));
		}
	}

	/**
	 * @see java.util.Map#remove(Object)
	 */
	public synchronized Object remove(Object key) {
		try {
            synchronized(keyLock) {
			    storage.remove(mSysKey, mPath+mName+"/"+key, mLocker);
			    keys = null; values = null;
            }			
		} catch (ClusterStorageException e) {
			Logger.error(e);
		}
		return null;
	}

	/**
	 * @see java.util.Map#size()
	 */
	public synchronized int size() {
		return getKeys().length;
	}

	/**
	 * @see java.util.Map#values()
	 */
	public synchronized Collection values() {
		return new RemoteMap.RemoteSet(this, VALUES);
	}

	/**
	 * Basic implementation of Set and Collection to bridge to the Iterator
	 * Disallows all writes.
	 */

	private class RemoteSet extends AbstractSet {
		RemoteMap mParent;
		boolean mMode;
		
		public RemoteSet(RemoteMap parent, boolean mode) {
			mParent = parent;
			mMode = mode;
		}

		// no modifications allowed		
		public boolean add(Object o) { 
			throw new UnsupportedOperationException();
		}
		public boolean addAll(Collection c) { 
			throw new UnsupportedOperationException();
		}
		public void clear() { 
			throw new UnsupportedOperationException();
		}
		public boolean remove(Object o) { 
			throw new UnsupportedOperationException();
		}
		public boolean removeAll(Collection c) { 
			throw new UnsupportedOperationException();
		}
		public boolean retainAll(Collection c) { 
			throw new UnsupportedOperationException();
		}

		public Iterator iterator() {
			return new RemoteIterator(mParent, mMode);
		}

		public int size() {
			return mParent.size();
		}

	}
	/**
	 * Iterator view on RemoteMap data. Doesn't preload anything.
	 * REVISIT: Will go strange if the RemoteMap is modified. Detect this and throw ConcurrentMod ex
	 */
	private class RemoteIterator implements Iterator {
		RemoteMap mParent;
		boolean mMode;
		String[] keyArr;
		int pos;
		
		public RemoteIterator(RemoteMap parent, boolean mode) {
			mParent = parent;
			mMode = mode;
			keyArr = mParent.getKeys();	
		}

		public boolean hasNext() {
			return (pos<keyArr.length);
		}

		public Object next() {
			if (pos == keyArr.length)
				throw new NoSuchElementException();
				
			if (mMode == KEYS) 
				return keyArr[pos++];
			else
				return mParent.get(keyArr[pos++]);
		}

		public void remove() {
			throw new UnsupportedOperationException();
		}

	}




}