/
MultipartInputImpl.java
493 lines (443 loc) · 15.9 KB
/
MultipartInputImpl.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
package org.jboss.resteasy.plugins.providers.multipart;
import org.apache.james.mime4j.MimeException;
import org.apache.james.mime4j.MimeIOException;
import org.apache.james.mime4j.codec.Base64InputStream;
import org.apache.james.mime4j.codec.QuotedPrintableInputStream;
import org.apache.james.mime4j.descriptor.BodyDescriptor;
import org.apache.james.mime4j.field.ContentTypeField;
import org.apache.james.mime4j.message.BinaryBody;
import org.apache.james.mime4j.message.Body;
import org.apache.james.mime4j.message.BodyFactory;
import org.apache.james.mime4j.message.BodyPart;
import org.apache.james.mime4j.message.Entity;
import org.apache.james.mime4j.message.Message;
import org.apache.james.mime4j.message.MessageBuilder;
import org.apache.james.mime4j.message.Multipart;
import org.apache.james.mime4j.message.TextBody;
import org.apache.james.mime4j.parser.Field;
import org.apache.james.mime4j.parser.MimeStreamParser;
import org.apache.james.mime4j.storage.DefaultStorageProvider;
import org.apache.james.mime4j.storage.StorageProvider;
import org.apache.james.mime4j.util.CharsetUtil;
import org.apache.james.mime4j.util.MimeUtil;
import org.jboss.resteasy.core.ProvidersContextRetainer;
import org.jboss.resteasy.plugins.providers.multipart.i18n.Messages;
import org.jboss.resteasy.spi.HttpRequest;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.jboss.resteasy.util.CaseInsensitiveMap;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Providers;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.SequenceInputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Stack;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class MultipartInputImpl implements MultipartInput, ProvidersContextRetainer
{
protected MediaType contentType;
protected Providers workers;
protected Message mimeMessage;
protected List<InputPart> parts = new ArrayList<InputPart>();
protected static final Annotation[] empty = {};
protected MediaType defaultPartContentType = MultipartConstants.TEXT_PLAIN_WITH_CHARSET_US_ASCII_TYPE;
protected String defaultPartCharset = null;
protected Providers savedProviders;
// We hack MIME4j so that it always returns a BinaryBody so we don't have to deal with Readers and their charset conversions
private static class BinaryOnlyMessageBuilder extends MessageBuilder
{
private Method expectMethod;
private java.lang.reflect.Field bodyFactoryField;
private java.lang.reflect.Field stackField;
private void init()
{
try
{
expectMethod = MessageBuilder.class.getDeclaredMethod("expect", Class.class);
expectMethod.setAccessible(true);
bodyFactoryField = MessageBuilder.class.getDeclaredField("bodyFactory");
bodyFactoryField.setAccessible(true);
stackField = MessageBuilder.class.getDeclaredField("stack");
stackField.setAccessible(true);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
private BinaryOnlyMessageBuilder(Entity entity)
{
super(entity);
init();
}
private BinaryOnlyMessageBuilder(Entity entity, StorageProvider storageProvider)
{
super(entity, storageProvider);
init();
}
@Override
public void body(BodyDescriptor bd, InputStream is) throws MimeException, IOException
{
// the only thing different from the superclass is that we just return a BinaryBody no matter what
try
{
expectMethod.invoke(this, Entity.class);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
final String enc = bd.getTransferEncoding();
final Body body;
final InputStream decodedStream;
if (MimeUtil.ENC_BASE64.equals(enc)) {
decodedStream = new Base64InputStream(is);
} else if (MimeUtil.ENC_QUOTED_PRINTABLE.equals(enc)) {
decodedStream = new QuotedPrintableInputStream(is);
} else {
decodedStream = is;
}
BodyFactory factory;
try
{
factory = (BodyFactory)bodyFactoryField.get(this);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
body = factory.binaryBody(decodedStream);
@SuppressWarnings("unchecked")
Stack<Object> st;
try
{
st = (Stack<Object>)stackField.get(this);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
Entity entity = ((Entity) st.peek());
entity.setBody(body);
}
}
private static class BinaryMessage extends Message
{
private BinaryMessage(InputStream is) throws IOException, MimeIOException
{
try {
MimeStreamParser parser = new MimeStreamParser(null);
parser.setContentHandler(new BinaryOnlyMessageBuilder(this, DefaultStorageProvider.getInstance()));
parser.parse(is);
} catch (MimeException e) {
throw new MimeIOException(e);
}
}
}
public MultipartInputImpl(MediaType contentType, Providers workers)
{
this.contentType = contentType;
this.workers = workers;
HttpRequest httpRequest = ResteasyProviderFactory
.getContextData(HttpRequest.class);
if (httpRequest != null)
{
String defaultContentType = (String) httpRequest
.getAttribute(InputPart.DEFAULT_CONTENT_TYPE_PROPERTY);
if (defaultContentType != null)
this.defaultPartContentType = MediaType
.valueOf(defaultContentType);
this.defaultPartCharset = (String) httpRequest.getAttribute(InputPart.DEFAULT_CHARSET_PROPERTY);
if (defaultPartCharset != null)
{
this.defaultPartContentType = getMediaTypeWithDefaultCharset(this.defaultPartContentType);
}
}
}
public MultipartInputImpl(MediaType contentType, Providers workers,
MediaType defaultPartContentType, String defaultPartCharset)
{
this.contentType = contentType;
this.workers = workers;
if (defaultPartContentType != null) this.defaultPartContentType = defaultPartContentType;
this.defaultPartCharset = defaultPartCharset;
if (defaultPartCharset != null)
{
this.defaultPartContentType = getMediaTypeWithDefaultCharset(this.defaultPartContentType);
}
}
public MultipartInputImpl(Multipart multipart, Providers workers) throws IOException
{
for (BodyPart bodyPart : multipart.getBodyParts())
parts.add(extractPart(bodyPart));
this.workers = workers;
}
public void parse(InputStream is) throws IOException
{
mimeMessage = new BinaryMessage(addHeaderToHeadlessStream(is));
extractParts();
}
protected InputStream addHeaderToHeadlessStream(InputStream is)
throws UnsupportedEncodingException
{
return new SequenceInputStream(createHeaderInputStream(), is);
}
protected InputStream createHeaderInputStream()
throws UnsupportedEncodingException
{
String header = HttpHeaders.CONTENT_TYPE + ": " + contentType
+ "\r\n\r\n";
return new ByteArrayInputStream(header.getBytes("utf-8"));
}
public String getPreamble()
{
return ((Multipart) mimeMessage.getBody()).getPreamble();
}
public List<InputPart> getParts()
{
return parts;
}
protected void extractParts() throws IOException
{
Multipart multipart = (Multipart) mimeMessage.getBody();
for (BodyPart bodyPart : multipart.getBodyParts())
parts.add(extractPart(bodyPart));
}
protected InputPart extractPart(BodyPart bodyPart) throws IOException
{
return new PartImpl(bodyPart);
}
public class PartImpl implements InputPart
{
private BodyPart bodyPart;
private MediaType contentType;
private MultivaluedMap<String, String> headers = new CaseInsensitiveMap<String>();
private boolean contentTypeFromMessage;
public PartImpl(BodyPart bodyPart)
{
this.bodyPart = bodyPart;
for (Field field : bodyPart.getHeader())
{
headers.add(field.getName(), field.getBody());
if (field instanceof ContentTypeField)
{
contentType = MediaType.valueOf(field.getBody());
contentTypeFromMessage = true;
}
}
if (contentType == null)
contentType = defaultPartContentType;
if (getCharset(contentType) == null)
{
if (defaultPartCharset != null)
{
contentType = getMediaTypeWithDefaultCharset(contentType);
}
else if (contentType.getType().equalsIgnoreCase("text"))
{
contentType = getMediaTypeWithCharset(contentType, "us-ascii");
}
}
}
@Override
public void setMediaType(MediaType mediaType)
{
contentType = mediaType;
contentTypeFromMessage = false;
headers.putSingle("Content-Type", mediaType.toString());
}
@SuppressWarnings("unchecked")
public <T> T getBody(Class<T> type, Type genericType)
throws IOException
{
if (MultipartInput.class.equals(type))
{
if (bodyPart.getBody() instanceof Multipart)
{
return (T) new MultipartInputImpl(Multipart.class.cast(bodyPart.getBody()), workers);
}
}
try
{
if (savedProviders != null)
{
ResteasyProviderFactory.pushContext(Providers.class, savedProviders);
}
MessageBodyReader<T> reader = workers.getMessageBodyReader(type, genericType, empty, contentType);
if (reader == null)
{
throw new RuntimeException(Messages.MESSAGES.unableToFindMessageBodyReader(contentType, type.getName()));
}
return reader.readFrom(type, genericType, empty, contentType, headers, getBody());
}
finally
{
if (savedProviders != null)
{
ResteasyProviderFactory.popContextData(Providers.class);
}
}
}
@SuppressWarnings("unchecked")
public <T> T getBody(GenericType<T> type) throws IOException
{
return getBody((Class<T>) type.getRawType(), type.getType());
}
public InputStream getBody() throws IOException
{
Body body = bodyPart.getBody();
InputStream result = null;
if (body instanceof TextBody)
{
throw new UnsupportedOperationException();
/*
InputStreamReader reader = (InputStreamReader)((TextBody) body).getReader();
StringBuilder inputBuilder = new StringBuilder();
char[] buffer = new char[1024];
while (true) {
int readCount = reader.read(buffer);
if (readCount < 0) {
break;
}
inputBuilder.append(buffer, 0, readCount);
}
String str = inputBuilder.toString();
return new ByteArrayInputStream(str.getBytes(reader.getEncoding()));
*/
}
else if (body instanceof BinaryBody)
{
return ((BinaryBody)body).getInputStream();
}
return result;
}
public String getBodyAsString() throws IOException
{
return getBody(String.class, null);
}
public MultivaluedMap<String, String> getHeaders()
{
return headers;
}
public MediaType getMediaType()
{
return contentType;
}
public boolean isContentTypeFromMessage()
{
return contentTypeFromMessage;
}
}
public static void main(String[] args) throws Exception
{
String input = "URLSTR: file:/Users/billburke/jboss/resteasy-jaxrs/resteasy-jaxrs/src/test/test-data/data.txt\r\n"
+ "--B98hgCmKsQ-B5AUFnm2FnDRCgHPDE3\r\n"
+ "Content-Disposition: form-data; name=\"part1\"\r\n"
+ "Content-Type: text/plain; charset=US-ASCII\r\n"
+ "Content-Transfer-Encoding: 8bit\r\n"
+ "\r\n"
+ "This is Value 1\r\n"
+ "--B98hgCmKsQ-B5AUFnm2FnDRCgHPDE3\r\n"
+ "Content-Disposition: form-data; name=\"part2\"\r\n"
+ "Content-Type: text/plain; charset=US-ASCII\r\n"
+ "Content-Transfer-Encoding: 8bit\r\n"
+ "\r\n"
+ "This is Value 2\r\n"
+ "--B98hgCmKsQ-B5AUFnm2FnDRCgHPDE3\r\n"
+ "Content-Disposition: form-data; name=\"data.txt\"; filename=\"data.txt\"\r\n"
+ "Content-Type: application/octet-stream; charset=ISO-8859-1\r\n"
+ "Content-Transfer-Encoding: binary\r\n"
+ "\r\n"
+ "hello world\r\n" + "--B98hgCmKsQ-B5AUFnm2FnDRCgHPDE3--";
ByteArrayInputStream bais = new ByteArrayInputStream(input.getBytes());
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("boundary", "B98hgCmKsQ-B5AUFnm2FnDRCgHPDE3");
MediaType contentType = new MediaType("multipart", "form-data",
parameters);
MultipartInputImpl multipart = new MultipartInputImpl(contentType, null);
multipart.parse(bais);
System.out.println(multipart.getPreamble());
System.out.println("**********");
for (InputPart part : multipart.getParts())
{
System.out.println("--");
System.out.println("\"" + part.getBodyAsString() + "\"");
}
System.out.println("done");
}
@Override
public void close()
{
if (mimeMessage != null)
{
try
{
mimeMessage.dispose();
}
catch (Exception e)
{
}
}
}
protected void finalize() throws Throwable
{
close();
}
protected String getCharset(MediaType mediaType)
{
for (Iterator<String> it = mediaType.getParameters().keySet().iterator(); it.hasNext(); )
{
String key = it.next();
if ("charset".equalsIgnoreCase(key))
{
return mediaType.getParameters().get(key);
}
}
return null;
}
private MediaType getMediaTypeWithDefaultCharset(MediaType mediaType)
{
String charset = defaultPartCharset;
return getMediaTypeWithCharset(mediaType, charset);
}
private MediaType getMediaTypeWithCharset(MediaType mediaType, String charset)
{
Map<String, String> params = mediaType.getParameters();
Map<String, String> newParams = new HashMap<String, String>();
newParams.put("charset", charset);
for (Iterator<String> it = params.keySet().iterator(); it.hasNext(); )
{
String key = it.next();
if (!"charset".equalsIgnoreCase(key))
{
newParams.put(key, params.get(key));
}
}
return new MediaType(mediaType.getType(), mediaType.getSubtype(), newParams);
}
@Override
public void setProviders(Providers providers)
{
savedProviders = providers;
}
}