KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > myvietnam > mvncore > web > fileupload > ParameterParser


1 /*
2  * Copyright 2001-2004 The Apache Software Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package net.myvietnam.mvncore.web.fileupload;
17
18 import java.util.HashMap JavaDoc;
19 import java.util.Map JavaDoc;
20
21 /**
22  * A simple parser intended to parse sequences of name/value pairs.
23  * Parameter values are exptected to be enclosed in quotes if they
24  * contain unsafe characters, such as '=' characters or separators.
25  * Parameter values are optional and can be omitted.
26  *
27  * <p>
28  * <code>param1 = value; param2 = "anything goes; really"; param3</code>
29  * </p>
30  *
31  * @author <a HREF="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
32  *
33  * @version $Id: ParameterParser.java,v 1.2 2006/02/12 04:43:11 minhnn Exp $
34  */

35
36 public class ParameterParser {
37     /**
38      * String to be parsed.
39      */

40     private char[] chars = null;
41
42     /**
43      * Current position in the string.
44      */

45     private int pos = 0;
46
47     /**
48      * Maximum position in the string.
49      */

50     private int len = 0;
51
52     /**
53      * Start of a token.
54      */

55     private int i1 = 0;
56
57     /**
58      * End of a token.
59      */

60     private int i2 = 0;
61
62     /**
63      * Whether names stored in the map should be converted to lower case.
64      */

65     private boolean lowerCaseNames = false;
66
67     /**
68      * Default ParameterParser constructor.
69      */

70     public ParameterParser() {
71         super();
72     }
73
74     /**
75      * Are there any characters left to parse?
76      *
77      * @return <tt>true</tt> if there are unparsed characters,
78      * <tt>false</tt> otherwise.
79      */

80     private boolean hasChar() {
81         return this.pos < this.len;
82     }
83
84     /**
85      * A helper method to process the parsed token. This method removes
86      * leading and trailing blanks as well as enclosing quotation marks,
87      * when necessary.
88      *
89      * @param quoted <tt>true</tt> if quotation marks are expected,
90      * <tt>false</tt> otherwise.
91      * @return the token
92      */

93     private String JavaDoc getToken(boolean quoted) {
94         // Trim leading white spaces
95
while ((i1 < i2) && (Character.isWhitespace(chars[i1]))) {
96             i1++;
97         }
98         // Trim trailing white spaces
99
while ((i2 > i1) && (Character.isWhitespace(chars[i2 - 1]))) {
100             i2--;
101         }
102         // Strip away quotation marks if necessary
103
if (quoted) {
104             if (((i2 - i1) >= 2)
105                 && (chars[i1] == '"')
106                 && (chars[i2 - 1] == '"')) {
107                 i1++;
108                 i2--;
109             }
110         }
111         String JavaDoc result = null;
112         if (i2 > i1) {
113             result = new String JavaDoc(chars, i1, i2 - i1);
114         }
115         return result;
116     }
117
118     /**
119      * Tests if the given character is present in the array of characters.
120      *
121      * @param ch the character to test for presense in the array of characters
122      * @param charray the array of characters to test against
123      *
124      * @return <tt>true</tt> if the character is present in the array of
125      * characters, <tt>false</tt> otherwise.
126      */

127     private boolean isOneOf(char ch, final char[] charray) {
128         boolean result = false;
129         for (int i = 0; i < charray.length; i++) {
130             if (ch == charray[i]) {
131                 result = true;
132                 break;
133             }
134         }
135         return result;
136     }
137
138     /**
139      * Parses out a token until any of the given terminators
140      * is encountered.
141      *
142      * @param terminators the array of terminating characters. Any of these
143      * characters when encountered signify the end of the token
144      *
145      * @return the token
146      */

147     private String JavaDoc parseToken(final char[] terminators) {
148         char ch;
149         i1 = pos;
150         i2 = pos;
151         while (hasChar()) {
152             ch = chars[pos];
153             if (isOneOf(ch, terminators)) {
154                 break;
155             }
156             i2++;
157             pos++;
158         }
159         return getToken(false);
160     }
161
162     /**
163      * Parses out a token until any of the given terminators
164      * is encountered outside the quotation marks.
165      *
166      * @param terminators the array of terminating characters. Any of these
167      * characters when encountered outside the quotation marks signify the end
168      * of the token
169      *
170      * @return the token
171      */

172     private String JavaDoc parseQuotedToken(final char[] terminators) {
173         char ch;
174         i1 = pos;
175         i2 = pos;
176         boolean quoted = false;
177         boolean charEscaped = false;
178         while (hasChar()) {
179             ch = chars[pos];
180             if (!quoted && isOneOf(ch, terminators)) {
181                 break;
182             }
183             if (!charEscaped && ch == '"') {
184                 quoted = !quoted;
185             }
186             charEscaped = (!charEscaped && ch == '\\');
187             i2++;
188             pos++;
189
190         }
191         return getToken(true);
192     }
193
194     /**
195      * Returns <tt>true</tt> if parameter names are to be converted to lower
196      * case when name/value pairs are parsed.
197      *
198      * @return <tt>true</tt> if parameter names are to be
199      * converted to lower case when name/value pairs are parsed.
200      * Otherwise returns <tt>false</tt>
201      */

202     public boolean isLowerCaseNames() {
203         return this.lowerCaseNames;
204     }
205
206     /**
207      * Sets the flag if parameter names are to be converted to lower case when
208      * name/value pairs are parsed.
209      *
210      * @param b <tt>true</tt> if parameter names are to be
211      * converted to lower case when name/value pairs are parsed.
212      * <tt>false</tt> otherwise.
213      */

214     public void setLowerCaseNames(boolean b) {
215         this.lowerCaseNames = b;
216     }
217
218     /**
219      * Extracts a map of name/value pairs from the given string. Names are
220      * expected to be unique.
221      *
222      * @param str the string that contains a sequence of name/value pairs
223      * @param separator the name/value pairs separator
224      *
225      * @return a map of name/value pairs
226      */

227     public Map JavaDoc parse(final String JavaDoc str, char separator) {
228         if (str == null) {
229             return new HashMap JavaDoc();
230         }
231         return parse(str.toCharArray(), separator);
232     }
233
234     /**
235      * Extracts a map of name/value pairs from the given array of
236      * characters. Names are expected to be unique.
237      *
238      * @param chars the array of characters that contains a sequence of
239      * name/value pairs
240      * @param separator the name/value pairs separator
241      *
242      * @return a map of name/value pairs
243      */

244     public Map JavaDoc parse(final char[] chars, char separator) {
245         if (chars == null) {
246             return new HashMap JavaDoc();
247         }
248         return parse(chars, 0, chars.length, separator);
249     }
250
251     /**
252      * Extracts a map of name/value pairs from the given array of
253      * characters. Names are expected to be unique.
254      *
255      * @param chars the array of characters that contains a sequence of
256      * name/value pairs
257      * @param offset - the initial offset.
258      * @param length - the length.
259      * @param separator the name/value pairs separator
260      *
261      * @return a map of name/value pairs
262      */

263     public Map JavaDoc parse(
264         final char[] chars,
265         int offset,
266         int length,
267         char separator) {
268
269         if (chars == null) {
270             return new HashMap JavaDoc();
271         }
272         HashMap JavaDoc params = new HashMap JavaDoc();
273         this.chars = chars;
274         this.pos = offset;
275         this.len = length;
276
277         String JavaDoc paramName = null;
278         String JavaDoc paramValue = null;
279         while (hasChar()) {
280             paramName = parseToken(new char[] {
281                     '=', separator });
282             paramValue = null;
283             if (hasChar() && (chars[pos] == '=')) {
284                 pos++; // skip '='
285
paramValue = parseQuotedToken(new char[] {
286                         separator });
287             }
288             if (hasChar() && (chars[pos] == separator)) {
289                 pos++; // skip separator
290
}
291             if ((paramName != null) && (paramName.length() > 0)) {
292                 if (this.lowerCaseNames) {
293                     paramName = paramName.toLowerCase();
294                 }
295                 params.put(paramName, paramValue);
296             }
297         }
298         return params;
299     }
300 }
301
Popular Tags