View Javadoc

1   /*
2    * $Id: ObjectToInputStream.java 19250 2010-08-30 16:53:14Z dirk.olmes $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.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.RequestContext;
14  import org.mule.api.transformer.TransformerException;
15  import org.mule.api.transport.OutputHandler;
16  import org.mule.transformer.types.DataTypeFactory;
17  
18  import java.io.ByteArrayInputStream;
19  import java.io.ByteArrayOutputStream;
20  
21  /**
22   * <code>ObjectToInputStream</code> converts Serializable objects to an InputStream
23   * but treats <code>java.lang.String</code>, <code>byte[]</code> and
24   * <code>org.mule.api.transport.OutputHandler</code> differently by using their
25   * byte[] content rather thqn Serializing them.
26   */
27  public class ObjectToInputStream extends SerializableToByteArray
28  {
29  
30      public ObjectToInputStream()
31      {
32          this.registerSourceType(DataTypeFactory.STRING);
33          this.registerSourceType(DataTypeFactory.create(OutputHandler.class));
34          setReturnDataType(DataTypeFactory.INPUT_STREAM);
35      }
36  
37      @Override
38      public Object doTransform(Object src, String encoding) throws TransformerException
39      {
40          try
41          {
42              if (src instanceof String)
43              {
44                  return new ByteArrayInputStream(((String) src).getBytes(encoding));
45              }
46              else if (src instanceof byte[])
47              {
48                  return new ByteArrayInputStream((byte[]) src);
49              }
50              else if (src instanceof OutputHandler)
51              {
52                  OutputHandler oh = (OutputHandler) src;
53  
54                  ByteArrayOutputStream out = new ByteArrayOutputStream();
55                  oh.write(RequestContext.getEvent(), out);
56  
57                  return new ByteArrayInputStream(out.toByteArray());
58              }
59              else
60              {
61                  return new ByteArrayInputStream((byte[]) super.doTransform(src, encoding));
62              }
63          }
64          catch (Exception e)
65          {
66              throw new TransformerException(this, e);
67          }
68      }
69  
70  }