Java Code Examples for java.util.UUID#randomUUID()

The following examples show how to use java.util.UUID#randomUUID() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PluginRegistryUnitTest.java    From hop with Apache License 2.0 6 votes vote down vote up
/**
 * Test that additional plugin mappings can be added via the PluginRegistry.
 */
@Test
public void testSupplementalPluginMappings() throws Exception {
  PluginRegistry registry = PluginRegistry.getInstance();
  IPlugin mockPlugin = mock( IPlugin.class );
  when( mockPlugin.getIds() ).thenReturn( new String[] { "mockPlugin" } );
  when( mockPlugin.matches( "mockPlugin" ) ).thenReturn( true );
  when( mockPlugin.getName() ).thenReturn( "mockPlugin" );
  doReturn( LoggingPluginType.class ).when( mockPlugin ).getPluginType();
  registry.registerPlugin( LoggingPluginType.class, mockPlugin );

  registry.addClassFactory( LoggingPluginType.class, String.class, "mockPlugin", () -> "Foo" );
  String result = registry.loadClass( LoggingPluginType.class, "mockPlugin", String.class );
  assertEquals( "Foo", result );
  assertEquals( 2, registry.getPlugins( LoggingPluginType.class ).size() );

  // Now add another mapping and verify that it works and the existing supplementalPlugin was reused.
  UUID uuid = UUID.randomUUID();
  registry.addClassFactory( LoggingPluginType.class, UUID.class, "mockPlugin", () -> uuid );
  UUID out = registry.loadClass( LoggingPluginType.class, "mockPlugin", UUID.class );
  assertEquals( uuid, out );
  assertEquals( 2, registry.getPlugins( LoggingPluginType.class ).size() );
}
 
Example 2
Source File: ClickHouseValueFormatterTest.java    From clickhouse-jdbc with Apache License 2.0 6 votes vote down vote up
@Test
public void testFormatBytesUUID() {
    UUID uuid = UUID.randomUUID();
    byte[] bytes = ByteBuffer.allocate(16)
        .putLong(uuid.getMostSignificantBits())
        .putLong(uuid.getLeastSignificantBits())
        .array();
    String formattedBytes = ClickHouseValueFormatter.formatBytes(bytes);
    byte[] reparsedBytes = new byte[16];
    for (int i = 0; i < 16; i++) {
        reparsedBytes[i] =  (byte)
            ((Character.digit(formattedBytes.charAt(i * 4 + 2), 16) << 4)
            + Character.digit(formattedBytes.charAt(i * 4 + 3), 16));
    }
    assertEquals(reparsedBytes, bytes);
}
 
Example 3
Source File: CertificateServiceImplTest.java    From ariADDna with Apache License 2.0 6 votes vote down vote up
@Test
public void getAllCertificatesTest() throws Exception {
    UUID uuid1 = UUID.randomUUID();
    UUID uuid2 = UUID.randomUUID();
    UUID uuid3 = UUID.randomUUID();
    CertificateDTO certificateDTO1 = new CertificateDTO();
    CertificateDTO certificateDTO2 = new CertificateDTO();
    CertificateDTO certificateDTO3 = new CertificateDTO();
    certificateDTO1.setActive(true);
    certificateDTO1.setUuid(uuid1.toString());
    certificateDTO2.setUuid(uuid2.toString());
    certificateDTO3.setUuid(uuid3.toString());
    certificateService.save(certificateDTO1);
    certificateService.save(certificateDTO2);
    certificateService.save(certificateDTO3);

    List<CertificateDTO> certificateDTOList = certificateService.getAllCertificates();
    assertEquals(certificateDTOList.size(), 3);
}
 
Example 4
Source File: CivilizationsWorldSaveData.java    From ToroQuest with GNU General Public License v3.0 6 votes vote down vote up
protected Province buildNewProvince(int chunkX, int chunkZ) {
	Province province;
	province = new Province();
	province.id = UUID.randomUUID();
	province.chunkX = chunkX;
	province.chunkZ = chunkZ;
	province.civilization = randomCivilizationType();
	province.name = ProvinceNames.random(new Random());
	province.hasLord = false;
	province.lowerVillageBoundX = chunkX;
	province.upperVillageBoundX = chunkX;
	province.lowerVillageBoundZ = chunkZ;
	province.upperVillageBoundZ = chunkZ;
	province.computeSize();

	addProvinceToSaveData(province);

	return province;
}
 
