1 package org.apache.fulcrum.parser;
2
3
4 /*
5 * Licensed to the Apache Software Foundation (ASF) under one
6 * or more contributor license agreements. See the NOTICE file
7 * distributed with this work for additional information
8 * regarding copyright ownership. The ASF licenses this file
9 * to you under the Apache License, Version 2.0 (the
10 * "License"); you may not use this file except in compliance
11 * with the License. You may obtain a copy of the License at
12 *
13 * http://www.apache.org/licenses/LICENSE-2.0
14 *
15 * Unless required by applicable law or agreed to in writing,
16 * software distributed under the License is distributed on an
17 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
18 * KIND, either express or implied. See the License for the
19 * specific language governing permissions and limitations
20 * under the License.
21 */
22
23
24 import java.net.URLDecoder;
25 import java.util.StringTokenizer;
26
27 /**
28 * An extension that parses a String for name/value pairs.
29 *
30 * @author <a href="mailto:jmcnally@collab.net">John McNally</a>
31 * @version $Id$
32 */
33 public class StringValueParser
34 extends BaseValueParser
35 {
36 /**
37 * Parses a String using a single delimiter.
38 *
39 * @param s a <code>String</code> value
40 * @param delim a <code>char</code> value
41 * @param urlDecode a <code>boolean</code> value
42 * @exception Exception Error decoding name/value pairs.
43 */
44 public void parse(String s, char delim, boolean urlDecode)
45 throws Exception
46 {
47 String delimChar = String.valueOf(delim);
48 StringTokenizer st = new StringTokenizer(s, delimChar);
49 boolean isNameTok = true;
50 String pathPart = null;
51 String key = null;
52 while (st.hasMoreTokens())
53 {
54 String tok = st.nextToken();
55 if ( urlDecode )
56 {
57 tok = URLDecoder.decode(tok, getCharacterEncoding());
58 }
59
60 if (isNameTok)
61 {
62 key = tok;
63 isNameTok = false;
64 }
65 else
66 {
67 pathPart = tok;
68 if (key != null && key.length() > 0)
69 {
70 add (convert(key), pathPart);
71 }
72 isNameTok = true;
73 }
74 }
75 }
76
77 public void parse(String s, char paramDelim, char pairDelim,
78 boolean urlDecode)
79 throws Exception
80 {
81 if ( paramDelim == pairDelim )
82 {
83 parse(s, paramDelim, urlDecode);
84 }
85 else
86 {
87 String delimChar = String.valueOf(paramDelim);
88 StringTokenizer st = new StringTokenizer(s, delimChar);
89
90 while (st.hasMoreTokens())
91 {
92 String pair = st.nextToken();
93 int pos = pair.indexOf(pairDelim);
94 String name = pair.substring(0, pos);
95 String value = pair.substring(pos+1);
96
97 if ( urlDecode )
98 {
99 name = URLDecoder.decode(name, getCharacterEncoding());
100 value = URLDecoder.decode(value, getCharacterEncoding());
101 }
102
103 if (name.length() > 0)
104 {
105 add (convert(name), value);
106 }
107 }
108 }
109 }
110 }