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.cache.keygenerator;
8   
9   import org.mule.api.MuleEvent;
10  
11  import java.io.NotSerializableException;
12  import java.io.Serializable;
13  import java.security.MessageDigest;
14  
15  import org.apache.commons.logging.Log;
16  import org.apache.commons.logging.LogFactory;
17  
18  /**
19   * Implements {@link KeyGenerator} applying an MD5 digest to the event's
20   * message payload.
21   */
22  public class MD5KeyGenerator implements KeyGenerator
23  {
24  
25      protected Log logger = LogFactory.getLog(getClass());
26  
27      public Serializable generateKey(MuleEvent event) throws NotSerializableException
28      {
29          try
30          {
31              byte[] bytesOfMessage = event.getMessageAsBytes();
32              MessageDigest md = MessageDigest.getInstance("MD5");
33              String key = new String(md.digest(bytesOfMessage));
34  
35              if (logger.isDebugEnabled())
36              {
37                  logger.debug("Generated key for event: " + event + " key: " + key);
38              }
39  
40              return key;
41          }
42          catch (Exception e)
43          {
44              NotSerializableException notSerializableException = new NotSerializableException(e.getMessage());
45              notSerializableException.initCause(e);
46  
47              throw notSerializableException;
48          }
49      }
50  }