1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.ini4j.demo;
17
18 import bsh.ConsoleInterface;
19 import bsh.EvalError;
20 import bsh.Interpreter;
21 import bsh.NameSpace;
22
23 import org.ini4j.Config;
24 import org.ini4j.Ini;
25 import org.ini4j.Options;
26 import org.ini4j.Persistable;
27 import org.ini4j.Reg;
28
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.io.InputStreamReader;
32 import java.io.Reader;
33 import java.io.StringReader;
34
35 public class DemoModel implements Runnable
36 {
37 public static enum Mode
38 {
39 INI,
40 REG,
41 OPTIONS;
42 }
43
44 private Persistable _data;
45 private Interpreter _interpreter;
46 private Mode _mode = Mode.INI;
47
48 public DemoModel(ConsoleInterface console)
49 {
50 _interpreter = new Interpreter(console);
51 NameSpace namespace = _interpreter.getNameSpace();
52
53 namespace.importPackage("org.ini4j.spi");
54 namespace.importPackage("org.ini4j");
55 namespace.importPackage("org.ini4j.sample");
56 }
57
58 public Object getData()
59 {
60 return _data;
61 }
62
63 public Mode getMode()
64 {
65 return _mode;
66 }
67
68 public void setMode(Mode mode)
69 {
70 _mode = mode;
71 }
72
73 public void clear() throws EvalError
74 {
75 _interpreter.unset("data");
76 }
77
78 public String help() throws IOException
79 {
80 return readResource("help.txt");
81 }
82
83 public String load() throws IOException
84 {
85 return readResource(_mode.name().toLowerCase() + "-data.txt");
86 }
87
88 public void parse(String text) throws IOException, EvalError
89 {
90 Persistable data = newData();
91
92 data.load(new StringReader(text));
93 _interpreter.set("data", data);
94 _data = data;
95 }
96
97 @Override public void run()
98 {
99 _interpreter.setExitOnEOF(false);
100 _interpreter.run();
101 }
102
103 public String tip() throws IOException
104 {
105 return readResource(_mode.name().toLowerCase() + "-tip.txt");
106 }
107
108 private Persistable newData()
109 {
110 Persistable ret = null;
111
112 switch (_mode)
113 {
114
115 case INI:
116 ret = new Ini();
117 break;
118
119 case REG:
120 ret = new Reg();
121 break;
122
123 case OPTIONS:
124 ret = new Options();
125 break;
126 }
127
128 return ret;
129 }
130
131 private String readResource(String path) throws IOException
132 {
133 InputStream in = getClass().getResourceAsStream(path);
134 Reader reader = new InputStreamReader(in, Config.DEFAULT_FILE_ENCODING);
135 StringBuilder str = new StringBuilder();
136 char[] buff = new char[8192];
137 int n;
138
139 while ((n = reader.read(buff)) >= 0)
140 {
141 str.append(buff, 0, n);
142 }
143
144 return str.toString();
145 }
146 }