File: MimeMultipart.java

package info (click to toggle)
libgnumail-java 1.0-5
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 3,620 kB
  • ctags: 2,193
  • sloc: java: 17,470; sh: 9,912; makefile: 432; xml: 159
file content (496 lines) | stat: -rw-r--r-- 15,613 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
/*
 * MimeMultipart.java
 * Copyright (C) 2002 The Free Software Foundation
 * 
 * This file is part of GNU JavaMail, a library.
 * 
 * GNU JavaMail 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.
 * 
 * GNU JavaMail 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 library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * As a special exception, if you link this library with other files to
 * produce an executable, this library does not by itself cause the
 * resulting executable to be covered by the GNU General Public License.
 * This exception does not however invalidate any other reasons why the
 * executable file might be covered by the GNU General Public License.
 */

package javax.mail.internet;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.activation.DataSource;
import javax.mail.BodyPart;
import javax.mail.MessageAware;
import javax.mail.MessageContext;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.MultipartDataSource;

import gnu.inet.util.CRLFOutputStream;
import gnu.inet.util.LineInputStream;

/**
 * The MimeMultipart class is an implementation of the abstract Multipart 
 * class that uses MIME conventions for the multipart data.
 * <p>
 * A MimeMultipart is obtained from a MimePart whose primary type is
 * "multipart" (by invoking the part's <code>getContent()</code> method)
 * or it can be created by a client as part of creating a new MimeMessage.
 * <p>
 * The default multipart subtype is "mixed".
 * The other multipart subtypes, such as "alternative", "related", and so on,
 * can be implemented as subclasses of MimeMultipart with additional methods 
 * to implement the additional semantics of that type of multipart content.
 * The intent is that service providers, mail JavaBean writers and mail 
 * clients will write many such subclasses and their Command Beans,
 * and will install them into the JavaBeans Activation Framework,
 * so that any JavaMail implementation and its clients can transparently 
 * find and use these classes.
 * Thus, a MIME multipart handler is treated just like any other type handler,
 * thereby decoupling the process of providing multipart handlers from 
 * the JavaMail API. Lacking these additional MimeMultipart subclasses,
 * all subtypes of MIME multipart data appear as MimeMultipart objects.
 * <p>
 * An application can directly construct a MIME multipart object of any 
 * subtype by using the MimeMultipart(String subtype) constructor.
 * For example, to create a "multipart/alternative" object,
 * use <code>new MimeMultipart("alternative")</code>.
 *
 * @author <a href="mailto:dog@gnu.org">Chris Burdess</a>
 * @version 1.3
 */
