1    // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
2    package org.xwt;
3    
4    import java.io.*;
5    import java.util.*;
6    import java.util.zip.*;
7    import org.xwt.js.*;
8    import org.xwt.util.*;
9    import org.bouncycastle.util.encoders.Base64;
10   
11   /** Manages access to ~/.xwt */
12   public class LocalStorage {
13   
14       static String xwtDirName = System.getProperty("user.home") + java.io.File.separatorChar + ".xwt";
15   
16       static java.io.File xwtDir = null;
17       static java.io.File cacheDir = null;
18   
19       static {
20           try {
21               xwtDir = new java.io.File(xwtDirName);
22               if (!xwtDir.mkdirs()) xwtDir = null;
23               try {
24                   cacheDir = new java.io.File(xwtDirName + java.io.File.separatorChar + "cache");
25                   if (!cacheDir.mkdirs()) cacheDir = null;
26               } catch (Exception e) {
27                   Log.warn(LocalStorage.class, "unable to create cache directory " +
28                            xwtDirName + java.io.File.separatorChar + "cache");
29               }
30           } catch (Exception e) {
31               Log.warn(LocalStorage.class, "unable to create xwt directory " + xwtDirName);
32           }
33       }
34   
35       // FEATURE: we ought to be able to do stuff like sha1-checking and date checking on cached resources    
36       public static class Cache {
37   
38           private static void delTree(java.io.File f) throws IOException {
39               if (f.isDirectory()) {
40                   String[] s = f.list();
41                   for(int i=0; i<s.length; i++)
42                       delTree(new java.io.File(f.getPath() + java.io.File.separatorChar + s[i]));
43               }
44               f.delete();
45           }
46   
47           public static void flush() throws IOException {
48               delTree(cacheDir);
49               cacheDir.mkdirs();
50           }
51   
52           public static java.io.File getCacheFileForKey(String key) {
53               // FEATURE: be smarter here
54               return new java.io.File(cacheDir.getPath() + File.separatorChar + new String(Base64.encode(key.getBytes())));
55           }
56   
57       }
58   }
59