/
Encode.java
executable file
·561 lines (523 loc) · 16.7 KB
/
Encode.java
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
package org.jboss.resteasy.util;
import org.jboss.resteasy.specimpl.MultivaluedMapImpl;
import javax.ws.rs.core.MultivaluedMap;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class Encode
{
private static final String UTF_8 = "UTF-8";
private static final Pattern PARAM_REPLACEMENT = Pattern.compile("_resteasy_uri_parameter");
private static final String[] pathEncoding = new String[128];
private static final String[] pathSegmentEncoding = new String[128];
private static final String[] matrixParameterEncoding = new String[128];
private static final String[] queryNameValueEncoding = new String[128];
private static final String[] queryStringEncoding = new String[128];
static
{
/*
* Encode via <a href="http://ietf.org/rfc/rfc3986.txt">RFC 3986</a>. PCHAR is allowed allong with '/'
*
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
/ "*" / "+" / "," / ";" / "="
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
*
*/
for (int i = 0; i < 128; i++)
{
if (i >= 'a' && i <= 'z') continue;
if (i >= 'A' && i <= 'Z') continue;
if (i >= '0' && i <= '9') continue;
switch ((char) i)
{
case '-':
case '.':
case '_':
case '~':
case '!':
case '$':
case '&':
case '\'':
case '(':
case ')':
case '*':
case '+':
case ',':
case '/':
case ';':
case '=':
case ':':
case '@':
continue;
}
StringBuffer sb = new StringBuffer();
sb.append((char) i);
pathEncoding[i] = URLEncoder.encode(sb.toString());
}
pathEncoding[' '] = "%20";
System.arraycopy(pathEncoding, 0, matrixParameterEncoding, 0, pathEncoding.length);
matrixParameterEncoding[';'] = "%3B";
matrixParameterEncoding['='] = "%3D";
matrixParameterEncoding['/'] = "%2F"; // RESTEASY-729
System.arraycopy(pathEncoding, 0, pathSegmentEncoding, 0, pathEncoding.length);
pathSegmentEncoding['/'] = "%2F";
/*
* Encode via <a href="http://ietf.org/rfc/rfc3986.txt">RFC 3986</a>.
*
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* space encoded as '+'
*
*/
for (int i = 0; i < 128; i++)
{
if (i >= 'a' && i <= 'z') continue;
if (i >= 'A' && i <= 'Z') continue;
if (i >= '0' && i <= '9') continue;
switch ((char) i)
{
case '-':
case '.':
case '_':
case '~':
case '?':
continue;
case ' ':
queryNameValueEncoding[i] = "+";
continue;
}
StringBuffer sb = new StringBuffer();
sb.append((char) i);
queryNameValueEncoding[i] = URLEncoder.encode(sb.toString());
}
/*
* query = *( pchar / "/" / "?" )
*/
for (int i = 0; i < 128; i++)
{
if (i >= 'a' && i <= 'z') continue;
if (i >= 'A' && i <= 'Z') continue;
if (i >= '0' && i <= '9') continue;
switch ((char) i)
{
case '-':
case '.':
case '_':
case '~':
case '!':
case '$':
case '&':
case '\'':
case '(':
case ')':
case '*':
case '+':
case ',':
case ';':
case '=':
case ':':
case '@':
case '?':
case '/':
continue;
case ' ':
queryStringEncoding[i] = "%20";
continue;
}
StringBuffer sb = new StringBuffer();
sb.append((char) i);
queryStringEncoding[i] = URLEncoder.encode(sb.toString());
}
}
/**
* Keep encoded values "%..." and template parameters intact.
*/
public static String encodeQueryString(String value)
{
return encodeValue(value, queryStringEncoding);
}
/**
* Keep encoded values "%...", matrix parameters, template parameters, and '/' characters intact.
*/
public static String encodePath(String value)
{
return encodeValue(value, pathEncoding);
}
/**
* Keep encoded values "%...", matrix parameters and template parameters intact.
*/
public static String encodePathSegment(String value)
{
return encodeValue(value, pathSegmentEncoding);
}
/**
* Keep encoded values "%..." and template parameters intact.
*/
public static String encodeFragment(String value)
{
return encodeValue(value, queryStringEncoding);
}
/**
* Keep encoded values "%..." and template parameters intact.
*/
public static String encodeMatrixParam(String value)
{
return encodeValue(value, matrixParameterEncoding);
}
/**
* Keep encoded values "%..." and template parameters intact.
*/
public static String encodeQueryParam(String value)
{
return encodeValue(value, queryNameValueEncoding);
}
//private static final Pattern nonCodes = Pattern.compile("%([^a-fA-F0-9]|$)");
private static final Pattern nonCodes = Pattern.compile("%([^a-fA-F0-9]|[a-fA-F0-9]$|$|[a-fA-F0-9][^a-fA-F0-9])");
private static final Pattern encodedChars = Pattern.compile("%([a-fA-F0-9][a-fA-F0-9])");
private static final Pattern encodedCharsMulti = Pattern.compile("((%[a-fA-F0-9][a-fA-F0-9])+)");
public static String decodePath(String path)
{
Matcher matcher = encodedCharsMulti.matcher(path);
StringBuffer buf = new StringBuffer();
CharsetDecoder decoder = Charset.forName(UTF_8).newDecoder();
while (matcher.find())
{
decoder.reset();
String decoded = decodeBytes(matcher.group(1), decoder);
decoded = decoded.replace("\\", "\\\\");
decoded = decoded.replace("$", "\\$");
matcher.appendReplacement(buf, decoded);
}
matcher.appendTail(buf);
return buf.toString();
}
private static String decodeBytes(String enc, CharsetDecoder decoder)
{
Matcher matcher = encodedChars.matcher(enc);
StringBuffer buf = new StringBuffer();
ByteBuffer bytes = ByteBuffer.allocate(enc.length() / 3);
while (matcher.find())
{
int b = Integer.parseInt(matcher.group(1), 16);
bytes.put((byte) b);
}
bytes.flip();
try
{
return decoder.decode(bytes).toString();
}
catch (CharacterCodingException e)
{
throw new RuntimeException(e);
}
}
/**
* Encode '%' if it is not an encoding sequence
*
* @param string
* @return
*/
public static String encodeNonCodes(String string)
{
Matcher matcher = nonCodes.matcher(string);
StringBuffer buf = new StringBuffer();
// FYI: we do not use the no-arg matcher.find()
// coupled with matcher.appendReplacement()
// because the matched text may contain
// a second % and we must make sure we
// encode it (if necessary).
int idx = 0;
while (matcher.find(idx))
{
int start = matcher.start();
buf.append(string.substring(idx, start));
buf.append("%25");
idx = start + 1;
}
buf.append(string.substring(idx));
return buf.toString();
}
public static boolean savePathParams(String segment, StringBuffer newSegment, List<String> params)
{
boolean foundParam = false;
// Regular expressions can have '{' and '}' characters. Replace them to do match
segment = PathHelper.replaceEnclosedCurlyBraces(segment);
Matcher matcher = PathHelper.URI_TEMPLATE_PATTERN.matcher(segment);
while (matcher.find())
{
foundParam = true;
String group = matcher.group();
// Regular expressions can have '{' and '}' characters. Recover earlier replacement
params.add(PathHelper.recoverEnclosedCurlyBraces(group));
matcher.appendReplacement(newSegment, "_resteasy_uri_parameter");
}
matcher.appendTail(newSegment);
return foundParam;
}
/**
* Keep encoded values "%..." and template parameters intact i.e. "{x}"
*
* @param segment
* @param encoding
* @return
*/
public static String encodeValue(String segment, String[] encoding)
{
ArrayList<String> params = new ArrayList<String>();
boolean foundParam = false;
StringBuffer newSegment = new StringBuffer();
if (savePathParams(segment, newSegment, params))
{
foundParam = true;
segment = newSegment.toString();
}
String result = encodeFromArray(segment, encoding, false);
result = encodeNonCodes(result);
segment = result;
if (foundParam)
{
segment = pathParamReplacement(segment, params);
}
return segment;
}
/**
* Encode via <a href="http://ietf.org/rfc/rfc3986.txt">RFC 3986</a>. PCHAR is allowed allong with '/'
* <p/>
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
*/
public static String encodePathAsIs(String segment)
{
return encodeFromArray(segment, pathEncoding, true);
}
/**
* Keep any valid encodings from string i.e. keep "%2D" but don't keep "%p"
*
* @param segment
* @return
*/
public static String encodePathSaveEncodings(String segment)
{
String result = encodeFromArray(segment, pathEncoding, false);
result = encodeNonCodes(result);
return result;
}
/**
* Encode via <a href="http://ietf.org/rfc/rfc3986.txt">RFC 3986</a>. PCHAR is allowed allong with '/'
* <p/>
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
*/
public static String encodePathSegmentAsIs(String segment)
{
return encodeFromArray(segment, pathSegmentEncoding, true);
}
/**
* Keep any valid encodings from string i.e. keep "%2D" but don't keep "%p"
*
* @param segment
* @return
*/
public static String encodePathSegmentSaveEncodings(String segment)
{
String result = encodeFromArray(segment, pathSegmentEncoding, false);
result = encodeNonCodes(result);
return result;
}
/**
* Encodes everything of a query parameter name or value.
*
* @param nameOrValue
* @return
*/
public static String encodeQueryParamAsIs(String nameOrValue)
{
return encodeFromArray(nameOrValue, queryNameValueEncoding, true);
}
/**
* Keep any valid encodings from string i.e. keep "%2D" but don't keep "%p"
*
* @param segment
* @return
*/
public static String encodeQueryParamSaveEncodings(String segment)
{
String result = encodeFromArray(segment, queryNameValueEncoding, false);
result = encodeNonCodes(result);
return result;
}
public static String encodeFragmentAsIs(String nameOrValue)
{
return encodeFromArray(nameOrValue, queryNameValueEncoding, true);
}
protected static String encodeFromArray(String segment, String[] encodingMap, boolean encodePercent)
{
StringBuffer result = new StringBuffer();
for (int i = 0; i < segment.length(); i++)
{
if (!encodePercent && segment.charAt(i) == '%')
{
result.append(segment.charAt(i));
continue;
}
int idx = segment.charAt(i);
String encoding = encode(idx, encodingMap);
if (encoding == null)
{
result.append(segment.charAt(i));
}
else
{
result.append(encoding);
}
}
return result.toString();
}
/**
* @param zhar integer representation of character
* @param encodingMap encoding map
* @return URL encoded character
*/
private static String encode(int zhar, String[] encodingMap)
{
String encoded;
if (zhar < encodingMap.length)
{
encoded = encodingMap[zhar];
}
else
{
try
{
encoded = URLEncoder.encode(Character.toString((char) zhar), UTF_8);
}
catch (UnsupportedEncodingException e)
{
throw new RuntimeException(e);
}
}
return encoded;
}
public static String pathParamReplacement(String segment, List<String> params)
{
StringBuffer newSegment = new StringBuffer();
Matcher matcher = PARAM_REPLACEMENT.matcher(segment);
int i = 0;
while (matcher.find())
{
String replacement = params.get(i++);
// double encode slashes, so that slashes stay where they are
replacement = replacement.replace("\\", "\\\\");
replacement = replacement.replace("$", "\\$");
matcher.appendReplacement(newSegment, replacement);
}
matcher.appendTail(newSegment);
segment = newSegment.toString();
return segment;
}
/**
* decode an encoded map
*
* @param map
* @return
*/
public static MultivaluedMap<String, String> decode(MultivaluedMap<String, String> map)
{
MultivaluedMapImpl<String, String> decoded = new MultivaluedMapImpl<String, String>();
for (Map.Entry<String, List<String>> entry : map.entrySet())
{
List<String> values = entry.getValue();
for (String value : values)
{
try
{
decoded.add(URLDecoder.decode(entry.getKey(), UTF_8), URLDecoder.decode(value, UTF_8));
}
catch (UnsupportedEncodingException e)
{
throw new RuntimeException(e);
}
}
}
return decoded;
}
/**
* decode an encoded map
*
* @param map
* @param charset
* @return
*/
public static MultivaluedMap<String, String> decode(MultivaluedMap<String, String> map, String charset)
{
if (charset == null)
{
charset = UTF_8;
}
MultivaluedMapImpl<String, String> decoded = new MultivaluedMapImpl<String, String>();
for (Map.Entry<String, List<String>> entry : map.entrySet())
{
List<String> values = entry.getValue();
for (String value : values)
{
try
{
decoded.add(URLDecoder.decode(entry.getKey(), charset), URLDecoder.decode(value, charset));
}
catch (UnsupportedEncodingException e)
{
throw new RuntimeException(e);
}
}
}
return decoded;
}
public static MultivaluedMap<String, String> encode(MultivaluedMap<String, String> map)
{
MultivaluedMapImpl<String, String> decoded = new MultivaluedMapImpl<String, String>();
for (Map.Entry<String, List<String>> entry : map.entrySet())
{
List<String> values = entry.getValue();
for (String value : values)
{
try
{
decoded.add(URLEncoder.encode(entry.getKey(), UTF_8), URLEncoder.encode(value, UTF_8));
}
catch (UnsupportedEncodingException e)
{
throw new RuntimeException(e);
}
}
}
return decoded;
}
public static String decode(String string)
{
try
{
return URLDecoder.decode(string, UTF_8);
}
catch (UnsupportedEncodingException e)
{
throw new RuntimeException(e);
}
}
}