Example 5
Source File: StringTypeTest.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
@Test
public void testDecodeNonStringWhenStringExpectedReportsUsefulError() {
    final DecoderImpl decoder = new DecoderImpl();
    final EncoderImpl encoder = new EncoderImpl(decoder);

    AMQPDefinedTypes.registerAllTypes(decoder, encoder);

    final ByteBuffer buffer = ByteBuffer.allocate(64);
    final UUID encoded = UUID.randomUUID();

    buffer.put(EncodingCodes.UUID);
    buffer.putLong(encoded.getMostSignificantBits());
    buffer.putLong(encoded.getLeastSignificantBits());
    buffer.flip();

    byte[] copy = new byte[buffer.remaining()];
    buffer.get(copy);

    CompositeReadableBuffer composite = new CompositeReadableBuffer();
    composite.append(copy);

    decoder.setBuffer(composite);

    TypeConstructor<?> stringType = decoder.peekConstructor();
    assertEquals(UUID.class, stringType.getTypeClass());

    composite.mark();

    try {
        decoder.readString();
    } catch (ProtonException ex) {
        // Should indicate the type that it found in the error
        assertTrue(ex.getMessage().contains(EncodingCodes.toString(EncodingCodes.UUID)));
    }

    composite.reset();
    UUID actual = decoder.readUUID();
    assertEquals(encoded, actual);
}
 
Example 6
Source File: RocksDBIncrementalRestoreOperation.java    From flink with Apache License 2.0 5 votes vote down vote up
public RocksDBIncrementalRestoreOperation(
	String operatorIdentifier,
	KeyGroupRange keyGroupRange,
	int keyGroupPrefixBytes,
	int numberOfTransferringThreads,
	CloseableRegistry cancelStreamRegistry,
	ClassLoader userCodeClassLoader,
	Map<String, RocksDbKvStateInfo> kvStateInformation,
	StateSerializerProvider<K> keySerializerProvider,
	File instanceBasePath,
	File instanceRocksDBPath,
	DBOptions dbOptions,
	Function<String, ColumnFamilyOptions> columnFamilyOptionsFactory,
	RocksDBNativeMetricOptions nativeMetricOptions,
	MetricGroup metricGroup,
	@Nonnull Collection<KeyedStateHandle> restoreStateHandles,
	@Nonnull RocksDbTtlCompactFiltersManager ttlCompactFiltersManager,
	@Nonnegative long writeBatchSize) {
	super(keyGroupRange,
		keyGroupPrefixBytes,
		numberOfTransferringThreads,
		cancelStreamRegistry,
		userCodeClassLoader,
		kvStateInformation,
		keySerializerProvider,
		instanceBasePath,
		instanceRocksDBPath,
		dbOptions,
		columnFamilyOptionsFactory,
		nativeMetricOptions,
		metricGroup,
		restoreStateHandles,
		ttlCompactFiltersManager);
	this.operatorIdentifier = operatorIdentifier;
	this.restoredSstFiles = new TreeMap<>();
	this.lastCompletedCheckpointId = -1L;
	this.backendUID = UUID.randomUUID();
	checkArgument(writeBatchSize >= 0, "Write batch size have to be no negative.");
	this.writeBatchSize = writeBatchSize;
}
 
Example 7
Source File: LocalPeer.java    From jReto with MIT License 5 votes vote down vote up
/**
   * Establishes a multicast connection to a set of peers.
   * @param destinations The RemotePeers to establish the connection with.
   * @return A Connection object. It can be used to send data immediately (the transfers will be started once the connection was successfully established).
   * */	
public Connection connect(Set<RemotePeer> destinations) {
	Set<Node> destinationNodes = new HashSet<>();
	for (RemotePeer peer : destinations) destinationNodes.add(peer.getNode());
	
	UUID connectionIdentifier = UUID.randomUUID();
	PacketConnection packetConnection = new PacketConnection(null, connectionIdentifier, destinationNodes);
	this.establishedConnections.put(connectionIdentifier, packetConnection);
		
	final Connection transferConnection = new Connection(packetConnection, this.localPeerIdentifier, this.executor, true, this.packetConnectionManager);
	transferConnection.attemptReconnect();

	return transferConnection;
}
 
