Java Code Examples for com.datastax.driver.core.utils.UUIDs

The following examples show how to use com.datastax.driver.core.utils.UUIDs. These examples are extracted from open source projects. 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 Project: Groza   Source File: AuditLogServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
private AuditLog createAuditLogEntry(TenantId tenantId,
                                     EntityId entityId,
                                     String entityName,
                                     CustomerId customerId,
                                     UserId userId,
                                     String userName,
                                     ActionType actionType,
                                     JsonNode actionData,
                                     ActionStatus actionStatus,
                                     String actionFailureDetails) {
    AuditLog result = new AuditLog();
    result.setId(new AuditLogId(UUIDs.timeBased()));
    result.setTenantId(tenantId);
    result.setEntityId(entityId);
    result.setEntityName(entityName);
    result.setCustomerId(customerId);
    result.setUserId(userId);
    result.setUserName(userName);
    result.setActionType(actionType);
    result.setActionData(actionData);
    result.setActionStatus(actionStatus);
    result.setActionFailureDetails(actionFailureDetails);
    return result;
}
 
Example 2
Source Project: Groza   Source File: AlarmEntity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Alarm toData() {
    Alarm alarm = new Alarm(new AlarmId(UUIDConverter.fromString(id)));
    alarm.setCreatedTime(UUIDs.unixTimestamp(UUIDConverter.fromString(id)));
    if (tenantId != null) {
        alarm.setTenantId(new TenantId(UUIDConverter.fromString(tenantId)));
    }
    alarm.setOriginator(EntityIdFactory.getByTypeAndUuid(originatorType, UUIDConverter.fromString(originatorId)));
    alarm.setType(type);
    alarm.setSeverity(severity);
    alarm.setStatus(status);
    alarm.setPropagate(propagate);
    alarm.setStartTs(startTs);
    alarm.setEndTs(endTs);
    alarm.setAckTs(ackTs);
    alarm.setClearTs(clearTs);
    alarm.setDetails(details);
    return alarm;
}
 
Example 3
Source Project: Groza   Source File: CustomerEntity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Customer toData() {
    Customer customer = new Customer(new CustomerId(getId()));
    customer.setCreatedTime(UUIDs.unixTimestamp(getId()));
    customer.setTenantId(new TenantId(UUIDConverter.fromString(tenantId)));
    customer.setTitle(title);
    customer.setCountry(country);
    customer.setState(state);
    customer.setCity(city);
    customer.setAddress(address);
    customer.setAddress2(address2);
    customer.setZip(zip);
    customer.setPhone(phone);
    customer.setEmail(email);
    customer.setAdditionalInfo(additionalInfo);
    return customer;
}
 
Example 4
Source Project: Groza   Source File: UserEntity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public User toData() {
    User user = new User(new UserId(getId()));
    user.setCreatedTime(UUIDs.unixTimestamp(getId()));
    user.setAuthority(authority);
    if (tenantId != null) {
        user.setTenantId(new TenantId(fromString(tenantId)));
    }
    if (customerId != null) {
        user.setCustomerId(new CustomerId(fromString(customerId)));
    }
    user.setEmail(email);
    user.setFirstName(firstName);
    user.setLastName(lastName);
    user.setAdditionalInfo(additionalInfo);
    return user;
}
 
Example 5
@Test
void updateShouldUpdateAnsweredFlag() {
    CassandraMessageId messageId = messageIdFactory.of(UUIDs.timeBased());
    CassandraId mailboxId = CassandraId.timeBased();
    MessageUid messageUid = MessageUid.of(1);

    ComposedMessageId composedMessageId = new ComposedMessageId(mailboxId, messageId, messageUid);
    testee.insert(ComposedMessageIdWithMetaData.builder()
            .composedMessageId(composedMessageId)
            .flags(new Flags())
            .modSeq(ModSeq.of(1))
            .build())
        .block();

    ComposedMessageIdWithMetaData expectedComposedMessageId = ComposedMessageIdWithMetaData.builder()
            .composedMessageId(composedMessageId)
            .flags(new Flags(Flag.ANSWERED))
            .modSeq(ModSeq.of(2))
            .build();
    testee.updateMetadata(expectedComposedMessageId, ModSeq.of(1)).block();

    List<ComposedMessageIdWithMetaData> messages = testee.retrieve(messageId, Optional.of(mailboxId)).collectList().block();
    assertThat(messages).containsOnly(expectedComposedMessageId);
}
 
