Java Code Examples for com.datastax.driver.core.utils.UUIDs#timeBased()

The following examples show how to use com.datastax.driver.core.utils.UUIDs#timeBased() . 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: BookRepositoryIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenDeletingABookByTitle_thenBookIsDeleted() {
    bookRepository.deleteTable(BOOKS_BY_TITLE);
    bookRepository.createTableBooksByTitle();

    Book book = new Book(UUIDs.timeBased(), "Effective Java", "Joshua Bloch", "Programming");
    bookRepository.insertbookByTitle(book);

    book = new Book(UUIDs.timeBased(), "Clean Code", "Robert C. Martin", "Programming");
    bookRepository.insertbookByTitle(book);

    bookRepository.deletebookByTitle("Clean Code");

    List<Book> books = bookRepository.selectAllBookByTitle();
    assertEquals(1, books.size());
    assertTrue(books.stream().anyMatch(b -> b.getTitle().equals("Effective Java")));
    assertFalse(books.stream().anyMatch(b -> b.getTitle().equals("Clean Code")));

}
 
Example 2
Source File: BookRepositoryIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenAddingANewBookBatch_ThenBookAddedInAllTables() {
    // Create table books
    bookRepository.deleteTable(BOOKS);
    bookRepository.createTable();

    // Create table booksByTitle
    bookRepository.deleteTable(BOOKS_BY_TITLE);
    bookRepository.createTableBooksByTitle();

    String title = "Effective Java";
    String author = "Joshua Bloch";
    Book book = new Book(UUIDs.timeBased(), title, author, "Programming");
    bookRepository.insertBookBatch(book);

    List<Book> books = bookRepository.selectAll();

    assertEquals(1, books.size());
    assertTrue(books.stream().anyMatch(b -> b.getTitle().equals("Effective Java")));

    List<Book> booksByTitle = bookRepository.selectAllBookByTitle();

    assertEquals(1, booksByTitle.size());
    assertTrue(booksByTitle.stream().anyMatch(b -> b.getTitle().equals("Effective Java")));
}
 
Example 3
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 4
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 5
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 6
Source File: CassandraTemplateIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenSavingBooks_thenAllAvailableOnRetrieval() {
    final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software"));
    final Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", ImmutableSet.of("Computer", "Software"));
    final List<Book> bookList = new ArrayList<>();
    bookList.add(javaBook);
    bookList.add(dPatternBook);
    cassandraTemplate.insert(bookList);

    final Select select = QueryBuilder.select().from("book").limit(10);
    final List<Book> retrievedBooks = cassandraTemplate.select(select, Book.class);
    assertThat(retrievedBooks.size(), is(2));
    assertEquals(javaBook.getId(), retrievedBooks.get(0).getId());
    assertEquals(dPatternBook.getId(), retrievedBooks.get(1).getId());
}
 
Example 7
Source File: CassandraTemplateIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenSavingBook_thenAvailableOnRetrieval() {
    final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software"));
    cassandraTemplate.insert(javaBook);
    final Select select = QueryBuilder.select().from("book").where(QueryBuilder.eq("title", "Head First Java")).and(QueryBuilder.eq("publisher", "O'Reilly Media")).limit(10);
    final Book retrievedBook = cassandraTemplate.selectOne(select, Book.class);
    assertEquals(javaBook.getId(), retrievedBook.getId());
}
 
Example 8
Source File: BookRepositoryIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test(expected = java.util.NoSuchElementException.class)
public void whenDeletingExistingBooks_thenNotAvailableOnRetrieval() {
    final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software"));
    bookRepository.save(ImmutableSet.of(javaBook));
    bookRepository.delete(javaBook);
    final Iterable<Book> books = bookRepository.findByTitleAndPublisher("Head First Java", "O'Reilly Media");
    assertNotEquals(javaBook.getId(), books.iterator().next().getId());
}
 
Example 9
Source File: BookRepositoryIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenAddingANewBook_thenBookExists() {
    bookRepository.deleteTable(BOOKS_BY_TITLE);
    bookRepository.createTableBooksByTitle();

    String title = "Effective Java";
    String author = "Joshua Bloch";
    Book book = new Book(UUIDs.timeBased(), title, author, "Programming");
    bookRepository.insertbookByTitle(book);

    Book savedBook = bookRepository.selectByTitle(title);
    assertEquals(book.getTitle(), savedBook.getTitle());
}
 
