1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.ini4j.spi;
17
18 import org.ini4j.Config;
19 import org.ini4j.InvalidFileFormatException;
20
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.io.Reader;
24
25 import java.net.URL;
26
27 import java.util.Locale;
28
29 abstract class AbstractParser
30 {
31 private final String _comments;
32 private Config _config = Config.getGlobal();
33 private final String _operators;
34
35 protected AbstractParser(String operators, String comments)
36 {
37 _operators = operators;
38 _comments = comments;
39 }
40
41 protected Config getConfig()
42 {
43 return _config;
44 }
45
46 protected void setConfig(Config value)
47 {
48 _config = value;
49 }
50
51 protected void parseError(String line, int lineNumber) throws InvalidFileFormatException
52 {
53 throw new InvalidFileFormatException("parse error (at line: " + lineNumber + "): " + line);
54 }
55
56 IniSource newIniSource(InputStream input, HandlerBase handler)
57 {
58 return new IniSource(input, handler, _comments, getConfig());
59 }
60
61 IniSource newIniSource(Reader input, HandlerBase handler)
62 {
63 return new IniSource(input, handler, _comments, getConfig());
64 }
65
66 IniSource newIniSource(URL input, HandlerBase handler) throws IOException
67 {
68 return new IniSource(input, handler, _comments, getConfig());
69 }
70
71 void parseOptionLine(String line, HandlerBase handler, int lineNumber) throws InvalidFileFormatException
72 {
73 int idx = indexOfOperator(line);
74 String name = null;
75 String value = null;
76
77 if (idx < 0)
78 {
79 if (getConfig().isEmptyOption())
80 {
81 name = line;
82 }
83 else
84 {
85 parseError(line, lineNumber);
86 }
87 }
88 else
89 {
90 name = unescapeFilter(line.substring(0, idx)).trim();
91 value = unescapeFilter(line.substring(idx + 1)).trim();
92 }
93
94 if (name.length() == 0)
95 {
96 parseError(line, lineNumber);
97 }
98
99 if (getConfig().isLowerCaseOption())
100 {
101 name = name.toLowerCase(Locale.getDefault());
102 }
103
104 handler.handleOption(name, value);
105 }
106
107 String unescapeFilter(String line)
108 {
109 return getConfig().isEscape() ? EscapeTool.getInstance().unescape(line) : line;
110 }
111
112 private int indexOfOperator(String line)
113 {
114 int idx = -1;
115
116 for (char c : _operators.toCharArray())
117 {
118 int index = line.indexOf(c);
119
120 if ((index >= 0) && ((idx == -1) || (index < idx)))
121 {
122 idx = index;
123 }
124 }
125
126 return idx;
127 }
128 }