public class MimeMultipart
  extends Multipart
{

  /**
   * The DataSource supplying our InputStream.
   */
  protected DataSource ds;

  /**
   * Have we parsed the data from our InputStream yet?
   * Defaults to true; set to false when our constructor is given 
   * a DataSource with an InputStream that we need to parse.
   */
  protected boolean parsed;

  /**
   * Default constructor. 
   * An empty MimeMultipart object is created. 
   * Its content type is set to "multipart/mixed".
   * A unique boundary string is generated and this string is set up
   * as the "boundary" parameter for the <code>contentType</code> field.
   * <p>
   * MimeBodyParts may be added later.
   */
  public MimeMultipart()
  {
    this("mixed");
  }

  /**
   * Construct a MimeMultipart object of the given subtype.
   * A unique boundary string is generated and this string is set up
   * as the "boundary" parameter for the <code>contentType</code> field.
   * <p>
   * MimeBodyParts may be added later.
   */
  public MimeMultipart(String subtype)
  {
    String boundary = MimeUtility.getUniqueBoundaryValue();
    ContentType ct = new ContentType("multipart", subtype, null);
    ct.setParameter("boundary", boundary);
    contentType = ct.toString();
    parsed = true;
  }

  /**
   * Constructs a MimeMultipart object and its bodyparts from the given
   * DataSource.
   * <p>
   * This constructor handles as a special case the situation where the given
   * DataSource is a MultipartDataSource object. In this case, this method 
   * just invokes the superclass (i.e., Multipart) constructor that takes a
   * MultipartDataSource object.
   * <p>
   * Otherwise, the DataSource is assumed to provide a MIME multipart byte
   * stream. The parsed flag is set to false. When the data for the body parts
   * are needed, the parser extracts the "boundary" parameter from the content
   * type of this DataSource, skips the 'preamble' and reads bytes till the
   * terminating boundary and creates MimeBodyParts for each part of the 
   * stream.
   * @param ds DataSource, can be a MultipartDataSource
   */
  public MimeMultipart(DataSource ds)
    throws MessagingException
  {
    if (ds instanceof MessageAware)
    {
      MessageContext mc = ((MessageAware)ds).getMessageContext();
      setParent(mc.getPart());
    }
    if (ds instanceof MultipartDataSource)
    {
      setMultipartDataSource((MultipartDataSource)ds);
      parsed = true;
    }
    else
    {
      this.ds = ds;
      contentType = ds.getContentType();
      parsed = false;
    }
  }

  /**
   * Set the subtype. 
   * This method should be invoked only on a new MimeMultipart object 
   * created by the client. The default subtype of such a multipart object 
   * is "mixed".
   * @param subtype Subtype
   */
  public void setSubType(String subtype)
    throws MessagingException
  {
    ContentType ct = new ContentType(contentType);
    ct.setSubType(subtype);
    contentType = ct.toString();
  }

  /**
   * * Return the number of enclosed BodyPart objects.
   */
  public int getCount()
    throws MessagingException
  {
    synchronized (this)
    {
      parse();
      return super.getCount();
    }
  }

  /**
   * Get the specified BodyPart.
   * BodyParts are numbered starting at 0.
   * @param index the index of the desired BodyPart
   * @exception MessagingException if no such BodyPart exists
   */
  public BodyPart getBodyPart(int index)
    throws MessagingException
  {
    synchronized (this)
    {
      parse();
      return super.getBodyPart(index);
    }
  }

  /**
   * Get the MimeBodyPart referred to by the given ContentID (CID).
   * Returns null if the part is not found.
   * @param CID the ContentID of the desired part
   */
  public BodyPart getBodyPart(String CID)
    throws MessagingException
  {
    synchronized (this)
    {
      parse();
      int count = getCount();
      for (int i = 0; i<count; i++)
      {
        MimeBodyPart bp = (MimeBodyPart)getBodyPart(i);
        String contentID = bp.getContentID();
        if (contentID!=null && contentID.equals(CID))
          return bp;
      }
      return null;
    }
  }

  /**
   * Update headers.
   * The default implementation here just calls the <code>updateHeaders</code>
   * method on each of its children BodyParts.
   * <p>
   * Note that the boundary parameter is already set up when a new and empty
   * MimeMultipart object is created.
   * <p>
   * This method is called when the <code>saveChanges</code> method is
   * invoked on the Message object containing this Multipart.
   * This is typically done as part of the Message send process,
   * however note that a client is free to call it any number of times.
   * So if the header updating process is expensive for a specific 
   * MimeMultipart subclass, then it might itself want to track whether
   * its internal state actually did change,
   * and do the header updating only if necessary.
   */
  protected void updateHeaders()
    throws MessagingException
  {
    synchronized (parts)
    {
      for (int i = 0; i<parts.size(); i++)
        ((MimeBodyPart)parts.get(i)).updateHeaders();
    }
  }

  /**
   * Iterates through all the parts and outputs each Mime part 
   * separated by a boundary.
   * @exception IOException if an IO related exception occurs
   */
  public void writeTo(OutputStream os)
    throws IOException, MessagingException
  {
    parse();
    ContentType ct = new ContentType(contentType);
    StringBuffer buffer = new StringBuffer();
    buffer.append("--");
    buffer.append(ct.getParameter("boundary"));
    byte[] boundary = buffer.toString().getBytes("UTF-8");
    
    synchronized (parts)
    {
      for (int i = 0; i<parts.size(); i++)
      {
        os.write(boundary);
        os.write(0x0d);
        os.flush();
        ((MimeBodyPart)parts.get(i)).writeTo(os);
        os.write(0x0d);
      }
    }

    buffer.append("--");
    boundary = buffer.toString().getBytes("UTF-8");
    os.write(boundary);
    os.write(0x0d);
    os.flush();
  }

  /**
   * Parse the InputStream from our DataSource, constructing the appropriate
   * MimeBodyParts.
   * The parsed flag is set to true, and if true on entry nothing is done.
   * This method is called by all other methods that need data for the body 
   * parts, to make sure the data has been parsed.
   */
  protected void parse()
    throws MessagingException
  {
    if (parsed)
      return;
    synchronized (this)
    {
      InputStream is = null;
      SharedInputStream sis = null;
      try
      {
        is = ds.getInputStream();
        if (is instanceof SharedInputStream)
          sis = (SharedInputStream)is;
        // buffer it
        if (!(is instanceof ByteArrayInputStream) && 
            !(is instanceof BufferedInputStream))
          is = new BufferedInputStream(is);
        
        ContentType ct = new ContentType(contentType);
        StringBuffer buffer = new StringBuffer();
        buffer.append("--");
        buffer.append(ct.getParameter("boundary"));
        String boundary = buffer.toString();
        
        byte[] bbytes = boundary.getBytes();
        int blen = bbytes.length;
        
        LineInputStream lis = new LineInputStream(is);
        String line;
        while ((line = lis.readLine())!=null)
        {
          if (line.trim().equals(boundary))
            break;
        }
        if (line==null)
          throw new MessagingException("No start boundary");
        
        long start = 0L, end = 0L;
        for (boolean done = false; !done;)
        {
          InternetHeaders headers = null;
          if (sis!=null)
          {
            start = sis.getPosition();
            while ((line = lis.readLine())!=null && line.length()>0);
            if (line==null)
              throw new IOException("EOF before content body");
          }
          else
          {
            headers = createInternetHeaders(is);
          }
          ByteArrayOutputStream bos = null;
          if (sis==null)
            bos = new ByteArrayOutputStream();

          // NB this routine uses the InputStream.mark() method
          // if it is not supported by the underlying stream we will run into
          // problems
					if (!is.markSupported())
						throw new MessagingException("FIXME: mark not supported on underlying input stream: "+is.getClass().getName());
          boolean eol = true;
          int last = -1;
          int afterLast = -1;
          while (true)
          {
            int c;
            if (eol)
            {
              is.mark(blen+1024);
              int pos = 0;
              while (pos<blen)
              {
                if (is.read()!=bbytes[pos])
                  break;
                pos++;
              }
              
              if (pos==blen)
              {
                c = is.read();
                if (c=='-' && is.read()=='-')
                {
                  done = true;
                  break;
                }
                while (c==' ' || c=='\t')
                  c = is.read();
                if (c=='\r')
                {
                  is.mark(1);
                  if (is.read()!='\n')
                    is.reset();
                  break;
                }
                if (c=='\n')
                  break;
              }
              if (bos!=null && last!=-1)
              {
                bos.write(last);
                if (afterLast!=-1)
                  bos.write(afterLast);
                last = afterLast = -1;
              }
              is.reset();
            }
            c = is.read();
            if (c<0)
            {
              done = true;
              break;
            }
            else if (c=='\r' || c=='\n')
            {
              eol = true;
              if (sis!=null)
                end = sis.getPosition()-1L;
              last = c;
              if (c=='\r')
              {
                is.mark(1);
                if ((c = is.read())=='\n')
                  afterLast = c;
                else
                  is.reset();
              }
            }
            else
            {
              eol = false;
              if (bos!=null)
                bos.write(c);
            }
          }
          
          // Create a body part from the stream
          MimeBodyPart bp;
          if (sis!=null)
            bp = createMimeBodyPart(sis.newStream(start, end));
          else
            bp = createMimeBodyPart(headers, bos.toByteArray());
          addBodyPart(bp);
        }
        
      }
      catch (IOException e)
      {
        throw new MessagingException("I/O error", e);
      }
      parsed = true;
    }
  }
  
  /**
   * Create and return an InternetHeaders object that loads the headers 
   * from the given InputStream.
   * Subclasses can override this method to return a subclass
   * of InternetHeaders, if necessary.
   * This implementation simply constructs and returns an InternetHeaders 
   * object.
   * @param is the InputStream to read the headers from
   */
  protected InternetHeaders createInternetHeaders(InputStream is)
    throws MessagingException
  {
    return new InternetHeaders(is);
  }
  
  /**
   * Create and return a MimeBodyPart object to represent a body part parsed
   * from the InputStream.
   * Subclasses can override this method to return a subclass of 
   * MimeBodyPart, if necessary. This implementation simply constructs and 
   * returns a MimeBodyPart object.
   * @param headers the headers for the body part
   * @param content the content of the body part
   */
  protected MimeBodyPart createMimeBodyPart(InternetHeaders headers,
      byte[] content)
    throws MessagingException
  {
    return new MimeBodyPart(headers, content);
  }
  
  /**
   * Create and return a MimeBodyPart object to represent a body part parsed
   * from the InputStream.
   * Subclasses can override this method to return a subclass of 
   * MimeBodyPart, if necessary. This implementation simply constructs and 
   * returns a MimeBodyPart object.
   * @param is InputStream containing the body part
   */
  protected MimeBodyPart createMimeBodyPart(InputStream is)
    throws MessagingException
  {
    return new MimeBodyPart(is);
  }
  
}