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.session;
8   
9   import org.mule.api.MuleException;
10  import org.mule.api.MuleMessage;
11  import org.mule.api.MuleSession;
12  import org.mule.api.config.MuleProperties;
13  import org.mule.api.model.SessionException;
14  import org.mule.config.i18n.MessageFactory;
15  import org.mule.util.Base64;
16  import org.mule.util.SerializationUtils;
17  
18  import java.io.IOException;
19  
20  /**
21   * A session handler used to store and retrieve session information on an
22   * event. The DefaultMuleSession information is stored as a header on the message (does not
23   * support Tcp, Udp, etc. unless the MuleMessage object is serialised across the
24   * wire). The session is stored in the "MULE_SESSION" property as Base64 encoded
25   * byte array.
26   */
27  public class SerializeAndEncodeSessionHandler extends SerializeOnlySessionHandler
28  {
29      @Override
30      public MuleSession retrieveSessionInfoFromMessage(MuleMessage message) throws MuleException
31      {
32          MuleSession session = null;
33          String serializedEncodedSession = message.getInboundProperty(MuleProperties.MULE_SESSION_PROPERTY);
34          
35          if (serializedEncodedSession != null)
36          {
37              byte[] serializedSession = Base64.decode(serializedEncodedSession);            
38              if (serializedSession != null)
39              {
40                  session = (MuleSession) SerializationUtils.deserialize(serializedSession, message.getMuleContext());
41              }
42          }
43          return session;
44      }
45  
46      @Override
47      public void storeSessionInfoToMessage(MuleSession session, MuleMessage message) throws MuleException
48      {        
49          byte[] serializedSession = SerializationUtils.serialize(removeNonSerializableProperties(session,message.getMuleContext()));
50          String serializedEncodedSession;
51          try
52          {
53              serializedEncodedSession = Base64.encodeBytes(serializedSession, Base64.DONT_BREAK_LINES);
54          }
55          catch (IOException e)
56          {
57              throw new SessionException(MessageFactory.createStaticMessage("Unable to serialize MuleSession"), e);
58          }
59          
60          if (logger.isDebugEnabled())
61          {
62              logger.debug("Adding serialized and base64-encoded Session header to message: " + serializedEncodedSession);
63          }
64          message.setOutboundProperty(MuleProperties.MULE_SESSION_PROPERTY, serializedEncodedSession);
65      }
66  }