View Javadoc

1   /*
2    * $Id: Rfc822ByteArraytoMimeMessage.java 11316 2008-03-11 15:50:38Z dirk.olmes $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSource, Inc.  All rights reserved.  http://www.mulesource.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.transport.email.transformers;
12  
13  import org.mule.api.transformer.TransformerException;
14  import org.mule.api.transport.Connector;
15  import org.mule.config.i18n.CoreMessages;
16  import org.mule.transformer.AbstractTransformer;
17  import org.mule.transport.email.AbstractMailConnector;
18  
19  import java.io.ByteArrayInputStream;
20  import java.io.InputStream;
21  
22  import javax.mail.MessagingException;
23  import javax.mail.Session;
24  import javax.mail.internet.MimeMessage;
25  
26  public class Rfc822ByteArraytoMimeMessage extends AbstractTransformer
27  {
28  
29      public Rfc822ByteArraytoMimeMessage()
30      {
31          registerSourceType(byte[].class);
32          registerSourceType(InputStream.class);
33          setReturnClass(MimeMessage.class);
34      }
35  
36      protected Object doTransform(Object src, String encoding) throws TransformerException
37      {
38          try
39          {
40              if (src instanceof byte[])
41              {
42                  byte[] bytes = (byte[]) src;
43                  return new MimeMessage(getSession(), new ByteArrayInputStream(bytes));
44              }
45              else if (src instanceof InputStream)
46              {
47                  return new MimeMessage(getSession(), (InputStream)src);
48              }
49              else
50              {
51                  throw new TransformerException(
52                      CoreMessages.transformOnObjectUnsupportedTypeOfEndpoint(this.getName(), src.getClass(), endpoint));
53              }
54          }
55          catch (MessagingException e)
56          {
57              throw new TransformerException(this, e);
58          }
59      }
60  
61      protected Session getSession() throws TransformerException
62      {
63          if (null == endpoint)
64          {
65              throw new TransformerException(this,
66                      new IllegalStateException("The transformer is no associated with an endpoint."));
67          }
68          Connector connector = endpoint.getConnector();
69          if (!(connector instanceof AbstractMailConnector))
70          {
71              throw new TransformerException(this,
72                      new IllegalStateException("The transformer is not associated with an email endpoint."));
73          }
74          return ((AbstractMailConnector) connector).getSessionDetails(endpoint).getSession();
75      }
76  
77  }