com.datastax.oss.driver.api.core.cql.Row Java Examples

The following examples show how to use com.datastax.oss.driver.api.core.cql.Row. 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: ScannerImplTest.java    From jesterj with Apache License 2.0 6 votes vote down vote up
@Test
public void testDocFoundDirtyStatus() {
  expect(scanner.getName()).andReturn("Dent, Aurthur Dent").anyTimes();
  expect(scanner.isRemembering()).andReturn(true).anyTimes();
  expect(scanner.isHashing()).andReturn(false).anyTimes();
  expect(docMock.getId()).andReturn("42").anyTimes();
  expect(scanner.getIdFunction()).andReturn((foo) -> foo);
  expect(scanner.getCassandra()).andReturn(supportMock).anyTimes();
  expect(supportMock.getPreparedQuery(ScannerImpl.FTI_CHECK_Q)).andReturn(statementMock);
  expect(supportMock.getSession()).andReturn(sessionMock);
  expect(statementMock.bind("42", "Dent, Aurthur Dent")).andReturn(bsMock);
  expect(sessionMock.execute(bsMock)).andReturn(rsMock);
  expect(rsMock.getAvailableWithoutFetching()).andReturn(1).anyTimes();
  expect(rsMock.isFullyFetched()).andReturn(true);
  List<Row> rows = new ArrayList<>();
  rows.add(rowMock);
  expect(rsMock.all()).andReturn(rows);
  expect(rowMock.getString(0)).andReturn("DIRTY");
  expect(docMock.getIdField()).andReturn("id");
  expect(docMock.put("id", "42")).andReturn(true);
  expect(docMock.removeAll("id")).andReturn(null);

  scanner.sendToNext(docMock);
  replay();
  scanner.docFound(docMock);
}
 
Example #2
Source File: CassandraClientImpl.java    From vertx-cassandra-client with Apache License 2.0 6 votes vote down vote up
private <C, R> Future<R> executeAndCollect(Statement statement, Collector<Row, C, R> collector) {
  C container = collector.supplier().get();
  BiConsumer<C, Row> accumulator = collector.accumulator();
  Function<C, R> finisher = collector.finisher();
  return queryStream(statement)
    .flatMap(cassandraRowStream -> {
      Promise<R> resultPromise = Promise.promise();
      cassandraRowStream.endHandler(end -> {
        R result = finisher.apply(container);
        resultPromise.complete(result);
      });
      cassandraRowStream.handler(row -> {
        accumulator.accept(container, row);
      });
      cassandraRowStream.exceptionHandler(resultPromise::fail);
      return resultPromise.future();
    });
}
 
Example #3
Source File: CassandraRowStreamImpl.java    From vertx-cassandra-client with Apache License 2.0 6 votes vote down vote up
private synchronized void handleFetched(Row row) {
  if (state == State.STOPPED) {
    return;
  }
  if (row != null) {
    inFlight++;
    if (internalQueue.write(row)) {
      context.runOnContext(v -> fetchRow());
    }
  } else {
    state = State.EXHAUSTED;
    if (inFlight == 0) {
      stop();
      handleEnd();
    }
  }
}
 
Example #4
Source File: CassandraStorageAccessor.java    From ShedLock with Apache License 2.0 6 votes vote down vote up
/**
 * Find existing row by primary key lock.name
 *
 * @param name lock name
 * @return optional lock row or empty
 */
Optional<Lock> find(String name) {
    SimpleStatement selectStatement = QueryBuilder.selectFrom(table)
        .column(LOCK_UNTIL)
        .column(LOCKED_AT)
        .column(LOCKED_BY)
        .whereColumn(LOCK_NAME).isEqualTo(literal(name))
        .build()
        .setConsistencyLevel(consistencyLevel);

    ResultSet resultSet = cqlSession.execute(selectStatement);
    Row row = resultSet.one();
    if (row != null) {
        return Optional.of(new Lock(row.getInstant(LOCK_UNTIL), row.getInstant(LOCKED_AT), row.getString(LOCKED_BY)));
    } else {
        return Optional.empty();
    }
}
 
