// PostFileResource.java
// $Id: PostFileResource.java,v 1.5 1996/10/02 16:17:13 abaird Exp $
// (c) COPYRIGHT MIT and INRIA, 1996.
// Please first read the full copyright statement in file COPYRIGHT.html

package w3c.jigsaw.forms ;

import java.io.*;

import w3c.www.mime.* ;
import w3c.www.http.*;
import w3c.jigsaw.http.* ;
import w3c.jigsaw.resources.*;

/**
 * This resource demonstrates how Jigsaw can handle file upload through POST.
 * It is based on this <a
 * href=ftp://ietf.cnri.reston.va.us/internet-drafts/draft-ietf-html-fileupload-03.txt">
 * draft </a>.  
 * <p>The whole work is in MIME input stream handling, rather than here, as 
 * you can see. This class just dumps its inputed entities.
 * <p>This resource has been written as a demo to the multipart parsing
 * engine, you should <em>not</em> use this way of uploading files since
 * the latest HTTP/1.1 specification defines the <code>PUT</code> method.
 */

public class PostFileResource extends FileResource {

    /**
     * Handle the post, wit its attached file.
     * @param request The request to handle.
     * @exception HTTPException If processing the request failed.
     */

    public Reply post (Request req) 
	throws HTTPException
    {
	// Check the form content type:
	MimeType type = req.getContentType () ;
	if ( (type.match (MimeType.MULTIPART_FORM_DATA) < 0)
	     || ( ! type.hasParameter ("boundary")) ) {
	    Reply error = req.makeReply(HTTP.BAD_REQUEST) ;
	    error.setContent("Invalid multipart stream.");
	    throw new HTTPException(error) ;
	}
	// Parse input:
	String sbound     = type.getParameterValue ("boundary") ;
	byte   boundary[] = new byte[sbound.length()] ;
	sbound.getBytes (0, boundary.length, boundary, 0) ;
	try {
	    // Notify the client that we are willing to continue processing:
	    Client client = req.getClient();
	    if ( client != null ) 
		client.sendContinue();
	    // And read the now available input:
	    MultipartInputStream in      = null ;
	    MimeHeadersFactory   factory = new MimeHeadersFactory();
	    in = new MultipartInputStream (req.getInputStream(), boundary);
	    MimeParser parser  = new MimeParser(in, factory);
	    while (in.nextInputStream()) {
		// these are themselves MIME streams (!)
		MimeHeaders headers = (MimeHeaders) parser.parse() ;
		System.out.println ("----- headers:") ;
		headers.dump(System.out) ;
		System.out.println ("----- body:") ;
		int  got      = -1 ;
		byte buffer[] = new byte[4096] ;
		InputStream body = parser.getInputStream();
		while ((got = body.read(buffer)) > 0) 
		    System.out.println (new String (buffer, 0, 0, got)) ;
		System.out.println ("----- end of body") ;
	    }
	} catch (Exception ex) {
	    ex.printStackTrace();
	    Reply error = req.makeReply(HTTP.BAD_REQUEST) ;
	    error.setContent ("Invalid request: unable to access entity.");
	    throw new HTTPException (error) ;
	}
	Reply reply = req.makeReply(HTTP.OK) ;
	reply.setContent ("Got the data !") ;
	return reply ;
    }

}
