001 // Copyright 2004, 2005 The Apache Software Foundation
002 //
003 // Licensed under the Apache License, Version 2.0 (the "License");
004 // you may not use this file except in compliance with the License.
005 // You may obtain a copy of the License at
006 //
007 // http://www.apache.org/licenses/LICENSE-2.0
008 //
009 // Unless required by applicable law or agreed to in writing, software
010 // distributed under the License is distributed on an "AS IS" BASIS,
011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012 // See the License for the specific language governing permissions and
013 // limitations under the License.
014
015 package org.apache.tapestry.multipart;
016
017 import java.io.File;
018 import java.io.IOException;
019 import java.io.InputStream;
020
021 import org.apache.commons.fileupload.FileItem;
022 import org.apache.hivemind.ApplicationRuntimeException;
023 import org.apache.hivemind.util.Defense;
024 import org.apache.tapestry.Tapestry;
025 import org.apache.tapestry.request.IUploadFile;
026
027 /**
028 * Portion of a multi-part request representing an uploaded file.
029 *
030 * @author Joe Panico
031 * @since 2.0.1
032 */
033 public class UploadPart extends Object implements IUploadFile
034 {
035 private FileItem _fileItem;
036
037 public UploadPart(FileItem fileItem)
038 {
039 Defense.notNull(fileItem, "fileItem");
040
041 _fileItem = fileItem;
042 }
043
044 public String getContentType()
045 {
046 return _fileItem.getContentType();
047 }
048
049 /**
050 * Leverages {@link File}to convert the full file path and extract the name.
051 */
052 public String getFileName()
053 {
054 File file = new File(this.getFilePath());
055
056 return file.getName();
057 }
058
059 /**
060 * @since 2.0.4
061 */
062
063 public String getFilePath()
064 {
065 return _fileItem.getName();
066 }
067
068 public InputStream getStream()
069 {
070 try
071 {
072 return _fileItem.getInputStream();
073 }
074 catch (IOException ex)
075 {
076 throw new ApplicationRuntimeException(MultipartMessages.unableToOpenContentFile(
077 this,
078 ex), ex);
079 }
080 }
081
082 /**
083 * Deletes the external content file, if one exists.
084 */
085
086 public void cleanup()
087 {
088 _fileItem.delete();
089 }
090
091 /**
092 * Writes the uploaded content to a file. This should be invoked at most once (perhaps we should
093 * add a check for this). This will often be a simple file rename.
094 *
095 * @since 3.0
096 */
097 public void write(File file)
098 {
099 try
100 {
101 _fileItem.write(file);
102 }
103 catch (Exception ex)
104 {
105 throw new ApplicationRuntimeException(Tapestry.format(
106 "UploadPart.write-failure",
107 file,
108 ex.getMessage()), ex);
109 }
110 }
111
112 /**
113 * @since 3.0
114 */
115 public long getSize()
116 {
117 return _fileItem.getSize();
118 }
119
120 /**
121 * @since 3.0
122 */
123 public boolean isInMemory()
124 {
125 return _fileItem.isInMemory();
126 }
127
128 }