MIME parsing

David Webster writes:
 > I would like to use the MIME code to parse MIME messages or files. 
 > Could you provide an example of how to parse a MIME file into parts?
 > 
 > 

Basically these are the steps needed. Say you have a InputStream 'in'
which is a MIME compliant stream:

a) Create a MimeFactory compliant class. As an example, check the
MimeHeadersFactory and the associated MimeHeaders class. The role of
this factory isto decide what object needs to be created as the result
of parsing the MIME stream (ie in HTTP, the object is an
w3c.www.http.HttpMessage). The sample MimeHeadersFactory creates a
MimeHeaders instance, which is basically a hashtable of headers.

b) Create a mime parser:

   MimeParser parser = new MimeParser(in, myfactory);

c) Parse the stream:
   MimeHeaders msg = (MimeHeaders) parser.parse();

   This is in case your using the MimeHeadersFactory, in the Http
   case, for example, this would be:

   HttpMessage msg = (HttpMessage) parser.parse();

   parser.parse() can only return instances of some class that
   implements the MimeHeaderHolder interface.

d) Assuming you want to parse multipart mime, check the content-type
   field value (to make sure the msg really contains multipart data),
   and create a mutlipart input stream out of the message body:
   [check w3c.jigsaw.forms.PostFileResource]

   // Retreieve the boundary from the content-type:
   // This depends on your MimeHeaderHolder type
   String boundary = <boundary>; 
   MultipartInputStream mis = null;
   mis = MultipartInputStream(parser.getInputStream(), boundary);
   MimeParser parser  = new MimeParser(mis, factory);
   // Read each part:
   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") ;
    }

Hope this helps,
Anselm.

Received on Friday, 15 November 1996 04:17:02 UTC