View Javadoc

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  {
18      private final FileItem fileItem;
19      private final String name;
20  
21      CommonsFileUploadFilePart(FileItem fileItem)
22      {
23          this.fileItem = Preconditions.checkNotNull(fileItem);
24          try
25          {
26              if (fileItem.getName() == null) 
27              {
28                  name = null;
29              } 
30              else 
31              {
32                  this.name = MimeUtility.decodeText(fileItem.getName());
33              }
34              
35          } 
36          catch (UnsupportedEncodingException e)
37          {
38              throw new UnsupportedFileNameEncodingException(fileItem.getName());
39          }
40      }
41  
42      public String getName()
43      {
44          return name;
45      }
46  
47      public InputStream getInputStream() throws IOException
48      {
49          return fileItem.getInputStream();
50      }
51  
52      public String getContentType()
53      {
54          return fileItem.getContentType();
55      }
56  
57      public void write(final File file) throws IOException
58      {
59          try
60          {
61              fileItem.write(file);
62          } catch (Exception e)
63          {
64              if (e instanceof IOException)
65              {
66                  throw (IOException) e;
67              }
68              else
69              {
70                  throw new IOException(e);
71              }
72          }
73      }
74  
75      public String getValue()
76      {
77          return fileItem.getString();
78      }
79  
80      public boolean isFormField()
81      {
82          return fileItem.isFormField();
83      }
84  }