常用工具类一
一 . Base64Util
package com.jarvis.base.util; import java.io.*; /** * @Title: Base64Util.java * @Package com.jarvis.base.util * @Description:Base64工具类 * @author Jack * @date 2017年9月2日 下午5:10:32 * @version V1.0 */ public final class Base64Util { private static final int BASELENGTH = 255; private static final int LOOKUPLENGTH = 64; private static final int TWENTYFOURBITGROUP = 24; private static final int EIGHTBIT = 8; private static final int SIXTEENBIT = 16; // private static final int SIXBIT = 6; private static final int FOURBYTE = 4; // private static final int TWOBYTE = 2; private static final int SIGN = -128; private static final byte PAD = (byte) '='; private static byte[] base64Alphabet = new byte[BASELENGTH]; private static byte[] lookUpBase64Alphabet = new byte[LOOKUPLENGTH]; static { for (int i = 0; i < BASELENGTH; i++) { base64Alphabet[i] = -1; } for (int i = 'Z'; i >= 'A'; i--) { base64Alphabet[i] = (byte) (i - 'A'); } for (int i = 'z'; i >= 'a'; i--) { base64Alphabet[i] = (byte) (i - 'a' + 26); } for (int i = '9'; i >= '0'; i--) { base64Alphabet[i] = (byte) (i - '0' + 52); } base64Alphabet['+'] = 62; base64Alphabet['/'] = 63; for (int i = 0; i <= 25; i++) { lookUpBase64Alphabet[i] = (byte) ('A' + i); } for (int i = 26, j = 0; i <= 51; i++, j++) { lookUpBase64Alphabet[i] = (byte) ('a' + j); } for (int i = 52, j = 0; i <= 61; i++, j++) { lookUpBase64Alphabet[i] = (byte) ('0' + j); } lookUpBase64Alphabet[62] = (byte) '+'; lookUpBase64Alphabet[63] = (byte) '/'; } public static boolean isBase64(String isValidString) { return isArrayByteBase64(isValidString.getBytes()); } public static boolean isBase64(byte octect) { // shall we ignore white space? JEFF?? return (octect == PAD || base64Alphabet[octect] != -1); } public static boolean isArrayByteBase64(byte[] arrayOctect) { int length = arrayOctect.length; if (length == 0) { // shouldn't a 0 length array be valid base64 data? // return false; return true; } for (int i = 0; i < length; i++) { if (!isBase64(arrayOctect[i])) { return false; } } return true; } /** * Encode String object; * * @param src String object to be encoded. * @return encoded String; */ public static String encodeString(String src) { return encode(src); } public static String encodeBytes(byte[] src) { if (src == null || src.length == 0) { return null; } byte[] bytes = encode(src); return new String(bytes); } /** * Encode String object; * * @param src String object to be encoded. * @return encoded String; */ public static String encode(String src) { String target = null; if (src != null) { byte[] bts1 = src.getBytes(); byte[] bts2 = encode(bts1); if (bts2 != null) { target = new String(bts2); } } return target; } /** * Encodes hex octects into Base64. * * @param binaryData Array containing binary data to encode. * @return Base64-encoded data. */ public static byte[] encode(byte[] binaryData) { int lengthDataBits = binaryData.length * EIGHTBIT; int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; byte encodedData[] = null; if (fewerThan24bits != 0) { // data not divisible by 24 bit encodedData = new byte[(numberTriplets + 1) * 4]; } else { // 16 or 8 bit encodedData = new byte[numberTriplets * 4]; } byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0; int encodedIndex = 0; int dataIndex = 0; int i = 0; for (i = 0; i < numberTriplets; i++) { dataIndex = i * 3; b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; b3 = binaryData[dataIndex + 2]; l = (byte) (b2 & 0x0f); k = (byte) (b1 & 0x03); encodedIndex = i * 4; byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0); byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[(l << 2) | val3]; encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f]; } // form integral number of 6-bit groups dataIndex = i * 3; encodedIndex = i * 4; if (fewerThan24bits == EIGHTBIT) { b1 = binaryData[dataIndex]; k = (byte) (b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4]; encodedData[encodedIndex + 2] = PAD; encodedData[encodedIndex + 3] = PAD; } else if (fewerThan24bits == SIXTEENBIT) { b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; l = (byte) (b2 & 0x0f); k = (byte) (b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2]; encodedData[encodedIndex + 3] = PAD; } return encodedData; } public static String decode(String src) { String target = null; if (src != null) { byte[] bts1 = src.getBytes(); byte[] bts2 = decode(bts1); if (bts2 != null) { target = new String(bts2); } } return target; } public static String decode(String src, String charSet) throws UnsupportedEncodingException { String target = null; if (src != null) { byte[] bts1 = src.getBytes(); byte[] bts2 = decode(bts1); if (bts2 != null) { target = new String(bts2, charSet); } } return target; } /** * Decodes Base64 data into octects * * @param base64Data Byte array containing Base64 data * @return Array containing decoded data. */ public static byte[] decode(byte[] base64Data) { // handle the edge case, so we don't have to worry about it later if (base64Data.length == 0) { return null; } int numberQuadruple = base64Data.length / FOURBYTE; byte decodedData[] = null; byte b1 = 0, b2 = 0, b3 = 0, b4 = 0, marker0 = 0, marker1 = 0; // Throw away anything not in base64Data int encodedIndex = 0; int dataIndex = 0; { // this sizes the output array properly - rlw int lastData = base64Data.length; // ignore the '=' padding while (base64Data[lastData - 1] == PAD) { if (--lastData == 0) { return new byte[0]; } } decodedData = new byte[lastData - numberQuadruple]; } for (int i = 0; i < numberQuadruple; i++) { dataIndex = i * 4; marker0 = base64Data[dataIndex + 2]; marker1 = base64Data[dataIndex + 3]; b1 = base64Alphabet[base64Data[dataIndex]]; b2 = base64Alphabet[base64Data[dataIndex + 1]]; if (marker0 != PAD && marker1 != PAD) { // No PAD e.g 3cQl b3 = base64Alphabet[marker0]; b4 = base64Alphabet[marker1]; decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); decodedData[encodedIndex + 2] = (byte) (b3 << 6 | b4); } else if (marker0 == PAD) { // Two PAD e.g. 3c[Pad][Pad] decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); } else if (marker1 == PAD) { // One PAD e.g. 3cQ[Pad] b3 = base64Alphabet[marker0]; decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); } encodedIndex += 3; } return decodedData; } /** * 隐藏工具类的构造方法 */ protected Base64Util() { throw new UnsupportedOperationException(); } /** * 文件读取缓冲区大小 */ private static final int CACHE_SIZE = 1024; /** *//** * <p> * BASE64字符串解码为二进制数据 * </p> * * @param base64 * @return * @throws Exception */ public static byte[] decodeString(String base64) throws Exception { return Base64Util.decode(base64.getBytes()); } /** *//** * <p> * 二进制数据编码为BASE64字符串 * </p> * * @param bytes * @return * @throws Exception */ public static String encodeByte(byte[] bytes) throws Exception { return new String(Base64Util.encode(bytes)); } /** *//** * <p> * 将文件编码为BASE64字符串 * </p> * <p> * 大文件慎用,可能会导致内存溢出 * </p> * * @param filePath 文件绝对路径 * @return * @throws Exception */ public static String encodeFile(String filePath) throws Exception { byte[] bytes = fileToByte(filePath); return encodeByte(bytes); } /** *//** * <p> * BASE64字符串转回文件 * </p> * * @param filePath 文件绝对路径 * @param base64 编码字符串 * @throws Exception */ public static void decodeToFile(String filePath, String base64) throws Exception { byte[] bytes = decodeString(base64); byteArrayToFile(bytes, filePath); } /** *//** * <p> * 文件转换为二进制数组 * </p> * * @param filePath 文件路径 * @return * @throws Exception */ public static byte[] fileToByte(String filePath) throws Exception { byte[] data = new byte[0]; File file = new File(filePath); if (file.exists()) { FileInputStream in = new FileInputStream(file); ByteArrayOutputStream out = new ByteArrayOutputStream(2048); byte[] cache = new byte[CACHE_SIZE]; int nRead = 0; while ((nRead = in.read(cache)) != -1) { out.write(cache, 0, nRead); out.flush(); } out.close(); in.close(); data = out.toByteArray(); } return data; } /** *//** * <p> * 二进制数据写文件 * </p> * * @param bytes 二进制数据 * @param filePath 文件生成目录 */ public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception { InputStream in = new ByteArrayInputStream(bytes); File destFile = new File(filePath); if (!destFile.getParentFile().exists()) { destFile.getParentFile().mkdirs(); } destFile.createNewFile(); OutputStream out = new FileOutputStream(destFile); byte[] cache = new byte[CACHE_SIZE]; int nRead = 0; while ((nRead = in.read(cache)) != -1) { out.write(cache, 0, nRead); out.flush(); } out.close(); in.close(); } }
二. FastJsonUtil
package com.jarvis.base.util; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.List; import java.util.Map; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.TypeReference; import com.alibaba.fastjson.serializer.JSONLibDataFormatSerializer; import com.alibaba.fastjson.serializer.SerializeConfig; import com.alibaba.fastjson.serializer.SerializerFeature; /** * * * @Title: FastJsonUtil.java * @Package com.jarvis.base.util * @Description:fastjson工具类 * @author Jack * @date 2017年9月2日 下午4:16:27 * @version V1.0 */ public class FastJsonUtil { private static final SerializeConfig config; static { config = new SerializeConfig(); config.put(java.util.Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式 config.put(java.sql.Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式 } private static final SerializerFeature[] features = { SerializerFeature.WriteMapNullValue, // 输出空置字段 SerializerFeature.WriteNullListAsEmpty, // list字段如果为null,输出为[],而不是null SerializerFeature.WriteNullNumberAsZero, // 数值字段如果为null,输出为0,而不是null SerializerFeature.WriteNullBooleanAsFalse, // Boolean字段如果为null,输出为false,而不是null SerializerFeature.WriteNullStringAsEmpty, // 字符类型字段如果为null,输出为"",而不是null SerializerFeature.PrettyFormat //是否需要格式化输出Json数据 }; /** * Author:Jack Time:2017年9月2日下午4:24:14 * * @param object * @return Return:String Description:将对象转成成Json对象 */ public static String toJSONString(Object object) { return JSON.toJSONString(object, config, features); } /** * Author:Jack Time:2017年9月2日下午4:27:25 * * @param object * @return Return:String Description:使用和json-lib兼容的日期输出格式 */ public static String toJSONNoFeatures(Object object) { return JSON.toJSONString(object, config); } /** * Author:Jack Time:2017年9月2日下午4:24:54 * * @param jsonStr * @return Return:Object Description:将Json数据转换成JSONObject */ public static JSONObject toJsonObj(String jsonStr) { return (JSONObject) JSON.parse(jsonStr); } /** * Author:Jack Time:2017年9月2日下午4:25:20 * * @param jsonStr * @param clazz * @return Return:T Description:将Json数据转换成Object */ public static <T> T toBean(String jsonStr, Class<T> clazz) { return JSON.parseObject(jsonStr, clazz); } /** * Author:Jack Time:2017年9月2日下午4:25:34 * * @param jsonStr * @return Return:Object[] Description:将Json数据转换为数组 */ public static <T> Object[] toArray(String jsonStr) { return toArray(jsonStr, null); } /** * Author:Jack Time:2017年9月2日下午4:25:57 * * @param jsonStr * @param clazz * @return Return:Object[] Description:将Json数据转换为数组 */ public static <T> Object[] toArray(String jsonStr, Class<T> clazz) { return JSON.parseArray(jsonStr, clazz).toArray(); } /** * Author:Jack Time:2017年9月2日下午4:26:08 * * @param jsonStr * @param clazz * @return Return:List<T> Description:将Json数据转换为List */ public static <T> List<T> toList(String jsonStr, Class<T> clazz) { return JSON.parseArray(jsonStr, clazz); } /** * 将javabean转化为序列化的JSONObject对象 * * @param keyvalue * @return */ public static JSONObject beanToJsonObj(Object bean) { String jsonStr = JSON.toJSONString(bean); JSONObject objectJson = (JSONObject) JSON.parse(jsonStr); return objectJson; } /** * json字符串转化为map * * @param s * @return */ public static Map<?, ?> stringToCollect(String jsonStr) { Map<?, ?> map = JSONObject.parseObject(jsonStr); return map; } /** * 将map转化为string * * @param m * @return */ public static String collectToString(Map<?, ?> map) { String jsonStr = JSONObject.toJSONString(map); return jsonStr; } /** * Author:Jack Time:2017年9月2日下午4:19:00 * * @param t * @param file * @throws IOException * Return:void Description:将对象的Json数据写入文件。 */ public static <T> void writeJsonToFile(T t, File file) throws IOException { String jsonStr = JSONObject.toJSONString(t, SerializerFeature.PrettyFormat); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))); bw.write(jsonStr); bw.close(); } /** * Author:Jack Time:2017年9月2日下午4:19:12 * * @param t * @param filename * @throws IOException * Return:void Description:将对象的Json数据写入文件。 */ public static <T> void writeJsonToFile(T t, String filename) throws IOException { writeJsonToFile(t, new File(filename)); } /** * Author:Jack Time:2017年9月2日下午4:22:07 * * @param cls * @param file * @return * @throws IOException * Return:T Description:将文件中的Json数据转换成Object对象 */ public static <T> T readJsonFromFile(Class<T> cls, File file) throws IOException { StringBuilder strBuilder = new StringBuilder(); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file))); String line = null; while ((line = br.readLine()) != null) { strBuilder.append(line); } br.close(); return JSONObject.parseObject(strBuilder.toString(), cls); } /** * Author:Jack Time:2017年9月2日下午4:22:30 * * @param cls * @param filename * @return * @throws IOException * Return:T Description:将文件中的Json数据转换成Object对象 */ public static <T> T readJsonFromFile(Class<T> cls, String filename) throws IOException { return readJsonFromFile(cls, new File(filename)); } /** * Author:Jack Time:2017年9月2日下午4:23:06 * * @param typeReference * @param file * @return * @throws IOException * Return:T Description:从文件中读取出Json对象 */ public static <T> T readJsonFromFile(TypeReference<T> typeReference, File file) throws IOException { StringBuilder strBuilder = new StringBuilder(); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file))); String line = null; while ((line = br.readLine()) != null) { strBuilder.append(line); } br.close(); return JSONObject.parseObject(strBuilder.toString(), typeReference); } /** * Author:Jack Time:2017年9月2日下午4:23:11 * * @param typeReference * @param filename * @return * @throws IOException * Return:T Description:从文件中读取出Json对象 */ public static <T> T readJsonFromFile(TypeReference<T> typeReference, String filename) throws IOException { return readJsonFromFile(typeReference, new File(filename)); } }
三. ImageHelper
package com.jarvis.base.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import net.coobird.thumbnailator.Thumbnails; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; /** * * * @Title: ImageHelper.java * @Package com.jarvis.base.util * @Description:图片处理工具类。 * @author Jack * @date 2017年9月2日 下午3:04:40 * @version V1.0 */ @SuppressWarnings("restriction") public class ImageHelper { /** * @描述:Base64解码并生成图片 * @入参:@param imgStr * @入参:@param imgFile * @入参:@throws IOException * @出参:void */ public static void generateImage(String imgStr, String imgFile) throws IOException { BASE64Decoder decoder = new BASE64Decoder(); // Base64解码 byte[] bytes; OutputStream out = null; try { bytes = decoder.decodeBuffer(imgStr); for (int i = 0; i < bytes.length; ++i) { if (bytes[i] < 0) {// 调整异常数据 bytes[i] += 256; } } // 生成图片 out = new FileOutputStream(imgFile); out.write(bytes); out.flush(); } catch (IOException e) { throw new IOException(); } finally { if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * @throws IOException * @描述:根据路径得到base编码后图片 * @入参:@param imgFilePath * @入参:@return * @出参:String */ public static String getImageStr(String imgFilePath) throws IOException {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理 byte[] data = null; // 读取图片字节数组 try { InputStream in = new FileInputStream(imgFilePath); data = new byte[in.available()]; in.read(data); in.close(); } catch (IOException e) { throw new IOException(); } // 对字节数组Base64编码 BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(data);// 返回Base64编码过的字节数组字符串 } /** * @throws IOException * @描述:图片旋转 * @入参:@param base64In 传入的图片base64 * @入参:@param angle 图片旋转度数 * @入参:@throws Exception * @出参:String 传出的图片base64 */ public static String imgAngleRevolve(String base64In, int angle) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); try { Thumbnails.of(base64ToIo(base64In)).scale(1.0).rotate(angle).toOutputStream(os); } catch (IOException e) { throw new IOException(); } byte[] bs = os.toByteArray(); String s = new BASE64Encoder().encode(bs); return s; } /** * @描述:base64转为io流 * @入参:@param strBase64 * @入参:@return * @入参:@throws IOException * @出参:InputStream */ public static InputStream base64ToIo(String strBase64) throws IOException { // 解码,然后将字节转换为文件 byte[] bytes = new BASE64Decoder().decodeBuffer(strBase64); // 将字符串转换为byte数组 return new ByteArrayInputStream(bytes); } }
四. UUID
package com.jarvis.base.util; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; /** * A class that represents an immutable universally unique identifier (UUID). * A UUID represents a 128-bit value. * <p/> * <p>There exist different variants of these global identifiers. The methods * of this class are for manipulating the Leach-Salz variant, although the * constructors allow the creation of any variant of UUID (described below). * <p/> * <p>The layout of a variant 2 (Leach-Salz) UUID is as follows: * <p/> * The most significant long consists of the following unsigned fields: * <pre> * 0xFFFFFFFF00000000 time_low * 0x00000000FFFF0000 time_mid * 0x000000000000F000 version * 0x0000000000000FFF time_hi * </pre> * The least significant long consists of the following unsigned fields: * <pre> * 0xC000000000000000 variant * 0x3FFF000000000000 clock_seq * 0x0000FFFFFFFFFFFF node * </pre> * <p/> * <p>The variant field contains a value which identifies the layout of * the <tt>UUID</tt>. The bit layout described above is valid only for * a <tt>UUID</tt> with a variant value of 2, which indicates the * Leach-Salz variant. * <p/> * <p>The version field holds a value that describes the type of this * <tt>UUID</tt>. There are four different basic types of UUIDs: time-based, * DCE security, name-based, and randomly generated UUIDs. These types * have a version value of 1, 2, 3 and 4, respectively. * <p/> * <p>For more information including algorithms used to create <tt>UUID</tt>s, * see the Internet-Draft <a href="http://www.ietf.org/internet-drafts/draft-mealling-uuid-urn-03.txt">UUIDs and GUIDs</a> * or the standards body definition at * <a href="http://www.iso.ch/cate/d2229.html">ISO/IEC 11578:1996</a>. * * @version 1.14, 07/12/04 * @since 1.5 */ @Deprecated public final class UUID implements java.io.Serializable { /** * Explicit serialVersionUID for interoperability. */ private static final long serialVersionUID = -4856846361193249489L; /* * The most significant 64 bits of this UUID. * * @serial */ private final long mostSigBits; /** * The least significant 64 bits of this UUID. * * @serial */ private final long leastSigBits; /* * The version number associated with this UUID. Computed on demand. */ private transient int version = -1; /* * The variant number associated with this UUID. Computed on demand. */ private transient int variant = -1; /* * The timestamp associated with this UUID. Computed on demand. */ private transient volatile long timestamp = -1; /* * The clock sequence associated with this UUID. Computed on demand. */ private transient int sequence = -1; /* * The node number associated with this UUID. Computed on demand. */ private transient long node = -1; /* * The hashcode of this UUID. Computed on demand. */ private transient int hashCode = -1; /* * The random number generator used by this class to create random * based UUIDs. */ private static volatile SecureRandom numberGenerator = null; // Constructors and Factories /* * Private constructor which uses a byte array to construct the new UUID. */ private UUID(byte[] data) { long msb = 0; long lsb = 0; for (int i = 0; i < 8; i++) msb = (msb << 8) | (data[i] & 0xff); for (int i = 8; i < 16; i++) lsb = (lsb << 8) | (data[i] & 0xff); this.mostSigBits = msb; this.leastSigBits = lsb; } /** * Constructs a new <tt>UUID</tt> using the specified data. * <tt>mostSigBits</tt> is used for the most significant 64 bits * of the <tt>UUID</tt> and <tt>leastSigBits</tt> becomes the * least significant 64 bits of the <tt>UUID</tt>. * * @param mostSigBits * @param leastSigBits */ public UUID(long mostSigBits, long leastSigBits) { this.mostSigBits = mostSigBits; this.leastSigBits = leastSigBits; } /** * Static factory to retrieve a type 4 (pseudo randomly generated) UUID. * <p/> * The <code>UUID</code> is generated using a cryptographically strong * pseudo random number generator. * * @return a randomly generated <tt>UUID</tt>. */ @SuppressWarnings("unused") public static UUID randomUUID() { SecureRandom ng = numberGenerator; if (ng == null) { numberGenerator = ng = new SecureRandom(); } byte[] randomBytes = new byte[16]; ng.nextBytes(randomBytes); randomBytes[6] &= 0x0f; /* clear version */ randomBytes[6] |= 0x40; /* set to version 4 */ randomBytes[8] &= 0x3f; /* clear variant */ randomBytes[8] |= 0x80; /* set to IETF variant */ UUID result = new UUID(randomBytes); return new UUID(randomBytes); } /** * Static factory to retrieve a type 3 (name based) <tt>UUID</tt> based on * the specified byte array. * * @param name a byte array to be used to construct a <tt>UUID</tt>. * @return a <tt>UUID</tt> generated from the specified array. */ public static UUID nameUUIDFromBytes(byte[] name) { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException nsae) { throw new InternalError("MD5 not supported"); } byte[] md5Bytes = md.digest(name); md5Bytes[6] &= 0x0f; /* clear version */ md5Bytes[6] |= 0x30; /* set to version 3 */ md5Bytes[8] &= 0x3f; /* clear variant */ md5Bytes[8] |= 0x80; /* set to IETF variant */ return new UUID(md5Bytes); } /** * Creates a <tt>UUID</tt> from the string standard representation as * described in the {@link #toString} method. * * @param name a string that specifies a <tt>UUID</tt>. * @return a <tt>UUID</tt> with the specified value. * @throws IllegalArgumentException if name does not conform to the * string representation as described in {@link #toString}. */ public static UUID fromString(String name) { String[] components = name.split("-"); if (components.length != 5) throw new IllegalArgumentException("Invalid UUID string: " + name); for (int i = 0; i < 5; i++) components[i] = "0x" + components[i]; long mostSigBits = Long.decode(components[0]).longValue(); mostSigBits <<= 16; mostSigBits |= Long.decode(components[1]).longValue(); mostSigBits <<= 16; mostSigBits |= Long.decode(components[2]).longValue(); long leastSigBits = Long.decode(components[3]).longValue(); leastSigBits <<= 48; leastSigBits |= Long.decode(components[4]).longValue(); return new UUID(mostSigBits, leastSigBits); } // Field Accessor Methods /** * Returns the least significant 64 bits of this UUID's 128 bit value. * * @return the least significant 64 bits of this UUID's 128 bit value. */ public long getLeastSignificantBits() { return leastSigBits; } /** * Returns the most significant 64 bits of this UUID's 128 bit value. * * @return the most significant 64 bits of this UUID's 128 bit value. */ public long getMostSignificantBits() { return mostSigBits; } /** * The version number associated with this <tt>UUID</tt>. The version * number describes how this <tt>UUID</tt> was generated. * <p/> * The version number has the following meaning:<p> * <ul> * <li>1 Time-based UUID * <li>2 DCE security UUID * <li>3 Name-based UUID * <li>4 Randomly generated UUID * </ul> * * @return the version number of this <tt>UUID</tt>. */ public int version() { if (version < 0) { // Version is bits masked by 0x000000000000F000 in MS long version = (int) ((mostSigBits >> 12) & 0x0f); } return version; } /** * The variant number associated with this <tt>UUID</tt>. The variant * number describes the layout of the <tt>UUID</tt>. * <p/> * The variant number has the following meaning:<p> * <ul> * <li>0 Reserved for NCS backward compatibility * <li>2 The Leach-Salz variant (used by this class) * <li>6 Reserved, Microsoft Corporation backward compatibility * <li>7 Reserved for future definition * </ul> * * @return the variant number of this <tt>UUID</tt>. */ public int variant() { if (variant < 0) { // This field is composed of a varying number of bits if ((leastSigBits >>> 63) == 0) { variant = 0; } else if ((leastSigBits >>> 62) == 2) { variant = 2; } else { variant = (int) (leastSigBits >>> 61); } } return variant; } /** * The timestamp value associated with this UUID. * <p/> * <p>The 60 bit timestamp value is constructed from the time_low, * time_mid, and time_hi fields of this <tt>UUID</tt>. The resulting * timestamp is measured in 100-nanosecond units since midnight, * October 15, 1582 UTC.<p> * <p/> * The timestamp value is only meaningful in a time-based UUID, which * has version type 1. If this <tt>UUID</tt> is not a time-based UUID then * this method throws UnsupportedOperationException. * * @throws UnsupportedOperationException if this UUID is not a * version 1 UUID. */ public long timestamp() { if (version() != 1) { throw new UnsupportedOperationException("Not a time-based UUID"); } long result = timestamp; if (result < 0) { result = (mostSigBits & 0x0000000000000FFFL) << 48; result |= ((mostSigBits >> 16) & 0xFFFFL) << 32; result |= mostSigBits >>> 32; timestamp = result; } return result; } /** * The clock sequence value associated with this UUID. * <p/> * <p>The 14 bit clock sequence value is constructed from the clock * sequence field of this UUID. The clock sequence field is used to * guarantee temporal uniqueness in a time-based UUID.<p> * <p/> * The clockSequence value is only meaningful in a time-based UUID, which * has version type 1. If this UUID is not a time-based UUID then * this method throws UnsupportedOperationException. * * @return the clock sequence of this <tt>UUID</tt>. * @throws UnsupportedOperationException if this UUID is not a * version 1 UUID. */ public int clockSequence() { if (version() != 1) { throw new UnsupportedOperationException("Not a time-based UUID"); } if (sequence < 0) { sequence = (int) ((leastSigBits & 0x3FFF000000000000L) >>> 48); } return sequence; } /** * The node value associated with this UUID. * <p/> * <p>The 48 bit node value is constructed from the node field of * this UUID. This field is intended to hold the IEEE 802 address * of the machine that generated this UUID to guarantee spatial * uniqueness.<p> * <p/> * The node value is only meaningful in a time-based UUID, which * has version type 1. If this UUID is not a time-based UUID then * this method throws UnsupportedOperationException. * * @return the node value of this <tt>UUID</tt>. * @throws UnsupportedOperationException if this UUID is not a * version 1 UUID. */ public long node() { if (version() != 1) { throw new UnsupportedOperationException("Not a time-based UUID"); } if (node < 0) { node = leastSigBits & 0x0000FFFFFFFFFFFFL; } return node; } // Object Inherited Methods /** * Returns a <code>String</code> object representing this * <code>UUID</code>. * <p/> * <p>The UUID string representation is as described by this BNF : * <pre> * UUID = <time_low> "-" <time_mid> "-" * <time_high_and_version> "-" * <variant_and_sequence> "-" * <node> * time_low = 4*<hexOctet> * time_mid = 2*<hexOctet> * time_high_and_version = 2*<hexOctet> * variant_and_sequence = 2*<hexOctet> * node = 6*<hexOctet> * hexOctet = <hexDigit><hexDigit> * hexDigit = * "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" * | "a" | "b" | "c" | "d" | "e" | "f" * | "A" | "B" | "C" | "D" | "E" | "F" * </pre> * * @return a string representation of this <tt>UUID</tt>. */ public String toString() { return (digits(mostSigBits >> 32, 8) + "-" + digits(mostSigBits >> 16, 4) + "-" + digits(mostSigBits, 4) + "-" + digits(leastSigBits >> 48, 4) + "-" + digits(leastSigBits, 12)); } /** * Returns val represented by the specified number of hex digits. */ private static String digits(long val, int digits) { long hi = 1L << (digits * 4); return Long.toHexString(hi | (val & (hi - 1))).substring(1); } /** * Returns a hash code for this <code>UUID</code>. * * @return a hash code value for this <tt>UUID</tt>. */ public int hashCode() { if (hashCode == -1) { hashCode = (int) ((mostSigBits >> 32) ^ mostSigBits ^ (leastSigBits >> 32) ^ leastSigBits); } return hashCode; } /** * Compares this object to the specified object. The result is * <tt>true</tt> if and only if the argument is not * <tt>null</tt>, is a <tt>UUID</tt> object, has the same variant, * and contains the same value, bit for bit, as this <tt>UUID</tt>. * * @param obj the object to compare with. * @return <code>true</code> if the objects are the same; * <code>false</code> otherwise. */ public boolean equals(Object obj) { if (!(obj instanceof UUID)) return false; if (((UUID) obj).variant() != this.variant()) return false; UUID id = (UUID) obj; return (mostSigBits == id.mostSigBits && leastSigBits == id.leastSigBits); } // Comparison Operations /** * Compares this UUID with the specified UUID. * <p/> * <p>The first of two UUIDs follows the second if the most significant * field in which the UUIDs differ is greater for the first UUID. * * @param val <tt>UUID</tt> to which this <tt>UUID</tt> is to be compared. * @return -1, 0 or 1 as this <tt>UUID</tt> is less than, equal * to, or greater than <tt>val</tt>. */ public int compareTo(UUID val) { // The ordering is intentionally set up so that the UUIDs // can simply be numerically compared as two numbers return (this.mostSigBits < val.mostSigBits ? -1 : (this.mostSigBits > val.mostSigBits ? 1 : (this.leastSigBits < val.leastSigBits ? -1 : (this.leastSigBits > val.leastSigBits ? 1 : 0)))); } /** * Reconstitute the <tt>UUID</tt> instance from a stream (that is, * deserialize it). This is necessary to set the transient fields * to their correct uninitialized value so they will be recomputed * on demand. */ private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { in.defaultReadObject(); // Set "cached computation" fields to their initial values version = -1; variant = -1; timestamp = -1; sequence = -1; node = -1; hashCode = -1; } }