package de.jeha.kame.crawler.core.model;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author jenshadlich@googlemail.com
 */
public class Hash {

    private static final MessageDigest MESSAGE_DIGEST;

    static {
        try {
            MESSAGE_DIGEST = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    private final String value;

    public Hash(String input) {
        byte[] digest = MESSAGE_DIGEST.digest((input == null ? "" : input).getBytes(Charset.forName("UTF-8")));
        this.value = Hex.encodeHexString(digest);
    }

    public String getValue() {
        return value;
    }

    @Override
    public String toString() {
        return ReflectionToStringBuilder.toString(this, ToStringStyle.MULTI_LINE_STYLE);
    }

}

@@ -202,16 +202,61 @@
 Style;%0A%0A
+import java.io.UnsupportedEncodingException;%0A
 import j
@@ -280,16 +280,16 @@
 harset;%0A
-
 import j
@@ -485,16 +485,75 @@
 _DIGEST;
+%0A    private static final String NULL_OR_EMPTY_STRING_HASH;
 %0A%0A    st
@@ -640,16 +640,122 @@
 -256%22);%0A
+            NULL_OR_EMPTY_STRING_HASH = Hex.encodeHexString(MESSAGE_DIGEST.digest(%22%22.getBytes(%22UTF-8%22)));%0A
         
@@ -788,16 +788,47 @@
 ception 
+%7C UnsupportedEncodingException 
 e) %7B%0A   
@@ -877,16 +877,17 @@
       %7D%0A
+%0A
     %7D%0A%0A 
@@ -946,24 +946,149 @@
 ng input) %7B%0A
+        if (input == null %7C%7C input.length() == 0) %7B%0A            this.value = NULL_OR_EMPTY_STRING_HASH;%0A        %7D else %7B%0A    
         byte
@@ -1125,36 +1125,13 @@
 est(
-(
 input
- == null ? %22%22 : input)
 .get
@@ -1156,32 +1156,36 @@
 ame(%22UTF-8%22)));%0A
+    
         this.val
@@ -1218,16 +1218,26 @@
 igest);%0A
+        %7D%0A
     %7D%0A%0A 

add special case for null or empty string