View Javadoc
1   /*
2    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
3    * The software in this package is published under the terms of the CPAL v1.0
4    * license, a copy of which has been included with this distribution in the
5    * LICENSE.txt file.
6    */
7   package org.mule.transformer.simple;
8   
9   import org.mule.RequestContext;
10  import org.mule.api.transformer.TransformerException;
11  import org.mule.api.transport.OutputHandler;
12  import org.mule.transformer.types.DataTypeFactory;
13  
14  import java.io.ByteArrayInputStream;
15  import java.io.ByteArrayOutputStream;
16  
17  /**
18   * <code>ObjectToInputStream</code> converts Serializable objects to an InputStream
19   * but treats <code>java.lang.String</code>, <code>byte[]</code> and
20   * <code>org.mule.api.transport.OutputHandler</code> differently by using their
21   * byte[] content rather thqn Serializing them.
22   */
23  public class ObjectToInputStream extends SerializableToByteArray
24  {
25  
26      public ObjectToInputStream()
27      {
28          this.registerSourceType(DataTypeFactory.STRING);
29          this.registerSourceType(DataTypeFactory.create(OutputHandler.class));
30          setReturnDataType(DataTypeFactory.INPUT_STREAM);
31      }
32  
33      @Override
34      public Object doTransform(Object src, String encoding) throws TransformerException
35      {
36          try
37          {
38              if (src instanceof String)
39              {
40                  return new ByteArrayInputStream(((String) src).getBytes(encoding));
41              }
42              else if (src instanceof byte[])
43              {
44                  return new ByteArrayInputStream((byte[]) src);
45              }
46              else if (src instanceof OutputHandler)
47              {
48                  OutputHandler oh = (OutputHandler) src;
49  
50                  ByteArrayOutputStream out = new ByteArrayOutputStream();
51                  oh.write(RequestContext.getEvent(), out);
52  
53                  return new ByteArrayInputStream(out.toByteArray());
54              }
55              else
56              {
57                  return new ByteArrayInputStream((byte[]) super.doTransform(src, encoding));
58              }
59          }
60          catch (Exception e)
61          {
62              throw new TransformerException(this, e);
63          }
64      }
65  
66  }