cn.tom.kit.ObjectId Maven / Gradle / Ivy
The newest version!
// ObjectId.java
package cn.tom.kit;
import java.math.BigInteger;
import java.net.*;
import java.nio.*;
import java.util.*;
import java.util.concurrent.atomic.*;
import java.util.logging.*;
/**
* A globally unique identifier for objects.
* Consists of 12 bytes, divided as follows:
*
*
* 0 1 2 3 4 5 6
* 7 8 9 10 11
* time machine
* pid inc
*
*
*
* @dochub objectids
*/
public class ObjectId implements ComparableObjectId
.
* @return whether the string could be an object id
*/
public static boolean isValid( String s ){
if ( s == null )
return false;
final int len = s.length();
if ( len != 24 )
return false;
for ( int i=0; iObjectId
, if possible.
* Strings will be converted into ObjectId
s, if possible, and ObjectId
s will
* be cast and returned. Passing in null
returns null
.
* @param o the object to convert
* @return an ObjectId
if it can be massaged, null otherwise
*/
public static ObjectId massageToObjectId( Object o ){
if ( o == null )
return null;
if ( o instanceof ObjectId )
return (ObjectId)o;
if ( o instanceof String ){
String s = o.toString();
if ( isValid( s ) )
return new ObjectId( s );
}
return null;
}
public ObjectId( Date time ){
this(time, _genmachine, _nextInc.getAndIncrement());
}
public ObjectId( Date time , int inc ){
this( time , _genmachine , inc );
}
public ObjectId( Date time , int machine , int inc ){
_time = (int)(time.getTime() / 1000);
_machine = machine;
_inc = inc;
_new = false;
}
/** Creates a new instance from a string.
* @param s the string to convert
* @throws IllegalArgumentException if the string is not a valid id
*/
public ObjectId( String s ){
this( s , false );
}
public ObjectId( String s , boolean babble ){
if ( ! isValid( s ) )
throw new IllegalArgumentException( "invalid ObjectId [" + s + "]" );
if ( babble )
s = babbleToMongod( s );
byte b[] = new byte[12];
for ( int i=0; i