Example #5
Source File: ConversionIntegrationTests.java    From spring-data-examples with Apache License 2.0 6 votes vote down vote up
/**
 * Creates and stores a new {@link Addressbook} inside of Cassandra. {@link Contact} classes are converted using the
 * custom {@link example.springdata.cassandra.convert.ConverterConfiguration.PersonWriteConverter}.
 */
@Test
public void shouldCreateAddressbook() {

	Addressbook addressbook = new Addressbook();
	addressbook.setId("private");

	addressbook.setMe(new Contact("Walter", "White"));
	addressbook.setFriends(Arrays.asList(new Contact("Jesse", "Pinkman"), new Contact("Saul", "Goodman")));

	operations.insert(addressbook);

	Row row = operations.selectOne(QueryBuilder.selectFrom("addressbook").all().asCql(), Row.class);

	assertThat(row).isNotNull();

	assertThat(row.getString("id")).isEqualTo("private");
	assertThat(row.getString("me")).contains("\"firstname\":\"Walter\"");
	assertThat(row.getList("friends", String.class)).hasSize(2);
}
 
Example #6
Source File: CassandraOperationsIntegrationTests.java    From spring-data-examples with Apache License 2.0 6 votes vote down vote up
/**
 * {@link CassandraTemplate} allows selection of projections on template-level. All basic data types including
 * {@link Row} can be selected.
 */
@Test
@SuppressWarnings("unchecked")
public void selectProjections() {

	User user = new User();
	user.setId(42L);
	user.setUsername("heisenberg");
	user.setFirstname("Walter");
	user.setLastname("White");

	template.insert(user);

	Long id = template.selectOne(QueryBuilder.selectFrom("users").column("user_id").asCql(), Long.class);
	assertThat(id).isEqualTo(user.getId());

	Row row = template.selectOne(QueryBuilder.selectFrom("users").column("user_id").asCql(), Row.class);
	assertThat(row.getLong(0)).isEqualTo(user.getId());

	Map<String, Object> map = template.selectOne(QueryBuilder.selectFrom("users").all().asCql(), Map.class);
	assertThat(map).containsEntry("user_id", user.getId());
	assertThat(map).containsEntry("fname", "Walter");
}
 
Example #7
Source File: CassandraAppender.java    From karaf-decanter with Apache License 2.0 6 votes vote down vote up
private static void createTable(CqlSession session, String keyspace, String tableName) {
    ResultSet execute = session.execute("select table_name from system_schema.tables where keyspace_name = '"+keyspace+"';");
    List<Row> all = execute.all();
    boolean found = false;
    for(Row row : all) {
        String table = row.getString("table_name");
        if (table.equalsIgnoreCase(tableName)) {
            found = true;
            break;
        }
    }
    if (!found) {
        session.execute(String.format(createTableTemplate, tableName));
        LOGGER.debug("Table {} has been created", tableName);
    }
}
 
Example #8
Source File: ResultSetImpl.java    From vertx-cassandra-client with Apache License 2.0 6 votes vote down vote up
private void loadMore(Context context, List<Row> loaded, Handler<AsyncResult<List<Row>>> handler) {
  int availableWithoutFetching = resultSetRef.get().remaining();
  List<Row> rows = new ArrayList<>(loaded.size() + availableWithoutFetching);
  rows.addAll(loaded);
  for (int i = 0; i < availableWithoutFetching; i++) {
    rows.add(resultSetRef.get().one());
  }

  if (resultSetRef.get().hasMorePages()) {
    Future.fromCompletionStage(resultSetRef.get().fetchNextPage(), context).onComplete(ar -> {
      if (ar.succeeded()) {
        resultSetRef.set(ar.result());
        loadMore(context, rows, handler);
      } else {
        if (handler != null) {
          handler.handle(Future.failedFuture(ar.cause()));
        }
      }
    });
  } else {
    if (handler != null) {
      handler.handle(Future.succeededFuture(rows));
    }
  }
}
 
