/*
 * Scone - The Web Enhancement Framework
 * Copyright (C) 2009 Harald Weinreich, Volkert Buchmann, Frank Wollenweber, Torsten Haß
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program 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.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package scone.proxy;


import java.io.IOException;

import com.ibm.wbi.MegInputStream;
import com.ibm.wbi.RequestEvent;
import com.ibm.wbi.RequestRejectedException;
import com.ibm.wbi.protocol.http.DocumentInfo;
import com.ibm.wbi.protocol.http.HttpRequestEditor;
import com.ibm.wbi.protocol.http.HttpRequestHeader;

/**
 * Extract the Post-Data from the request. Store maxlen bytes in 
 * requestEvent.getMegContext().setMegResource("post-data", postData);  
 * 
 * @see HttpRequestEditor
 * @see ParsingMeg
 * @see scone.util.DocumentParser
 **/
class PostDataExtractor extends HttpRequestEditor {
	/**
	 * Handle the request and store the post-data in             
	 * requestEvent.getMegContext().setMegResource("post-data", postData.substring(0, maxlen-1));  
	 *
	 * @param e a <code>RequestEvent</code> value
	 * @exception IOException if an error occurs
	 * @exception RequestRejectedException if an error occurs 
	 */

    private int maxlen = 2048; // Only two kilobyte is used for now

	public void handleRequest(RequestEvent e) throws IOException, RequestRejectedException {
        String postData = "";
        int c;
	    DocumentInfo dInfo = (DocumentInfo)e.getRequestInfo();
	    HttpRequestHeader hReq = dInfo.getHttpRequestHeader();
	    MegInputStream mi = e.getMegInputStream();
	    while ((c = mi.read())>=0) {
	       if (postData.length()<maxlen) postData += (char)c;
	       e.getMegOutputStream().write(c);
	    }
	    // if (!postData.equals("")) dInfo.setTransactionData("post-data", postData);  // THIS METHOD IST BUGGY!
	    // System.out.println("Post-data: " + dInfo.getTransactionData("post-data"));

        if (!postData.equals("")) // set Post-Data. Read by ParsingMeg and stored by DocumentParser.
            e.getMegContext().setMegResource("post-data", postData);  
            // e.getMegContext().setMegResource("post-data", postData.substring(0, maxlen-1));  
	}
}