Example 10
Source File: CassandraClient.java    From tutorials with MIT License 5 votes vote down vote up
public static void main(String args[]) {
    CassandraConnector connector = new CassandraConnector();
    connector.connect("127.0.0.1", null);
    Session session = connector.getSession();

    KeyspaceRepository sr = new KeyspaceRepository(session);
    sr.createKeyspace("library", "SimpleStrategy", 1);
    sr.useKeyspace("library");

    BookRepository br = new BookRepository(session);
    br.createTable();
    br.alterTablebooks("publisher", "text");

    br.createTableBooksByTitle();

    Book book = new Book(UUIDs.timeBased(), "Effective Java", "Joshua Bloch", "Programming");
    br.insertBookBatch(book);

    br.selectAll().forEach(o -> LOG.info("Title in books: " + o.getTitle()));
    br.selectAllBookByTitle().forEach(o -> LOG.info("Title in booksByTitle: " + o.getTitle()));

    br.deletebookByTitle("Effective Java");
    br.deleteTable("books");
    br.deleteTable("booksByTitle");

    sr.deleteKeyspace("library");

    connector.close();
}
 
Example 11
Source File: CqlQueriesIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenSavingBook_thenAvailableOnRetrieval_usingCQLStatements() {
    final UUID uuid = UUIDs.timeBased();
    final String insertCql = "insert into book (id, title, publisher, tags) values " + "(" + uuid + ", 'Head First Java', 'OReilly Media', {'Software'})";
    cassandraTemplate.execute(insertCql);
    final Select select = QueryBuilder.select().from("book").limit(10);
    final Book retrievedBook = cassandraTemplate.selectOne(select, Book.class);
    assertEquals(uuid, retrievedBook.getId());
}
 
Example 12
Source File: CassandraTemplateIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenAddingBooks_thenCountShouldBeCorrectOnRetrieval() {
    final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software"));
    final Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", ImmutableSet.of("Computer", "Software"));
    cassandraTemplate.insert(javaBook);
    cassandraTemplate.insert(dPatternBook);
    final long bookCount = cassandraTemplate.count(Book.class);
    assertEquals(2, bookCount);
}
 
Example 13
Source File: CObjectCQLGenerator.java    From Rhombus with MIT License 5 votes vote down vote up
protected static CQLStatementIterator makeCQLforInsert(@NotNull String keyspace, @NotNull CDefinition def, @NotNull Map<String,Object> data, @Nullable Object uuid, Long timestamp, Integer ttl) throws CQLGenerationException{
	List<CQLStatement> ret = Lists.newArrayList();
	if(uuid == null){
		uuid = UUIDs.timeBased();
	}
	if(timestamp == 0){
		timestamp = System.currentTimeMillis();
	}
	if(!validateData(def, data)){
		throw new CQLGenerationException("Invalid Insert Requested. Missing Field(s)");
	}
	Map<String,ArrayList> fieldsAndValues = makeFieldAndValueList(def,data);
	//Static Table
	ret.add(makeInsertStatementStatic(
			keyspace,
			makeTableName(def,null),
			(List<String>)fieldsAndValues.get("fields").clone(),
			(List<Object>)fieldsAndValues.get("values").clone(),
			uuid,
			timestamp,
			ttl
	));
	//Index Tables
	if(def.getIndexes() != null) {
		for(CIndex i : def.getIndexes().values()){
			if(def.isAllowNullPrimaryKeyInserts()){
				//check if we have the necessary primary fields to insert on this index. If not just continue;
				if(!i.validateIndexKeys(i.getIndexKeyAndValues(data))){
					continue;
				}
			}
			//insert it into the index
			addCQLStatmentsForIndexInsert(keyspace, true, ret, def,data,i,uuid,fieldsAndValues,timestamp,ttl);
		}
	}
	return new BoundedCQLStatementIterator(ret);
}
 