Example #9
Source File: ScannerImplTest.java    From jesterj with Apache License 2.0 6 votes vote down vote up
@Test
public void testDocFoundProcessingStatus() {
  expect(scanner.getName()).andReturn("Dent, Aurthur Dent").anyTimes();
  expect(scanner.isRemembering()).andReturn(true).anyTimes();   // remembering
  expect(scanner.isHashing()).andReturn(false).anyTimes();      // but not hashing
  expect(docMock.getId()).andReturn("42").anyTimes();
  expect(scanner.getIdFunction()).andReturn((foo) -> foo);
  expect(scanner.getCassandra()).andReturn(supportMock).anyTimes();
  expect(supportMock.getPreparedQuery(ScannerImpl.FTI_CHECK_Q)).andReturn(statementMock);
  expect(supportMock.getSession()).andReturn(sessionMock);
  expect(statementMock.bind("42", "Dent, Aurthur Dent")).andReturn(bsMock);
  expect(sessionMock.execute(bsMock)).andReturn(rsMock);
  expect(rsMock.getAvailableWithoutFetching()).andReturn(1).anyTimes();
  expect(rsMock.isFullyFetched()).andReturn(true);
  List<Row> rows = new ArrayList<>();
  rows.add(rowMock);
  expect(rsMock.all()).andReturn(rows);
  expect(rowMock.getString(0)).andReturn("PROCESSING");
  expect(docMock.getIdField()).andReturn("id");
  expect(docMock.put("id", "42")).andReturn(true);
  expect(docMock.removeAll("id")).andReturn(null);
  expect(scanner.heuristicDirty(docMock)).andReturn(false);
  replay();
  scanner.docFound(docMock);
}
 
Example #10
Source File: ScannerImplTest.java    From jesterj with Apache License 2.0 6 votes vote down vote up
@Test
public void testDocFoundProcessingStatusButHeuristicDirty() {
  expect(scanner.getName()).andReturn("Dent, Aurthur Dent").anyTimes();
  expect(scanner.isRemembering()).andReturn(true).anyTimes();
  expect(scanner.isHashing()).andReturn(false);
  expect(docMock.getId()).andReturn("42").anyTimes();
  expect(scanner.getIdFunction()).andReturn((foo) -> foo);
  expect(scanner.getCassandra()).andReturn(supportMock).anyTimes();
  expect(supportMock.getPreparedQuery(ScannerImpl.FTI_CHECK_Q)).andReturn(statementMock);
  expect(supportMock.getSession()).andReturn(sessionMock);
  expect(statementMock.bind("42", "Dent, Aurthur Dent")).andReturn(bsMock);
  expect(sessionMock.execute(bsMock)).andReturn(rsMock);
  expect(rsMock.getAvailableWithoutFetching()).andReturn(1).anyTimes();
  expect(rsMock.isFullyFetched()).andReturn(true);
  List<Row> rows = new ArrayList<>();
  rows.add(rowMock);
  expect(rsMock.all()).andReturn(rows);
  expect(rowMock.getString(0)).andReturn("PROCESSING");
  expect(scanner.heuristicDirty(docMock)).andReturn(true);
  expect(docMock.getIdField()).andReturn("id");
  expect(docMock.removeAll("id")).andReturn(null);
  expect(docMock.put("id", "42")).andReturn(true);
  scanner.sendToNext(docMock);
  replay();
  scanner.docFound(docMock);
}
 
Example #11
Source File: CassandraActorSystemEventListenerRepository.java    From elasticactors with Apache License 2.0 6 votes vote down vote up
@Override
public List<ActorSystemEventListener> getAll(ShardKey shardKey, ActorSystemEvent event) {
    ResultSet resultSet = executeWithRetry(cassandraSession, selectStatement.bind(clusterName, shardKey.toString(), event.name()).setPageSize(Integer.MAX_VALUE), logger);
    List<ActorSystemEventListener> resultList = new LinkedList<>();
    for (Row resultRow : resultSet) {
        for (int i = 0; i < resultRow.getColumnDefinitions().size(); i++) {
            ByteBuffer resultBuffer = resultRow.getByteBuffer(i);
            try {
                byte[] resultBytes = new byte[requireNonNull(resultBuffer).remaining()];
                resultBuffer.get(resultBytes);
                resultList.add(ActorSystemEventListenerDeserializer.get().deserialize(resultBytes));
            } catch(NullPointerException | IOException e)  {
                logger.error("IOException while deserializing ActorSystemEventListener",e);
            }
        }
    }
    return resultList;
}
 
