/*
 * Paraselene
 * Copyright (c) 2009  Akira Terasaki
 * このファイルは同梱されているLicense.txtに定めた条件に同意できる場合にのみ
 * 利用可能です。
 */
package paraselene.supervisor;


import java.io.*;
import java.util.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.*;
import org.apache.commons.fileupload.servlet.*;


/**
 * サイト制御(ファイルアップロード機能付き)。
 */
public abstract class UploadableSupervisor extends Supervisor {
	/**
	 * コンストラクタ。
	 */
	public UploadableSupervisor() {
		super();
	}

	RequestParameter parseRequest( HttpServletRequest request, PathData p )
	throws Exception {
		if ( !ServletFileUpload.isMultipartContent( request ) ) {
			return normalReq( request );
		}
		else {
			return fileReq( request, p );
		}
	}

	private RequestParameter fileReq( HttpServletRequest req, PathData p )
	throws Exception {
		RequestParameter	ret = new RequestParameter();
		DiskFileItemFactory	fact = new DiskFileItemFactory();
		ServletFileUpload	upload = new ServletFileUpload( fact );
		int	max = p.from.getUploadMaxBytes();
		if ( max < 0 )	max = -1;
		upload.setSizeMax( max );
		upload.setHeaderEncoding( p.from.getCharset() );
		List<?>	items = upload.parseRequest( req );
		for ( Object o : items ) {
			FileItem	item = (FileItem)o;
			if ( item.isFormField() ) {
				ret.addItem( item.getFieldName(), item.getString( req.getCharacterEncoding() ) );
			}
			else {
				File	file = File.createTempFile( "dog", null );
				file.deleteOnExit();
				item.write( file );
				ret.addItem( item.getFieldName(), item.getName(), file, item.getContentType() );
			}
		}
		return ret;
	}

}

