Example usage for java.util UUID UUID

List of usage examples for java.util UUID UUID

Introduction

In this page you can find the example usage for java.util UUID UUID.

Prototype

public UUID(long mostSigBits, long leastSigBits) 

Source Link

Document

Constructs a new UUID using the specified data.

Usage

From source file:de.undercouch.bson4jackson.BsonParser.java

/**
 * Reads binary data from the input stream
 * @return the json token read/*ww  w  .  j ava 2s .co m*/
 * @throws IOException if an I/O error occurs
 */
protected JsonToken handleBinary() throws IOException {
    int size = _in.readInt();
    byte subtype = _in.readByte();
    Context ctx = getContext();
    switch (subtype) {
    case BsonConstants.SUBTYPE_BINARY_OLD:
        int size2 = _in.readInt();
        byte[] buf2 = new byte[size2];
        _in.readFully(buf2);
        ctx.value = buf2;
        break;

    case BsonConstants.SUBTYPE_UUID:
        long l1 = _in.readLong();
        long l2 = _in.readLong();
        ctx.value = new UUID(l1, l2);
        break;

    default:
        byte[] buf = new byte[size];
        _in.readFully(buf);
        ctx.value = buf;
        break;
    }

    return JsonToken.VALUE_EMBEDDED_OBJECT;
}

From source file:info.archinnov.achilles.it.TestDSLEntityWithClusterings.java

@Test
public void should_dsl_delete_multiple_partitions() throws Exception {
    //Given/*from www  .ja v  a2s .  c o m*/
    final Map<String, Object> values = new HashMap<>();
    final long id = RandomUtils.nextLong(0L, Long.MAX_VALUE);
    values.put("id1", id);
    values.put("id2", id);
    values.put("id3", id);
    values.put("id4", id);
    values.put("id5", id);

    final UUID uuid = new UUID(0L, 0L);

    values.put("uuid1", uuid);
    values.put("uuid2", uuid);
    values.put("uuid3", uuid);
    values.put("uuid4", uuid);
    values.put("uuid5", uuid);

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    final Date date2 = dateFormat.parse("2015-10-02 00:00:00 GMT");

    values.put("date1", "'2015-10-01 00:00:00+0000'");
    values.put("date2", "'2015-10-02 00:00:00+0000'");
    values.put("date3", "'2015-10-03 00:00:00+0000'");
    values.put("date4", "'2015-10-04 00:00:00+0000'");
    values.put("date5", "'2015-10-05 00:00:00+0000'");

    scriptExecutor.executeScriptTemplate("EntityWithClusteringColumns/insert_many_rows.cql", values);

    /*
    Data are ordered as:
            
    uuid, date5,
    uuid, date4,
    uuid, date3,
    uuid, date2,
    uuid, date1
            
    because date is ORDERED BY DESC natively
     */

    //When
    manager.dsl().delete().value().fromBaseTable().where().id_Eq(id).uuid_Eq(uuid).date_Eq(date2).execute();

    //Then
    final List<Row> actuals = session
            .execute("SELECT value FROM entity_with_clusterings WHERE id = " + id + " AND uuid = " + uuid)
            .all();

    assertThat(actuals).hasSize(5);
    assertThat(actuals.get(0).getString("value")).isEqualTo("val5");
    assertThat(actuals.get(1).getString("value")).isEqualTo("val4");
    assertThat(actuals.get(2).getString("value")).isEqualTo("val3");
    assertThat(actuals.get(3).isNull("value")).isTrue();
    assertThat(actuals.get(4).getString("value")).isEqualTo("val1");
}

From source file:io.rapidpro.androidchannel.RapidPro.java

/**
 * Generates a UUID that should be constant across devices.  This uses a combination of the IMEI if available
 * and the AndroidId.  Note that both of these could be empty but it is very unlikely both are.
 *
 * @return/*  w  w  w .  j a  v  a2s .  c  om*/
 */
public String generateUUID() {
    final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);

    final String tmDevice, androidId;
    tmDevice = "" + tm.getDeviceId();
    androidId = "" + android.provider.Settings.Secure.getString(getContentResolver(),
            android.provider.Settings.Secure.ANDROID_ID);

    UUID deviceUUID = new UUID(androidId.hashCode(), tmDevice.hashCode());
    return deviceUUID.toString();
}