Example #12
Source File: CassandraScheduledMessageRepository.java    From elasticactors with Apache License 2.0 6 votes vote down vote up
@Override
public List<ScheduledMessage> getAll(ShardKey shardKey) {
    ResultSet resultSet = executeWithRetry(cassandraSession, selectStatement.bind(clusterName, shardKey.toString()).setPageSize(Integer.MAX_VALUE), logger);
    List<ScheduledMessage> resultList = new LinkedList<>();
    for (Row resultRow : resultSet) {
        for (int i = 0; i < resultRow.getColumnDefinitions().size(); i++) {
            ByteBuffer resultBuffer = resultRow.getByteBuffer(i);
            try {
                byte[] resultBytes = new byte[requireNonNull(resultBuffer).remaining()];
                resultBuffer.get(resultBytes);
                resultList.add(scheduledMessageDeserializer.deserialize(resultBytes));
            } catch (NullPointerException | IOException e) {
                logger.error("IOException while deserializing ScheduledMessage", e);
            }
        }
    }
    return resultList;
}
 
Example #13
Source File: AbstractBackupTest.java    From cassandra-backup with Apache License 2.0 5 votes vote down vote up
protected void dumpTable(final String keyspace, final String table, int expectedLength) {
    try (CqlSession session = CqlSession.builder().build()) {
        List<Row> rows = session.execute(selectFrom(keyspace, table).all().build()).all();

        for (Row row : rows) {
            logger.info(format("id: %s, date: %s, name: %s", row.getString(ID), uuidToDate(requireNonNull(row.getUuid(DATE))), row.getString(NAME)));
        }

        assertEquals(rows.size(), expectedLength);
    }
}
 
Example #14
Source File: InputFormatGrakn.java    From grakn with GNU Affero General Public License v3.0 5 votes vote down vote up
public RecordReader<Long, Row> getRecordReader(InputSplit split, JobConf jobConf, Reporter reporter) throws IOException {
    TaskAttemptContext tac = HadoopCompat.newMapContext(
            jobConf,
            TaskAttemptID.forName(jobConf.get(MAPRED_TASK_ID)),
            null,
            null,
            null,
            new ReporterWrapper(reporter),
            null);


    RecordReaderGrakn recordReader = new RecordReaderGrakn();
    recordReader.initialize((org.apache.hadoop.mapreduce.InputSplit) split, tac);
    return recordReader;
}
 
Example #15
Source File: InputFormatGrakn.java    From grakn with GNU Affero General Public License v3.0 5 votes vote down vote up
private Map<TokenRange, Long> describeSplits(String keyspace, String table, TokenRange tokenRange, int splitSize, int splitSizeMb, CqlSession session) {
    String query = String.format("SELECT mean_partition_size, partitions_count " +
                    "FROM %s.%s " +
                    "WHERE keyspace_name = ? AND table_name = ? AND range_start = ? AND range_end = ?",
            SchemaConstants.SYSTEM_KEYSPACE_NAME,
            SystemKeyspace.SIZE_ESTIMATES);

    ResultSet resultSet = session.execute(session.prepare(query).bind(keyspace, table, tokenRange.getStart().toString(), tokenRange.getEnd().toString()));

    Row row = resultSet.one();

    long meanPartitionSize = 0;
    long partitionCount = 0;
    int splitCount = 0;

    if (row != null) {
        meanPartitionSize = row.getLong("mean_partition_size");
        partitionCount = row.getLong("partitions_count");

        splitCount = splitSizeMb > 0
                ? (int) (meanPartitionSize * partitionCount / splitSizeMb / 1024 / 1024)
                : (int) (partitionCount / splitSize);
    }

    // If we have no data on this split or the size estimate is 0,
    // return the full split i.e., do not sub-split
    // Assume smallest granularity of partition count available from CASSANDRA-7688
    if (splitCount == 0) {
        Map<TokenRange, Long> wrappedTokenRange = new HashMap<>();
        wrappedTokenRange.put(tokenRange, (long) 128);
        return wrappedTokenRange;
    }

    List<TokenRange> splitRanges = tokenRange.splitEvenly(splitCount);
    Map<TokenRange, Long> rangesWithLength = new HashMap<>();
    for (TokenRange range : splitRanges) {
        rangesWithLength.put(range, partitionCount / splitCount);
    }
    return rangesWithLength;
}
 
