package com.jt.boot.utils;

 import com.google.common.base.Objects;

 import java.net.NetworkInterface;
import java.nio.ByteBuffer;
import java.util.Date;
import java.util.Enumeration;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger; /**
* <p>A globally unique identifier for objects.</p>
* <p/>
* <p>Consists of 12 bytes, divided as follows:</p>
* <table border="1">
* <caption>ObjectID layout</caption>
* <tr>
* <td>0</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><td>10</td><td>11</td>
* </tr>
* <tr>
* <td colspan="4">time</td><td colspan="3">machine</td> <td colspan="2">pid</td><td colspan="3">inc</td>
* </tr>
* </table>
* <p/>
* <p>Instances of this class are immutable.</p>
*/
public class ObjectId implements Comparable<ObjectId>, java.io.Serializable { private final int _time;
private final int _machine;
private final int _inc;
private boolean _new;
private static final int _genmachine; private static AtomicInteger _nextInc = new AtomicInteger((new Random()).nextInt()); private static final long serialVersionUID = -4415279469780082174L; private static final Logger LOGGER = Logger.getLogger("org.bson.ObjectId"); /**
* Create a new object id.
*/
public ObjectId() {
_time = (int) (System.currentTimeMillis() / 1000);
_machine = _genmachine;
_inc = _nextInc.getAndIncrement();
_new = true;
} public static String id() {
return get().toHexString();
} /**
* Gets a new object id.
*
* @return the new id
*/
public static ObjectId get() {
return new ObjectId();
} /**
* Checks if a string could be an {@code ObjectId}.
*
* @param s a potential ObjectId as a String.
* @return whether the string could be an object id
* @throws IllegalArgumentException if hexString is null
*/
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; i < len; i++) {
char c = s.charAt(i);
if (c >= '0' && c <= '9')
continue;
if (c >= 'a' && c <= 'f')
continue;
if (c >= 'A' && c <= 'F')
continue; return false;
} return true;
} /**
* Converts this instance into a 24-byte hexadecimal string representation.
*
* @return a string representation of the ObjectId in hexadecimal format
*/
public String toHexString() {
final StringBuilder buf = new StringBuilder(24);
for (final byte b : toByteArray()) {
buf.append(String.format("%02x", b & 0xff));
}
return buf.toString();
} /**
* Convert to a byte array. Note that the numbers are stored in big-endian order.
*
* @return the byte array
*/
public byte[] toByteArray() {
byte b[] = new byte[12];
ByteBuffer bb = ByteBuffer.wrap(b);
// by default BB is big endian like we need
bb.putInt(_time);
bb.putInt(_machine);
bb.putInt(_inc);
return b;
} private int _compareUnsigned(int i, int j) {
long li = 0xFFFFFFFFL;
li = i & li;
long lj = 0xFFFFFFFFL;
lj = j & lj;
long diff = li - lj;
if (diff < Integer.MIN_VALUE)
return Integer.MIN_VALUE;
if (diff > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
return (int) diff;
} public int compareTo(ObjectId id) {
if (id == null)
return -1; int x = _compareUnsigned(_time, id._time);
if (x != 0)
return x; x = _compareUnsigned(_machine, id._machine);
if (x != 0)
return x; return _compareUnsigned(_inc, id._inc);
} /**
* Gets the timestamp (number of seconds since the Unix epoch).
*
* @return the timestamp
*/
public int getTimestamp() {
return _time;
} /**
* Gets the timestamp as a {@code Date} instance.
*
* @return the Date
*/
public Date getDate() {
return new Date(_time * 1000L);
} /**
* Gets the current value of the auto-incrementing counter.
*
* @return the current counter value.
*/
public static int getCurrentCounter() {
return _nextInc.get();
} static { try {
// build a 2-byte machine piece based on NICs info
int machinePiece;
{
try {
StringBuilder sb = new StringBuilder();
Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
while (e.hasMoreElements()) {
NetworkInterface ni = e.nextElement();
sb.append(ni.toString());
}
machinePiece = sb.toString().hashCode() << 16;
} catch (Throwable e) {
// exception sometimes happens with IBM JVM, use random
LOGGER.log(Level.WARNING, e.getMessage(), e);
machinePiece = (new Random().nextInt()) << 16;
}
LOGGER.fine("machine piece post: " + Integer.toHexString(machinePiece));
} // add a 2 byte process piece. It must represent not only the JVM but the class loader.
// Since static var belong to class loader there could be collisions otherwise
final int processPiece;
{
int processId = new Random().nextInt();
try {
processId = java.lang.management.ManagementFactory.getRuntimeMXBean().getName().hashCode();
} catch (Throwable t) {
} ClassLoader loader = ObjectId.class.getClassLoader();
int loaderId = loader != null ? System.identityHashCode(loader) : 0; StringBuilder sb = new StringBuilder();
sb.append(Integer.toHexString(processId));
sb.append(Integer.toHexString(loaderId));
processPiece = sb.toString().hashCode() & 0xFFFF;
LOGGER.fine("process piece: " + Integer.toHexString(processPiece));
} _genmachine = machinePiece | processPiece;
LOGGER.fine("machine : " + Integer.toHexString(_genmachine));
} catch (Exception e) {
throw new RuntimeException(e);
} } @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; ObjectId that = (ObjectId) o; return Objects.equal(this.serialVersionUID, that.serialVersionUID) &&
Objects.equal(this.LOGGER, that.LOGGER) &&
Objects.equal(this._time, that._time) &&
Objects.equal(this._machine, that._machine) &&
Objects.equal(this._inc, that._inc) &&
Objects.equal(this._new, that._new) &&
Objects.equal(this._nextInc, that._nextInc) &&
Objects.equal(this._genmachine, that._genmachine);
} @Override
public int hashCode() {
return Objects.hashCode(serialVersionUID, LOGGER, _time, _machine, _inc, _new,
_nextInc, _genmachine);
} public static void main(String[] args) {
System.out.println(new ObjectId().toHexString());
System.out.println(new ObjectId().toHexString());
System.out.println(new ObjectId().toHexString());
}
}

