/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */



import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URL;
import java.util.Collection;
import java.util.Locale;
import net.sourceforge.stripes.action.FileBean;
import net.sourceforge.stripes.validation.TypeConverter;
import net.sourceforge.stripes.validation.ValidationError;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;

/**
 *
 * @author nick
 */
public class FileBeanConverter implements TypeConverter<FileBean> {

    private Logger log = Logger.getLogger(FileBeanConverter.class);

    @Override
    public void setLocale(Locale locale) {
    }

    @Override
    public FileBean convert(String filePath, Class<? extends FileBean> type, Collection<ValidationError> clctn) {
        try {
            File tmp = File.createTempFile("test-file", "");
            String name = FilenameUtils.getName(filePath);

            InputStream stream;
            if(getClass().getClassLoader().getResourceAsStream(filePath) != null){
                stream = getClass().getClassLoader().getResourceAsStream(filePath);
            }else{
                stream = FileUtils.openInputStream(new File(filePath));
            }

            OutputStream out = new FileOutputStream(tmp);
            int data;
            while((data = stream.read()) != -1){
                out.write(data);
            }
            out.close();
            stream.close();
            FileBean bean = new FileBean(tmp, ContentTypes.TYPES.get(FilenameUtils.getExtension(name)), name);
            return bean;
        } catch (Exception e) {
            log.error("Could not convert file.", e);
            return null;
        }
    }
}
