View Javadoc

1   /*
2    * $Id: ObjectToByteArray.java 11336 2008-03-12 17:53:18Z 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.transformer.simple;
12  
13  import org.mule.api.transformer.TransformerException;
14  import org.mule.util.IOUtils;
15  
16  import java.io.ByteArrayOutputStream;
17  import java.io.InputStream;
18  
19  /**
20   * <code>ObjectToByteArray</code> converts serilaizable object to a byte array but
21   * treats <code>java.lang.String</code> differently by converting to bytes using
22   * the <code>String.getBytrs()</code> method.
23   */
24  public class ObjectToByteArray extends SerializableToByteArray
25  {
26  
27      public ObjectToByteArray()
28      {
29          this.registerSourceType(InputStream.class);
30          this.registerSourceType(String.class);
31          setReturnClass(byte[].class);
32      }
33  
34      // @Override
35      public Object doTransform(Object src, String encoding) throws TransformerException
36      {
37          try
38          {
39              if (src instanceof String)
40              {
41                  return src.toString().getBytes(encoding);
42              }
43              else if (src instanceof InputStream)
44              {
45                  InputStream is = (InputStream) src;
46                  ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
47                  try
48                  {
49                      IOUtils.copyLarge(is, byteOut);
50                  }
51                  finally
52                  {
53                      is.close();
54                  }
55                  return byteOut.toByteArray();
56              }
57          }
58          catch (Exception e)
59          {
60              throw new TransformerException(this, e);
61          }
62  
63          return super.doTransform(src, encoding);
64      }
65  
66  }