Example 8
Source File: TableBalancerResumedTableTest.java    From flex-poker with GNU General Public License v2.0 5 votes vote down vote up
@Test
void testTwoBalancedTablesOnePaused() {
    var subjectTableId = UUID.randomUUID();
    var tableToPlayersMap = createTableToPlayersMap(subjectTableId, 8, 8);
    var otherTableId = tableToPlayersMap.keySet().stream()
            .filter(x -> !x.equals(subjectTableId)).findFirst().get();

    var tableBalancer = new TableBalancer(UUID.randomUUID(), 9);
    var event = tableBalancer.createSingleBalancingEvent(subjectTableId, Collections.singleton(otherTableId),
            tableToPlayersMap, createDefaultChipMapForSubjectTable(subjectTableId, tableToPlayersMap));
    assertEquals(TableResumedAfterBalancingEvent.class, event.get().getClass());
    assertEquals(otherTableId, ((TableResumedAfterBalancingEvent) event.get()).getTableId());
}
 
Example 9
Source File: PermObj.java    From directory-fortress-core with Apache License 2.0 5 votes vote down vote up
/**
 * This attribute is required but is set automatically by Fortress DAO class before object is persisted to ldap.
 * This generated internal id is associated with PermObj.  This method is used by DAO class and
 * is not available to outside classes.   The generated attribute maps to 'ftId' in 'ftObject' object class.
 */
public void setInternalId()
{
    // generate a unique id`:
    UUID uuid = UUID.randomUUID();
    this.internalId = uuid.toString();

    //UID iid = new UID();
    // assign the unique id to the internal id of the entity:
    //this.internalId = iid.toString();
}
 
Example 10
Source File: MessageRequest.java    From peer-os with Apache License 2.0 5 votes vote down vote up
public MessageRequest( final Payload payload, final String recipient, final Map<String, String> headers )
{
    this.id = UUID.randomUUID();
    this.payload = payload;
    this.recipient = recipient;
    this.headers = headers;
}
 
Example 11
Source File: StorPoolDefinition.java    From linstor-server with GNU General Public License v3.0 5 votes vote down vote up
StorPoolDefinition(
    UUID id,
    ObjectProtection objProtRef,
    StorPoolName nameRef,
    StorPoolDefinitionDatabaseDriver dbDriverRef,
    PropsContainerFactory propsContainerFactory,
    TransactionObjectFactory transObjFactory,
    Provider<? extends TransactionMgr> transMgrProviderRef,
    Map<NodeName, StorPool> storPoolsMapRef
)
    throws DatabaseException
{
    super(transMgrProviderRef);

    uuid = id;
    dbgInstanceId = UUID.randomUUID();
    objProt = objProtRef;
    name = nameRef;
    dbDriver = dbDriverRef;
    storPools = transObjFactory.createTransactionMap(storPoolsMapRef, null);

    props = propsContainerFactory.getInstance(
        PropsContainer.buildPath(nameRef)
    );
    deleted = transObjFactory.createTransactionSimpleObject(this, false, null);

    transObjs = Arrays.<TransactionObject>asList(
        objProt,
        storPools,
        props,
        deleted
    );
    activateTransMgr();
}
 
Example 12
Source File: MapSideDataCollectOperationTest.java    From crate with Apache License 2.0 5 votes vote down vote up
@Test
public void testFileUriCollect() throws Exception {
    Functions functions = getFunctions();
    FileCollectSource fileCollectSource = new FileCollectSource(functions, clusterService, Collections.emptyMap());

    File tmpFile = temporaryFolder.newFile("fileUriCollectOperation.json");
    try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(tmpFile), StandardCharsets.UTF_8)) {
        writer.write("{\"name\": \"Arthur\", \"id\": 4, \"details\": {\"age\": 38}}\n");
        writer.write("{\"id\": 5, \"name\": \"Trillian\", \"details\": {\"age\": 33}}\n");
    }

    FileUriCollectPhase collectNode = new FileUriCollectPhase(
        UUID.randomUUID(),
        0,
        "test",
        Collections.singletonList("noop_id"),
        Literal.of(Paths.get(tmpFile.toURI()).toUri().toString()),
        Arrays.asList(
            createReference("name", DataTypes.STRING),
            createReference(new ColumnIdent("details", "age"), DataTypes.INTEGER)
        ),
        Collections.emptyList(),
        null,
        false,
        FileUriCollectPhase.InputFormat.JSON
    );
    TestingRowConsumer consumer = new TestingRowConsumer();
    CollectTask collectTask = mock(CollectTask.class);
    BatchIterator<Row> iterator = fileCollectSource.getIterator(
        CoordinatorTxnCtx.systemTransactionContext(), collectNode, collectTask, false);
    consumer.accept(iterator, null);
    assertThat(new CollectionBucket(consumer.getResult()), contains(
        isRow("Arthur", 38),
        isRow("Trillian", 33)
    ));
}
 
