1 /*
2 * $Id: IdempotentSecureHashReceiver.java 7976 2007-08-21 14:26:13Z dirk.olmes $
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 CPAL v1.0
7 * license, a copy of which has been included with this distribution in the
8 * LICENSE.txt file.
9 */
10
11 package org.mule.routing.inbound;
12
13 import org.mule.transformers.simple.ByteArrayToHexString;
14 import org.mule.transformers.simple.SerializableToByteArray;
15 import org.mule.umo.MessagingException;
16 import org.mule.umo.UMOEvent;
17 import org.mule.umo.routing.RoutingException;
18 import org.mule.umo.transformer.TransformerException;
19
20 import java.security.MessageDigest;
21 import java.security.NoSuchAlgorithmException;
22
23 /**
24 * <code>IdempotentSecureHashReceiver</code> ensures that only unique messages are
25 * received by a component. It does this by calculating the SHA-256 hash of the
26 * message itself. This provides a value with an infinitesimally small chance of a
27 * collision. This can be used to filter message duplicates. Please keep in mind that
28 * the hash is calculated over the entire byte array representing the message, so any
29 * leading or trailing spaces or extraneous bytes (like padding) can produce
30 * different hash values for the same semantic message content. Care should be taken
31 * to ensure that messages do not contain extraneous bytes. This class is useful when
32 * the message does not support unique identifiers. This implementation provides for
33 * a persistent store of message hash values via the underlying file system and is
34 * suitable in failover environments.
35 */
36
37 public class IdempotentSecureHashReceiver extends IdempotentReceiver
38 {
39 private static final String messageDigestAlgorithm = "SHA-256";
40
41 private final SerializableToByteArray objectToByteArray = new SerializableToByteArray();
42 private final ByteArrayToHexString byteArrayToHexString = new ByteArrayToHexString();
43
44 // @Override
45 protected Object getIdForEvent(UMOEvent event) throws MessagingException
46 {
47 try
48 {
49 MessageDigest md = MessageDigest.getInstance(messageDigestAlgorithm);
50 return byteArrayToHexString.transform(md.digest((byte[]) objectToByteArray.transform(event.getMessage()
51 .getPayload())));
52 }
53 catch (NoSuchAlgorithmException nsa)
54 {
55 throw new RoutingException(event.getMessage(), event.getEndpoint(), nsa);
56 }
57 catch (TransformerException te)
58 {
59 throw new RoutingException(event.getMessage(), event.getEndpoint(), te);
60 }
61 }
62 }