package com.ekexiu.portal.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

import org.jfw.util.JpgUtil;
import org.jfw.util.context.JfwAppContext;
import org.jfw.util.exception.JfwBaseException;
import org.jfw.util.io.IoUtil;
import org.jfw.web.servlet.fileupload.cached.CachedItem;
import org.jfw.web.servlet.fileupload.cached.CachedItemValidator;
import org.jfw.web.servlet.fileupload.cached.CachedUploadServletConfig;

public class ImageValidator implements CachedItemValidator {

	private byte[] read(CachedUploadServletConfig config, CachedItem item) throws IOException {
		if (config.isCacheByMemory()) {
			return (byte[]) JfwAppContext.getCachedObject(item.getCacheKey());
		} else {
			File file = new File(config.getCachePath(), item.getCacheKey());
			return IoUtil.readStream(new FileInputStream(file), true);
		}
	}

	@Override
	public void validdate(CachedUploadServletConfig config, List<CachedItem> files) throws JfwBaseException {
		try {
			for (CachedItem item : files) {
				JpgUtil.read(this.read(config, item));
			}
		} catch (Exception e) {
			throw new JfwBaseException(302, "upload file type unsupported with setting");
		}
	}

}
