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

The following are Jave code examples for showing how to use randomUUID() of the java.util.UUID class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: swblocks-decisiontree   File: ValueGroupChangeBuilderTest.java   View Source Code Vote up 6 votes
@Test
public void createsNewChange() {
    this.builder.with(ValueGroupChangeBuilder::drivers, Arrays.asList("Test1", "Test2", "Test4"));
    this.builder.with(ValueGroupChangeBuilder::changeRange, new DateRange(NOW, NOW.plus(Period.ofWeeks(1))));
    this.builder.with(ValueGroupChangeBuilder::driver, "TestDriver");

    final UUID id = UUID.randomUUID();
    this.builder.with(ValueGroupChangeBuilder::ruleCodes, Collections.singletonList(id));

    final List<ValueGroupChange> changes = this.builder.build();
    assertThat(changes, hasSize(1));

    final ValueGroupChange change = changes.get(0);

    assertValueGroupChange(change, Type.NEW, null, "TestValueGroup",
            NOW, NOW.plus(Period.ofWeeks(1)), Arrays.asList("Test1", "Test2", "Test4"));
    assertEquals("TestDriver", change.getValueGroup().getDriverName());
    assertThat(change.getValueGroup().getRuleCodes(), contains(id));
}
 
Example 2
Project: loom-core   File: AbstractAggregateRootSpecs.java   View Source Code Vote up 6 votes
@Test
public void raise_adds_pending_event_correctly() {
    // Arrange
    AggregateRootProxy sut = new AggregateRootProxy(UUID.randomUUID());
    AbstractDomainEvent domainEvent = Mockito.spy(AbstractDomainEvent.class);
    final ZonedDateTime lowerBoundOfOccurrenceTime = ZonedDateTime.now();

    // Act
    sut.raise(domainEvent);

    // Assert
    List<DomainEvent> actual = new ArrayList<>();
    sut.pollAllPendingEvents().forEach(actual::add);
    Assert.assertEquals(1, actual.size());
    Assert.assertEquals(domainEvent, actual.get(0));
    Assert.assertEquals(1, actual.get(0).getVersion());
    Assert.assertEquals(sut.getId(), actual.get(0).getAggregateId());
    Assert.assertTrue(
            lowerBoundOfOccurrenceTime.compareTo(actual.get(0).getOccurrenceTime()) <= 0);
    Assert.assertTrue(ZonedDateTime.now().compareTo(actual.get(0).getOccurrenceTime()) >= 0);
}
 
Example 3
Project: elastic-db-tools-for-java   File: ShardMapManager.java   View Source Code Vote up 6 votes
/**
 * Tries to obtains a <see cref="ListShardMap{KeyT}"/> given the name. <typeparam name="KeyT">Key type.</typeparam>
 *
 * @param shardMapName
 *            Name of shard map.
 * @return ListShardMap
 */
public <KeyT> boolean tryGetListShardMap(String shardMapName,
        ShardKeyType keyType,
        ReferenceObjectHelper<ListShardMap<KeyT>> shardMap) {
    ShardMapManager.validateShardMapName(shardMapName);

    try (ActivityIdScope activityIdScope = new ActivityIdScope(UUID.randomUUID())) {
        log.info("ShardMapManager TryGetListShardMap Start; ShardMap: {}", shardMapName);

        shardMap.argValue = (ListShardMap<KeyT>) this.lookupAndConvertShardMapHelper("TryGetListShardMap", shardMapName, keyType, false);

        log.info("Complete; ShardMap: {}", shardMapName);

        return shardMap.argValue != null;
    }
}
 
Example 4
Project: spring-session-data-mongodb   File: AbstractMongoRepositoryITest.java   View Source Code Vote up 6 votes
@Test
public void findByPrincipalNameNoPrincipalNameChange() throws Exception {
	
	String principalName = "findByPrincipalNameNoPrincipalNameChange"
			+ UUID.randomUUID();
	MongoSession toSave = this.repository.createSession();
	toSave.setAttribute(INDEX_NAME, principalName);

	this.repository.save(toSave);

	toSave.setAttribute("other", "value");
	this.repository.save(toSave);

	Map<String, MongoSession> findByPrincipalName = this.repository
			.findByIndexNameAndIndexValue(INDEX_NAME, principalName);

	assertThat(findByPrincipalName).hasSize(1);
	assertThat(findByPrincipalName.keySet()).containsOnly(toSave.getId());
}
 