Example 6
@Test
void deleteShouldDeleteWhenRowExists() {
    CassandraMessageId messageId = messageIdFactory.of(UUIDs.timeBased());
    CassandraId mailboxId = CassandraId.timeBased();
    MessageUid messageUid = MessageUid.of(1);
    testee.insert(ComposedMessageIdWithMetaData.builder()
                .composedMessageId(new ComposedMessageId(mailboxId, messageId, messageUid))
                .flags(new Flags())
                .modSeq(ModSeq.of(1))
                .build())
            .block();

    testee.delete(messageId, mailboxId).block();

    List<ComposedMessageIdWithMetaData> messages = testee.retrieve(messageId, Optional.of(mailboxId)).collectList().block();
    assertThat(messages).isEmpty();
}
 
Example 7
Source Project: iotplatform   Source File: AlarmEntity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Alarm toData() {
    Alarm alarm = new Alarm(new AlarmId(id));
    alarm.setCreatedTime(UUIDs.unixTimestamp(id));
    if (tenantId != null) {
        alarm.setTenantId(new TenantId(tenantId));
    }
    alarm.setOriginator(EntityIdFactory.getByTypeAndUuid(originatorType, originatorId));
    alarm.setType(type);
    alarm.setSeverity(severity);
    alarm.setStatus(status);
    alarm.setPropagate(propagate);
    alarm.setStartTs(startTs);
    alarm.setEndTs(endTs);
    alarm.setAckTs(ackTs);
    alarm.setClearTs(clearTs);
    alarm.setDetails(details);
    return alarm;
}
 
Example 8
@Test
void updateShouldUpdateDeletedFlag() {
    CassandraMessageId messageId = messageIdFactory.of(UUIDs.timeBased());
    CassandraId mailboxId = CassandraId.timeBased();
    MessageUid messageUid = MessageUid.of(1);

    ComposedMessageId composedMessageId = new ComposedMessageId(mailboxId, messageId, messageUid);
    testee.insert(ComposedMessageIdWithMetaData.builder()
            .composedMessageId(composedMessageId)
            .flags(new Flags())
            .modSeq(ModSeq.of(1))
            .build())
        .block();

    ComposedMessageIdWithMetaData expectedComposedMessageId = ComposedMessageIdWithMetaData.builder()
            .composedMessageId(composedMessageId)
            .flags(new Flags(Flag.DELETED))
            .modSeq(ModSeq.of(2))
            .build();
    testee.updateMetadata(expectedComposedMessageId, ModSeq.of(1)).block();

    List<ComposedMessageIdWithMetaData> messages = testee.retrieve(messageId, Optional.of(mailboxId)).collectList().block();
    assertThat(messages).containsOnly(expectedComposedMessageId);
}
 
Example 9
@Test
void updateShouldUpdateDraftFlag() {
    CassandraMessageId messageId = messageIdFactory.of(UUIDs.timeBased());
    CassandraId mailboxId = CassandraId.timeBased();
    MessageUid messageUid = MessageUid.of(1);

    ComposedMessageId composedMessageId = new ComposedMessageId(mailboxId, messageId, messageUid);
    testee.insert(ComposedMessageIdWithMetaData.builder()
            .composedMessageId(composedMessageId)
            .flags(new Flags())
            .modSeq(ModSeq.of(1))
            .build())
        .block();

    ComposedMessageIdWithMetaData expectedComposedMessageId = ComposedMessageIdWithMetaData.builder()
            .composedMessageId(composedMessageId)
            .flags(new Flags(Flag.DRAFT))
            .modSeq(ModSeq.of(2))
            .build();
    testee.updateMetadata(expectedComposedMessageId, ModSeq.of(1)).block();

    List<ComposedMessageIdWithMetaData> messages = testee.retrieve(messageId, Optional.of(mailboxId)).collectList().block();
    assertThat(messages).containsOnly(expectedComposedMessageId);
}
 
