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 org.apache.commons.fileupload.FileItem; 018 import org.apache.commons.io.FilenameUtils; 019 import org.apache.hivemind.ApplicationRuntimeException; 020 import org.apache.hivemind.util.Defense; 021 import org.apache.tapestry.Tapestry; 022 import org.apache.tapestry.request.IUploadFile; 023 024 import java.io.File; 025 import java.io.IOException; 026 import java.io.InputStream; 027 028 /** 029 * Portion of a multi-part request representing an uploaded file. 030 * 031 * @author Joe Panico 032 * @since 2.0.1 033 */ 034 public class UploadPart implements IUploadFile 035 { 036 037 private FileItem _fileItem; 038 039 public UploadPart(FileItem fileItem) 040 { 041 Defense.notNull(fileItem, "fileItem"); 042 043 _fileItem = fileItem; 044 } 045 046 public String getContentType() 047 { 048 return _fileItem.getContentType(); 049 } 050 051 /** 052 * Leverages {@link File}to convert the full file path and extract the 053 * name. 054 */ 055 public String getFileName() 056 { 057 return FilenameUtils.getName(getFilePath()); 058 } 059 060 /** 061 * @since 2.0.4 062 */ 063 064 public String getFilePath() 065 { 066 return _fileItem.getName(); 067 } 068 069 public InputStream getStream() 070 { 071 try 072 { 073 return _fileItem.getInputStream(); 074 } 075 catch (IOException ex) 076 { 077 throw new ApplicationRuntimeException(MultipartMessages 078 .unableToOpenContentFile(this, 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 093 * once (perhaps we should add a check for this). This will often be a 094 * simple file rename. 095 * 096 * @since 3.0 097 */ 098 public void write(File file) 099 { 100 try 101 { 102 _fileItem.write(file); 103 } 104 catch (Exception ex) 105 { 106 throw new ApplicationRuntimeException(Tapestry.format( 107 "UploadPart.write-failure", file, ex.getMessage()), ex); 108 } 109 } 110 111 /** 112 * @since 3.0 113 */ 114 public long getSize() 115 { 116 return _fileItem.getSize(); 117 } 118 119 /** 120 * @since 3.0 121 */ 122 public boolean isInMemory() 123 { 124 return _fileItem.isInMemory(); 125 } 126 127 }