/*
 * Copyright 2007 Kickmogu Co. Ltd. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */



/*
 * 作成日: 2006/11/15
 *
 */
package com.kickmogu.rhythm.mail;

import com.kickmogu.*;
import com.kickmogu.rhythm.core.SessionManager;

import java.io.File;
import java.io.IOException;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.*;
import org.apache.commons.fileupload.servlet.*;
import org.apache.log4j.Category;
/**
 * FileUploadの練習
 */
public class FileUploader extends HttpServlet {
	static Category log = Category.getInstance(FileUploader.class.getName());

	protected void doPost(HttpServletRequest req, HttpServletResponse res)
		throws ServletException, IOException {
		
		try {
//			 Create a factory for disk-based file items
			DiskFileItemFactory factory = new DiskFileItemFactory();

//			 Set factory constraints
			factory.setSizeThreshold(10240);
			factory.setRepository(new File(Config.getProperty("mail.upload.tmpdir")));

//			 Create a new file upload handler
			ServletFileUpload upload = new ServletFileUpload(factory);

//			 Set overall request size constraint
			upload.setSizeMax(Config.getInt("mail.attach.maxsize") * 1024);

//			 Parse the request
			List fileItems = upload.parseRequest(req);
			

			Iterator iter = fileItems.iterator();
			Map<String, String> params = new HashMap<String, String>();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (item.isFormField()) {
					String val = new String(item.getString().getBytes("8859_1"), "UTF8");
					params.put(item.getFieldName(), val);
				}
			}

			// セッションの有効性を確認
			if (!SessionManager.isValidSession(params.get("sessionid"), Integer.parseInt(params.get("memid")))) {
				log.info("Upload File session timeout:" + params.get("memid") + "," + params.get("sessionid"));
				return;
			}
			
			File attachDir = new File(Config.getProperty("mail.attach.dir"), params.get("memid"));
			attachDir = new File(attachDir, params.get("attachFileKey"));
			
			if (!attachDir.exists()) {
				attachDir.mkdirs();
			}
			
			// ファイルのダウンロード処理
			iter = fileItems.iterator();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (!item.isFormField()) {
					item.write(new File(attachDir, Util.encodeHex(params.get("Filename"))));
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			throw new ServletException(e);
		}

	}
}