Example 10
Source Project: cassandra-reaper   Source File: RepairUnitServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void getTablesToRepairRemoveOneTableFromListTest() throws ReaperException {
  JmxProxy proxy = JmxProxyTest.mockJmxProxyImpl();
  when(proxy.getCassandraVersion()).thenReturn("3.11.4");
  when(context.jmxConnectionFactory.connectAny(Mockito.any(Collection.class))).thenReturn(proxy);

  when(proxy.getTablesForKeyspace(Mockito.anyString()))
          .thenReturn(Sets.newHashSet(
                  Table.builder().withName("table1").withCompactionStrategy(STCS).build(),
                  Table.builder().withName("table2").withCompactionStrategy(STCS).build(),
                  Table.builder().withName("table3").withCompactionStrategy(STCS).build()));

  RepairUnit unit = RepairUnit.builder()
      .clusterName(cluster.getName())
      .keyspaceName("test")
      .columnFamilies(Sets.newHashSet("table1", "table2"))
      .blacklistedTables(Sets.newHashSet("table1"))
      .incrementalRepair(false)
      .repairThreadCount(4)
      .build(UUIDs.timeBased());

  assertEquals(Sets.newHashSet("table2"), service.getTablesToRepair(cluster, unit));
}
 
Example 11
Source Project: iotplatform   Source File: AlarmEntity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Alarm toData() {
    Alarm alarm = new Alarm(new AlarmId(UUIDConverter.fromString(id)));
    alarm.setCreatedTime(UUIDs.unixTimestamp(UUIDConverter.fromString(id)));
    if (tenantId != null) {
        alarm.setTenantId(new TenantId(UUIDConverter.fromString(tenantId)));
    }
    alarm.setOriginator(EntityIdFactory.getByTypeAndUuid(originatorType, UUIDConverter.fromString(originatorId)));
    alarm.setType(type);
    alarm.setSeverity(severity);
    alarm.setStatus(status);
    alarm.setPropagate(propagate);
    alarm.setStartTs(startTs);
    alarm.setEndTs(endTs);
    alarm.setAckTs(ackTs);
    alarm.setClearTs(clearTs);
    alarm.setDetails(details);
    return alarm;
}
 
Example 12
Source Project: tutorials   Source File: CqlQueriesIntegrationTest.java    License: MIT License 6 votes vote down vote up
@Test
public void whenSavingBook_thenAvailableOnRetrieval_usingPreparedStatements() throws InterruptedException {
    final UUID uuid = UUIDs.timeBased();
    final String insertPreparedCql = "insert into book (id, title, publisher, tags) values (?, ?, ?, ?)";
    final List<Object> singleBookArgsList = new ArrayList<>();
    final List<List<?>> bookList = new ArrayList<>();
    singleBookArgsList.add(uuid);
    singleBookArgsList.add("Head First Java");
    singleBookArgsList.add("OReilly Media");
    singleBookArgsList.add(ImmutableSet.of("Software"));
    bookList.add(singleBookArgsList);
    cassandraTemplate.ingest(insertPreparedCql, bookList);
    // This may not be required, just added to avoid any transient issues
    Thread.sleep(5000);
    final Select select = QueryBuilder.select().from("book");
    final Book retrievedBook = cassandraTemplate.selectOne(select, Book.class);
    assertEquals(uuid, retrievedBook.getId());
}
 
Example 13
@Test
void insertShouldWork() {
    CassandraMessageId messageId = messageIdFactory.of(UUIDs.timeBased());
    CassandraId mailboxId = CassandraId.timeBased();
    MessageUid messageUid = MessageUid.of(1);

    testee.insert(ComposedMessageIdWithMetaData.builder()
            .composedMessageId(new ComposedMessageId(mailboxId, messageId, messageUid))
            .flags(new Flags())
            .modSeq(ModSeq.of(1))
            .build())
        .block();

    ComposedMessageIdWithMetaData expectedComposedMessageId = ComposedMessageIdWithMetaData.builder()
            .composedMessageId(new ComposedMessageId(mailboxId, messageId, messageUid))
            .flags(new Flags())
            .modSeq(ModSeq.of(1))
            .build();
    List<ComposedMessageIdWithMetaData> messages = testee.retrieve(messageId, Optional.of(mailboxId)).collectList().block();
    assertThat(messages).containsOnly(expectedComposedMessageId);
}
 
Example 14
Source Project: iotplatform   Source File: TenantEntity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Tenant toData() {
    Tenant tenant = new Tenant(new TenantId(getId()));
    tenant.setCreatedTime(UUIDs.unixTimestamp(getId()));
    tenant.setTitle(title);
    tenant.setRegion(region);
    tenant.setCountry(country);
    tenant.setState(state);
    tenant.setCity(city);
    tenant.setAddress(address);
    tenant.setAddress2(address2);
    tenant.setZip(zip);
    tenant.setPhone(phone);
    tenant.setEmail(email);
    tenant.setAdditionalInfo(additionalInfo);
    return tenant;
}
 
