changeset 8659:af415396d9ca

(issue1803) Use MD5 instead of a homegrown hashing algorithm For creating a digest of the parametrization we should use an algorithm that does not create collisions if there are small changes in the parametrization so that wrong results are returned.
author Andre Heinecke <andre.heinecke@intevation.de>
date Thu, 02 Apr 2015 17:40:18 +0200
parents 3531f0cee5e1
children 7faf1dad15a6
files artifacts/src/main/java/org/dive4elements/river/artifacts/D4EArtifact.java
diffstat 1 files changed, 22 insertions(+), 14 deletions(-) [+]
line wrap: on
line diff
--- a/artifacts/src/main/java/org/dive4elements/river/artifacts/D4EArtifact.java	Thu Apr 02 17:17:51 2015 +0200
+++ b/artifacts/src/main/java/org/dive4elements/river/artifacts/D4EArtifact.java	Thu Apr 02 17:40:18 2015 +0200
@@ -18,7 +18,14 @@
 import java.util.Set;
 import java.util.TreeMap;
 
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.io.ByteArrayOutputStream;
+import java.io.ObjectOutputStream;
+import java.io.IOException;
+
 import javax.xml.xpath.XPathConstants;
+import javax.xml.bind.DatatypeConverter;
 
 import net.sf.ehcache.Cache;
 
@@ -1135,20 +1142,21 @@
      */
     @Override
     public String hash() {
-
-        long hash  = 0L;
-        int  shift = 3;
-
-        for (Map.Entry<String, StateData> entry: data.entrySet()) {
-            String key   = entry.getKey();
-            Object value = entry.getValue().getValue();
-
-            hash ^= ((long)key.hashCode() << shift)
-                 |  ((long)value.hashCode() << (shift + 3));
-            shift += 2;
+        try {
+            ByteArrayOutputStream ba = new ByteArrayOutputStream();
+            ObjectOutputStream oa = new ObjectOutputStream(ba);
+            for (Map.Entry<String, StateData> entry: data.entrySet()) {
+                oa.writeObject(entry.getKey());
+                oa.writeObject(entry.getValue().getValue());
+            }
+            MessageDigest md = MessageDigest.getInstance("MD5");
+            byte[] md5sum = md.digest(ba.toByteArray());
+            return DatatypeConverter.printBase64Binary(md5sum);
+        } catch (NoSuchAlgorithmException e) {
+            throw new RuntimeException("MD5 unavailable. Can't happen.");
+        } catch (IOException e) {
+            throw new RuntimeException("Cant write parameter. Can't happen.");
         }
-
-        return getCurrentStateId() + hash;
     }
 
 
@@ -1509,7 +1517,7 @@
             if (cache != null) {
                 net.sf.ehcache.Element element = cache.get(key);
                 if (element != null) {
-                    log.debug("Got computation result from cache.");
+                    log.debug("Got computation result from cache for key: " + key);
                     old = element.getValue();
                 }
             }

http://dive4elements.wald.intevation.org