]> 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 <T> T read(final String filename, final Class<T> resultClass) {
20     try {
21       Object object = (objects.get(filename));
22       if (object != null) {
23         return resultClass.cast(object);
24       }
25       Log.d(getClass().getSimpleName(), "Cache miss.");
26       final File src = new File(dir, filename);
27       if (!src.canRead()) {
28         Log.d(getClass().getSimpleName(), "File empty: " + src);
29         return null;
30       }
31       try {
32         final ObjectInputStream in = new ObjectInputStream(new FileInputStream(src));
33         object = in.readObject();
34         in.close();
35       } catch (Exception e) {
36         Log.e(getClass().getSimpleName(), "Deserialization failed: " + src, e);
37         return null;
38       }
39       objects.put(filename, object);
40       return resultClass.cast(object);
41     } catch (ClassCastException e) {
42       return null;
43     }
44   }
45   
46   public synchronized void write(final String filename, final Object object) {
47     objects.put(filename, object);
48     final File dest = new File(dir, filename);
49     try {
50       final ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(dest));
51       out.writeObject(object);
52       out.close();
53     } catch (Exception e) {
54       Log.e(getClass().getSimpleName(), "Serialization failed: " + dest, e);
55     }
56   }
57
58   private PersistentObjectCache(final Context context) {
59     dir = context.getFilesDir();
60   }
61   
62   public static synchronized PersistentObjectCache getInstance() {
63     if (instance == null) {
64       throw new RuntimeException("getInstance called before init.");
65     }
66     return instance;
67   }
68
69   public static synchronized PersistentObjectCache init(final Context context) {
70       if (instance == null) {
71         instance = new PersistentObjectCache(context);
72       } else {
73         if (!instance.dir.equals(context.getFilesDir())) {
74           throw new RuntimeException("File dir changed.  old=" + instance.dir + ", new=" + context.getFilesDir());
75         }
76       }
77       return instance;
78   }
79   
80   private static PersistentObjectCache instance = null;
81
82 }