Example 13
Source File: TinkerPopOperationsTest.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void replaceEntityUpdatesTheKnownProperties() throws Exception {
  Vres vres = createConfiguration();
  Collection collection = vres.getCollection("testthings").get();
  UUID id = UUID.randomUUID();
  TinkerPopGraphManager graphManager = newGraph()
    .withVertex(v -> v
      .withTimId(id)
      .withVre("test")
      .withType("thing")
      .withProperty("testthing_prop1", "oldValue")
      .withProperty("isLatest", true)
      .withProperty("rev", 1)
    ).wrap();
  TinkerPopOperations instance = forGraphWrapperAndMappings(graphManager, vres);
  ArrayList<TimProperty<?>> properties = Lists.newArrayList(
    new StringProperty("prop1", "newValue"),
    new StringProperty("prop2", "prop2Value")
  );
  UpdateEntity updateEntity = new UpdateEntity(id, properties, 1);
  long timeStamp = Instant.now().toEpochMilli();
  updateEntity.setModified(new Change(timeStamp, "userId", null));

  instance.replaceEntity(collection, updateEntity);

  Vertex vertex = graphManager.getGraph().traversal().V().has("tim_id", id.toString()).has("isLatest", true).next();
  assertThat(vertex, is(
    likeVertex().withProperty("testthing_prop1", "newValue").withProperty("testthing_prop2", "prop2Value")
  ));
}
 
Example 14
Source File: MultiServerUserRegistry.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private static String generateId() {
	String host;
	try {
		host = InetAddress.getLocalHost().getHostAddress();
	}
	catch (UnknownHostException e) {
		host = "unknown";
	}
	return host + "-" + UUID.randomUUID();
}
 
Example 15
Source File: NotificationPublisherTest.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
@Test
public void testUuid() {
    UUID uuid = UUID.randomUUID();
    NotificationPublisher publisher = new NotificationPublisher();
    publisher.setUuid(uuid);
    Assert.assertEquals(uuid.toString(), publisher.getUuid().toString());
}
 
Example 16
Source File: GridCacheMvccFlagsTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 *
 */
@Test
public void testAllFalseFlags() {
    GridCacheAdapter<String, String> cache = grid.internalCache(DEFAULT_CACHE_NAME);

    GridCacheTestEntryEx entry = new GridCacheTestEntryEx(cache.context(), "1");

    UUID id = UUID.randomUUID();

    GridCacheVersion ver = new GridCacheVersion(1, 0, 0, 0);

    GridCacheMvccCandidate c = new GridCacheMvccCandidate(
        entry,
        id,
        id,
        ver,
        1,
        ver,
        false,
        false,
        false,
        false,
        false,
        false,
        null,
        false
    );

    short flags = c.flags();

    info("Candidate: " + c);

    for (GridCacheMvccCandidate.Mask mask : GridCacheMvccCandidate.Mask.values())
        assertFalse("Mask check failed [mask=" + mask + ", c=" + c + ']', mask.get(flags));
}
 
Example 17
Source File: FileUsageLoggingClientTest.java    From rtg-tools with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void testMultipleMessageWriting() throws Exception {
  // Randomly write a mixture of open and close events and random junk
  try (TestDirectory dir = new TestDirectory()) {
    final FileUsageLoggingClient client = new FileUsageLoggingClient(dir, new UsageConfiguration(new Properties()), false);
    final Date date = new Date();
    final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
    final String expectedFilename = df.format(date) + ".usage";
    final File file = new File(dir, expectedFilename);
    final Random r = new Random();
    final TreeSet<UUID> notYetEnded = new TreeSet<>();
    for (int k = 0; k < 200; ++k) {
      switch (r.nextInt(3)) {
        case 0:
          final UUID code = UUID.randomUUID();
          client.recordBeginning("unitTest", code);
          notYetEnded.add(code);
          break;
        case 1:
          final UUID closeCode = notYetEnded.pollFirst();
          if (closeCode != null) {
            client.recordEnd(r.nextInt(), "unitTest", closeCode, true);
          }
          break;
        default:
          FileUtils.appendToFile(file,  JUNK[r.nextInt(JUNK.length)] + StringUtils.LS);
          break;
      }
    }
    // Some messages will not be ended, but that is ok
    final File[] files = dir.listFiles();
    assertNotNull(files);
    assertEquals(1, files.length);
    final File usageOut = files[0];
    assertEquals(df.format(new Date()) + ".usage", usageOut.getName());
    final String str = FileUtils.fileToString(usageOut);
    //System.out.println(str);
    final String[] outputLines = str.split("\r\n|\n");
    String prevHash = "";
    for (final String line : outputLines) {
      final String[] line1 = line.split("\tS="); //splits into message and md5 sum
      if (line1.length > 1) {
        assertEquals(MD5Utils.md5(prevHash + line1[0]), line1[1]);
        prevHash = line1[1];
      }
    }
  }
}
 
