forked from google/gdata-java-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFastURLEncoder.java
More file actions
404 lines (374 loc) · 15.1 KB
/
Copy pathFastURLEncoder.java
File metadata and controls
404 lines (374 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gdata.util.httputil;
import com.google.common.annotations.VisibleForTesting;
import com.google.gdata.util.common.base.PercentEscaper;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.BitSet;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This class has been <b>deprecated</b>; use {@link
* com.google.gdata.util.common.base.CharEscapers#uriEscaper()},
* {@link com.google.gdata.util.common.base.CharEscapers#cppUriEscaper()} or create your
* own custom {@link com.google.gdata.util.common.base.PercentEscaper}.
*
* <p>Almost every use of FastURLEncoder can now be replaced with an instance of
* the PercentEscaper class, which is much faster.
*
* <p>In most cases it should be possible to use the static instances available
* from {@link com.google.gdata.util.common.base.CharEscapers} but it is also possible to
* create your own escaper with custom behaviour.
*
* <p>See <a href="https://docs.google.com/a/google.com/View?docID=ahmsnsb8b5_85dwj83whg">
* Deprecating FastURLEncoder</a> for more information.
*
* <p>Note that the new uriEscaper only escapes using UTF-8 encoding and while
* no examples of other encodings were found when preparing this class for
* deprecation, it's possible that some instance were missed. If you have a
* valid reason to escape URIs via an encoding other than UTF-8 please let
* the java-libraries-team know.
*
* <p>FastURLEncoder is intended as a replacement for the slow and inefficient
* java.net.URLEncoder. There are a few differences though:
* <ul>
* <li> URLEncoder.encode(String) uses the platform's default encoding
* while FastURLEncoder.encode(String) always uses UTF-8. The default
* encoding is unpredictable and so it shouldn't be used anyway.
* <li> FastURLEncoder allocates much less memory. In my tests I escaped
* 81735 bytes of data 20 bytes at a time. URLEncoder allocated over
* 200 MB! FastURLEncoder allocated much less (probably about 500 kB).
* <li> FastURLEncoder is over 30 times as fast.
* <li> FastURLEncoder (optionally) lets you specify which octets should and
* shouldn't be escaped and also whether spaces should be escaped as "+" or
* "%20".
* </ul>
*
* <p>It is possible that URLEncoder is doing really complicated stuff for
* a reason and that I just don't understand why. If you are unsure of
* FastURLEncoder just call FastURLEncoder.setVerifyAgainstJava(true). This
* will run both versions and verify that the outputs are the same.
* Of course this will be slow but it is useful for testing. I wouldn't
* be surprised if the two differ for non-latin1, non-utf-8 encodings.
*
* <p>FastURLEncoder requires jdk 1.5.
*
* @see java.net.URLEncoder
*
*/
public class FastURLEncoder {
private static boolean verifyAgainstJava = false;
private FastURLEncoder() {
}
/**
* Set this to 'true' if you are not certain that FastURLEncoder is
* going to do the right thing for you and want to test for a while.
* Set to 'false' if you want the speed and memory benefits of
* FastURLEncoder. If this is set to 'true' and FastURLEncoder disagrees
* with URLEncoder then FastURLEncoder will log a
* java.util.logging.Level.SEVERE message and return the value provided
* by URLEncoder.
*/
@VisibleForTesting
static void setVerifyAgainstJava(boolean shouldVerify) {
verifyAgainstJava = shouldVerify;
}
/**
* @return 'true' if we are going to verify all results against URLEncoder.
*/
@VisibleForTesting
static boolean getVerifyAgainstJava() {
return verifyAgainstJava;
}
/**
* URL-escapes s by encoding it with the specified character encoding, and
* then escaping all octets not included in safeOctets.
*
* @param s String to encode.
* @param encoding character encoding to use (e.g., "UTF-8")
* @param safeOctets set of octets that should not be escaped.
* @param plusForSpace whether octet 0x20, i.e. "space", should be encoded as
* a plus sign rather than "%20". Note that this parameter is effectively
* ignored if 0x20 is in safeOctets.
*
* @return the encoded version of {@code s}. Will return {@code s}
* itself if no encoding is necessary.
*
* @throws UnsupportedEncodingException if {@code encoding} is not supported.
*
* @deprecated Use {@link com.google.gdata.util.common.base.CharEscapers#uriEscaper()}
* or create an instance of {@link com.google.gdata.util.common.base.PercentEscaper}.
* See {@link FastURLEncoder} for more details.
*/
@Deprecated
public static String encode(final String s, final String encoding,
BitSet safeOctets, boolean plusForSpace)
throws UnsupportedEncodingException {
StringBuilder out = new StringBuilder(s.length() * 2);
boolean needsEncoding;
try {
needsEncoding = encode(s, encoding, safeOctets, plusForSpace, out);
} catch (UnsupportedEncodingException e) {
throw e;
} catch (IOException e) {
throw new AssertionError(e);
}
if (needsEncoding) {
return out.toString();
} else {
return s;
}
}
/**
* URL-escapes s by encoding it with the specified character encoding,
* escaping all octets not included in safeOctets, and then outputting
* the result to an Appendable.
*
* @param s String to encode.
* @param encoding character encoding to use (e.g., "UTF-8")
* @param safeOctets set of octets that should not be escaped.
* @param plusForSpace whether octet 0x20, i.e. "space", should be encoded as
* a plus sign rather than "%20". Note that this parameter is effectively
* ignored if 0x20 is in safeOctets.
* @param out the Appendable destination for the encoded string.
*
* @return true if {@code s} did need escaping, false otherwise. In
* other words, this returns false only if {@code s} was output to
* {@code out} verbatim.
*
* @throws UnsupportedEncodingException if {@code encoding} is not supported.
* @throws IOException if {@code out} does so when appended to.
*
* @deprecated Use {@link com.google.gdata.util.common.base.CharEscapers#uriEscaper()}
* or create an instance of {@link com.google.gdata.util.common.base.PercentEscaper}.
* See {@link FastURLEncoder} for more details.
*/
@Deprecated
public static boolean encode(final String s, final String encoding,
BitSet safeOctets, boolean plusForSpace,
Appendable out)
throws UnsupportedEncodingException, IOException {
byte[] data = s.getBytes(encoding);
boolean containsSpace = false;
int outputLength = 0;
for (int i = 0; i < data.length; i++) {
int c = data[i];
if (c < 0)
c += 256; // convert from [-128, 127] to [0, 255]
if (safeOctets.get(c)) {
out.append((char)c);
outputLength += 1;
} else if (plusForSpace && (c == ' ')) {
containsSpace = true;
out.append('+');
outputLength += 1;
} else {
out.append('%');
out.append(HEX_DIGITS[c >> 4]);
out.append(HEX_DIGITS[c & 0xf]);
outputLength += 3;
}
}
return containsSpace || (outputLength != s.length());
}
/**
* This should be a direct replacement for java.net.URLEncoder.encode().
* @see java.net.URLEncoder#encode(String, String)
* @param s String to encode.
* @param encoding character encoding to use (e.g., "UTF-8")
*
* @deprecated Use {@link com.google.gdata.util.common.base.CharEscapers#uriEscaper()}.
* See {@link FastURLEncoder} for more details.
*/
@Deprecated
public static String encode(String s, String encoding)
throws UnsupportedEncodingException {
String result = encode(s, encoding, DEFAULT_SAFE_OCTETS, true);
if (verifyAgainstJava) {
String jresult = URLEncoder.encode(s, encoding);
if (!jresult.equals(result)) {
Logger.getLogger(FastURLEncoder.class.getName()).
log(Level.SEVERE, "FastURLEncoder does not match java. Java: '" +
jresult + "' FastURLEncoder: '" + result + "'");
return jresult;
}
}
return result;
}
/**
* This should be a direct replacement for java.net.URLEncoder.encode(),
* but appends its output to an Appendable.
*
* @see java.net.URLEncoder#encode(String, String)
* @param s String to encode.
* @param encoding character encoding to use (e.g., "UTF-8")
* @param out the Appendable destination for the encoded string.
*
* @throws UnsupportedEncodingException if {@code encoding} is not supported.
* @throws IOException if {@code out} does so when appended to.
*
* @deprecated Use {@link com.google.gdata.util.common.base.CharEscapers#uriEscaper()}.
* See {@link FastURLEncoder} for more details.
*/
@Deprecated
public static void encode(String s, String encoding, Appendable out)
throws UnsupportedEncodingException, IOException {
/*
* Note that this method never compares its result with Java's
* encoding; it does not not respect the verifyAgainstJava value
*/
encode(s, encoding, DEFAULT_SAFE_OCTETS, true, out);
}
/**
* Shortcut for encode(s, "UTF-8").
* This is very similiar to java.net.URLEncoder.encode() except that it
* uses UTF-8 instead of the platform's default encoding.
* @see java.net.URLEncoder#encode(String)
* @param s String to encode.
*
* @deprecated Use {@link com.google.gdata.util.common.base.CharEscapers#uriEscaper()}.
*/
@Deprecated
public static String encode(String s) {
try {
return encode(s, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new AssertionError(e);
}
}
/**
* Shortcut for encode(s, "UTF-8", out).
* This is very similiar to java.net.URLEncoder.encode() except that it
* uses UTF-8 instead of the platform's default encoding.
* @see java.net.URLEncoder#encode(String)
* @param s String to encode.
* @param out the Appendable destination for the encoded string.
*
* @deprecated Use {@link com.google.gdata.util.common.base.CharEscapers#uriEscaper()}.
* See {@link FastURLEncoder} for more details.
*/
@Deprecated
public static void encode(String s, Appendable out) throws IOException {
try {
/*
* Note that this method never compares its result with Java's
* encoding; it does not not respect the verifyAgainstJava value
*/
encode(s, "UTF-8", out);
} catch (UnsupportedEncodingException e) {
throw new AssertionError(e);
}
}
/**
* Shortcut for encode(s, "UTF-8").
* This is very similiar to java.net.URLEncoder.encode() except that it
* uses UTF-8 instead of the platform's default encoding.
* @see java.net.URLEncoder#encode(String)
* @param s String to encode.
* @param safeOctets set of octets that should not be escaped.
* @param plusForSpace whether octet 0x20, i.e., "space", should be encoded as
* a plus sign rather than "%20". Note that this parameter is effectively
* ignored if 0x20 is in safeOctets.
*
* @deprecated Use {@link com.google.gdata.util.common.base.CharEscapers#uriEscaper()}.
* or create an instance of {@link com.google.gdata.util.common.base.PercentEscaper}.
* See {@link FastURLEncoder} for more details.
*/
@Deprecated
public static String encode(String s, BitSet safeOctets,
boolean plusForSpace) {
try {
return encode(s, "UTF-8", safeOctets, plusForSpace);
} catch (UnsupportedEncodingException e) {
throw new AssertionError(e);
}
}
/** java.net.URLEncoder uses upper-case hex digits so we should too. */
private static final char[] HEX_DIGITS = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F'};
/**
* These octets all go directly into the URL, all others are escaped.
*/
private static final BitSet DEFAULT_SAFE_OCTETS = new BitSet(256);
static {
// These characters are specified as unreservered in RFC 2396:
// "-", "_", ".", "!", "~", "*", "'", "(", ")",
// "0".."9", "A".."Z", "a".."z"
// But wait... Java also escapes !, ~, ', (, and )
// I'm only going to include -, _, ., and * to be consistent with java
for (int i = '0'; i <= '9'; i++)
DEFAULT_SAFE_OCTETS.set(i);
for (int i = 'A'; i <= 'Z'; i++)
DEFAULT_SAFE_OCTETS.set(i);
for (int i = 'a'; i <= 'z'; i++)
DEFAULT_SAFE_OCTETS.set(i);
DEFAULT_SAFE_OCTETS.set('-');
DEFAULT_SAFE_OCTETS.set('_');
DEFAULT_SAFE_OCTETS.set('.');
DEFAULT_SAFE_OCTETS.set('*');
}
/**
* These octets mimic the ones escaped by the C++ webutil/url URL class --
* the kGoogle1Escape set.
* To produce the same escaping as C++, use this BitSet with the plusForSpace
* option.
*
* @deprecated Use {@link com.google.gdata.util.common.base.CharEscapers#cppUriEscaper()}
*/
@Deprecated
public static final BitSet CPLUSPLUS_COMPAT_SAFE_OCTETS = new BitSet(256);
static {
CPLUSPLUS_COMPAT_SAFE_OCTETS.set('!');
CPLUSPLUS_COMPAT_SAFE_OCTETS.set(')');
CPLUSPLUS_COMPAT_SAFE_OCTETS.set('(');
CPLUSPLUS_COMPAT_SAFE_OCTETS.set('*');
CPLUSPLUS_COMPAT_SAFE_OCTETS.set(',');
CPLUSPLUS_COMPAT_SAFE_OCTETS.set('-');
CPLUSPLUS_COMPAT_SAFE_OCTETS.set('.');
CPLUSPLUS_COMPAT_SAFE_OCTETS.set('/');
for (int i = '0'; i <= '9'; i++)
CPLUSPLUS_COMPAT_SAFE_OCTETS.set(i);
CPLUSPLUS_COMPAT_SAFE_OCTETS.set(':');
for (int i = 'A'; i <= 'Z'; i++)
CPLUSPLUS_COMPAT_SAFE_OCTETS.set(i);
CPLUSPLUS_COMPAT_SAFE_OCTETS.set('_');
for (int i = 'a'; i <= 'z'; i++)
CPLUSPLUS_COMPAT_SAFE_OCTETS.set(i);
CPLUSPLUS_COMPAT_SAFE_OCTETS.set('~');
}
/**
* Instead of retrieving this set to add your own safe characters, simply
* provide your additional safe characters to the
* {@link PercentEscaper#PercentEscaper(String, boolean)} constructor.
* If you don't need to add your own safe characters, just use
* {@link com.google.gdata.util.common.base.CharEscapers#uriEscaper()}.
*
* @return a BitSet suitable for passing to
* {@link #encode(String,String,BitSet,boolean)} or
* {@link #encode(String,BitSet,boolean)}. It defaults to containing the
* octets that would not be escaped by
* {@link java.net.URLEncoder#encode(String)}. Callers can edit the
* result for specialized purposes.
*
* @deprecated Use {@link com.google.gdata.util.common.base.CharEscapers#uriEscaper()}.
* or create an instance of {@link com.google.gdata.util.common.base.PercentEscaper}.
* See {@link FastURLEncoder} for more details.
*/
@Deprecated
public static BitSet createSafeOctetBitSet() {
return (BitSet) DEFAULT_SAFE_OCTETS.clone();
}
}