/*
 * Copyright (C) The Apache Software Foundation. All rights reserved.
 *
 * This software is published under the terms of the Apache Software License
 * version 1.1, a copy of which has been included with this distribution in
 * the docs/licenses/apache-1.1.txt file.
 */
package org.jboss.axis.attachments;

import javax.activation.DataSource;
import javax.mail.internet.MimeMultipart;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class MimeMultipartDataSource implements DataSource
{
   public static final String CONTENT_TYPE = "multipart/mixed";

   private final String name;
   private final String contentType;
   private byte[] data;
   private ByteArrayInputStream is;
   private ByteArrayOutputStream os;

   public MimeMultipartDataSource(String name, MimeMultipart data)
   {
      this.name = name;
      this.contentType = data == null ? CONTENT_TYPE : data.getContentType();
      os = new ByteArrayOutputStream();
      try
      {
         if (data != null)
         {
            data.writeTo(os);
         }
      }
      catch (Exception e)
      {
         // Is this sufficient?
      }
   } // ctor

   public String getName()
   {
      return name;
   } // getName

   public String getContentType()
   {
      return contentType;
   } // getContentType

   public InputStream getInputStream() throws IOException
   {
      if (os.size() != 0)
      {
         data = os.toByteArray();
         os.reset();
      }
      return new ByteArrayInputStream(data == null ? new byte[0] : data);
   } // getInputStream

   public OutputStream getOutputStream() throws IOException
   {
      if (os.size() != 0)
      {
         data = os.toByteArray();
         os.reset();
      }
      return os;
   } // getOutputStream
} // class MimeMultipartDataSource