Example 14
Source File: CassandraTemplateIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenDeletingAllBooks_thenNotAvailableOnRetrieval() {
    final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software"));
    final Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", ImmutableSet.of("Computer", "Software"));
    cassandraTemplate.insert(javaBook);
    cassandraTemplate.insert(dPatternBook);
    cassandraTemplate.deleteAll(Book.class);
    final Select select = QueryBuilder.select().from("book").limit(10);
    final Book retrievedUpdatedBook = cassandraTemplate.selectOne(select, Book.class);
    assertNull(retrievedUpdatedBook);
}
 
Example 15
Source File: PurgeServiceTest.java    From cassandra-reaper with 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 16
Source File: PurgeServiceTest.java    From cassandra-reaper with Apache License 2.0 5 votes vote down vote up
@Test
public void testPurgeByHistoryDepth() throws InterruptedException, ReaperException {
  AppContext context = new AppContext();
  context.config = new ReaperApplicationConfiguration();
  context.config.setNumberOfRunsToKeepPerUnit(5);

  // 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();
  UUID repairUnitId = UUIDs.timeBased();
  for (int i = 0; i < 20; i++) {
    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)
            .endTime(startTime.plusSeconds(1))
            .runState(RunState.DONE)
            .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(15, purged);
}
 
Example 17
Source File: BookRepositoryIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenSavingBook_thenAvailableOnRetrieval() {
    final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software"));
    bookRepository.save(ImmutableSet.of(javaBook));
    final Iterable<Book> books = bookRepository.findByTitleAndPublisher("Head First Java", "O'Reilly Media");
    assertEquals(javaBook.getId(), books.iterator().next().getId());
}
 
Example 18
Source File: DeviceApiController.java    From Groza with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/testAttribute",method = RequestMethod.POST)
public void testAttributeKvEntity() throws ExecutionException, InterruptedException {
    DeviceId deviceId = new DeviceId(UUIDs.timeBased());
   KvEntry attrNewValue = new StringDataEntry("attribute5","value5");
   AttributeKvEntry attrNew = new BaseAttributeKvEntry(attrNewValue,73L);
    attributesService.save(deviceId, DataConstants.CLIENT_SCOPE, Collections.singletonList(attrNew)).get();

}
 
Example 19
Source File: ObjectMapper.java    From Rhombus with MIT License 4 votes vote down vote up
/**
 * Insert a batch of mixed new object with values
 * @param objects Objects to insert
 * @return Map of ids of inserted objects
 * @throws CQLGenerationException
 */
public Map<String, List<UUID>> insertBatchMixed(Map<String, List<Map<String, Object>>> objects) throws CQLGenerationException, RhombusException {
	logger.debug("Insert batch mixed");
	List<CQLStatementIterator> statementIterators = Lists.newArrayList();
	Map<String, List<UUID>> insertedIds = Maps.newHashMap();
	Integer ttl = null;
	for(String objectType : objects.keySet()) {
		List<UUID> ids = Lists.newArrayList();
		for(Map<String, Object> values : objects.get(objectType)) {
			UUID uuid;
			//use the id that was passed in for the insert if it was provided. Otherwise assume the key is a timeuuid
			if(values.containsKey("id")){
				try {
					uuid = UUID.fromString(values.get("id").toString());
				} catch (IllegalArgumentException e) {
					throw new RhombusException("Failed to parse input id " + values.get("id").toString() + " as UUID for object type " + objectType + " in insertBatchMixed");
				}
				values.remove("id");
			}
			else{
				uuid = UUIDs.timeBased();
			}

			// The TTL value can be set on an object-by-object basis.
			ttl = null;
			if(values.containsKey("_ttl")) {
				try {
					ttl = (Integer)values.get("_ttl");
				}
				catch (ClassCastException cce) {
					ttl = null;
				}
			}

			long timestamp = System.currentTimeMillis();
			CQLStatementIterator statementIterator = cqlGenerator.makeCQLforInsert(objectType, values, uuid, timestamp, ttl);
			statementIterators.add(statementIterator);
			ids.add(uuid);
		}
		if (!ids.isEmpty()) {
			insertedIds.put(objectType, ids);
		}
	}
	executeStatements(statementIterators);
	return insertedIds;
}
 
Example 20
Source File: QakkaUtils.java    From usergrid with Apache License 2.0 4 votes vote down vote up
public static UUID getTimeUuid() {
    return UUIDs.timeBased();
}