1 package com.atlassian.plugins.rest.common.multipart.jersey;
2
3 import com.atlassian.plugins.rest.common.multipart.MultipartConfig;
4 import com.atlassian.plugins.rest.common.multipart.MultipartConfigClass;
5 import com.atlassian.plugins.rest.common.multipart.MultipartForm;
6 import com.atlassian.plugins.rest.common.multipart.fileupload.CommonsFileUploadMultipartHandler;
7 import com.sun.jersey.core.provider.AbstractMessageReaderWriterProvider;
8 import org.apache.commons.fileupload.RequestContext;
9
10 import java.io.IOException;
11 import java.io.InputStream;
12 import java.lang.annotation.Annotation;
13 import java.lang.reflect.Type;
14 import javax.ws.rs.WebApplicationException;
15 import javax.ws.rs.core.MediaType;
16 import javax.ws.rs.core.MultivaluedMap;
17 import javax.ws.rs.ext.MessageBodyReader;
18 import javax.ws.rs.ext.Provider;
19
20
21
22
23
24
25 @Provider
26 public class MultipartFormMessageBodyReader implements MessageBodyReader<MultipartForm>
27 {
28 public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType)
29 {
30 return type.equals(MultipartForm.class);
31 }
32
33 public MultipartForm readFrom(final Class<MultipartForm> type, final Type genericType,
34 final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, String> httpHeaders,
35 final InputStream entityStream)
36 throws IOException, WebApplicationException
37 {
38 CommonsFileUploadMultipartHandler handler = getMultipartHandler(annotations);
39 return handler.getForm(new RequestContext()
40 {
41 public String getCharacterEncoding()
42 {
43 return AbstractMessageReaderWriterProvider.getCharset(mediaType).name();
44 }
45
46 public String getContentType()
47 {
48 return mediaType.toString();
49 }
50
51 public int getContentLength()
52 {
53 return -1;
54 }
55
56 public InputStream getInputStream() throws IOException
57 {
58 return entityStream;
59 }
60 });
61 }
62
63 private CommonsFileUploadMultipartHandler getMultipartHandler(Annotation[] annotations)
64 {
65 for (Annotation annotation : annotations)
66 {
67 if (annotation instanceof MultipartConfigClass)
68 {
69 Class<? extends MultipartConfig> configClass = ((MultipartConfigClass) annotation).value();
70 try
71 {
72 MultipartConfig multipartConfig = configClass.newInstance();
73 return new CommonsFileUploadMultipartHandler(multipartConfig.getMaxFileSize(), multipartConfig.getMaxSize());
74 }
75 catch (InstantiationException e)
76 {
77 throw new RuntimeException(e);
78 }
79 catch (IllegalAccessException e)
80 {
81 throw new RuntimeException(e);
82 }
83 }
84 }
85 return new CommonsFileUploadMultipartHandler(-1, -1);
86 }
87 }