Example 15
Source Project: Rhombus   Source File: ObjectMapper.java    License: MIT License 6 votes vote down vote up
/**
 * Insert a new object with values and key and TTL
 * @param objectType Type of object to insert
 * @param values Values to insert
 * @param key Time UUID to use as key
 * @return ID if newly inserted object
 * @throws CQLGenerationException
 */
public Object insert(String objectType, Map<String, Object> values, Object key) throws CQLGenerationException, RhombusException {
	logger.debug("Insert {}", objectType);
	if(key == null) {
		key = UUIDs.timeBased();
	}
	long timestamp = System.currentTimeMillis();

	Integer ttl = null;
	if (values.containsKey("_ttl")) {
		try {
			ttl = (Integer)values.get("_ttl");
		}
		catch (ClassCastException cce) {
			ttl = null;
		}
	}

	CQLStatementIterator statementIterator = cqlGenerator.makeCQLforInsert(objectType, values, key, timestamp, ttl);
	executeStatements(statementIterator);
	return key;
}
 
Example 16
Source Project: iotplatform   Source File: JpaAbstractDao.java    License: Apache License 2.0 6 votes vote down vote up
@Override
@Transactional
public D save(D domain) {
    E entity;
    try {
        entity = getEntityClass().getConstructor(domain.getClass()).newInstance(domain);
    } catch (Exception e) {
        log.error("Can't create entity for domain object {}", domain, e);
        throw new IllegalArgumentException("Can't create entity for domain object {" + domain + "}", e);
    }
    setSearchText(entity);
    log.debug("Saving entity {}", entity);
    if (entity.getId() == null) {
        entity.setId(UUIDs.timeBased());
    }
    entity = getCrudRepository().save(entity);
    return DaoUtil.getData(entity);
}
 
Example 17
Source Project: Rhombus   Source File: FakeCDefinition.java    License: MIT License 6 votes vote down vote up
public List<FakeCIndex> buildFakeIndexes() throws RhombusException {
	this.fakeCIndexes = Lists.newArrayList();
	FakeCIndex lastIndex = null;
	for(CIndex i: this.cdef.getIndexesAsList()){
		Object startingId = (lastIndex==null) ? UUIDs.timeBased() : lastIndex.getSuggestedIdForStartofNextIndex(i.getShardingStrategy());
		FakeCIndex toadd = new FakeCIndex(
				i,
				cdef,
				startingId,
				this.totalWideRowsPerIndex,
				this.totalObjectsPerWideRange,
				this.objectsPerShard );
		this.fakeCIndexes.add(toadd);
		lastIndex = toadd;
	}
	return this.fakeCIndexes;
}
 
Example 18
private Optional<ComponentDescriptor> saveIfNotExist(ComponentDescriptorEntity entity) {
    if (entity.getId() == null) {
        entity.setId(UUIDs.timeBased());
    }

    ResultSet rs = executeRead(QueryBuilder.insertInto(getColumnFamilyName())
            .value(ModelConstants.ID_PROPERTY, entity.getId())
            .value(ModelConstants.COMPONENT_DESCRIPTOR_NAME_PROPERTY, entity.getName())
            .value(ModelConstants.COMPONENT_DESCRIPTOR_CLASS_PROPERTY, entity.getClazz())
            .value(ModelConstants.COMPONENT_DESCRIPTOR_TYPE_PROPERTY, entity.getType())
            .value(ModelConstants.COMPONENT_DESCRIPTOR_SCOPE_PROPERTY, entity.getScope())
            .value(ModelConstants.COMPONENT_DESCRIPTOR_CONFIGURATION_DESCRIPTOR_PROPERTY, entity.getConfigurationDescriptor())
            .value(ModelConstants.COMPONENT_DESCRIPTOR_ACTIONS_PROPERTY, entity.getActions())
            .value(ModelConstants.SEARCH_TEXT_PROPERTY, entity.getSearchText())
            .ifNotExists()
    );
    if (rs.wasApplied()) {
        return Optional.of(DaoUtil.getData(entity));
    } else {
        return Optional.empty();
    }
}
 
