Added README file
[metux-java.git] / util / ShellVariableDef.java
blobf22d4b52b13763cc87fcc9cb882221e622e9d8a5
2 package org.de.metux.util;
4 // a simplicistic parser for shell style variable definitions
5 // FIXME: has to be improved
7 public class ShellVariableDef
9 public String name;
10 public String value;
12 public boolean getBoolean ()
14 if ((value!=null) && (value.equals("yes")))
15 return true;
16 else
17 return false;
20 public class XEmpty extends Exception
22 public XEmpty(String s) { super(s); }
24 public class XParseFailed extends Exception
26 public XParseFailed(String s) { super(s); }
29 public int getInt()
31 try
33 return Integer.parseInt(value);
35 catch (NumberFormatException e)
37 System.err.println(
38 "ShellVariableDef::getInt() format error: "+
39 name+"'"+value+"'");
40 throw e;
44 public int getInt(int def)
46 try
48 return Integer.parseInt(value);
50 catch (NumberFormatException e)
52 return def;
56 public ShellVariableDef(String line) throws XEmpty, XParseFailed
58 if (line==null)
59 throw new XEmpty("null pointer assigned");
61 line = line.trim();
63 if (line.length()<1)
64 throw new ShellVariableDef.XEmpty("empty string (1)");
66 // look for an # (comment)
67 int comment_pos = line.indexOf('#');
69 // look for an equal sign
70 int equal_pos;
71 if ((equal_pos=line.indexOf("='"))>0)
73 if ((comment_pos>-1) && (comment_pos<equal_pos))
74 throw new ShellVariableDef.XParseFailed("# before =");
76 int fin_pos = line.indexOf('\'', equal_pos+2);
77 if (fin_pos <= -1)
78 throw new ShellVariableDef.XParseFailed("missing closing \"'\"");
80 name = line.substring(0,equal_pos).trim();
81 value = line.substring(equal_pos+2,fin_pos);
84 else if ((equal_pos=line.indexOf("="))>0)
86 if ((comment_pos>-1) && (comment_pos<equal_pos))
87 throw new ShellVariableDef.XParseFailed("# before =");
89 name = line.substring(0,equal_pos).trim();
91 int fin_pos = line.indexOf(' ', equal_pos);
93 if (fin_pos>1)
94 value = line.substring(equal_pos+1,fin_pos);
95 else
96 value = line.substring(equal_pos+1);
99 else
101 // we have to test, whether the line is in fact empty
102 if (comment_pos==0)
103 throw new ShellVariableDef.XEmpty("just comments (1)");
105 if ((comment_pos>0)&&(line.substring(0,comment_pos).trim().length()<1))
106 throw new ShellVariableDef.XEmpty("just comments (2)");
108 throw new ShellVariableDef.XParseFailed("missing =");