01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: */
17: package org.apache.wicket.request.target.coding;
18:
19: import java.io.UnsupportedEncodingException;
20: import java.net.URLEncoder;
21:
22: import org.apache.wicket.Application;
23: import org.apache.wicket.util.string.AppendingStringBuffer;
24:
25: /**
26: * {@link AppendingStringBuffer}-based query string encoder, handles String[]
27: * and String properly, and properly URL-encodes the values
28: *
29: * @author <a href="mailto:jbq@apache.org">Jean-Baptiste Quenot</a>
30: */
31: public class WebRequestEncoder {
32: boolean firstParameter = true;
33: AppendingStringBuffer url;
34: Application application;
35:
36: /**
37: * Construct.
38: *
39: * @param url
40: * the {@link AppendingStringBuffer} where to append query string
41: */
42: public WebRequestEncoder(AppendingStringBuffer url) {
43: this .url = url;
44: application = Application.get();
45: }
46:
47: /**
48: * Add an {@link Object}
49: *
50: * @param key
51: * @param value
52: */
53: public void addValue(String key, Object value) {
54: if (value instanceof String[]) {
55: String[] values = (String[]) value;
56: for (int i = 0; i < values.length; i++) {
57: addValue(key, values[i]);
58: }
59: } else if (value instanceof String) {
60: addValue(key, (String) value);
61: } else {
62: throw new IllegalArgumentException(
63: "PageParameters can only contain String or String[]");
64: }
65: }
66:
67: /**
68: * Add a {@link String}
69: *
70: * @param key
71: * @param value
72: */
73: public void addValue(String key, String value) {
74: String escapedValue = value;
75: try {
76: escapedValue = URLEncoder.encode(escapedValue, application
77: .getRequestCycleSettings()
78: .getResponseRequestEncoding());
79: } catch (UnsupportedEncodingException ex) {
80: // ignore
81: }
82: if (!firstParameter) {
83: url.append('&');
84: } else {
85: firstParameter = false;
86: url.append('?');
87: }
88: url.append(key);
89: url.append('=');
90: url.append(escapedValue);
91: }
92:
93: }
|