Example #16
Source File: InputFormatCQL.java    From grakn with GNU Affero General Public License v3.0 5 votes vote down vote up
private KV completeNextKV() throws IOException {
    KV completedKV = null;
    boolean hasNext;
    do {
        hasNext = reader.nextKeyValue();

        if (!hasNext) {
            completedKV = incompleteKV;
            incompleteKV = null;
        } else {
            Row row = reader.getCurrentValue();
            StaticArrayBuffer key = StaticArrayBuffer.of(row.getBytesUnsafe(CQLKeyColumnValueStore.KEY_COLUMN_NAME));
            StaticBuffer column1 = StaticArrayBuffer.of(row.getBytesUnsafe(CQLKeyColumnValueStore.COLUMN_COLUMN_NAME));
            StaticBuffer value = StaticArrayBuffer.of(row.getBytesUnsafe(CQLKeyColumnValueStore.VALUE_COLUMN_NAME));
            Entry entry = StaticArrayEntry.of(column1, value);

            if (null == incompleteKV) {
                // Initialization; this should happen just once in an instance's lifetime
                incompleteKV = new KV(key);
            } else if (!incompleteKV.key.equals(key)) {
                // The underlying Cassandra reader has just changed to a key we haven't seen yet
                // This implies that there will be no more entries for the prior key
                completedKV = incompleteKV;
                incompleteKV = new KV(key);
            }

            incompleteKV.addEntry(entry);
        }
        /* Loop ends when either
         * A) the cassandra reader ran out of data
         * or
         * B) the cassandra reader switched keys, thereby completing a KV */
    } while (hasNext && null == completedKV);

    return completedKV;
}
 
Example #17
Source File: ClusterManager.java    From act-platform with ISC License 5 votes vote down vote up
private boolean keyspaceExists() {
  // Fetch all existing keyspaces from the system table and check if 'act' exists.
  for (Row row : session.execute("SELECT * FROM system_schema.keyspaces")) {
    if (Objects.equals(KEY_SPACE, row.getString("keyspace_name"))) return true;
  }

  return false;
}
 
Example #18
Source File: InputFormatGrakn.java    From grakn with GNU Affero General Public License v3.0 5 votes vote down vote up
public boolean next(Long key, Row value) throws IOException {
    if (nextKeyValue()) {
        ((WrappedRow) value).setRow(getCurrentValue());
        return true;
    }
    return false;
}
 
Example #19
Source File: StreamingTest.java    From vertx-cassandra-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadStream(TestContext testContext) throws Exception {
  initializeRandomStringKeyspace();
  insertRandomStrings(50);
  String query = "select random_string from random_strings.random_string_by_first_letter where first_letter = 'A'";
  Statement statement = SimpleStatement.newInstance(query)
    .setPageSize(5); // make sure data is not loaded at once from Cassandra
  Async async = testContext.async();
  client.queryStream(query, testContext.asyncAssertSuccess(stream -> {
    List<Row> items = Collections.synchronizedList(new ArrayList<>());
    AtomicInteger idx = new AtomicInteger();
    long pause = 500;
    long start = System.nanoTime();
    stream.endHandler(end -> {
      long duration = NANOSECONDS.toMillis(System.nanoTime() - start);
      testContext.assertTrue(duration >= 5 * pause);
      async.countDown();
    }).exceptionHandler(testContext::fail).handler(item -> {
      items.add(item);
      int j = idx.getAndIncrement();
      if (j == 3 || j == 16 || j == 21 || j == 38 || j == 47) {
        stream.pause();
        int emitted = items.size();
        vertx.setTimer(pause, tid -> {
          testContext.assertTrue(emitted == items.size());
          stream.resume();
        });
      }
    });
  }));
}
 
Example #20
Source File: CassandraClientTestBase.java    From vertx-cassandra-client with Apache License 2.0 5 votes vote down vote up
protected static void getCassandraReleaseVersion(CassandraClient client, Handler<AsyncResult<String>> handler) {
  client.executeWithFullFetch("select release_version from system.local", ar -> {
    if (ar.succeeded()) {
      List<Row> result = ar.result();
      handler.handle(Future.succeededFuture(result.iterator().next().getString("release_version")));
    } else {
      handler.handle(Future.failedFuture(ar.cause()));
    }
  });
}
 
