]> gitweb.fperrin.net Git - Dictionary.git/blob - src/com/hughes/android/util/PersistentObjectCache.java
go
[Dictionary.git] / src / com / hughes / android / util / PersistentObjectCache.java
1 package com.hughes.android.util;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.FileOutputStream;
6 import java.io.ObjectInputStream;
7 import java.io.ObjectOutputStream;
8 import java.util.LinkedHashMap;
9 import java.util.Map;
10
11 import android.content.Context;
12 import android.util.Log;
13
14 public class PersistentObjectCache {
15
16   private final File dir;
17   private final Map<String, Object> objects = new LinkedHashMap<String, Object>();
18   
19   public synchronized Object read(final String filename) {
20     Object object = (objects.get(filename));
21     if (object != null) {
22       return object;
23     }
24     Log.d(getClass().getSimpleName(), "Cache miss.");
25     final File src = new File(dir, filename);
26     if (!src.canRead()) {
27       Log.d(getClass().getSimpleName(), "File empty: " + src);
28       return null;
29     }
30     try {
31       final ObjectInputStream in = new ObjectInputStream(new FileInputStream(src));
32       object = in.readObject();
33       in.close();
34     } catch (Exception e) {
35       Log.e(getClass().getSimpleName(), "Deserialization failed: " + src, e);
36       return null;
37     }
38     objects.put(filename, object);
39     return object;
40   }
41   
42   public synchronized void write(final String filename, final Object object) {
43     objects.put(filename, object);
44     final File dest = new File(dir, filename);
45     try {
46       final ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(dest));
47       out.writeObject(object);
48       out.close();
49     } catch (Exception e) {
50       Log.e(getClass().getSimpleName(), "Serialization failed: " + dest, e);
51     }
52   }
53
54   private PersistentObjectCache(final Context context) {
55     dir = context.getFilesDir();
56   }
57   
58   public static synchronized PersistentObjectCache getInstance() {
59     if (instance == null) {
60       throw new RuntimeException("getInstance called before init.");
61     }
62     return instance;
63   }
64
65   public static synchronized PersistentObjectCache init(final Context context) {
66       if (instance == null) {
67         instance = new PersistentObjectCache(context);
68       } else {
69         if (!instance.dir.equals(context.getFilesDir())) {
70           throw new RuntimeException("File dir changed.  old=" + instance.dir + ", new=" + context.getFilesDir());
71         }
72       }
73       return instance;
74   }
75   
76   private static PersistentObjectCache instance = null;
77
78 }