Example 19
Source Project: cassandra-reaper   Source File: RepairUnitServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void getTablesToRepairRemoveOneTableFromListOneWithTwcsTest() throws ReaperException {
  JmxProxy proxy = JmxProxyTest.mockJmxProxyImpl();
  when(proxy.getCassandraVersion()).thenReturn("3.11.4");
  when(context.jmxConnectionFactory.connectAny(Mockito.any(Collection.class))).thenReturn(proxy);

  when(proxy.getTablesForKeyspace(Mockito.anyString()))
          .thenReturn(Sets.newHashSet(
                  Table.builder().withName("table1").withCompactionStrategy(STCS).build(),
                  Table.builder().withName("table2").withCompactionStrategy(TWCS).build(),
                  Table.builder().withName("table3").withCompactionStrategy(STCS).build()));

  RepairUnit unit = RepairUnit.builder()
      .clusterName(cluster.getName())
      .keyspaceName("test")
      .columnFamilies(Sets.newHashSet("table1", "table2"))
      .blacklistedTables(Sets.newHashSet("table1"))
      .incrementalRepair(false)
      .repairThreadCount(4)
      .build(UUIDs.timeBased());

  assertEquals(Sets.newHashSet("table2"), service.getTablesToRepair(cluster, unit));
}
 
Example 20
@Test
public void testInsert() throws InterruptedException {
	Book book = new Book();
	book.setIsbn(UUIDs.timeBased());
	book.setTitle("Spring Integration Cassandra");
	book.setAuthor("Cassandra Guru");
	book.setPages(521);
	book.setSaleDate(new Date());
	book.setInStock(true);

	this.sink.input().send(new GenericMessage<>(book));

	final Select select = QueryBuilder.select().all().from("book");

	assertEqualsEventually(1, new Supplier<Integer>() {

		@Override
		public Integer get() {
			return cassandraTemplate.select(select, Book.class).size();
		}

	});

	this.cassandraTemplate.delete(book);
}
 
Example 21
@Test
void updateShouldUpdateRecentFlag() {
    CassandraMessageId messageId = messageIdFactory.of(UUIDs.timeBased());
    CassandraId mailboxId = CassandraId.timeBased();
    MessageUid messageUid = MessageUid.of(1);

    ComposedMessageId composedMessageId = new ComposedMessageId(mailboxId, messageId, messageUid);
    testee.insert(ComposedMessageIdWithMetaData.builder()
            .composedMessageId(composedMessageId)
            .flags(new Flags())
            .modSeq(ModSeq.of(1))
            .build())
        .block();

    ComposedMessageIdWithMetaData expectedComposedMessageId = ComposedMessageIdWithMetaData.builder()
            .composedMessageId(composedMessageId)
            .flags(new Flags(Flag.RECENT))
            .modSeq(ModSeq.of(2))
            .build();
    testee.updateMetadata(expectedComposedMessageId, ModSeq.of(1)).block();

    List<ComposedMessageIdWithMetaData> messages = testee.retrieve(messageId, Optional.of(mailboxId)).collectList().block();
    assertThat(messages).containsOnly(expectedComposedMessageId);
}
 
Example 22
@Test
void updateShouldUpdateUserFlag() {
    CassandraMessageId messageId = messageIdFactory.of(UUIDs.timeBased());
    CassandraId mailboxId = CassandraId.timeBased();
    MessageUid messageUid = MessageUid.of(1);

    ComposedMessageId composedMessageId = new ComposedMessageId(mailboxId, messageId, messageUid);
    testee.insert(ComposedMessageIdWithMetaData.builder()
            .composedMessageId(composedMessageId)
            .flags(new Flags())
            .modSeq(ModSeq.of(1))
            .build())
        .block();

    ComposedMessageIdWithMetaData expectedComposedMessageId = ComposedMessageIdWithMetaData.builder()
            .composedMessageId(composedMessageId)
            .flags(new Flags(Flag.USER))
            .modSeq(ModSeq.of(2))
            .build();
    testee.updateMetadata(expectedComposedMessageId, ModSeq.of(1)).block();

    List<ComposedMessageIdWithMetaData> messages = testee.retrieve(messageId, Optional.of(mailboxId)).collectList().block();
    assertThat(messages).containsOnly(expectedComposedMessageId);
}
 