Example 5
Project: wurmloch-crdt   File: USetTest.java   View Source Code Vote up 6 votes
@SuppressWarnings("unchecked")
@Test
public void shouldSendNotificationForAdds() {
    // given:
    final UUID uuid1 = UUID.randomUUID();
    final UUID uuid2 = UUID.randomUUID();
    final TestSubscriber<CrdtCommand> subscriber = TestSubscriber.create();
    final USet<UUID> set = new USet<>("ID_1");
    set.subscribe(subscriber);

    // when:
    set.add(uuid1);
    set.add(uuid2);

    // then:
    subscriber.assertNotComplete();
    subscriber.assertNoErrors();
    assertThat(subscriber.values(), contains(
            new AddCommandMatcher<>(set.getCrdtId(), uuid1),
            new AddCommandMatcher<>(set.getCrdtId(), uuid2)
    ));
}
 
Example 6
Project: mod-circulation-storage   File: LoansApiTest.java   View Source Code Vote up 6 votes
@Test
public void cannotProvideAdditionalPropertiesInLoanStatus()
  throws InterruptedException,
  MalformedURLException,
  TimeoutException,
  ExecutionException {

  UUID id = UUID.randomUUID();

  JsonObject requestWithAdditionalProperty = new LoanRequestBuilder()
    .withId(id)
    .create();

  requestWithAdditionalProperty.getJsonObject("status")
    .put("somethingAdditional", "foo");

  CompletableFuture<JsonErrorResponse> createCompleted = new CompletableFuture();

  client.post(loanStorageUrl(), requestWithAdditionalProperty,
    StorageTestSuite.TENANT_ID, ResponseHandler.jsonErrors(createCompleted));

  JsonErrorResponse response = createCompleted.get(5, TimeUnit.SECONDS);

  assertThat(response.getStatusCode(), is(UNPROCESSABLE_ENTITY));
  assertThat(response.getErrors(), hasSoleMessgeContaining("Unrecognized field"));
}
 
Example 7
Project: java-memory-assistant   File: HeapDumpNameFormatter.java   View Source Code Vote up 5 votes
HeapDumpNameFormatter(final String pattern, final String hostName) {
  this(pattern, hostName, new Provider<UUID>() {
    @Override
    public UUID get() {
      return UUID.randomUUID();
    }
  });
}
 
Example 8
Project: swblocks-decisiontree   File: DecisionTreeRuleMatcher.java   View Source Code Vote up 5 votes
@Test
public void testRuleMatcher() {
    final Map<String, String> outputDriver = Collections.singletonMap("outputDriver", "result");

    final DecisionTreeRule decisionTreeRule1 =
            new DecisionTreeRule(new UUID(0, 1), UUID.randomUUID(),
                    new InputDriver[]{new StringDriver("Test1"), new StringDriver("Test2")},
                    outputDriver, null, null);

    assertThat(decisionTreeRule1, isSame(decisionTreeRule1));
    assertThat(decisionTreeRule1, isSame(new DecisionTreeRule(new UUID(0, 1),
            UUID.randomUUID(), new InputDriver[]{new StringDriver("Test1"), new StringDriver("Test2")},
            outputDriver, null, null)));
}
 
Example 9
Project: spring-oauth2-cassandra-token-store   File: TokenStoreBaseTests.java   View Source Code Vote up 5 votes
@Test
public void testFindAccessTokensByClientIdAndUserName() {
	String clientId = "id" + UUID.randomUUID();
	String name = "test2" + UUID.randomUUID();
	OAuth2Authentication expectedAuthentication = new OAuth2Authentication(RequestTokenFactory.createOAuth2Request(clientId, false), new TestAuthentication(name, false));
	OAuth2AccessToken expectedOAuth2AccessToken = new DefaultOAuth2AccessToken("testToken");
	getTokenStore().storeAccessToken(expectedOAuth2AccessToken, expectedAuthentication);

	Collection<OAuth2AccessToken> actualOAuth2AccessTokens = getTokenStore().findTokensByClientIdAndUserName(clientId, name);
	assertEquals(1, actualOAuth2AccessTokens.size());
}
 
Example 10
Project: Mevius-IO   File: MeviusClient.java   View Source Code Vote up 5 votes
public MeviusClient(SocketChannel channel, PublicKey publickey, MeviusHandler handler) {
	this.sc = channel;
	this.handler = handler;
	handler.getClientHandler().join(this);
	uuid = UUID.randomUUID();
	self = false;
	this.publickey = publickey;
}
 
