Added README file
[metux-java.git] / datasource / TextTable.java
blob4c8b99269c4f5aca8f63788cbacf6617c9bd7922
1 package org.de.metux.datasource;
3 import java.util.Hashtable;
4 import java.util.Properties;
5 import java.util.Enumeration;
6 import java.io.BufferedReader;
7 import java.io.FileNotFoundException;
8 import java.io.Reader;
9 import java.io.IOException;
10 import java.io.FileReader;
11 import java.io.InputStreamReader;
12 import java.net.URL;
13 import java.net.MalformedURLException;
14 import org.de.metux.util.Filename;
16 public class TextTable extends Hashtable<String,Properties>
18 public String primary_key;
20 public TextTable(String pkey)
22 primary_key = pkey;
25 public TextTable(String pkey, Filename fn)
26 throws MalformedURLException, FileNotFoundException, IOException
28 primary_key = pkey;
29 load(fn);
32 private void __store_record(Properties record)
34 if (record.size()<1)
35 return;
37 String k = record.getProperty(primary_key);
39 if ((k!=null) && (k.length()>0))
40 put(k,record);
41 else
42 put(record.toString(),record);
45 public void loadFrom(BufferedReader in, String name)
46 throws IOException
48 String line;
49 Properties record = new Properties();
50 int linecnt = 0;
52 while ((line=in.readLine())!=null)
54 int x;
55 int len;
57 /* strip off comments */
58 if ((x=line.indexOf('#'))>=0)
59 line = line.substring(0,x);
61 line = line.trim();
62 if ((len=line.length())>0)
64 /* -- split into key and value -- */
65 if ((x = line.indexOf(':'))>0)
67 String key = (line.substring(0,x)).trim();
68 String value = (line.substring(x+1)).trim();
69 /* if the property already exits, add the new value behind additional newline */
70 if (record.containsKey(key))
71 record.setProperty(key,record.get(key)+"\n"+value);
72 else
73 record.setProperty(key,value);
75 else if ((line.indexOf("--")==0)&&(!record.isEmpty()))
77 __store_record(record);
78 record = new Properties();
80 else
81 System.err.println("CORRUPT LINE ("+name+":"+linecnt+"): "+line);
83 linecnt++;
87 public void load(Filename fn)
88 throws MalformedURLException, FileNotFoundException, IOException
90 loadFrom(new BufferedReader(fn.getReader()),fn.toString());
93 private String __dump_record(Properties record)
95 if (record == null)
96 return "";
98 String res = "";
99 for (Enumeration re = record.keys(); re.hasMoreElements(); )
101 String rk = (String)re.nextElement();
102 res += rk+": "+record.getProperty(rk)+"\n";
104 return res;
107 public String dump ()
109 String res = "";
110 for (Enumeration e = keys(); e.hasMoreElements(); )
112 String key = (String)e.nextElement();
113 Properties cur = (Properties)get(key);
114 res += "#PKEY: "+key+"\n"+__dump_record(cur)+"-- \n";
116 return res;