Example 23
Source Project: cassandra-reaper   Source File: CassandraStorage.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public RepairUnit addRepairUnit(RepairUnit.Builder newRepairUnit) {
  RepairUnit repairUnit = newRepairUnit.build(UUIDs.timeBased());
  session.execute(
      insertRepairUnitPrepStmt.bind(
          repairUnit.getId(),
          repairUnit.getClusterName(),
          repairUnit.getKeyspaceName(),
          repairUnit.getColumnFamilies(),
          repairUnit.getIncrementalRepair(),
          repairUnit.getNodes(),
          repairUnit.getDatacenters(),
          repairUnit.getBlacklistedTables(),
          repairUnit.getRepairThreadCount()));

  repairUnits.put(repairUnit.getId(), repairUnit);
  return repairUnit;
}
 
Example 24
Source Project: cassandra-reaper   Source File: RepairUnitServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void getTablesToRepairDefaultCompactionStrategyTable() throws ReaperException {
  JmxProxy proxy = JmxProxyTest.mockJmxProxyImpl();
  when(proxy.getCassandraVersion()).thenReturn("3.11.4");
  when(context.jmxConnectionFactory.connectAny(Mockito.any(Collection.class))).thenReturn(proxy);

  when(proxy.getTablesForKeyspace(Mockito.anyString()))
        .thenReturn(Sets.newHashSet(
              Table.builder().withName("table1").build(),
              Table.builder().withName("table2").build(),
              Table.builder().withName("table3").build()));

  RepairUnit unit = RepairUnit.builder()
        .clusterName(cluster.getName())
        .keyspaceName("test")
        .blacklistedTables(Sets.newHashSet("table1"))
        .incrementalRepair(false)
        .repairThreadCount(4)
        .build(UUIDs.timeBased());

  assertEquals(Sets.newHashSet("table2", "table3"), service.getTablesToRepair(cluster, unit));
}
 
Example 25
Source Project: cassandra-reaper   Source File: RepairUnitServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void getTablesToRepairRemoveTwoTablesTest() throws ReaperException {
  JmxProxy proxy = JmxProxyTest.mockJmxProxyImpl();
  when(proxy.getCassandraVersion()).thenReturn("3.11.4");
  when(context.jmxConnectionFactory.connectAny(Mockito.any(Collection.class))).thenReturn(proxy);

  when(proxy.getTablesForKeyspace(Mockito.anyString()))
          .thenReturn(Sets.newHashSet(
                  Table.builder().withName("table1").withCompactionStrategy(STCS).build(),
                  Table.builder().withName("table2").withCompactionStrategy(STCS).build(),
                  Table.builder().withName("table3").withCompactionStrategy(STCS).build()));

  RepairUnit unit = RepairUnit.builder()
      .clusterName(cluster.getName())
      .keyspaceName("test")
      .blacklistedTables(Sets.newHashSet("table1", "table3"))
      .incrementalRepair(false)
      .repairThreadCount(4)
      .build(UUIDs.timeBased());

  assertEquals(Sets.newHashSet("table2"), service.getTablesToRepair(cluster, unit));
}
 
Example 26
Source Project: Groza   Source File: UserCredentialsEntity.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public UserCredentials toData() {
    UserCredentials userCredentials = new UserCredentials(new UserCredentialsId(getId()));
    userCredentials.setCreatedTime(UUIDs.unixTimestamp(getId()));
    if (userId != null) {
        userCredentials.setUserId(new UserId(toUUID(userId)));
    }
    userCredentials.setEnabled(enabled);
    userCredentials.setPassword(password);
    userCredentials.setActivateToken(activateToken);
    userCredentials.setResetToken(resetToken);
    return userCredentials;
}
 
Example 27
Source Project: cassandra-reaper   Source File: PurgeServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSkipPurgeOngoingRuns() throws InterruptedException, ReaperException {
  AppContext context = new AppContext();
  context.config = new ReaperApplicationConfiguration();
  context.config.setPurgeRecordsAfterInDays(1);

  // Create storage mock
  context.storage = mock(IStorage.class);

  List<Cluster> clusters = Arrays.asList(Cluster.builder().withName(CLUSTER_NAME).withSeedHosts(SEEDS).build());

  when(context.storage.getClusters()).thenReturn(clusters);

  // Add repair runs to the mock
  List<RepairRun> repairRuns = Lists.newArrayList();
  DateTime currentDate = DateTime.now();
  for (int i = 0; i < 10; i++) {
    UUID repairUnitId = UUIDs.timeBased();
    DateTime startTime = currentDate.minusDays(i).minusHours(1);

    repairRuns.add(
        RepairRun.builder(CLUSTER_NAME, repairUnitId)
            .startTime(startTime)
            .intensity(0.9)
            .segmentCount(10)
            .repairParallelism(RepairParallelism.DATACENTER_AWARE)
            .tables(TABLES)
            .pauseTime(startTime.plusSeconds(1))
            .runState(RunState.PAUSED)
            .build(UUIDs.timeBased()));
  }

  when(context.storage.getRepairRunsForCluster(anyString(), any())).thenReturn(repairRuns);

  // Invoke the purge manager
  int purged = PurgeService.create(context).purgeDatabase();

  // Check that runs were removed
  assertEquals(0, purged);
}
 
