KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mule > transformers > simple > SerializableToByteArray


1 /*
2  * $Id: SerializableToByteArray.java 3982 2006-11-22 14:28:01Z lajos $
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 MuleSource MPL
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.apache.commons.lang.SerializationUtils;
14 import org.mule.transformers.AbstractEventAwareTransformer;
15 import org.mule.umo.UMOEventContext;
16 import org.mule.umo.UMOMessage;
17 import org.mule.umo.transformer.TransformerException;
18
19 import java.io.Serializable JavaDoc;
20
21 /**
22  * <code>SerializableToByteArray</code> converts a serializable object or a String
23  * to a byte array. If <code>UMOMessage</code> is added as a source type on this
24  * transformer then the UMOMessage will be serialised. This is useful for transports
25  * such as TCP where the message headers would normally be lost.
26  */

27 public class SerializableToByteArray extends AbstractEventAwareTransformer
28 {
29     /**
30      * Serial version
31      */

32     private static final long serialVersionUID = 8899970312989435192L;
33
34     public SerializableToByteArray()
35     {
36         registerSourceType(Serializable JavaDoc.class);
37         registerSourceType(byte[].class);
38         this.setReturnClass(byte[].class);
39     }
40
41     public Object JavaDoc transform(Object JavaDoc src, String JavaDoc encoding, UMOEventContext context) throws TransformerException
42     {
43         // If the UMOMessage source type has been registered that we can assume
44
// that the whole message is to be serialised, not just the payload.
45
// This can be useful for protocols such as tcp where the protocol does
46
// not support headers, thus the whole message needs to be serialized.
47

48         if (isSourceTypeSupported(UMOMessage.class, true))
49         {
50             src = context.getMessage();
51         }
52         else if (src instanceof byte[])
53         {
54             return src;
55         }
56
57         try
58         {
59             return SerializationUtils.serialize((Serializable JavaDoc)src);
60         }
61         catch (Exception JavaDoc e)
62         {
63             throw new TransformerException(this, e);
64         }
65     }
66 }
67
Popular Tags