Example #21
Source File: CQLResultSetKeyIterator.java    From grakn with GNU Affero General Public License v3.0 5 votes vote down vote up
EntryRecordIterator(SliceQuery sliceQuery, CQLColValGetter getter, Iterator<Row> iterator, StaticBuffer key) {
    this.getter = getter;
    StaticBuffer sliceEnd = sliceQuery.getSliceEnd();
    this.iterator = iterator
            .<Tuple3<StaticBuffer, StaticBuffer, Row>> map(row -> Tuple.of(
                    StaticArrayBuffer.of(row.getByteBuffer(CQLKeyColumnValueStore.COLUMN_COLUMN_NAME)),
                    StaticArrayBuffer.of(row.getByteBuffer(CQLKeyColumnValueStore.VALUE_COLUMN_NAME)),
                    row))
            .takeWhile(tuple -> key.equals(StaticArrayBuffer.of(tuple._3.getByteBuffer(CQLKeyColumnValueStore.KEY_COLUMN_NAME))) && !sliceEnd.equals(tuple._1))
            .take(sliceQuery.getLimit());
}
 
Example #22
Source File: CQLColValGetter.java    From grakn with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Object getMetaData(Tuple3<StaticBuffer, StaticBuffer, Row> tuple, EntryMetaData metaData) {
    switch (metaData) {
        case TIMESTAMP:
            return tuple._3.getLong(grakn.core.graph.diskstorage.cql.CQLKeyColumnValueStore.WRITETIME_COLUMN_NAME);
        case TTL:
            return tuple._3.getInt(grakn.core.graph.diskstorage.cql.CQLKeyColumnValueStore.TTL_COLUMN_NAME);
        default:
            throw new UnsupportedOperationException("Unsupported meta data: " + metaData);
    }
}
 
Example #23
Source File: CQLKeyColumnValueStore.java    From grakn with GNU Affero General Public License v3.0 5 votes vote down vote up
private static EntryList fromResultSet(ResultSet resultSet, StaticArrayEntry.GetColVal<Tuple3<StaticBuffer, StaticBuffer, Row>, StaticBuffer> getter) {
    Lazy<ArrayList<Row>> lazyList = Lazy.of(() -> Lists.newArrayList(resultSet));

    // Use the Iterable overload of of ByteBuffer as it's able to allocate
    // the byte array up front.
    // To ensure that the Iterator instance is recreated, it is created
    // within the closure otherwise
    // the same iterator would be reused and would be exhausted.
    return StaticArrayEntryList.ofStaticBuffer(() -> Iterator.ofAll(lazyList.get()).map(row -> Tuple.of(
            StaticArrayBuffer.of(row.getByteBuffer(COLUMN_COLUMN_NAME)),
            StaticArrayBuffer.of(row.getByteBuffer(VALUE_COLUMN_NAME)),
            row)),
            getter);
}
 
Example #24
Source File: ConversionIntegrationTests.java    From spring-data-examples with Apache License 2.0 5 votes vote down vote up
/**
 * Creates and stores a new {@link Addressbook} inside of Cassandra writing map and tuple columns.
 */
@Test
public void shouldWriteConvertedMapsAndTuples() {

	Addressbook addressbook = new Addressbook();
	addressbook.setId("private");

	Map<Integer, Currency> preferredCurrencies = new HashMap<>();
	preferredCurrencies.put(1, Currency.getInstance("USD"));
	preferredCurrencies.put(2, Currency.getInstance("EUR"));

	Address address = new Address();
	address.setAddress("3828 Piermont Dr");
	address.setCity("Albuquerque");
	address.setZip("87111");

	addressbook.setPreferredCurrencies(preferredCurrencies);
	addressbook.setAddress(address);

	operations.insert(addressbook);

	Row row = operations.selectOne(QueryBuilder.selectFrom("addressbook").all().asCql(), Row.class);

	assertThat(row).isNotNull();

	TupleValue tupleValue = row.getTupleValue("address");
	assertThat(tupleValue.getString(0)).isEqualTo(address.getAddress());
	assertThat(tupleValue.getString(1)).isEqualTo(address.getCity());
	assertThat(tupleValue.getString(2)).isEqualTo(address.getZip());

	Map<Integer, String> rawPreferredCurrencies = row.getMap("preferredCurrencies", Integer.class, String.class);

	assertThat(rawPreferredCurrencies).containsEntry(1, "USD").containsEntry(2, "EUR");
}
 
