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.api.transformer.DiscoverableTransformer;
10  import org.mule.api.transformer.TransformerException;
11  import org.mule.transformer.AbstractTransformer;
12  import org.mule.transformer.types.DataTypeFactory;
13  import org.mule.util.SerializationUtils;
14  
15  import java.io.Serializable;
16  
17  /**
18   * <code>SerializableToByteArray</code> converts a serializable object or a String
19   * to a byte array. If <code>MuleMessage</code> is configured as a source type on this
20   * transformer by calling <code>setAcceptMuleMessage(true)</code> then the MuleMessage
21   * will be serialised. This is useful for transports such as TCP where the message
22   * headers would normally be lost.
23   */
24  public class SerializableToByteArray extends AbstractTransformer implements DiscoverableTransformer
25  {
26      private int priorityWeighting = DiscoverableTransformer.DEFAULT_PRIORITY_WEIGHTING;
27  
28      public SerializableToByteArray()
29      {
30          this.registerSourceType(DataTypeFactory.create(Serializable.class));
31          this.setReturnDataType(DataTypeFactory.BYTE_ARRAY);
32      }
33  
34      public boolean isAcceptMuleMessage()
35      {
36          return this.isSourceDataTypeSupported(DataTypeFactory.MULE_MESSAGE, true);
37      }
38  
39      public void setAcceptMuleMessage(boolean value)
40      {
41          if (value)
42          {
43              this.registerSourceType(DataTypeFactory.MULE_MESSAGE);
44          }
45          else
46          {
47              this.unregisterSourceType(DataTypeFactory.MULE_MESSAGE);
48          }
49      }
50  
51      @Override
52      public Object doTransform(Object src, String outputEncoding) throws TransformerException
53      {
54          /*
55           * If the MuleMessage source type has been registered then we can assume that
56           * the whole message is to be serialised, not just the payload. This can be
57           * useful for protocols such as tcp where the protocol does not support
58           * headers and the whole message needs to be serialized.
59           */
60  
61          try
62          {
63              return SerializationUtils.serialize((Serializable) src);
64          }
65          catch (Exception e)
66          {
67              throw new TransformerException(this, e);
68          }
69      }
70  
71      public int getPriorityWeighting()
72      {
73          return priorityWeighting;
74      }
75  
76      public void setPriorityWeighting(int priorityWeighting)
77      {
78          this.priorityWeighting = priorityWeighting;
79      }
80  }