1 /*
2 * The Kuali Financial System, a comprehensive financial management system for higher education.
3 *
4 * Copyright 2005-2014 The Kuali Foundation
5 *
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as
8 * published by the Free Software Foundation, either version 3 of the
9 * License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
15 *
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19 package org.kuali.rice.kns.util;
20
21 import java.security.MessageDigest;
22 import java.security.NoSuchAlgorithmException;
23
24 import org.apache.ojb.broker.util.GUID;
25
26 /**
27 *
28 * This class wraps an OJB Guid so that it conforms to the format (and using the algorithm) described in
29 * RFC 4122 entitled " A Universally Unique IDentifier (UUID) URN Namespace"
30 */
31 public class Guid {
32
33 private final static char HYPHEN='-';
34 private final static String DIGITS="0123456789ABCDEF";
35 private String stringValue=null;
36 private GUID guid;
37
38 public Guid() {
39
40 guid = new GUID(); // This OJB class is deprecated; remove this line when we upgrade OJB
41
42
43 String guidString=guid.toString();
44 // this is roughly the prefered way with the new OJB GUIDFactory:
45 // String guidString=org.apache.ojb.broker.util.GUIDFactory.next();
46
47
48 MessageDigest sha;
49 try {
50 sha = MessageDigest.getInstance("SHA-1");
51 }
52 catch (NoSuchAlgorithmException e) {
53 throw new RuntimeException(e);
54 }
55 sha.update(guidString.getBytes());
56 byte[] hash=sha.digest();
57
58 StringBuffer result=new StringBuffer();
59 for (int i=0; i<hash.length; i++) {
60 result.append(toHex(hash[i]));
61 }
62
63 // hyphenate
64 for (int i=20; i>4; i-=4) {
65 result.insert(i,HYPHEN);
66 }
67
68 // truncate
69 result.delete(32,40);
70 stringValue=result.toString();
71 }
72
73 public static String toHex(byte b) {
74
75 int ub=b<0?b+256:b;
76
77 StringBuffer result=new StringBuffer(2);
78 result.append(DIGITS.charAt(ub/16));
79 result.append(DIGITS.charAt(ub%16));
80
81 return result.toString();
82 }
83
84 @Override
85 public String toString() {
86 return stringValue;
87 }
88
89 }