View Javadoc

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