imported from svn
[metux-java.git] / util / CachedDatasource.java
blob5bab4f00ead482dc9acb2ad44e9c4abb28f7f9db
2 package org.de.metux.util;
4 import java.net.URL;
5 import java.io.IOException;
6 import java.util.Hashtable;
7 import java.io.File;
8 import java.io.FileNotFoundException;
10 public class CachedDatasource
12 private Hashtable cache = new Hashtable();
13 public boolean enabled = true;
15 public String loadContent(URL url, boolean strip_comments)
17 String filename = url.toString();
19 if (!enabled)
21 try{
22 return LoadFile.load(url,strip_comments);
24 catch (IOException e)
26 return null;
30 String key = "::URL::CONTENT::"+(strip_comments?"STRIP::":"")+url;
31 String content;
33 try
35 content = (String)cache.get(key);
37 catch (ClassCastException e)
39 /* we've got an cached NOT-FOUND */
40 return null;
43 if (content != null)
44 return content;
46 try
48 content = LoadFile.load(url,strip_comments);
49 cache.put(key,content);
50 return content;
52 catch (IOException e)
54 /* put the error into the cache */
55 cache.put(key,e);
56 return null;
60 public String loadContent(File filename, boolean strip_comments)
62 if (!enabled)
64 try{
65 return LoadFile.load(filename,strip_comments);
67 catch (IOException e)
69 return null;
73 String key = "::FILENAME::CONTENT::"+(strip_comments?"STRIP::":"")+filename;
74 String content;
76 try
78 content = (String)cache.get(key);
80 catch (ClassCastException e)
82 /* we've got an cached NOT-FOUND */
83 return null;
86 if (content != null)
87 return content;
89 try
91 content = LoadFile.load(filename,strip_comments);
92 if (content==null)
93 throw new RuntimeException("Could not load file: "+filename);
94 cache.put(key,content);
95 return content;
97 catch (IOException e)
99 /* put the error into the cache */
100 cache.put(key,e);
101 return null;
105 public Hashtable loadTextTable(String fn, String pkey)
107 Hashtable ht;
108 String key = "::FILENAME::TEXTDB::["+pkey+"]"+fn;
110 if (!enabled)
111 return TextTable.Load(fn,pkey);
115 ht = (Hashtable)cache.get(key);
116 if (ht!=null)
117 return ht;
119 catch (ClassCastException e)
121 return null;
124 ht = TextTable.Load(fn,pkey);
125 if (ht==null)
127 cache.put(key,new FileNotFoundException(fn));
128 return null;
131 cache.put(key,ht);
132 return ht;