View Javadoc
1   package com.randomnoun.common.email;
2   
3   /* (c) 2013 randomnoun. All Rights Reserved. This work is licensed under a
4    * BSD Simplified License. (http://www.randomnoun.com/bsd-simplified.html)
5    */
6   import java.io.ByteArrayInputStream;
7   import java.io.ByteArrayOutputStream;
8   import java.io.IOException;
9   import java.io.InputStream;
10  import java.io.OutputStream;
11  
12  import jakarta.activation.DataSource;
13  
14  
15  /** A DataSource generated from an array of bytes
16   *  Used to send arbitrary data through the JavaMail API
17   *
18   * @author knoxg
19   */
20  public class ByteArrayDataSource
21      implements DataSource
22  {
23      private byte[] data;
24      private String name;
25      private String contentType;
26  
27      /** Creates a DataSource from an array of bytes
28       * @param data byte[] Array of bytes to convert into a DataSource
29       * @param name String Name of the DataSource (ex: filename)
30       */
31      public ByteArrayDataSource(byte[] data, String name, String contentType)
32      {
33          this.data = data;
34          this.name = name;
35          this.contentType = contentType; // e.g. "application/octet-stream";
36      }
37  
38      /** Returns the name of the DataSource
39       * @return String Name of the DataSource
40       */
41      public String getName()
42      {
43          return name;
44      }
45  
46      /** Returns the content type of the DataSource
47       * @return String Content type of the DataSource
48       */
49      public String getContentType()
50      {
51          return contentType;
52      }
53  
54      /** Returns an InputStream from the DataSource
55       * @return InputStream Array of bytes converted into an InputStream
56       */
57      public InputStream getInputStream()
58          throws IOException
59      {
60          return new ByteArrayInputStream(data);
61      }
62  
63      /** Returns an OutputStream from the DataSource
64       * @return OutputStream Array of bytes converted into an OutputStream
65       */
66      public OutputStream getOutputStream()
67          throws IOException
68      {
69          OutputStream out = new ByteArrayOutputStream();
70  
71          out.write(data);
72  
73          return out;
74      }
75  }