From source file:org.apache.hadoop.hbase.regionserver.wal.HLogKey.java

@Override
public void readFields(DataInput in) throws IOException {
    Version version = Version.UNVERSIONED;
    // HLogKey was not versioned in the beginning.
    // In order to introduce it now, we make use of the fact
    // that encodedRegionName was written with Bytes.writeByteArray,
    // which encodes the array length as a vint which is >= 0.
    // Hence if the vint is >= 0 we have an old version and the vint
    // encodes the length of encodedRegionName.
    // If < 0 we just read the version and the next vint is the length.
    // @see Bytes#readByteArray(DataInput)
    this.scopes = null; // writable HLogKey does not contain scopes
    int len = WritableUtils.readVInt(in);
    byte[] tablenameBytes = null;
    if (len < 0) {
        // what we just read was the version
        version = Version.fromCode(len);
        // We only compress V2 of HLogkey.
        // If compression is on, the length is handled by the dictionary
        if (compressionContext == null || !version.atLeast(Version.COMPRESSED)) {
            len = WritableUtils.readVInt(in);
        }//from  ww  w . j  a  v  a  2  s . co m
    }
    if (compressionContext == null || !version.atLeast(Version.COMPRESSED)) {
        this.encodedRegionName = new byte[len];
        in.readFully(this.encodedRegionName);
        tablenameBytes = Bytes.readByteArray(in);
    } else {
        this.encodedRegionName = Compressor.readCompressed(in, compressionContext.regionDict);
        tablenameBytes = Compressor.readCompressed(in, compressionContext.tableDict);
    }

    this.logSeqNum = in.readLong();
    this.writeTime = in.readLong();

    this.clusterIds.clear();
    if (version.atLeast(Version.INITIAL)) {
        if (in.readBoolean()) {
            // read the older log
            // Definitely is the originating cluster
            clusterIds.add(new UUID(in.readLong(), in.readLong()));
        }
    } else {
        try {
            // dummy read (former byte cluster id)
            in.readByte();
        } catch (EOFException e) {
            // Means it's a very old key, just continue
        }
    }
    try {
        this.tablename = TableName.valueOf(tablenameBytes);
    } catch (IllegalArgumentException iae) {
        if (Bytes.toString(tablenameBytes).equals(TableName.OLD_META_STR)) {
            // It is a pre-namespace meta table edit, continue with new format.
            LOG.info("Got an old .META. edit, continuing with new format ");
            this.tablename = TableName.META_TABLE_NAME;
            this.encodedRegionName = HRegionInfo.FIRST_META_REGIONINFO.getEncodedNameAsBytes();
        } else if (Bytes.toString(tablenameBytes).equals(TableName.OLD_ROOT_STR)) {
            this.tablename = TableName.OLD_ROOT_TABLE_NAME;
            throw iae;
        } else
            throw iae;
    }
    // Do not need to read the clusters information as we are using protobufs from 0.95
}

From source file:org.o3project.odenos.component.federator.FederatorBoundaryTableTest.java

/**
 * Test method for {@link org.o3project.odenos.component.federator.FederatorBoundaryTable#getUniqueId()}.
 * @throws Exception//from w  ww  .jav  a2 s .  c  om
 */
@Test
public void testGetUniqueId() throws Exception {

    /*
     * setting
     */
    PowerMockito.mockStatic(UUID.class);

    PowerMockito.when(UUID.randomUUID()).thenReturn(new UUID(1, 1))
            /*
             * return
             * 00000000-0000-0001-0000-000000000001
             */

            .thenReturn(new UUID(1, 1))
            /*
             * return
             * 00000000-0000-0001-0000-000000000001
             */

            .thenCallRealMethod();
    /*
     * return
     * (random UUID value)
     */

    /*
     * test
     */
    String result = Whitebox.invokeMethod(target, "getUniqueId");

    /*
     * check
     */
    PowerMockito.verifyStatic(times(3));

    assertThat(result, is(notNullValue()));
    assertThat(result, is(not("00000000-0000-0001-0000-000000000001")));

}

From source file:org.midonet.brain.southbound.midonet.MidoVxLanPeerTest.java