Example #25
Source File: CassandraAppenderTest.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    Marshaller marshaller = new JsonMarshaller();
    CassandraAppender appender = new CassandraAppender();
    Dictionary<String, Object> config = new Hashtable<>();
    config.put(CassandraAppender.CASSANDRA_PORT_PROPERTY, CASSANDRA_HOST);
    config.put(CassandraAppender.CASSANDRA_PORT_PROPERTY, CASSANDRA_PORT);
    config.put(CassandraAppender.KEYSPACE_PROPERTY, KEYSPACE);
    config.put(CassandraAppender.TABLE_PROPERTY, TABLE_NAME);
    appender.marshaller = marshaller;
    appender.activate(config);
    
    Map<String, Object> properties = new HashMap<>();
    properties.put(EventConstants.TIMESTAMP, TIMESTAMP);
    Event event = new Event(TOPIC, properties);
    
    appender.handleEvent(event);
    appender.deactivate();

    CqlSession session = getSession();

    ResultSet execute = session.execute("SELECT * FROM "+ KEYSPACE+"."+TABLE_NAME+";");
    List<Row> all = execute.all();
    Assert.assertEquals(1, all.size());
    assertThat(all, not(nullValue()));
    
    assertThat(all.get(0).getInstant("timeStamp").toEpochMilli(), is(TIMESTAMP));
    
    session.close();
}
 
Example #26
Source File: ScannerImplTest.java    From jesterj with Apache License 2.0 5 votes vote down vote up
@Test
public void testDocFoundProcessingStatusButHashChange() {
  expect(scanner.getName()).andReturn("Dent, Aurthur Dent").anyTimes();
  expect(scanner.isRemembering()).andReturn(true).anyTimes();
  expect(scanner.isHashing()).andReturn(true).anyTimes();
  expect(docMock.getId()).andReturn("42").anyTimes();
  expect(scanner.getIdFunction()).andReturn((foo) -> foo);
  expect(scanner.getCassandra()).andReturn(supportMock).anyTimes();
  expect(supportMock.getPreparedQuery(ScannerImpl.FTI_CHECK_Q)).andReturn(statementMock);
  expect(supportMock.getSession()).andReturn(sessionMock);
  expect(statementMock.bind("42", "Dent, Aurthur Dent")).andReturn(bsMock);
  expect(sessionMock.execute(bsMock)).andReturn(rsMock);
  expect(rsMock.getAvailableWithoutFetching()).andReturn(1).anyTimes();
  expect(rsMock.isFullyFetched()).andReturn(true);
  List<Row> rows = new ArrayList<>();
  rows.add(rowMock);
  expect(rsMock.all()).andReturn(rows);
  expect(rowMock.getString(0)).andReturn("PROCESSING");
  expect(rowMock.getString(1)).andReturn("CAFEBABE");
  expect(scanner.heuristicDirty(docMock)).andReturn(false);
  expect(docMock.getHash()).andReturn("DEADBEEF");
  expect(docMock.removeAll("id")).andReturn(null);
  expect(docMock.getIdField()).andReturn("id");
  expect(docMock.put("id", "42")).andReturn(true);
  scanner.sendToNext(docMock);
  replay();
  scanner.docFound(docMock);
}
 
