01: /*
02: * argun 1.0
03: * Web 2.0 delivery framework
04: * Copyright (C) 2007 Hammurapi Group
05: *
06: * This program is free software; you can redistribute it and/or
07: * modify it under the terms of the GNU Lesser General Public
08: * License as published by the Free Software Foundation; either
09: * version 2 of the 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 GNU
14: * Lesser General Public License for more details.
15: *
16: * You should have received a copy of the GNU Lesser General Public
17: * License along with this library; if not, write to the Free Software
18: * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19: *
20: * URL: http://www.hammurapi.biz
21: * e-Mail: support@hammurapi.biz
22: */
23: package biz.hammurapi.web.util;
24:
25: import java.io.ByteArrayOutputStream;
26: import java.io.DataOutputStream;
27: import java.io.IOException;
28: import java.net.InetAddress;
29: import java.net.URL;
30: import java.net.UnknownHostException;
31: import java.security.MessageDigest;
32: import java.security.NoSuchAlgorithmException;
33:
34: import org.apache.commons.codec.binary.Hex;
35:
36: import biz.hammurapi.web.HammurapiWebException;
37:
38: public class GuidGenerator {
39: private byte[] address;
40: private static int counter;
41: private String path;
42:
43: public GuidGenerator() {
44: try {
45: address = InetAddress.getLocalHost().getAddress();
46: } catch (UnknownHostException e) {
47: address = new byte[] { 0, 0, 0, 0 };
48: }
49: }
50:
51: /**
52: * Constructor
53: * @param url
54: */
55: public GuidGenerator(String urlStr) {
56: try {
57: URL url = new URL(urlStr);
58: address = InetAddress.getByName(url.getHost()).getAddress();
59: path = url.getPath();
60: } catch (Exception e) {
61: address = new byte[] { 0, 0, 0, 0 };
62: path = urlStr;
63: }
64: }
65:
66: public String nextGUID() throws HammurapiWebException {
67: try {
68: final MessageDigest digest = MessageDigest
69: .getInstance("SHA");
70: ByteArrayOutputStream baos = new ByteArrayOutputStream();
71: DataOutputStream dos = new DataOutputStream(baos);
72: dos.write(address);
73: synchronized (this ) {
74: dos.write(++counter);
75: }
76: dos.writeLong(System.currentTimeMillis());
77: if (path != null) {
78: dos.writeBytes(path);
79: }
80: dos.close();
81: baos.close();
82: digest.update(baos.toByteArray());
83: return new String(Hex.encodeHex(digest.digest()));
84: } catch (IOException e) {
85: throw new HammurapiWebException("Could not generate GUID: "
86: + e, e);
87: } catch (NoSuchAlgorithmException e) {
88: throw new HammurapiWebException("Could not generate GUID: "
89: + e, e);
90: }
91: }
92:
93: }
|