一、前言
基于directwebremoting包dwr-3.0.jar中的org.directwebremoting.util.IdGenerator主键生成器,通过MD5随机自定义长度generateId生成id序列。
二、源码说明
package org.directwebremoting.util;@b@@b@import java.security.MessageDigest;@b@import java.security.NoSuchAlgorithmException;@b@import java.security.SecureRandom;@b@import java.util.Random;@b@import org.apache.commons.logging.Log;@b@import org.apache.commons.logging.LogFactory;@b@@b@public class IdGenerator@b@{@b@ protected static final String DEFAULT_ALGORITHM = "MD5";@b@ private String algorithm = "MD5";@b@ private Random random = new SecureRandom();@b@ private MessageDigest digest = null;@b@ private static final Log log = LogFactory.getLog(IdGenerator.class);@b@@b@ public IdGenerator()@b@ {@b@ long seed = System.currentTimeMillis();@b@@b@ char[] entropy = toString().toCharArray();@b@ for (int i = 0; i < entropy.length; ++i)@b@ {@b@ long update = (byte)entropy[i] << i % 8 * 8;@b@ seed ^= update;@b@ }@b@@b@ this.random.setSeed(seed);@b@ }@b@@b@ public synchronized String generateId(int length)@b@ {@b@ int j;@b@ byte[] buffer = new byte[length];@b@@b@ StringBuffer reply = new StringBuffer();@b@@b@ int resultLenBytes = 0;@b@ while (resultLenBytes < length)@b@ {@b@ this.random.nextBytes(buffer);@b@ buffer = getDigest().digest(buffer);@b@@b@ for (j = 0; (j < buffer.length) && (resultLenBytes < length); ++j)@b@ {@b@ byte b1 = (byte)((buffer[j] & 0xF0) >> 4);@b@ if (b1 < 10)@b@ {@b@ reply.append((char)(48 + b1));@b@ }@b@ else@b@ {@b@ reply.append((char)(65 + b1 - 10));@b@ }@b@@b@ byte b2 = (byte)(buffer[j] & 0xF);@b@ if (b2 < 10)@b@ {@b@ reply.append((char)(48 + b2));@b@ }@b@ else@b@ {@b@ reply.append((char)(65 + b2 - 10));@b@ }@b@@b@ ++resultLenBytes;@b@ }@b@ }@b@@b@ return reply.toString();@b@ }@b@@b@ public synchronized String getAlgorithm()@b@ {@b@ return this.algorithm;@b@ }@b@@b@ public synchronized void setAlgorithm(String algorithm)@b@ {@b@ this.algorithm = algorithm;@b@ this.digest = null;@b@ }@b@@b@ private MessageDigest getDigest()@b@ {@b@ if (this.digest == null)@b@ {@b@ try@b@ {@b@ this.digest = MessageDigest.getInstance(this.algorithm);@b@ }@b@ catch (NoSuchAlgorithmException ex)@b@ {@b@ try@b@ {@b@ this.digest = MessageDigest.getInstance("MD5");@b@ }@b@ catch (NoSuchAlgorithmException ex2)@b@ {@b@ this.digest = null;@b@ throw new IllegalStateException("No algorithms for IdGenerator");@b@ }@b@ }@b@@b@ log.debug("Using MessageDigest: " + this.digest.getAlgorithm());@b@ }@b@@b@ return this.digest;@b@ }@b@@b@ public final String toString()@b@ {@b@ return super.toString();@b@ }@b@}