生成类似于MongoDB产生的ObjectId的更多相关文章

  1. MongoDB中_id(ObjectId)生成

    MongoDB 中我们经常会接触到一个自动生成的字段:"_id",类型为ObjectId. 之前我们使用MySQL等关系型数据库时,主键都是设置成自增的.但在分布式环境下,这种方法 ...

  2. ThinkPhp5 mongodb 使用自定义objectID出错解决

    在Tp5中使用mongodb 使用自定义ObjectId时报错:Cannot use object of type MongoDB\\BSON\\ObjectID as array 查询源码发现在to ...

  3. MongoDB学习笔记~ObjectId主键的设计

    回到目录 说一些关于ObjectId的事 MongoDB确实是最像关系型数据库的NoSQL,这在它主键设计上可以体现的出来,它并没有采用自动增长主键,因为在分布式服务器之间做数据同步很麻烦,而是采用了 ...

  4. java 查询 mongodb 中的objectid

    网上找了很久查询objectid的方法都是错的,用mongovue能查询出来,但就是用java不知道怎么查询 1.mongovue里的查询方式: {"_id" : ObjectId ...

  5. 从MongoDB的ObjectId中获取时间信息

    MongoDB默认使用_id字段作为主键,类型为ObjectId.ObjectId的生成有一定的规则,详情可以查看这篇文章 - MongoDB深究之ObjectId.如果你在写入数据库的时候忘记写入创 ...

  6. mongoose手动生成ObjectId

    用mongoose驱动保存数据,如果_id没有定义,那么在save的时候,mongoose驱动会自己生成一个_id.那么如果需要手动生成可以用mongoose.Types.ObjectId()方法. ...

  7. mongoose和mongodb的几篇文章 (ObjectId,ref)

    http://mongoosejs.com/docs/populate.html http://stackoverflow.com/questions/6578178/node-js-mongoose ...

  8. 【翻译】MongoDB指南/引言

    [原文地址]https://docs.mongodb.com/manual/ 引言 MongoDB是一种开源文档型数据库,它具有高性能,高可用性,自动扩展性 1.文档数据库 MongoDB用一个文档来 ...

  9. Python操作MongoDB和Redis

    1. python对mongo的常见CURD的操作 1.1 mongo简介 mongodb是一个nosql数据库,无结构化.和去中心化. 那为什么要用mongo来存呢? 1. 首先.数据关系复杂,没有 ...

随机推荐

  1. nodejs 获取文件的编码方式

    使用nodejs获取文件夹内文件的编码方式:使用jschardet模块. 下面的代码还有问题,没有添加结束的语句,没有判断应该在哪执行res.send(). res.send()不能放在forEach ...

  2. 软件工程 wc.exe 代码统计作业

    软件工程 wc.exe 代码统计作业分享 1. Github 项目地址 https://github.com/EdwardLiu-Aurora/WordCount 更好地阅读本文,可点击这里 基本要求 ...

  3. C# 如何防止重放攻击(转载)

    转载地址:http://www.cnblogs.com/similar/p/6776921.html 重放攻击 重放攻击是指黑客通过抓包的方式,得到客户端的请求数据及请求连接,重复的向服务器发送请求的 ...

  4. MySQLdb & pymsql

    python有两个模块可以连接和操作mysql数据库,分别是MySQLdb和pymysql,python3建议使用pymysql MySQLdb安装 pip install mysql-python ...

  5. asp.net—工厂模式

    一.什么是工厂模式 定义:定义一个创建对象的接口,让其子类自己决定实例化哪一个工厂类. 二.怎么使用工厂模式 首先模拟一个场景:有一个汽车工厂,  可以日本车.美国车.中国车... 这个场景怎么用工厂 ...

  6. Basic Auth

    开放平台 把网站服务封装成一系列接口供第三方开发者使用,这种行为就叫做Open API,提供开放API的平台本身就被称为开放平台.比如一些网站支持QQ登录,那QQ就相当于开放平台,QQ提供了一些OPE ...

  7. BitAdminCore框架应用篇:(四)核心套件querySuite按钮功能

    索引 NET Core应用框架之BitAdminCore框架应用篇系列 框架演示:http://bit.bitdao.cn 框架源码:https://github.com/chenyinxin/coo ...

  8. 使用Spring Boot,Spring Cloud和Docker实现微服务架构

    https://github.com/sqshq/PiggyMetrics     Microservice Architecture with Spring Boot, Spring Cloud a ...

  9. 前端入门CSS(1)

    day48 参考:https://www.cnblogs.com/liwenzhou/p/7999532.html CSS的几种引入方式 行内样式 行内式是在标记的style属性中设定CSS样式,不推 ...

  10. string的相关问题

    http://blog.csdn.net/seu_calvin/article/details/51404589 http://rednaxelafx.iteye.com/blog/774673 ht ...