Example 11
Project: wurmloch-crdt   File: USetTest.java   View Source Code Vote up 5 votes
@Test
public void shouldRemoveElements() {
    // given:
    final UUID uuid1 = UUID.randomUUID();
    final UUID uuid2 = UUID.randomUUID();
    final UUID uuid3 = UUID.randomUUID();
    final Set<UUID> expected = new HashSet<>();
    expected.addAll(Arrays.asList(uuid1, uuid2, uuid3));
    final USet<UUID> set = new USet<>("ID_1");
    set.addAll(expected);
    final Iterator<UUID> it = set.iterator();

    // when:
    final UUID e1 = it.next();
    it.remove();
    expected.remove(e1);

    // then:
    assertThat(set, equalTo(expected));

    // when:
    final UUID e2 = it.next();
    it.remove();
    expected.remove(e2);

    // then:
    assertThat(set, equalTo(expected));

    // when:
    it.next();
    it.remove();

    // then:
    assertThat(set, empty());
}
 
Example 12
Project: act-platform   File: SecurityContextTest.java   View Source Code Vote up 5 votes
@Test(expected = AuthenticationFailedException.class)
public void testCheckPermissionForOrganizationThrowsAuthenticationFailedException() throws Exception {
  UUID organizationID = UUID.randomUUID();
  when(identityResolver.resolveOrganizationIdentity(organizationID)).thenReturn(organization);
  when(accessController.hasPermission(credentials, viewFactObjects, organization)).thenThrow(InvalidCredentialsException.class);
  context.checkPermission(viewFactObjects, organizationID);
}
 
Example 13
Project: swblocks-decisiontree   File: ValueGroupTest.java   View Source Code Vote up 4 votes
@Test(expected = IllegalArgumentException.class)
public void testNullRange() {
    this.bean = new ValueGroup(UUID.randomUUID(), "test-group", Arrays.asList("input1"), null);
}
 
Example 14
Project: diorite-configs-java8   File: ConfigTestNoSpecial.java   View Source Code Vote up 4 votes
@Test
public void test() throws Exception
{
    SerializationTest.prepareSerialization();
    ToStringBuilder.setDefaultStyle(ToStringStyle.SHORT_PREFIX_STYLE);


    ConfigTemplate<SomeConfigNoSpecial> configTemplate = this.configManager.getConfigFile(SomeConfigNoSpecial.class);
    Assert.assertNotNull(configTemplate);
    Assert.assertEquals(SomeConfigNoSpecial.class.getSimpleName(), configTemplate.getName());
    Assert.assertEquals(StandardCharsets.UTF_8, configTemplate.getDefaultDecoder().charset());
    Assert.assertEquals(StandardCharsets.UTF_8, configTemplate.getDefaultEncoder().charset());

    System.out.println("[ConfigTest] creating config instance.");
    SomeConfigNoSpecial someConfig = configTemplate.create();
    Assert.assertNotNull(someConfig);

    this.testNicknames(someConfig);
    Assert.assertNotNull(someConfig.getSpecialData());
    someConfig.setStorage(SerializationTest.prepareObject());

    someConfig.save(System.out);

    try
    {
        someConfig.getSpecialData().clear();
        Assert.assertTrue("This should never happen, special data should be immutable.", false);
    }
    catch (UnsupportedOperationException e)
    {
    }
    MetaObject snowflake = new MetaObject("snowflake", new MetaValue("so special", 25));
    someConfig.putInSpecialData(snowflake);
    Assert.assertEquals(ImmutableList.of(snowflake), someConfig.getSpecialData());

    UUID randomUUID = UUID.randomUUID();
    someConfig.putInEvenMoreSpecialData(randomUUID, snowflake);
    Assert.assertEquals(1, someConfig.getEvenMoreSpecialData().size());

    System.out.println("\n====================\n");
    someConfig.save(System.out);

    Assert.assertEquals(snowflake, someConfig.removeFromEvenMoreSpecialData(randomUUID));
    Assert.assertTrue(someConfig.getEvenMoreSpecialData().isEmpty());


    // check if all data is still valid after reload of config.
    StringBuilderWriter writer = new StringBuilderWriter(500);
    someConfig.save(writer);
    Assert.assertEquals(someConfig, configTemplate.load(new StringReader(writer.toString())));
}
 
