PropertyFile regex bugfix
[org.ibex.core.git] / src / org / ibex / js / PropertyFile.java
1 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL] 
2 package org.ibex.js; 
3
4 import org.ibex.util.*; 
5 import java.util.*;
6 import java.io.*;
7
8 /** A JS interface to a Java '.properties' file; very crude */
9 public class PropertyFile extends JS {
10
11     private final Properties p = new Properties();
12     private final Hash cache = new Hash(10, 3);
13     private File f;
14
15     private class Minion extends JS {
16         private final String prefix;
17         Minion(String prefix) { this.prefix = prefix; }
18         public Number coerceToNumber()  { return N(coerceToString()); }
19         public Boolean coerceToBoolean() { return B(coerceToString().equals("true")); }
20         public String coerceToString()  { return (String)p.get(prefix.substring(0, prefix.length() - 1)); }
21         public Enumeration keys() throws JSExn { throw new JSExn("PropertyFile.keys() not supported"); }
22         public Object get(Object key) throws JSExn {
23             if (toString(key).equals("")) return coerceToString();
24             Object ret = p.get(prefix + escape(toString(key)));
25             if (ret != null) return ret;
26             return new Minion(prefix + escape(toString(key)) + ".");
27         }
28         public void put(Object key, Object val) throws JSExn {
29             try {
30                 p.put(prefix + (prefix.equals("") ? "" : ".") + escape(toString(key)), toString(val));
31                 File fnew = new File(f.getName() + ".new");
32                 FileOutputStream fo = new FileOutputStream(fnew);
33                 p.save(fo, "");
34                 fo.close();
35                 fnew.renameTo(f);
36                 f = fnew;
37             } catch (IOException e) { throw new JSExn(e); }
38         }
39     }
40
41     public static String escape(String s) {
42         return s.replaceAll("\\\\", "\\\\\\\\").replaceAll("\\.", "\\\\.").replaceAll("=","\\\\="); }
43     public PropertyFile(File f) throws IOException { this.f = f; this.p.load(new FileInputStream(f)); }
44     public void put(Object key, Object val) throws JSExn { new Minion("").put(key, val); }
45     public Enumeration keys() throws JSExn { return new Minion("").keys(); }
46     public Object get(Object key) throws JSExn {
47         Object ret = p.get(toString(key));
48         if (ret != null) return ret;
49         return new Minion(escape(toString(key)));
50     }
51 }