1 package com.atlassian.plugins.rest.common.multipart.fileupload;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.io.UnsupportedEncodingException;
7
8 import com.atlassian.plugins.rest.common.multipart.FilePart;
9 import com.atlassian.plugins.rest.common.multipart.UnsupportedFileNameEncodingException;
10
11 import com.google.common.base.Preconditions;
12
13 import org.apache.commons.fileupload.FileItem;
14 import org.apache.commons.fileupload.util.mime.MimeUtility;
15
16 public final class CommonsFileUploadFilePart implements FilePart {
17 private final FileItem fileItem;
18 private final String name;
19
20 CommonsFileUploadFilePart(FileItem fileItem) {
21 this.fileItem = Preconditions.checkNotNull(fileItem);
22 try {
23 if (fileItem.getName() == null) {
24 name = null;
25 } else {
26 this.name = new File(
27 MimeUtility.decodeText(fileItem.getName())
28 ).getName();
29 }
30
31 } catch (UnsupportedEncodingException e) {
32 throw new UnsupportedFileNameEncodingException(fileItem.getName());
33 }
34 }
35
36 public String getName() {
37 return name;
38 }
39
40 public InputStream getInputStream() throws IOException {
41 return fileItem.getInputStream();
42 }
43
44 public String getContentType() {
45 return fileItem.getContentType();
46 }
47
48 public void write(final File file) throws IOException {
49 try {
50 fileItem.write(file);
51 } catch (Exception e) {
52 if (e instanceof IOException) {
53 throw (IOException) e;
54 } else {
55 throw new IOException(e);
56 }
57 }
58 }
59
60 public String getValue() {
61 return fileItem.getString();
62 }
63
64 public boolean isFormField() {
65 return fileItem.isFormField();
66 }
67 }