View Javadoc

1   /*
2    * $Id: SerializableToByteArray.java 7976 2007-08-21 14:26:13Z 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.transformers.simple;
12  
13  import org.mule.transformers.AbstractEventAwareTransformer;
14  import org.mule.umo.UMOEventContext;
15  import org.mule.umo.UMOMessage;
16  import org.mule.umo.transformer.TransformerException;
17  
18  import java.io.Serializable;
19  
20  import org.apache.commons.lang.SerializationUtils;
21  
22  /**
23   * <code>SerializableToByteArray</code> converts a serializable object or a String
24   * to a byte array. If <code>UMOMessage</code> is configured as a source type on this
25   * transformer by calling <code>setAcceptUMOMessage(true)</code> then the UMOMessage
26   * will be serialised. This is useful for transports such as TCP where the message
27   * headers would normally be lost.
28   */
29  public class SerializableToByteArray extends AbstractEventAwareTransformer
30  {
31  
32      public SerializableToByteArray()
33      {
34          this.registerSourceType(Serializable.class);
35          this.registerSourceType(byte[].class);
36          this.setReturnClass(byte[].class);
37      }
38  
39      public boolean isAcceptUMOMessage()
40      {
41          return this.isSourceTypeSupported(UMOMessage.class, true);
42      }
43  
44      public void setAcceptUMOMessage(boolean value)
45      {
46          if (value)
47          {
48              this.registerSourceType(UMOMessage.class);
49          }
50          else
51          {
52              this.unregisterSourceType(UMOMessage.class);
53          }
54      }
55  
56      public Object transform(Object src, String encoding, UMOEventContext context) throws TransformerException
57      {
58          /*
59           * If the UMOMessage source type has been registered then we can assume that
60           * the whole message is to be serialised, not just the payload. This can be
61           * useful for protocols such as tcp where the protocol does not support
62           * headers and the whole message needs to be serialized.
63           */
64          if (this.isAcceptUMOMessage())
65          {
66              src = context.getMessage();
67          }
68          else if (src instanceof byte[])
69          {
70              return src;
71          }
72  
73          try
74          {
75              return SerializationUtils.serialize((Serializable) src);
76          }
77          catch (Exception e)
78          {
79              throw new TransformerException(this, e);
80          }
81      }
82  
83  }