/*
 * 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 java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class OctetStreamDataSource implements DataSource
{
   public static final String CONTENT_TYPE = "application/octetstream";

   private final String name;
   private byte[] data;
   private ByteArrayOutputStream os;

   public OctetStreamDataSource(String name, OctetStream data)
   {
      this.name = name;
      this.data = data == null ? null : data.getBytes();
      os = new ByteArrayOutputStream();
   } // ctor

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

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

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

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