All Downloads are FREE. Search and download functionalities are using the official Maven repository.

se.cambio.cm.model.util.CheckSumManager Maven / Gradle / Ivy

The newest version!
package se.cambio.cm.model.util;

import se.cambio.cm.model.util.comparators.CMElementComparator;
import se.cambio.openehr.util.exceptions.InternalErrorException;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class CheckSumManager {

    public static  String generateChecksum(Collection cmElements) throws InternalErrorException {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            List cmElementList = getSortedCMElementList(cmElements);
            return getMD5Checksum(md, cmElementList);
        } catch (NoSuchAlgorithmException ex) {
            throw new InternalErrorException(ex);
        }
    }

    private static  String getMD5Checksum(MessageDigest md, List cmElementList) {
        for (E cmElement : cmElementList) {
            try {
                md.update(cmElement.getSource().getBytes("UTF-8"));
            } catch (UnsupportedEncodingException ex) {
                throw new RuntimeException(ex);
            }
        }
        byte[] md5Bytes = md.digest();
        StringBuilder sb = new StringBuilder();
        for (byte md5Byte : md5Bytes) {
            sb.append(Integer.toString((md5Byte & 0xff) + 0x100, 16).substring(1));
        }
        return sb.toString();
    }

    private static  List getSortedCMElementList(Collection cmElements) {
        List cmElementList = new ArrayList<>();
        cmElementList.addAll(cmElements);
        cmElementList.sort(new CMElementComparator());
        return cmElementList;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy