0b4b7382fd1351d819fe6feac5711a24fc1a9251
[mir.git] / source / mir / storage / DatabaseCache.java
1 package mir.storage;
2
3 import java.util.*;
4
5 public class DatabaseCache {
6   private final ArrayList _cache;
7   private int _counter;
8   private final int _max;
9   
10   public DatabaseCache(int i_max){
11     _counter = 0;
12     _max = i_max;
13     _cache = new ArrayList(_max);
14   }
15   
16   public DatabaseCache(){
17     _counter = -1;
18     _max = 100;
19     _cache = new ArrayList(_max);
20   }
21   
22   public synchronized void put(String key, Object value){
23     if(_counter >=_max){
24       _cache.remove(0);
25       _cache.trimToSize();
26       _counter --;
27       System.out.println("put: remove " + _counter);
28     }
29     _cache.add(new Entry(key,value));
30     _counter ++;
31     System.out.println("put: put " + _counter);
32   }
33   
34   public synchronized void clear(){
35     _cache.clear();
36   }
37       
38   public int containsKey(String key){
39     for(int i = 0; i<_cache.size(); i++){
40       if( ((Entry)_cache.get(i)).getKey().equals(key) )
41         return i;
42     }
43     return -1;
44   }
45   
46   public int containsValue(Object o){
47     for(int i = 0; i<_cache.size(); i++){
48       if(((Entry)_cache.get(i)).getValue().equals(o) )
49         return i;
50     }
51     return -1;
52   }
53   
54   public Object get(String key){
55     for(int i = 0; i<_cache.size(); i++){
56       if( ((Entry)_cache.get(i)).getKey(key).equals(key) )
57           ((Entry)_cache.get(i)).getValue();
58     }
59     return null;
60   }
61   
62   public synchronized boolean remove(String key){
63     int i = containsKey(key);
64     if(i==-1){
65       return false;
66     }
67     _cache.remove(i);
68     _cache.trimToSize();
69     _counter --;
70     return true;
71   }
72   
73   public int size(){
74     return _counter;
75   }
76   
77   private class Entry {
78     private String _key;
79     private Object _value;
80     
81     public Entry(String i_key, Object i_value){
82       _key = i_key;
83       _value = i_value;
84     }
85         
86     public void put(String i_key, Object i_value){
87       _key = i_key;
88       _value = i_value;
89     }
90     
91     public Object getValue(String i_key){
92       if(i_key.equals(_key)){
93         return _value;
94       } else {
95         return null;
96       }
97     }
98     
99     public Object getValue(){
100       return _value;
101     }
102     
103     public String getKey(Object i_o){
104       if(i_o.equals(_value)){
105         return _key;
106       } else {
107         return null;
108       }
109     }
110
111     public String getKey(){
112         return _key;
113     }
114   }//Entry
115
116 }
117
118