001: /*
002: * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
003: */
004: package com.tc.util;
005:
006: import com.tc.logging.TCLogger;
007: import com.tc.logging.TCLogging;
008:
009: import java.lang.reflect.Method;
010: import java.security.SecureRandom;
011: import java.util.Random;
012:
013: public class UUID {
014:
015: private static final TCLogger logger = TCLogging
016: .getLogger(UUID.class);
017: private static final Method jdk15createMethod;
018:
019: private final String uuid;
020:
021: public static UUID getUUID() {
022: if (jdk15createMethod != null) {
023: return new UUID(getJDK15());
024: }
025: return new UUID(getDefault());
026: }
027:
028: private static String getDefault() {
029: Random r = new SecureRandom();
030: long l1 = r.nextLong();
031: long l2 = r.nextLong();
032: return Long.toHexString(l1) + Long.toHexString(l2);
033: }
034:
035: private static String getJDK15() {
036: try {
037: Object object = jdk15createMethod.invoke(null,
038: new Object[] {});
039: String s = object.toString();
040: return s.replaceAll("[^A-Fa-f0-9]", "");
041: } catch (Exception e) {
042: throw new AssertionError(e);
043: }
044: }
045:
046: public String toString() {
047: return uuid;
048: }
049:
050: private UUID(String uuid) {
051: this .uuid = makeSize32(uuid);
052: if (32 != this .uuid.length()) {
053: throw new AssertionError("UUID : length is not 32 but "
054: + this .uuid.length() + " : UUID is : " + this .uuid);
055: }
056: }
057:
058: // TODO:: TIM FIXME
059: private String makeSize32(String uuid2) {
060: int len = uuid2.length();
061: if (len < 32) {
062: StringBuffer sb = new StringBuffer(32);
063: while (len++ < 32) {
064: sb.append('0');
065: }
066: sb.append(uuid2);
067: return sb.toString();
068: } else if (len > 32) {
069: return uuid2.substring(0, 32);
070: } else {
071: return uuid2;
072: }
073: }
074:
075: public static boolean usesJDKImpl() {
076: return jdk15createMethod != null;
077: }
078:
079: static {
080: Method jdk15UUID = null;
081: try {
082: Class c = Class.forName("java.util.UUID");
083: jdk15UUID = c.getDeclaredMethod("randomUUID",
084: new Class[] {});
085: } catch (Throwable t) {
086: logger
087: .warn("JDK1.5+ UUID class not available, falling back to default implementation. "
088: + t.getMessage());
089: }
090:
091: jdk15createMethod = jdk15UUID;
092: }
093:
094: public static void main(String args[]) {
095: for (int i = 0; i < 10; i++) {
096: System.out.println(UUID.getUUID());
097: }
098: }
099:
100: }
|