001/*
002 * The Kuali Financial System, a comprehensive financial management system for higher education.
003 * 
004 * Copyright 2005-2014 The Kuali Foundation
005 * 
006 * This program is free software: you can redistribute it and/or modify
007 * it under the terms of the GNU Affero General Public License as
008 * published by the Free Software Foundation, either version 3 of the
009 * License, or (at your option) any later version.
010 * 
011 * This program is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
014 * GNU Affero General Public License for more details.
015 * 
016 * You should have received a copy of the GNU Affero General Public License
017 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
018 */
019package org.kuali.rice.kns.util;
020
021import java.security.MessageDigest;
022import java.security.NoSuchAlgorithmException;
023
024import org.apache.ojb.broker.util.GUID;
025
026/**
027 * 
028 * This class wraps an OJB Guid so that it conforms to the format (and using the algorithm) described in
029 * RFC 4122 entitled " A Universally Unique IDentifier (UUID) URN Namespace" 
030 */
031public class Guid {
032 
033    private final static char HYPHEN='-';
034    private final static String DIGITS="0123456789ABCDEF";
035    private String stringValue=null;
036    private GUID guid;
037    
038    public Guid() {
039        
040        guid = new GUID(); // This OJB class is deprecated; remove this line when we upgrade OJB
041        
042        
043        String guidString=guid.toString();
044        // this is roughly the prefered way with the new OJB GUIDFactory:
045        // String guidString=org.apache.ojb.broker.util.GUIDFactory.next(); 
046        
047    
048        MessageDigest sha;
049        try {
050            sha = MessageDigest.getInstance("SHA-1");
051        }
052        catch (NoSuchAlgorithmException e) {
053            throw new RuntimeException(e);
054        }
055        sha.update(guidString.getBytes());
056        byte[] hash=sha.digest();
057        
058        StringBuffer result=new StringBuffer();
059        for (int i=0; i<hash.length; i++) {
060            result.append(toHex(hash[i]));
061        }
062        
063        // hyphenate
064        for (int i=20; i>4; i-=4) {
065            result.insert(i,HYPHEN);
066        }
067        
068        // truncate
069        result.delete(32,40);
070        stringValue=result.toString();
071    }    
072    
073    public static String toHex(byte b) {
074
075        int ub=b<0?b+256:b;
076        
077        StringBuffer result=new StringBuffer(2);
078        result.append(DIGITS.charAt(ub/16));
079        result.append(DIGITS.charAt(ub%16));
080        
081        return result.toString();
082    }
083
084    @Override
085    public String toString() {
086        return stringValue;
087    }
088    
089}