View Javadoc
1   /*
2    * Copyright 2005-2008 The Kuali Foundation
3    * 
4    * Licensed under the Educational Community License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * 
8    * http://www.opensource.org/licenses/ecl2.php
9    * 
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.kuali.rice.kns.util;
17  
18  import java.security.MessageDigest;
19  import java.security.NoSuchAlgorithmException;
20  
21  import org.apache.ojb.broker.util.GUID;
22  
23  /**
24   * 
25   * This class wraps an OJB Guid so that it conforms to the format (and using the algorithm) described in
26   * RFC 4122 entitled " A Universally Unique IDentifier (UUID) URN Namespace" 
27   */
28  public class Guid {
29   
30      private final static char HYPHEN='-';
31      private final static String DIGITS="0123456789ABCDEF";
32      private String stringValue=null;
33      private GUID guid;
34      
35      public Guid() {
36          
37          guid = new GUID(); // This OJB class is deprecated; remove this line when we upgrade OJB
38          
39          
40          String guidString=guid.toString();
41          // this is roughly the prefered way with the new OJB GUIDFactory:
42          // String guidString=org.apache.ojb.broker.util.GUIDFactory.next(); 
43          
44      
45          MessageDigest sha;
46          try {
47              sha = MessageDigest.getInstance("SHA-1");
48          }
49          catch (NoSuchAlgorithmException e) {
50              throw new RuntimeException(e);
51          }
52          sha.update(guidString.getBytes());
53          byte[] hash=sha.digest();
54          
55          StringBuffer result=new StringBuffer();
56          for (int i=0; i<hash.length; i++) {
57              result.append(toHex(hash[i]));
58          }
59          
60          // hyphenate
61          for (int i=20; i>4; i-=4) {
62              result.insert(i,HYPHEN);
63          }
64          
65          // truncate
66          result.delete(32,40);
67          stringValue=result.toString();
68      }    
69      
70      public static String toHex(byte b) {
71  
72          int ub=b<0?b+256:b;
73          
74          StringBuffer result=new StringBuffer(2);
75          result.append(DIGITS.charAt(ub/16));
76          result.append(DIGITS.charAt(ub%16));
77          
78          return result.toString();
79      }
80  
81      @Override
82      public String toString() {
83          return stringValue;
84      }
85      
86  }