@Test
public void testMacPortMapBehavior() throws Exception {
    UUID bridgeId = makeBridge("bridge");
    MacPortMap macPortMap = dataClient.bridgeGetMacTable(bridgeId, Bridge.UNTAGGED_VLAN_ID, false);
    macPortMap.start();//from w  ww.  j  a va 2 s  .co  m

    //UUID port1 = UUID.randomUUID();
    //UUID port2 = UUID.randomUUID();
    UUID port1 = new UUID(0, 2);
    UUID port2 = new UUID(0, 1);

    // a first value is set
    macPortMap.put(mac1, port1);
    assertEquals(port1, macPortMap.get(mac1));
    assertTrue(macPortMap.containsKey(mac1));
    assertTrue(macPortMap.containsValue(port1));
    assertTrue(dataClient.bridgeHasMacPort(bridgeId, Bridge.UNTAGGED_VLAN_ID, mac1, port1));

    // remove value
    macPortMap.removeIfOwner(mac1);
    assertNull(macPortMap.get(mac1));
    assertTrue(!macPortMap.containsKey(mac1));
    assertTrue(!macPortMap.containsValue(port1));
    assertTrue(!dataClient.bridgeHasMacPort(bridgeId, Bridge.UNTAGGED_VLAN_ID, mac1, port1));

    // set a different value
    //macPortMap.put(mac1, port2);
    dataClient.bridgeAddMacPort(bridgeId, Bridge.UNTAGGED_VLAN_ID, mac1, port2);
    assertEquals(port2, macPortMap.get(mac1));
    assertTrue(macPortMap.containsKey(mac1));
    assertTrue(macPortMap.containsValue(port2));
    assertTrue(dataClient.bridgeHasMacPort(bridgeId, Bridge.UNTAGGED_VLAN_ID, mac1, port2));

    // try to re-set the same value (is silently ignored)
    macPortMap.put(mac1, port2);
    assertEquals(port2, macPortMap.get(mac1));
    assertTrue(macPortMap.containsKey(mac1));
    assertTrue(macPortMap.containsValue(port2));
    assertTrue(dataClient.bridgeHasMacPort(bridgeId, Bridge.UNTAGGED_VLAN_ID, mac1, port2));

    // try to re-set the same value via dataclient causes a complain
    try {
        dataClient.bridgeAddMacPort(bridgeId, Bridge.UNTAGGED_VLAN_ID, mac1, port2);
        fail("Adding a previously existing mac->port");
    } catch (StateAccessException e) {
        // ok
    }
    assertEquals(port2, macPortMap.get(mac1));
    assertTrue(macPortMap.containsKey(mac1));
    assertTrue(macPortMap.containsValue(port2));
    assertTrue(dataClient.bridgeHasMacPort(bridgeId, Bridge.UNTAGGED_VLAN_ID, mac1, port2));

    // associate another value to the same key
    // FIXME: the new value should be rejected, or the previous one removed
    // BREAKS the replicated map (entries cannot be deleted).
    //macPortMap.put(mac1, port1);
    dataClient.bridgeAddMacPort(bridgeId, Bridge.UNTAGGED_VLAN_ID, mac1, port1);
    assertTrue(macPortMap.containsKey(mac1));
    assertTrue(dataClient.bridgeHasMacPort(bridgeId, Bridge.UNTAGGED_VLAN_ID, mac1, port1));
    assertTrue(dataClient.bridgeHasMacPort(bridgeId, Bridge.UNTAGGED_VLAN_ID, mac1, port2));

    // FIXME: the following should work
    // FIXME: Or setting multiple values for the same key (above) should not
    // remove value
    //dataClient.bridgeDeleteMacPort(bridgeId, Bridge.UNTAGGED_VLAN_ID,
    //                               mac1, port1);
    //dataClient.bridgeDeleteMacPort(bridgeId, Bridge.UNTAGGED_VLAN_ID,
    //                               mac1, port2);
    //assertNull(macPortMap.get(mac1));
    //assertTrue(!macPortMap.containsKey(mac1));
    //assertTrue(!dataClient.bridgeHasMacPort(bridgeId,
    //                                        Bridge.UNTAGGED_VLAN_ID,
    //                                        mac1, port1));
    //assertTrue(!dataClient.bridgeHasMacPort(bridgeId,
    //                                        Bridge.UNTAGGED_VLAN_ID,
    //                                        mac1, port2));

    macPortMap.stop();
}

