package it.mice.voila.runtime.springmvc.editors;

import java.beans.PropertyEditorSupport;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Hibernate;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

public class BlobEditor extends PropertyEditorSupport {
	Log log = LogFactory.getLog(BlobEditor.class);

	private CommonsMultipartFile file;
	
	
	public CommonsMultipartFile getFile() {
		return file;
	}

	public void setFile(CommonsMultipartFile file) {
		this.file = file;
	}

	/**
	 * Create a new CustomDateEditor instance, using the given DateFormat
	 * for parsing and rendering.
	 * <p>The "allowEmpty" parameter states if an empty String should
	 * be allowed for parsing, i.e. get interpreted as null value.
	 * Otherwise, an IllegalArgumentException gets thrown in that case.
	 */
	public BlobEditor() {
	}

	@Override
	public void setValue(Object value) {
		file = (CommonsMultipartFile)value;
	}

	@Override
	public Object getValue() {
		try {
			if (file.getSize() == 0) {
				return null;
			}
			return Hibernate.createBlob(file.getInputStream());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
