]> gitweb.fperrin.net Git - Dictionary.git/blob - src/com/hughes/android/util/PersistentObjectCache.java
17be956b10563cc1ebb20ae723434af4e8cf8038
[Dictionary.git] / src / com / hughes / android / util / PersistentObjectCache.java
1 // Copyright 2011 Google Inc. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package com.hughes.android.util;
16
17 import android.content.Context;
18 import android.os.Environment;
19 import android.util.Log;
20
21 import com.hughes.android.dictionary.DictionaryApplication;
22 import com.hughes.android.dictionary.DictionaryInfo;
23
24 import java.io.BufferedInputStream;
25 import java.io.BufferedOutputStream;
26 import java.io.File;
27 import java.io.FileInputStream;
28 import java.io.FileOutputStream;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.io.InvalidClassException;
32 import java.io.ObjectInputStream;
33 import java.io.ObjectOutputStream;
34 import java.io.ObjectStreamClass;
35 import java.io.Serializable;
36 import java.util.ArrayList;
37 import java.util.HashMap;
38 import java.util.LinkedHashMap;
39 import java.util.Map;
40
41 public class PersistentObjectCache {
42
43     private final File dir;
44     private final Map<String, Object> objects = new HashMap<>();
45
46     class ConstrainedOIS extends ObjectInputStream {
47         ConstrainedOIS(InputStream in) throws IOException {
48             super(in);
49         }
50
51         protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
52             String name = desc.getName();
53             // Note: try to avoid adding more classes.
54             // LinkedHashMap is already more than enough for a DoS
55             if (name.equals(String.class.getName()) ||
56                     name.equals(DictionaryInfo.IndexInfo.class.getName()) ||
57                     name.equals(ArrayList.class.getName()) ||
58                     name.equals(HashMap.class.getName()) ||
59                     name.equals(DictionaryInfo.class.getName()) ||
60                     name.equals(DictionaryApplication.DictionaryConfig.class.getName()) ||
61                     name.equals(LinkedHashMap.class.getName())) {
62                 return super.resolveClass(desc);
63             }
64             throw new InvalidClassException("Not allowed to deserialize class", name);
65         }
66     }
67
68     public synchronized <T extends Serializable> T read(final String filename, final Class<T> resultClass) {
69         try {
70             Object object = objects.get(filename);
71             if (object != null) {
72                 return resultClass.cast(object);
73             }
74             Log.d(getClass().getSimpleName(), "Cache miss.");
75             final File src = new File(dir, filename);
76             if (!src.canRead()) {
77                 Log.d(getClass().getSimpleName(), "File empty: " + src);
78                 return null;
79             }
80             ObjectInputStream in = null;
81             try {
82                 in = new ConstrainedOIS(new BufferedInputStream(new FileInputStream(src)));
83                 object = in.readObject();
84                 in.close();
85             } catch (Exception e) {
86                 Log.e(getClass().getSimpleName(), "Deserialization failed: " + src, e);
87                 try {
88                     if (in != null) in.close();
89                 } catch (IOException ignored) {}
90                 return null;
91             }
92             objects.put(filename, object);
93             return resultClass.cast(object);
94         } catch (ClassCastException e) {
95             return null;
96         }
97     }
98
99     public synchronized void write(final String filename, final Serializable object) {
100         objects.put(filename, object);
101         final File dest = new File(dir, filename);
102         ObjectOutputStream out = null;
103         try {
104             out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(dest)));
105             out.writeObject(object);
106         } catch (Exception e) {
107             Log.e(getClass().getSimpleName(), "Serialization failed: " + dest, e);
108         }
109         try {
110             if (out != null) out.close();
111         } catch (IOException ignored) {}
112     }
113
114     private PersistentObjectCache(final Context context) {
115         final File filesDir = context.getFilesDir();
116         dir = filesDir != null ? filesDir : Environment.getExternalStorageDirectory();
117         if (dir == null) {
118             throw new RuntimeException("context.getFilesDir() == " + context.getFilesDir()
119                                        + ", Environment.getExternalStorageDirectory()="
120                                        + Environment.getExternalStorageDirectory());
121         }
122     }
123
124     public static synchronized PersistentObjectCache getInstance() {
125         if (instance == null) {
126             throw new RuntimeException("getInstance called before init.");
127         }
128         return instance;
129     }
130
131     public static synchronized PersistentObjectCache init(final Context context) {
132         if (instance == null) {
133             instance = new PersistentObjectCache(context);
134         } else {
135             if (!instance.dir.equals(context.getFilesDir())) {
136                 throw new RuntimeException("File dir changed.  old=" + instance.dir + ", new="
137                                            + context.getFilesDir());
138             }
139         }
140         return instance;
141     }
142
143     private static PersistentObjectCache instance = null;
144
145 }