From source file:org.spout.engine.filesystem.WorldFiles.java

@SuppressWarnings("unchecked")
private static SpoutEntity loadEntityImpl(World w, CompoundTag tag, String name) {
    CompoundMap map = tag.getValue();/* www  . j  a va2 s . c o  m*/

    @SuppressWarnings("unused")
    byte version = SafeCast.toByte(NBTMapper.toTagValue(map.get("version")), (byte) 0);
    boolean player = SafeCast.toByte(NBTMapper.toTagValue(map.get("player")), (byte) 0) == 1;

    //Read entity
    Float pX = SafeCast.toFloat(NBTMapper.toTagValue(map.get("posX")), Float.MAX_VALUE);
    Float pY = SafeCast.toFloat(NBTMapper.toTagValue(map.get("posY")), Float.MAX_VALUE);
    Float pZ = SafeCast.toFloat(NBTMapper.toTagValue(map.get("posZ")), Float.MAX_VALUE);

    if (pX == Float.MAX_VALUE || pY == Float.MAX_VALUE || pZ == Float.MAX_VALUE) {
        return null;
    }

    float sX = SafeCast.toFloat(NBTMapper.toTagValue(map.get("scaleX")), 1.0F);
    float sY = SafeCast.toFloat(NBTMapper.toTagValue(map.get("scaleY")), 1.0F);
    float sZ = SafeCast.toFloat(NBTMapper.toTagValue(map.get("scaleZ")), 1.0F);

    float qX = SafeCast.toFloat(NBTMapper.toTagValue(map.get("quatX")), 0.0F);
    float qY = SafeCast.toFloat(NBTMapper.toTagValue(map.get("quatY")), 0.0F);
    float qZ = SafeCast.toFloat(NBTMapper.toTagValue(map.get("quatZ")), 0.0F);
    float qW = SafeCast.toFloat(NBTMapper.toTagValue(map.get("quatW")), 1.0F);

    long msb = SafeCast.toLong(NBTMapper.toTagValue(map.get("UUID_msb")), new Random().nextLong());
    long lsb = SafeCast.toLong(NBTMapper.toTagValue(map.get("UUID_lsb")), new Random().nextLong());
    UUID uid = new UUID(msb, lsb);

    int view = SafeCast.toInt(NBTMapper.toTagValue(map.get("view")), 0);
    boolean observer = SafeCast
            .toGeneric(NBTMapper.toTagValue(map.get("observer")), new ByteTag("", (byte) 0), ByteTag.class)
            .getBooleanValue();

    //Setup data
    boolean controllerDataExists = SafeCast.toGeneric(NBTMapper.toTagValue(map.get("controller_data_exists")),
            new ByteTag("", (byte) 0), ByteTag.class).getBooleanValue();
    byte[] dataMap = null;
    if (controllerDataExists) {
        dataMap = SafeCast.toByteArray(NBTMapper.toTagValue(map.get("controller_data")), new byte[0]);
    }

    //Setup entity
    Region r = w.getRegionFromBlock(Math.round(pX), Math.round(pY), Math.round(pZ),
            player ? LoadOption.LOAD_GEN : LoadOption.NO_LOAD);
    if (r == null) {
        // TODO - this should never happen - entities should be located in the chunk that was just loaded
        Spout.getLogger().info("Attempted to load entity to unloaded region");
        Thread.dumpStack();
        return null;
    }
    final Transform t = new Transform(new Point(r.getWorld(), pX, pY, pZ),
            new Quaternion(qX, qY, qZ, qW, false), new Vector3(sX, sY, sZ));

    ListTag<StringTag> components = (ListTag<StringTag>) map.get("components");
    List<Class<? extends Component>> types = new ArrayList<Class<? extends Component>>(
            components.getValue().size());
    for (StringTag component : components.getValue()) {
        try {
            try {
                Class<? extends Component> clazz = (Class<? extends Component>) CommonClassLoader
                        .findPluginClass(component.getValue());
                types.add(clazz);
            } catch (ClassNotFoundException e) {
                Class<? extends Component> clazz = (Class<? extends Component>) Class
                        .forName(component.getValue());
                types.add(clazz);
            }
        } catch (ClassNotFoundException e) {
            Spout.getLogger().log(Level.SEVERE, "Unable to find component class " + component.getValue(), e);
        }
    }

    SpoutEntity e;
    if (!player) {
        e = new SpoutEntity(t, view, uid, false, dataMap, types.toArray(new Class[types.size()]));
        e.setObserver(observer);
    } else {
        e = new SpoutPlayer(name, t, view, uid, false, dataMap, types.toArray(new Class[types.size()]));
    }

    return e;
}