Example 28
Source Project: Groza   Source File: DeviceCredentialsEntity.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public DeviceCredentials toData() {
    DeviceCredentials deviceCredentials = new DeviceCredentials(new DeviceCredentialsId(getId()));
    deviceCredentials.setCreatedTime(UUIDs.unixTimestamp(getId()));
    if (deviceId != null) {
        deviceCredentials.setDeviceId(new DeviceId(toUUID(deviceId)));
    }
    deviceCredentials.setCredentialsType(credentialsType);
    deviceCredentials.setCredentialsId(credentialsId);
    deviceCredentials.setCredentialsValue(credentialsValue);
    return deviceCredentials;
}
 
Example 29
Source Project: twissandra-j   Source File: CassandraTweetRepository.java    License: Apache License 2.0 5 votes vote down vote up
public Tweet saveTweet(String username, String body) {
	UUID id = UUIDs.timeBased();

	// Create the tweet in the tweets cf
	execute("INSERT INTO tweets (tweetid, username, body) VALUES (%s, '%s', '%s')",
			id.toString(),
			username,
			body);
	// Store the tweet in this users userline
	execute("INSERT INTO userline (username, tweetid, body) VALUES ('%s', %s, '%s')",
			username,
			id.toString(),
			body);
	// Store the tweet in this users timeline
	execute("INSERT INTO timeline (username, tweetid, posted_by, body) VALUES ('%s', %s, '%s', '%s')",
			username,
			id.toString(),
			username,
			body);
	// Store the tweet in the public timeline
	execute("INSERT INTO timeline (username, tweetid, posted_by, body) VALUES ('%s', %s, '%s', '%s')",
			PUBLIC_USERLINE_KEY,
			id.toString(),
			username,
			body);

	// Insert the tweet into follower timelines
	for (String follower : getFollowers(username)) {
		execute("INSERT INTO timeline (username, tweetid, posted_by, body) VALUES ('%s', %s, '%s', '%s')",
				follower,
				id.toString(),
				username,
				body);
	}

	return new Tweet(username, body, id, fromUUID1(id));
}
 
Example 30
Source Project: Rhombus   Source File: ObjectMapperShardingITCase.java    License: MIT License 5 votes vote down vote up
@Test
public void testShardedQueries() throws Exception {
	logger.debug("Starting testShardedQueries");

	// Get an object mapper for the keyspace and truncate the data
	ConnectionManager cm = getConnectionManager();
	ObjectMapper om = cm.getObjectMapper(keyspaceDefinition);
	om.truncateTables();
	om.setLogCql(true);

	//Set up test data
	List<Map<String, Object>> values = JsonUtil.rhombusMapFromResource(this.getClass().getClassLoader(), "ShardedTestData.js");
	for(Map<String, Object> object : values) {
		Map<String, Object> updatedObject = JsonUtil.rhombusMapFromJsonMap(object, keyspaceDefinition.getDefinitions().get("object1"));
		Long createdAt = ((Date)(updatedObject.get("created_at"))).getTime();
		logger.debug("Inserting object with created_at: {}", createdAt);
		UUID id = (UUID)om.insert("object1", updatedObject, createdAt);
		logger.debug("Inserted object with uuid unix time: {}", UUIDs.unixTimestamp(id));
	}

	//Query it back out
	//Make sure that we have the proper number of results
	SortedMap<String, Object> indexValues = Maps.newTreeMap();
	indexValues.put("account_id", UUID.fromString("00000003-0000-0030-0040-000000030000"));
	indexValues.put("user_id", UUID.fromString("00000003-0000-0030-0040-000000030000"));
	Criteria criteria = new Criteria();
	criteria.setIndexKeys(indexValues);
	criteria.setLimit(50L);
	List<Map<String, Object>> results = om.list("object1", criteria);
	assertEquals(3, results.size());

	cm.teardown();
}