added org.ibex.js.PropertiesFile
authoradam <adam@megacz.com>
Sat, 8 May 2004 06:11:29 +0000 (06:11 +0000)
committeradam <adam@megacz.com>
Sat, 8 May 2004 06:11:29 +0000 (06:11 +0000)
darcs-hash:20040508061129-5007d-43ea42f386ad85a7514d04cfcae7ca8e27175c67.gz

src/org/ibex/js/PropertyFile.java [new file with mode: 0644]

diff --git a/src/org/ibex/js/PropertyFile.java b/src/org/ibex/js/PropertyFile.java
new file mode 100644 (file)
index 0000000..162fc81
--- /dev/null
@@ -0,0 +1,49 @@
+// Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL] 
+package org.ibex.js; 
+
+import org.ibex.util.*; 
+import java.util.*;
+import java.io.*;
+
+/** A JS interface to a Java '.properties' file; very crude */
+public class PropertyFile extends JS {
+
+    private final Properties p = new Properties();
+    private final Hash cache = new Hash(10, 3);
+    private File f;
+
+    private class Minion extends JS {
+        private final String prefix;
+        Minion(String prefix) { this.prefix = prefix; }
+        public Number coerceToNumber()  { return N(coerceToString()); }
+        public Boolean coerceToBoolean() { return B(coerceToString().equals("true")); }
+        public String coerceToString()  { return (String)p.get(prefix.substring(0, prefix.length() - 1)); }
+        public Enumeration keys() throws JSExn { throw new JSExn("PropertyFile.keys() not supported"); }
+        public Object get(Object key) throws JSExn {
+            Object ret = p.get(prefix + escape(toString(key)));
+            if (ret != null) return ret;
+            return new Minion(prefix + escape(toString(key)) + ".");
+        }
+        public void put(Object key, Object val) throws JSExn {
+            try {
+                p.put(prefix + "." + escape(toString(key)), toString(val));
+                File fnew = new File(f.getName() + ".new");
+                FileOutputStream fo = new FileOutputStream(fnew);
+                p.save(fo, "");
+                fo.close();
+                fnew.renameTo(f);
+                f = fnew;
+            } catch (IOException e) { throw new JSExn(e); }
+        }
+    }
+
+    public static String escape(String s) { return s.replaceAll("\\", "\\\\").replaceAll(".", "\\.").replaceAll("=","\\="); }
+    public PropertyFile(File f) throws IOException { this.f = f; this.p.load(new FileInputStream(f)); }
+    public void put(Object key, Object val) throws JSExn { new Minion("").put(key, val); }
+    public Enumeration keys() throws JSExn { return new Minion("").keys(); }
+    public Object get(Object key) throws JSExn {
+        Object ret = p.get(toString(key));
+        if (ret != null) return ret;
+        return new Minion(escape(toString(key)));
+    }
+}