View Javadoc

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