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: */
18:
19: package org.apache.jmeter.protocol.http.util;
20:
21: import java.io.UnsupportedEncodingException;
22: import java.net.URLEncoder;
23:
24: import org.apache.oro.util.Cache;
25: import org.apache.oro.util.CacheLRU;
26:
27: public class EncoderCache {
28:
29: /** The encoding which should be usd for URLs, according to HTTP specification */
30: public static final String URL_ARGUMENT_ENCODING = "UTF-8";
31:
32: private Cache cache;
33:
34: public EncoderCache(int cacheSize) {
35: cache = new CacheLRU(cacheSize);
36: }
37:
38: /**
39: * Get the specified value URL encoded using UTF-8 encoding
40: *
41: * @param k the value to encode
42: * @return the value URL encoded using UTF-8
43: */
44: public String getEncoded(String k) {
45: try {
46: return getEncoded(k, URL_ARGUMENT_ENCODING);
47: } catch (UnsupportedEncodingException e) {
48: // This can't happen (how should utf8 not be supported!?!),
49: // so just throw an Error:
50: throw new Error("Should not happen: " + e.toString());
51: }
52: }
53:
54: /**
55: * Get the specified value URL encoded using the specified encoding
56: *
57: * @param k the value to encode
58: * @param contentEncoding the encoding to use when URL encoding
59: * @return the value URL encoded using the specified encoding
60: * @throws UnsupportedEncodingException if the specified encoding is not supported
61: */
62: public String getEncoded(String k, String contentEncoding)
63: throws UnsupportedEncodingException {
64: String cacheKey = k + contentEncoding;
65: // Check if we have it in the cache
66: Object encodedValue = cache.getElement(cacheKey);
67: if (encodedValue != null) {
68: return (String) encodedValue;
69: }
70: // Perform the encoding
71: encodedValue = URLEncoder.encode(k, contentEncoding);
72: // Add to cache
73: cache.addElement(cacheKey, encodedValue);
74: return (String) encodedValue;
75: }
76: }
|