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

The following examples show how to use com.datastax.driver.core.utils.UUIDs. 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: RepairUnitServiceTest.java    From cassandra-reaper with 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 #2
Source File: CassandraMessageIdToImapUidDAOTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: CustomerEntity.java    From Groza with 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 File: CassandraMessageIdToImapUidDAOTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: UserEntity.java    From Groza with 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 #6
Source File: AlarmEntity.java    From Groza with 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 #7
Source File: AlarmEntity.java    From iotplatform with 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
Source File: CassandraMessageIdToImapUidDAOTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@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
Source File: CassandraMessageIdToImapUidDAOTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@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 File: RepairUnitServiceTest.java    From cassandra-reaper with 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 File: AlarmEntity.java    From iotplatform with 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 File: CqlQueriesIntegrationTest.java    From tutorials with 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
Source File: CassandraMessageIdToImapUidDAOTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@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 File: ObjectMapper.java    From Rhombus with 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 #15
Source File: AuditLogServiceImpl.java    From Groza with 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 #16
Source File: RepairUnitServiceTest.java    From cassandra-reaper with 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 #17
Source File: CassandraStorage.java    From cassandra-reaper with 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 #18
Source File: CassandraMessageIdToImapUidDAOTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@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 #19
Source File: CassandraMessageIdToImapUidDAOTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@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 #20
Source File: CassandraSinkIntegrationTests.java    From spring-cloud-stream-app-starters with Apache License 2.0 6 votes vote down vote up
@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
Source File: RepairUnitServiceTest.java    From cassandra-reaper with 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 #22
Source File: CassandraBaseComponentDescriptorDao.java    From iotplatform with Apache License 2.0 6 votes vote down vote up
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 #23
Source File: FakeCDefinition.java    From Rhombus with 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 #24
Source File: JpaAbstractDao.java    From iotplatform with 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 #25
Source File: TenantEntity.java    From iotplatform with 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 #26
Source File: CassandraStorage.java    From cassandra-reaper with Apache License 2.0 5 votes vote down vote up
@Override
public RepairSchedule addRepairSchedule(io.cassandrareaper.core.RepairSchedule.Builder repairSchedule) {
  RepairSchedule schedule = repairSchedule.build(UUIDs.timeBased());
  updateRepairSchedule(schedule);

  return schedule;
}
 
Example #27
Source File: FakeIdRange.java    From Rhombus with MIT License 5 votes vote down vote up
public static UUID makeTimeUUIDFromLowestTimeUnit(Long timestamp){
		return UUIDs.startOf(timestamp);
//		// UUID v1 timestamp must be in 100-nanoseconds interval since 00:00:00.000 15 Oct 1582.
//		Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT-0"));
//		c.set(Calendar.YEAR, 1582);
//		c.set(Calendar.MONTH, Calendar.OCTOBER);
//		c.set(Calendar.DAY_OF_MONTH, 15);
//		c.set(Calendar.HOUR_OF_DAY, 0);
//		c.set(Calendar.MINUTE, 0);
//		c.set(Calendar.SECOND, 0);
//		c.set(Calendar.MILLISECOND, 0);
//		timestamp = timestamp - c.getTimeInMillis()*10000;
//
//		UUIDs.startOf(timestamp);
//		long clock = 42;
//		long node = 0x0000010000000000L;
//
//		long CLOCK_SEQ_AND_NODE = 0;
//		CLOCK_SEQ_AND_NODE |= (clock & 0x0000000000003FFFL) << 48;
//		CLOCK_SEQ_AND_NODE |= 0x8000000000000000L;
//		CLOCK_SEQ_AND_NODE |= node;
//
//		long msb = 0L;
//		msb |= (0x00000000ffffffffL & timestamp) << 32;
//		msb |= (0x0000ffff00000000L & timestamp) >>> 16;
//		msb |= (0x0fff000000000000L & timestamp) >>> 48;
//		msb |= 0x0000000000001000L; // sets the version to 1.
//		return new UUID(msb, CLOCK_SEQ_AND_NODE);
	}
 
Example #28
Source File: WidgetTypeEntity.java    From iotplatform with Apache License 2.0 5 votes vote down vote up
@Override
public WidgetType toData() {
  WidgetType widgetType = new WidgetType(new WidgetTypeId(getId()));
  widgetType.setCreatedTime(UUIDs.unixTimestamp(getId()));
  if (tenantId != null) {
    widgetType.setTenantId(new TenantId(toUUID(tenantId)));
  }
  widgetType.setBundleAlias(bundleAlias);
  widgetType.setAlias(alias);
  widgetType.setName(name);
  widgetType.setDescriptor(descriptor);
  return widgetType;
}
 
Example #29
Source File: ObjectMapper.java    From Rhombus with MIT License 5 votes vote down vote up
/**
 * Insert a new objectType with values
 * @param objectType Type of object to insert
 * @param values Values to insert
 * @return UUID of inserted object
 * @throws CQLGenerationException
 */
public Object insert(String objectType, Map<String, Object> values) throws CQLGenerationException, RhombusException {
	Object key = null;
	if(values.containsKey("id")) {
		key = values.get("id");
		values.remove("id");
	}
	else{
		key = UUIDs.timeBased();
	}
	return insert(objectType, values, key);
}
 
Example #30
Source File: ObjectMapperShardingITCase.java    From Rhombus with MIT License 5 votes vote down vote up
@Test
public void testQueriesUseShardIndex() throws Exception {
	logger.debug("Starting testQueriesUseShardIndex");

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

	// Insert a record that is more than ObjectMapper.reasonableStatementLimit months old
	DateTime dateTime = DateTime.now().minusMonths(om.getReasonableStatementLimit() * 2);
	UUID id = UUIDs.startOf(dateTime.getMillis());
	UUID accountId = UUID.fromString("00000003-0000-0030-0040-000000030000");
	UUID userId = UUID.fromString("00000003-0000-0030-0040-000000030000");
	Map<String, Object> record = Maps.newHashMap();
	record.put("id", id);
	record.put("account_id", accountId);
	record.put("user_id", userId);
	om.insert("object1", record);

	//Query it back out, make sure that we are using the shard index, because if we are not, we will surpass reasonable statement limit
	SortedMap<String, Object> indexValues = Maps.newTreeMap();
	indexValues.put("account_id", accountId);
	indexValues.put("user_id", userId);
	Criteria criteria = new Criteria();
	criteria.setIndexKeys(indexValues);
	criteria.setEndTimestamp(DateTime.now().getMillis());
	criteria.setLimit(50L);
	List<Map<String, Object>> results = om.list("object1", criteria);

	assertEquals(1, results.size());

	cm.teardown();
}