Example 15
Project: elastic-db-tools-for-java   File: RangeShardMap.java   View Source Code Vote up 4 votes
/**
 * Gets the lock owner id of the specified mapping.
 *
 * @param mapping
 *            Input range mapping.
 * @return An instance of <see cref="MappingLockToken"/>
 */
public MappingLockToken getMappingLockOwner(RangeMapping mapping) {
    ExceptionUtils.disallowNullArgument(mapping, "mapping");

    try (ActivityIdScope activityIdScope = new ActivityIdScope(UUID.randomUUID())) {
        log.info("LookupLockOwner Start");

        Stopwatch stopwatch = Stopwatch.createStarted();

        UUID storeLockOwnerId = this.rsm.getLockOwnerForMapping(mapping);

        stopwatch.stop();

        log.info("LookupLockOwner Complete; Duration: {}; StoreLockOwnerId: {}", stopwatch.elapsed(TimeUnit.MILLISECONDS), storeLockOwnerId);

        return new MappingLockToken(storeLockOwnerId);
    }
}
 
Example 16
Project: mod-circulation-storage   File: RequestsApiTest.java   View Source Code Vote up 4 votes
@Test
  public void updateRequestWithoutUserHeaderDoesSomething()
    throws InterruptedException,
    MalformedURLException,
    TimeoutException,
    ExecutionException,
    UnsupportedEncodingException {

    UUID id = UUID.randomUUID();

    JsonObject request = new RequestRequestBuilder().withId(id).create();

    JsonResponse createResponse = createRequest(request);

//    JsonObject createdMetadata = createResponse.getJson()
//      .getJsonObject(METADATA_PROPERTY);

    CompletableFuture<TextResponse> updateCompleted = new CompletableFuture<>();

//    DateTime requestMade = DateTime.now();

    client.put(requestStorageUrl(String.format("/%s", id)),
      request, StorageTestSuite.TENANT_ID, null,
      ResponseHandler.text(updateCompleted));

    TextResponse response = updateCompleted.get(5, TimeUnit.SECONDS);

    assertThat("No user header causes JSON to be null when saved",
      response.getStatusCode(), is(500));

//    assertThat(String.format("Failed to update request: %s", response.getBody()),
//      response.getStatusCode(), is(HttpURLConnection.HTTP_NO_CONTENT));
//
//    JsonResponse getAfterUpdateResponse = getById(id);
//
//    JsonObject updatedRequest = getAfterUpdateResponse.getJson();
//
//    assertThat("Request should have metadata property",
//      updatedRequest.containsKey(METADATA_PROPERTY), is(true));
//
//    JsonObject metadata = updatedRequest.getJsonObject(METADATA_PROPERTY);
//
//    assertThat("Request should have same created user",
//      metadata.getString("createdByUserId"),
//      is(createdMetadata.getString("createdByUserId")));
//
//    assertThat("Request should have same created date",
//      metadata.getString("createdDate"),
//      is(createdMetadata.getString("createdDate")));
//
//    assertThat("Request should have updated user",
//      metadata.getString("updatedByUserId"),
//      is(createdMetadata.getString("updatedByUserId")));
//
//    assertThat("Request should have updated date close to when request was made",
//      metadata.getString("updatedDate"),
//      is(withinSecondsAfter(Seconds.seconds(2), requestMade)));
//
//    assertThat("Request should have updated date different to original updated date",
//      metadata.getString("updatedDate"), is(not(createdMetadata.getString("updatedDate"))));
  }
 
Example 17
Project: Proj4   File: AbstractObject.java   View Source Code Vote up 4 votes
/**
 * Resets the UUID of the object (for respawning)
 */
public void resetId() {
	id = UUID.randomUUID();
}
 
Example 18
Project: Android-Programming-BigNerd   File: Crime.java   View Source Code Vote up 4 votes
public Crime() {
    this(UUID.randomUUID());
}
 
Example 19
Project: mod-circulation-storage   File: LoanPolicyRequestBuilder.java   View Source Code Vote up 4 votes
public LoanPolicyRequestBuilder() {
  this(UUID.randomUUID(), "Example Loan Policy", "An example loan policy");
}
 
Example 20
Project: swblocks-decisiontree   File: ValueGroup.java   View Source Code Vote up 2 votes
/**
 * Constructor taking a name and values only.
 *
 * @param name   the value group name
 * @param values the list of driver values
 */
public ValueGroup(final String name, final List<String> values) {
    this(UUID.randomUUID(), name, values, DEFAULT_DATE_RANGE);
}