001// Copyright 2007, 2008 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
015package org.apache.tapestry5.upload.internal.services;
016
017import org.apache.commons.fileupload.FileItem;
018import org.apache.commons.io.FilenameUtils;
019import org.apache.tapestry5.upload.services.UploadedFile;
020
021import java.io.File;
022import java.io.IOException;
023import java.io.InputStream;
024
025/**
026 * Implentation of {@link org.apache.tapestry5.upload.services.UploadedFile} for FileItems.
027 */
028public class UploadedFileItem implements UploadedFile
029{
030    private final FileItem item;
031
032    public UploadedFileItem(FileItem item)
033    {
034        this.item = item;
035    }
036
037    @Override
038    public String getContentType()
039    {
040        return item.getContentType();
041    }
042
043    @Override
044    public String getFileName()
045    {
046        return FilenameUtils.getName(getFilePath());
047    }
048
049    @Override
050    public String getFilePath()
051    {
052        return item.getName();
053    }
054
055    @Override
056    public long getSize()
057    {
058        return item.getSize();
059    }
060
061    @Override
062    public InputStream getStream()
063    {
064        try
065        {
066            return item.getInputStream();
067        }
068        catch (IOException e)
069        {
070            throw new RuntimeException(UploadMessages.unableToOpenContentFile(this), e);
071        }
072    }
073
074    @Override
075    public boolean isInMemory()
076    {
077        return item.isInMemory();
078    }
079
080    @Override
081    public void write(File file)
082    {
083        try
084        {
085            item.write(file);
086        }
087        catch (Exception e)
088        {
089            throw new RuntimeException(UploadMessages.writeFailure(file), e);
090        }
091    }
092
093    public void cleanup()
094    {
095        item.delete();
096    }
097}