From source file:org.openhealthtools.openxds.repository.Utility.java

public UUID getNewUUID() {
    secRand.nextBytes(secRandBuf16);//from  w  w w . j  ava  2 s  .  com
    secRandBuf16[6] &= 0x0f;
    secRandBuf16[6] |= 0x40; /* version 4 */
    secRandBuf16[8] &= 0x3f;
    secRandBuf16[8] |= 0x80; /* IETF variant */
    secRandBuf16[10] |= 0x80; /* multicast bit */

    long mostSig = 0;

    for (int i = 0; i < 8; i++) {
        mostSig = (mostSig << 8) | (secRandBuf16[i] & 0xff);
    }

    long leastSig = 0;

    for (int i = 8; i < 16; i++) {
        leastSig = (leastSig << 8) | (secRandBuf16[i] & 0xff);
    }

    return new UUID(mostSig, leastSig);
}

From source file:org.apache.hadoop.hbase.wal.WALKey.java

public void readFieldsFromPb(org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey walKey,
        WALCellCodec.ByteStringUncompressor uncompressor) throws IOException {
    if (this.compressionContext != null) {
        this.encodedRegionName = uncompressor.uncompress(walKey.getEncodedRegionName(),
                compressionContext.regionDict);
        byte[] tablenameBytes = uncompressor.uncompress(walKey.getTableName(), compressionContext.tableDict);
        this.tablename = TableName.valueOf(tablenameBytes);
    } else {/*from  w  w  w  .ja va  2  s  . c om*/
        this.encodedRegionName = walKey.getEncodedRegionName().toByteArray();
        this.tablename = TableName.valueOf(walKey.getTableName().toByteArray());
    }
    clusterIds.clear();
    if (walKey.hasClusterId()) {
        //When we are reading the older log (0.95.1 release)
        //This is definitely the originating cluster
        clusterIds
                .add(new UUID(walKey.getClusterId().getMostSigBits(), walKey.getClusterId().getLeastSigBits()));
    }
    for (HBaseProtos.UUID clusterId : walKey.getClusterIdsList()) {
        clusterIds.add(new UUID(clusterId.getMostSigBits(), clusterId.getLeastSigBits()));
    }
    if (walKey.hasNonceGroup()) {
        this.nonceGroup = walKey.getNonceGroup();
    }
    if (walKey.hasNonce()) {
        this.nonce = walKey.getNonce();
    }
    this.scopes = null;
    if (walKey.getScopesCount() > 0) {
        this.scopes = new TreeMap<byte[], Integer>(Bytes.BYTES_COMPARATOR);
        for (FamilyScope scope : walKey.getScopesList()) {
            byte[] family = (compressionContext == null) ? scope.getFamily().toByteArray()
                    : uncompressor.uncompress(scope.getFamily(), compressionContext.familyDict);
            this.scopes.put(family, scope.getScopeType().getNumber());
        }
    }
    this.logSeqNum = walKey.getLogSequenceNumber();
    this.writeTime = walKey.getWriteTime();
    if (walKey.hasOrigSequenceNumber()) {
        this.origLogSeqNum = walKey.getOrigSequenceNumber();
    }
}

From source file:org.apache.jackrabbit.oak.plugins.segment.file.TarReader.java

Set<UUID> getUUIDs() {
    Set<UUID> uuids = newHashSetWithExpectedSize(index.remaining() / 24);
    int position = index.position();
    while (position < index.limit()) {
        uuids.add(new UUID(index.getLong(position), index.getLong(position + 8)));
        position += 24;/*w ww. j a va  2 s.  c  o m*/
    }
    return uuids;
}