package to.etc.domui.hibernate.idgen;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;
import to.etc.util.StringTool;

import java.io.Serializable;
import java.util.UUID;

/**
 * Create a String identifier that is based on an UUID, but which does
 * not use the very verbose string format of those things. Instead the
 * 128 bits are rendered as a base64 string (with the last 2 == signs
 * stripped), forming a 23 char identifier.
 *
 * To use the generator annotate your class(es) ID property as follows:
 * <pre>
 *  &#064;GeneratedValue(generator = "uuid3")
 * 	&#064;GenericGenerator(name = "uuid3", strategy = "to.etc.domui.hibernate.idgen.UUIDGenerator23")
 * 	&#064;Id
 * 	&#064;Column(name = "id", length = 23, nullable = false)
 * 	&#064;Nullable @Override public String getId() {
 * 		return m_id;
 *  }
 * </pre>
 *
 * @author <a href="mailto:jal@etc.to">Frits Jalvingh</a>
 * Created on 12-2-18.
 */
final public class UUIDGenerator23 implements IdentifierGenerator {
	@Override public Serializable generate(SharedSessionContractImplementor sharedSessionContractImplementor, Object o) throws HibernateException {
		UUID uuid = UUID.randomUUID();
		byte[] data = new byte[16];

		moveBytes(data, 0, uuid.getMostSignificantBits());
		moveBytes(data, 8, uuid.getLeastSignificantBits());
		String str = StringTool.encodeBase64ToString(data);

		return str.substring(0, 23);				// Strip the ==
	}

	private void moveBytes(byte[] bytes, int offset, long bits) {
		for(int i = 8; --i >= 0;) {
			bytes[i + offset] = (byte) (bits & 0xff);
			bits = bits >> 8;
		}
	}

}

@@ -531,16 +531,20 @@
 fier.%0A *
+ %3Cp%3E
 %0A * To u
@@ -1084,33 +1084,34 @@
 tor %7B%0A%09@Override
- 
+%0A%09
 public Serializa
@@ -1488,12 +1488,24 @@
 23);
-%09%09%09%09
+                
 // S
@@ -1521,16 +1521,23 @@
 ==%0A%09%7D%0A%0A%09
+static 
 private 
@@ -1616,16 +1616,17 @@
 -i %3E= 0;
+ 
 ) %7B%0A%09%09%09b
@@ -1695,10 +1695,339 @@
 %09%09%7D%0A%09%7D%0A%0A
+%09static public String createUUID() %7B%0A%09%09UUID uuid = UUID.randomUUID();%0A%09%09byte%5B%5D data = new byte%5B16%5D;%0A%0A%09%09moveBytes(data, 0, uuid.getMostSignificantBits());%0A%09%09moveBytes(data, 8, uuid.getLeastSignificantBits());%0A%09%09String str = StringTool.encodeBase64ToString(data);%0A%0A%09%09return str.substring(0, 23);                // Strip the ==%0A%09%7D%0A%0A
 %7D%0A

Add static method to calculate a database uuid.