Example #27
Source File: ScannerImplTest.java    From jesterj with Apache License 2.0 5 votes vote down vote up
@Test
public void testDocFoundProcessingStatusButNoHashChange() {
  expect(scanner.getName()).andReturn("Dent, Aurthur Dent").anyTimes();
  expect(scanner.isRemembering()).andReturn(true).anyTimes();
  expect(scanner.isHashing()).andReturn(true).anyTimes();
  expect(docMock.getId()).andReturn("42").anyTimes();
  expect(scanner.getIdFunction()).andReturn((foo) -> foo);
  expect(scanner.getCassandra()).andReturn(supportMock).anyTimes();
  expect(supportMock.getPreparedQuery(ScannerImpl.FTI_CHECK_Q)).andReturn(statementMock);
  expect(supportMock.getSession()).andReturn(sessionMock);
  expect(statementMock.bind("42", "Dent, Aurthur Dent")).andReturn(bsMock);
  expect(sessionMock.execute(bsMock)).andReturn(rsMock);
  expect(rsMock.getAvailableWithoutFetching()).andReturn(1).anyTimes();
  expect(rsMock.isFullyFetched()).andReturn(true);
  List<Row> rows = new ArrayList<>();
  rows.add(rowMock);
  expect(rsMock.all()).andReturn(rows);
  expect(rowMock.getString(0)).andReturn("PROCESSING");
  expect(rowMock.getString(1)).andReturn("CAFEBABE");
  expect(docMock.getIdField()).andReturn("id");
  expect(docMock.put("id", "42")).andReturn(true);
  expect(docMock.removeAll("id")).andReturn(null);
  expect(scanner.heuristicDirty(docMock)).andReturn(false);
  expect(docMock.getHash()).andReturn("CAFEBABE");
  replay();
  scanner.docFound(docMock);
}
 
Example #28
Source File: ScannerImplTest.java    From jesterj with Apache License 2.0 5 votes vote down vote up
@Test
public void testDocFoundProcessingStatusButNoHash() {
  expect(scanner.getName()).andReturn("Dent, Aurthur Dent").anyTimes();
  expect(scanner.isRemembering()).andReturn(true).anyTimes();
  expect(scanner.isHashing()).andReturn(true).anyTimes();
  expect(docMock.getId()).andReturn("42").anyTimes();
  expect(scanner.getIdFunction()).andReturn((foo) -> foo);
  expect(scanner.getCassandra()).andReturn(supportMock).anyTimes();
  expect(supportMock.getPreparedQuery(ScannerImpl.FTI_CHECK_Q)).andReturn(statementMock);
  expect(supportMock.getSession()).andReturn(sessionMock);
  expect(statementMock.bind("42", "Dent, Aurthur Dent")).andReturn(bsMock);
  expect(sessionMock.execute(bsMock)).andReturn(rsMock);
  expect(rsMock.getAvailableWithoutFetching()).andReturn(1).anyTimes();
  expect(rsMock.isFullyFetched()).andReturn(true);
  List<Row> rows = new ArrayList<>();
  rows.add(rowMock);
  expect(rsMock.all()).andReturn(rows);
  expect(rowMock.getString(0)).andReturn("PROCESSING");
  expect(rowMock.getString(1)).andReturn(null);
  expect(scanner.heuristicDirty(docMock)).andReturn(false);
  expect(docMock.getIdField()).andReturn("id");
  expect(docMock.removeAll("id")).andReturn(null);
  expect(docMock.put("id", "42")).andReturn(true);
  scanner.sendToNext(docMock);
  replay();
  scanner.docFound(docMock);
}
 
Example #29
Source File: CassandraPersistentActorRepository.java    From elasticactors with Apache License 2.0 5 votes vote down vote up
@Override
public PersistentActor<ShardKey> get(final ShardKey shard,final String actorId) throws IOException {
    Row resultRow = internalGet(shard, actorId);
    if (resultRow == null || resultRow.getColumnDefinitions().size() == 0) {
        return null;
    } else {
        // should have only a single column here
        return this.deserializer.deserialize(resultRow.getByteBuffer(0));
    }
}
 
Example #30
Source File: CassandraPersistentActorRepository.java    From elasticactors with Apache License 2.0 5 votes vote down vote up
private Row internalGet(final ShardKey shard,final String actorId) {
    // log a warning when we exceed the readExecutionThreshold
    final long startTime = currentTimeMillis();
    try {
        ResultSet resultSet = executeWithRetry(cassandraSession, selectStatement.bind(clusterName, shard.toString(), actorId), logger);
        return resultSet.one();
    } finally {
        final long endTime = currentTimeMillis();
        if((endTime - startTime) > readExecutionThresholdMillis) {
            logger.warn("Cassandra read operation took {} msecs for actorId [{}] on shard [{}]", (endTime - startTime), actorId, shard);
        }
    }
}