001package com.randomnoun.common.email;
002
003/* (c) 2013 randomnoun. All Rights Reserved. This work is licensed under a
004 * BSD Simplified License. (http://www.randomnoun.com/bsd-simplified.html)
005 */
006import java.io.ByteArrayInputStream;
007import java.io.ByteArrayOutputStream;
008import java.io.IOException;
009import java.io.InputStream;
010import java.io.OutputStream;
011
012import jakarta.activation.DataSource;
013
014
015/** A DataSource generated from an array of bytes
016 *  Used to send arbitrary data through the JavaMail API
017 *
018 * @author knoxg
019 */
020public class ByteArrayDataSource
021    implements DataSource
022{
023    private byte[] data;
024    private String name;
025    private String contentType;
026
027    /** Creates a DataSource from an array of bytes
028     * @param data byte[] Array of bytes to convert into a DataSource
029     * @param name String Name of the DataSource (ex: filename)
030     */
031    public ByteArrayDataSource(byte[] data, String name, String contentType)
032    {
033        this.data = data;
034        this.name = name;
035        this.contentType = contentType; // e.g. "application/octet-stream";
036    }
037
038    /** Returns the name of the DataSource
039     * @return String Name of the DataSource
040     */
041    public String getName()
042    {
043        return name;
044    }
045
046    /** Returns the content type of the DataSource
047     * @return String Content type of the DataSource
048     */
049    public String getContentType()
050    {
051        return contentType;
052    }
053
054    /** Returns an InputStream from the DataSource
055     * @return InputStream Array of bytes converted into an InputStream
056     */
057    public InputStream getInputStream()
058        throws IOException
059    {
060        return new ByteArrayInputStream(data);
061    }
062
063    /** Returns an OutputStream from the DataSource
064     * @return OutputStream Array of bytes converted into an OutputStream
065     */
066    public OutputStream getOutputStream()
067        throws IOException
068    {
069        OutputStream out = new ByteArrayOutputStream();
070
071        out.write(data);
072
073        return out;
074    }
075}