Example 18
Source File: DispatcherFactory.java    From flink with Apache License 2.0 4 votes vote down vote up
default String generateEndpointIdWithUUID() {
	return getEndpointId() + UUID.randomUUID();
}
 
Example 19
Source File: SpatialQProcessor.java    From defense-solutions-proofs-of-concept with Apache License 2.0 4 votes vote down vote up
public ArrayList<Object> CreateQueries(GeoEvent ge) throws Exception {
	Set<String> eventTokens = eventTokenMap.keySet();
	Iterator<String> eventIt = eventTokens.iterator();
	while (eventIt.hasNext()) {
		String et = eventIt.next();
		String fn = eventTokenMap.get(et);
		String val = null;
		if (ge.getField(fn) != null) {
			val = ge.getField(fn).toString();
			wc = wc.replace(et, val);
		}
	}
	ArrayList<Object> queries = new ArrayList<Object>();
	URL url = conn.getUrl();
	String protocol = url.getProtocol();
	String host = url.getHost();
	Integer port = url.getPort();
	String path = url.getPath();
	String baseUrl = null;
	String curPath=null;
	if (endpoint != null)
	{
		curPath = endpoint;
	}
	else
	{
		baseUrl = protocol + "://" + host +":" + port.toString() + path + "rest/services";
		curPath = baseUrl + "/" + folder + "/" + service+ "/FeatureServer/" + layerId;
	}
	//String baseUrl = url.getProtocol() + "://" + url.getHost() + ":"
			//+ url.getPort() + url.getPath() + "rest/services/";
	if(connectionType == ConnectionType.AGOL)
	{
		
		//String agolUrl = DefaultAGOLConnection.ARCGIS_Dot_Com_URL;
		//token = agolconn.getToken();
	}
			
	String restpath = curPath + "/query?";
	HashMap<String, Object> query = new HashMap<String, Object>();
	HashMap<String, String> fieldMap = new HashMap<String, String>();

	String fldsString = field;
	String[] fieldArray = fldsString.split(",");
	for (String f : fieldArray) {
		String tk = tokenizer.tokenize(f);
		fieldMap.put(f, tk);
	}

	query.put("restpath", restpath);
	query.put("path", curPath);
	query.put("whereclause", wc);
	query.put("fields", fldsString);
	query.put("tokenMap", fieldMap);
	query.put("usingdist", calcDist);
	query.put("layer", layer.getName());
	UUID uid = UUID.randomUUID();
	query.put("id", uid);
	queries.add(query);
	return queries;
}
 
Example 20
Source File: BigdataGraphEmbedded.java    From database with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Determines the {@link UUID} which will be associated with the
 * {@link IRunningQuery}. If {@link QueryHints#QUERYID} has already been
 * used by the application to specify the {@link UUID} then that
 * {@link UUID} is noted. Otherwise, a random {@link UUID} is generated and
 * assigned to the query by binding it on the query hints.
 * <p>
 * Note: The ability to provide metadata from the {@link ASTContainer} in
 * the {@link StatusServlet} or the "EXPLAIN" page depends on the ability to
 * cross walk the queryIds as established by this method.
 * 
 * @param query
 *            The query.
 * 
 * @param queryUuid
 * 
 * @return The {@link UUID} which will be associated with the
 *         {@link IRunningQuery} and never <code>null</code>.
 */
protected UUID setQueryId(final ASTContainer astContainer, UUID queryUuid) {

	// Figure out the effective UUID under which the query will run.
	final String queryIdStr = astContainer.getQueryHint(QueryHints.QUERYID);
	if (queryIdStr == null) {
		// Not specified, so generate and set on query hint.
		queryUuid = UUID.randomUUID();
	} 

	astContainer.setQueryHint(QueryHints.QUERYID, queryUuid.toString());

	return queryUuid;
}