/* D-RexGxt - D-RexGxt - GUI Design Tool for GWT
 * Copyright (c) 2008,  KPS Corporation
 * All rights reserved.
 *
 * Open Source License
 * ------------------------------------------------------------------------------------------
 * D-RexGxt is licensed under the terms of the Open Source GPL 3.0 license.
 *
 * http://www.gnu.org/licenses/gpl.html
 *
 * --
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 */
package jp.co.kpscorp.gwt.server;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class OpenFile extends HttpServlet {

	private static final long serialVersionUID = 1L;

	final static String FILE_NAME_STRING = "filename=";
	final static String CONTENT_TYPE_HEADER = "Content-Type: ";

	/*
	 * clientからuploadされたファイルの文字列をsessionに保持しておく (非 Javadoc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		// 受信用バッファ
		byte buffer[] = new byte[4096];
		int size;
		String header;

		// 入力用ストリームを取得
		ServletInputStream in = request.getInputStream();

		// boundaryの読み込み
		size = in.readLine(buffer, 0, buffer.length);
		// 末尾の改行(CR+LF)を除いて文字列に変換
		String boundary = new String(buffer, 0, size - 2);

		// Content-Dispositionヘッダ読み込み
		size = in.readLine(buffer, 0, buffer.length);
		header = new String(buffer, 0, size - 1);
		// Content-Dispositionからファイル名の獲得
		String fileName = header.substring(header.indexOf(FILE_NAME_STRING)
				+ FILE_NAME_STRING.length() + 1, header.length() - 2);
		// InternetExplorerはフルパスでファイル名を送ってくるためファイル名部分のみ取り出す
		File file = new File(fileName);
		fileName = file.getName();

		// Content-Typeヘッダ読み込み
		size = in.readLine(buffer, 0, buffer.length);
		header = new String(buffer, 0, size - 1);

		// 空行をスキップ
		size = in.readLine(buffer, 0, buffer.length);

		// 以下本体部の読み込み
		StringBuffer stringBuffer = new StringBuffer();
		String line;
		// ByteArrayOutputStreamに読み込んだ内容を出力しておく
		while ((size = in.readLine(buffer, 0, buffer.length)) != -1) {
			line = new String(buffer, 0, size, "MS932");
			if (line.indexOf(boundary) != -1) {
				break;
			}
			stringBuffer.append(line);
		}
		in.close();

		request.getSession()
				.setAttribute("filesource", stringBuffer.toString());
		// debug
		//System.out.print(stringBuffer.toString());
	}
}
