View Javadoc

1   /*
2    * $Id: MD5KeyGenerator.java 22607 2011-08-08 02:13:54Z pablo.kraan $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.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  package org.mule.cache.keygenerator;
11  
12  import org.mule.api.MuleEvent;
13  
14  import java.io.NotSerializableException;
15  import java.io.Serializable;
16  import java.security.MessageDigest;
17  
18  import org.apache.commons.logging.Log;
19  import org.apache.commons.logging.LogFactory;
20  
21  /**
22   * Implements {@link KeyGenerator} applying an MD5 digest to the event's
23   * message payload.
24   */
25  public class MD5KeyGenerator implements KeyGenerator
26  {
27  
28      protected Log logger = LogFactory.getLog(getClass());
29  
30      public Serializable generateKey(MuleEvent event) throws NotSerializableException
31      {
32          try
33          {
34              byte[] bytesOfMessage = event.getMessageAsBytes();
35              MessageDigest md = MessageDigest.getInstance("MD5");
36              String key = new String(md.digest(bytesOfMessage));
37  
38              if (logger.isDebugEnabled())
39              {
40                  logger.debug("Generated key for event: " + event + " key: " + key);
41              }
42  
43              return key;
44          }
45          catch (Exception e)
46          {
47              NotSerializableException notSerializableException = new NotSerializableException(e.getMessage());
48              notSerializableException.initCause(e);
49  
50              throw notSerializableException;
51          }
52      }
53  }