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.routing;
8   
9   import org.mule.api.MessagingException;
10  import org.mule.api.MuleEvent;
11  import org.mule.api.routing.RoutingException;
12  import org.mule.api.transformer.TransformerException;
13  import org.mule.transformer.simple.ByteArrayToHexString;
14  import org.mule.transformer.simple.SerializableToByteArray;
15  
16  import java.security.MessageDigest;
17  import java.security.NoSuchAlgorithmException;
18  
19  /**
20   * <code>IdempotentSecureHashMessageFilter</code> ensures that only unique messages are
21   * received by a service. It does this by calculating the SHA-256 hash of the message
22   * itself. This provides a value with an infinitesimally small chance of a collision. This
23   * can be used to filter message duplicates. Please keep in mind that the hash is
24   * calculated over the entire byte array representing the message, so any leading or
25   * trailing spaces or extraneous bytes (like padding) can produce different hash values
26   * for the same semantic message content. Care should be taken to ensure that messages do
27   * not contain extraneous bytes. This class is useful when the message does not support
28   * unique identifiers.
29   */
30  
31  public class IdempotentSecureHashMessageFilter extends IdempotentMessageFilter
32  {
33      private String messageDigestAlgorithm = "SHA-256";
34  
35      private final SerializableToByteArray objectToByteArray = new SerializableToByteArray();
36      private final ByteArrayToHexString byteArrayToHexString = new ByteArrayToHexString();
37  
38      @Override
39      protected String getIdForEvent(MuleEvent event) throws MessagingException
40      {
41          try
42          {
43              MessageDigest md = MessageDigest.getInstance(messageDigestAlgorithm);
44              return (String)byteArrayToHexString.transform(md.digest((byte[]) objectToByteArray.transform(event.getMessage()
45                  .getPayload())));
46          }
47          catch (NoSuchAlgorithmException nsa)
48          {
49              throw new RoutingException(event,this, nsa);
50          }
51          catch (TransformerException te)
52          {
53              throw new RoutingException(event, this, te);
54          }
55      }
56  
57      public String getMessageDigestAlgorithm()
58      {
59          return messageDigestAlgorithm;
60      }
61  
62      public void setMessageDigestAlgorithm(String messageDigestAlgorithm)
63      {
64          this.messageDigestAlgorithm = messageDigestAlgorithm;
65      }
66  }