com.datastax.driver.core.BoundStatement Java Examples
The following examples show how to use
com.datastax.driver.core.BoundStatement.
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: CassandraQueryExecutor.java From arcusplatform with Apache License 2.0 | 7 votes |
public static <T> PagedResults<T> page(Session session, BoundStatement statement, int limit, Function<Row, T> transformer, Function<Row, String> token) { List<T> results = new ArrayList<>(limit); statement.setFetchSize(limit + 1); ResultSet rs = session.execute( statement ); Row row = rs.one(); while(row != null && results.size() < limit) { try { T result = transformer.apply(row); results.add(result); } catch(Exception e) { log.warn("Unable to deserialize row {}", row, e); } row = rs.one(); } if(row == null) { return PagedResults.newPage(results); } else { return PagedResults.newPage(results, token.apply(row)); } }
Example #2
Source File: IncidentDao.java From glowroot with Apache License 2.0 | 6 votes |
@Override public List<OpenIncident> readOpenIncidents(String agentRollupId) throws Exception { BoundStatement boundStatement = readOpenIncidentsPS.bind(); boundStatement.setString(0, agentRollupId); ResultSet results = session.read(boundStatement); List<OpenIncident> openIncidents = new ArrayList<>(); for (Row row : results) { int i = 0; AlertCondition condition = AlertCondition.parseFrom(checkNotNull(row.getBytes(i++))); AlertSeverity severity = AlertSeverity .valueOf(checkNotNull(row.getString(i++)).toUpperCase(Locale.ENGLISH)); AlertNotification notification = AlertNotification.parseFrom(checkNotNull(row.getBytes(i++))); long openTime = checkNotNull(row.getTimestamp(i++)).getTime(); openIncidents.add(ImmutableOpenIncident.builder() .agentRollupId(agentRollupId) .condition(condition) .severity(severity) .notification(notification) .openTime(openTime) .build()); } return openIncidents; }
Example #3
Source File: Session.java From glowroot with Apache License 2.0 | 6 votes |
public ResultSet update(Statement statement) throws Exception { if (statement instanceof BoundStatement) { BoundStatement boundStatement = (BoundStatement) statement; PreparedStatement preparedStatement = boundStatement.preparedStatement(); String queryString = preparedStatement.getQueryString(); if (!queryString.contains(" if ")) { throw new IllegalStateException("Unexpected update query: " + queryString); } if (!queryString.startsWith("update ") && !queryString.startsWith("insert ")) { throw new IllegalStateException("Unexpected update query: " + queryString); } } // do not use session.execute() because that calls getUninterruptibly() which can cause // central shutdown to timeout while waiting for executor service to shutdown return updateAsync(statement).get(); }
Example #4
Source File: TraceDaoImpl.java From glowroot with Apache License 2.0 | 6 votes |
private static int bind(BoundStatement boundStatement, String agentRollupId, String agentId, String traceId, Trace.Header header, boolean overall, boolean useCaptureTimePartialRollup) { int i = 0; boundStatement.setString(i++, agentRollupId); boundStatement.setString(i++, header.getTransactionType()); if (!overall) { boundStatement.setString(i++, header.getTransactionName()); } if (useCaptureTimePartialRollup) { boundStatement.setTimestamp(i++, new Date(header.getCaptureTimePartialRollup())); } else { boundStatement.setTimestamp(i++, new Date(header.getCaptureTime())); } boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); return i; }
Example #5
Source File: Cassandra2xDefaultMapDAO.java From cumulusrdf with Apache License 2.0 | 6 votes |
@Override public K getKey(final V value) { if (!_bidirectional) { throw new IllegalStateException("Map is not bidirectional"); } ByteBuffer serializedValue = _valueSerializer.serialize(value); BoundStatement getKeyStatement = _getKeyStatement.bind(serializedValue); Row result = _session.execute(getKeyStatement).one(); if (result == null) { return _defaultKey; } else { return _keySerializer.deserialize(result.getBytesUnsafe(0)); } }
Example #6
Source File: GuicedCassandraSessionDAO.java From arcusplatform with Apache License 2.0 | 6 votes |
private Session doCassandraReadSession(Serializable sessionId) { UUID id = toUuid(sessionId); BoundStatement bs = new BoundStatement(this.readPreparedStatement); bs.bind(id); bs.setConsistencyLevel(consistencyLevel); ResultSet results = cassandraSession.execute(bs); for(Row row : results) { Session session = hydrateSession(id, row); if (session != null && !isExpired(session)) { return session; } } throw NO_SESSION_EXCEPTION; }
Example #7
Source File: SetPrimaryPlace.java From arcusplatform with Apache License 2.0 | 6 votes |
@Override public void execute(ExecutionContext context, boolean autoRollback) throws CommandExecutionException { PreparedStatement stmt = context.getSession().prepare(update); List<Row> rows = context.getSession().execute("SELECT id, accountid, created FROM place").all(); List<Row> ordered = rows.stream().sorted((r1, r2) -> r1.getTimestamp("created").compareTo(r2.getTimestamp("created"))).collect(Collectors.toList()); Set<UUID> accountsSeen = new HashSet<>(); BatchStatement batch = new BatchStatement(); ordered.forEach((r) -> { batch.add(new BoundStatement(stmt) .setBool("is_primary", !accountsSeen.contains(r.getUUID("accountid"))) .setUUID("id", r.getUUID("id"))); accountsSeen.add(r.getUUID("accountid")); }); context.getSession().execute(batch); }
Example #8
Source File: AggregateDaoImpl.java From glowroot with Apache License 2.0 | 6 votes |
private ListenableFuture<?> rollupOverallSummaryFromRows(RollupParams rollup, AggregateQuery query, Iterable<Row> rows) throws Exception { double totalDurationNanos = 0; long transactionCount = 0; for (Row row : rows) { totalDurationNanos += row.getDouble(0); transactionCount += row.getLong(1); } BoundStatement boundStatement = getInsertOverallPS(summaryTable, rollup.rollupLevel()).bind(); int i = 0; boundStatement.setString(i++, rollup.agentRollupId()); boundStatement.setString(i++, query.transactionType()); boundStatement.setTimestamp(i++, new Date(query.to())); boundStatement.setDouble(i++, totalDurationNanos); boundStatement.setLong(i++, transactionCount); boundStatement.setInt(i++, rollup.adjustedTTL().generalTTL()); return session.writeAsync(boundStatement); }
Example #9
Source File: RowRead.java From geowave with Apache License 2.0 | 6 votes |
public CassandraRow result() { if ((partitionKey != null) && (sortKey != null)) { final BoundStatement boundRead = new BoundStatement(preparedRead); boundRead.set( CassandraField.GW_SORT_KEY.getBindMarkerName(), ByteBuffer.wrap(sortKey), ByteBuffer.class); boundRead.set( CassandraField.GW_ADAPTER_ID_KEY.getBindMarkerName(), internalAdapterId, TypeCodec.smallInt()); boundRead.set( CassandraField.GW_PARTITION_ID_KEY.getBindMarkerName(), ByteBuffer.wrap(partitionKey), ByteBuffer.class); try (CloseableIterator<CassandraRow> it = operations.executeQuery(boundRead)) { if (it.hasNext()) { // there should only be one entry with this index return it.next(); } } } return null; }
Example #10
Source File: MobileDeviceDAOImpl.java From arcusplatform with Apache License 2.0 | 6 votes |
@Override public MobileDevice findWithToken(String token) { if (StringUtils.isBlank(token)){ return null; } try(Context ctxt = findWithTokenTimer.time()){ Row row = session.execute(new BoundStatement(getPersonAndIdForToken).bind(token)).one(); if (row == null){ return null; } UUID personId = row.getUUID("personId"); int deviceIndex = row.getInt("deviceIndex"); return findOne(personId, deviceIndex); } }
Example #11
Source File: TraceDaoImpl.java From glowroot with Apache License 2.0 | 6 votes |
@Override public long readSlowCount(String agentRollupId, TraceQuery query) throws Exception { BoundStatement boundStatement; BoundStatement boundStatementPartial; String transactionName = query.transactionName(); if (transactionName == null) { boundStatement = readOverallSlowCount.bind(); boundStatementPartial = readOverallSlowCountPartial.bind(); bindTraceQuery(boundStatement, agentRollupId, query, true); bindTraceQueryPartial(boundStatementPartial, agentRollupId, query, true, cassandra2x); } else { boundStatement = readTransactionSlowCount.bind(); boundStatementPartial = readTransactionSlowCountPartial.bind(); bindTraceQuery(boundStatement, agentRollupId, query, false); bindTraceQueryPartial(boundStatementPartial, agentRollupId, query, false, cassandra2x); } Future<ResultSet> future = session.readAsync(boundStatement); Future<ResultSet> futurePartial = session.readAsync(boundStatementPartial); return future.get().one().getLong(0) + futurePartial.get().one().getLong(0); }
Example #12
Source File: TraceDaoImpl.java From glowroot with Apache License 2.0 | 6 votes |
@Override public Result<TracePoint> readErrorPoints(String agentRollupId, TraceQuery query, TracePointFilter filter, int limit) throws Exception { BoundStatement boundStatement; String transactionName = query.transactionName(); if (transactionName == null) { boundStatement = readOverallErrorPoint.bind(); bindTraceQuery(boundStatement, agentRollupId, query, true); } else { boundStatement = readTransactionErrorPoint.bind(); bindTraceQuery(boundStatement, agentRollupId, query, false); } ResultSet results = session.read(boundStatement); List<TracePoint> errorPoints = processPoints(results, filter, false, true); return createResult(errorPoints, limit); }
Example #13
Source File: SchemaUpgrade.java From glowroot with Apache License 2.0 | 6 votes |
private void rewriteAgentConfigTablePart1() throws Exception { dropTableIfExists("agent_config_temp"); session.updateSchemaWithRetry("create table if not exists agent_config_temp" + " (agent_rollup_id varchar, config blob, config_update boolean," + " config_update_token uuid, primary key (agent_rollup_id))"); PreparedStatement insertTempPS = session.prepare("insert into agent_config_temp" + " (agent_rollup_id, config, config_update, config_update_token) values" + " (?, ?, ?, ?)"); ResultSet results = session.read("select agent_rollup_id, config, config_update," + " config_update_token from agent_config"); for (Row row : results) { BoundStatement boundStatement = insertTempPS.bind(); boundStatement.setString(0, row.getString(0)); boundStatement.setBytes(1, row.getBytes(1)); boundStatement.setBool(2, row.getBool(2)); boundStatement.setUUID(3, row.getUUID(3)); session.write(boundStatement); } }
Example #14
Source File: HubDAOImpl.java From arcusplatform with Apache License 2.0 | 6 votes |
@Override public Map<String, Object> disconnected(String hubId) { Date ts = new Date(); BoundStatement bs = disconnected.bind(HubCapability.STATE_DOWN, JSON.toJson(HubConnectionCapability.STATE_OFFLINE), JSON.toJson(ts), ts, hubId); try(Context ctx = disconnectedTimer.time()) { ResultSet rs = session.execute(bs); if( !rs.wasApplied() ) { throw new NotFoundException( Address.hubService(hubId, HubCapability.NAMESPACE) ); } } return ImmutableMap.of( HubCapability.ATTR_STATE, HubCapability.STATE_DOWN, HubConnectionCapability.ATTR_STATE, HubConnectionCapability.STATE_OFFLINE, HubConnectionCapability.ATTR_LASTCHANGE, ts ); }
Example #15
Source File: CassandraTransactionalKeyValue.java From yb-sample-apps with Apache License 2.0 | 6 votes |
@Override public long doRead() { Key key = getSimpleLoadGenerator().getKeyToRead(); if (key == null) { // There are no keys to read yet. return 0; } // Do the read from Cassandra. // Bind the select statement. BoundStatement select = getPreparedSelect().bind(Arrays.asList(key.asString() + "_1", key.asString() + "_2")); ResultSet rs = getCassandraClient().execute(select); List<Row> rows = rs.all(); if (rows.size() != 2) { LOG.fatal("Read key: " + key.asString() + " expected 2 row in result, got " + rows.size()); return 1; } verifyValue(key, rows.get(0).getLong(1), rows.get(1).getLong(1)); if (rows.get(0).getLong(2) != rows.get(1).getLong(2)) { LOG.fatal("Writetime mismatch for key: " + key.toString() + ", " + rows.get(0).getLong(2) + " vs " + rows.get(1).getLong(2)); } LOG.debug("Read key: " + key.toString()); return 1; }
Example #16
Source File: TraceDaoImpl.java From glowroot with Apache License 2.0 | 6 votes |
private List<Aggregate.Query> readQueriesInternal(String agentId, String traceId) throws Exception { BoundStatement boundStatement = readQueriesV2.bind(); boundStatement.setString(0, agentId); boundStatement.setString(1, traceId); ResultSet results = session.read(boundStatement); List<Aggregate.Query> queries = new ArrayList<>(); while (!results.isExhausted()) { Row row = results.one(); int i = 0; Aggregate.Query.Builder query = Aggregate.Query.newBuilder() .setType(checkNotNull(row.getString(i++))) .setSharedQueryTextIndex(row.getInt(i++)) .setTotalDurationNanos(row.getDouble(i++)) .setExecutionCount(row.getLong(i++)); long totalRows = row.getLong(i++); if (!NotAvailableAware.isNA(totalRows)) { query.setTotalRows(OptionalInt64.newBuilder().setValue(totalRows)); } query.setActive(row.getBool(i++)); queries.add(query.build()); } return queries; }
Example #17
Source File: DTimerIO.java From blueflood with Apache License 2.0 | 6 votes |
/** * Retrieves the {@link BoundStatement} for a particular counter metric * @param metric * @param granularity * @return */ @Override protected BoundStatement getBoundStatementForMetric(IMetric metric, Granularity granularity) { Object metricValue = metric.getMetricValue(); if (!(metricValue instanceof BluefloodTimerRollup)) { throw new InvalidDataException( String.format("getBoundStatementForMetric(locator=%s, granularity=%s): metric value %s is not type BluefloodTimerRollup", metric.getLocator(), granularity, metric.getMetricValue().getClass().getSimpleName()) ); } PreparedStatement statement = metricsCFPreparedStatements.preaggrGranToInsertStatement.get(granularity); return statement.bind( metric.getLocator().toString(), metric.getCollectionTime(), serDes.serialize( (BluefloodTimerRollup) metricValue ), metric.getTtlInSeconds() ); }
Example #18
Source File: AggregateDaoImpl.java From glowroot with Apache License 2.0 | 6 votes |
@Override public void mergeTransactionNameSummariesInto(String agentRollupId, SummaryQuery query, SummarySortOrder sortOrder, int limit, TransactionNameSummaryCollector collector) throws Exception { // currently have to do group by / sort / limit client-side BoundStatement boundStatement = checkNotNull(readTransactionPS.get(summaryTable)).get(query.rollupLevel()).bind(); bindQuery(boundStatement, agentRollupId, query); ResultSet results = session.read(boundStatement); for (Row row : results) { int i = 0; long captureTime = checkNotNull(row.getTimestamp(i++)).getTime(); String transactionName = checkNotNull(row.getString(i++)); double totalDurationNanos = row.getDouble(i++); long transactionCount = row.getLong(i++); collector.collect(transactionName, totalDurationNanos, transactionCount, captureTime); } }
Example #19
Source File: SchemaUpgrade.java From glowroot with Apache License 2.0 | 6 votes |
private void renameAgentColumnFromSystemInfoToEnvironment() throws Exception { if (!columnExists("agent", "system_info")) { // previously failed mid-upgrade prior to updating schema version return; } addColumnIfNotExists("agent", "environment", "blob"); ResultSet results = session.read("select agent_id, system_info from agent"); PreparedStatement preparedStatement = session.prepare("insert into agent (agent_id, environment) values (?, ?)"); for (Row row : results) { BoundStatement boundStatement = preparedStatement.bind(); boundStatement.setString(0, row.getString(0)); boundStatement.setBytes(1, row.getBytes(1)); session.write(boundStatement); } session.updateSchemaWithRetry("alter table agent drop system_info"); }
Example #20
Source File: CassandraPersonalization.java From yb-sample-apps with Apache License 2.0 | 6 votes |
@Override public long doRead() { Key key = getSimpleLoadGenerator().getKeyToRead(); if (key == null) { // There are no keys to read yet. return 0; } // Do the read from Cassandra. // Bind the select statement. String customerId = key.asString(); String storeId = Integer.toString(rand.nextInt(appConfig.numStores)); BoundStatement select = getPreparedSelect().bind(customerId, storeId); ResultSet rs = getCassandraClient().execute(select); List<Row> rows = rs.all(); LOG.debug("Read coupon count: " + rows.size()); return 1; }
Example #21
Source File: CassandraLoadBalancerStoreTest.java From titus-control-plane with Apache License 2.0 | 6 votes |
@Test(timeout = TIMEOUT_MS) public void testUpdateTarget() throws Exception { Session session = cassandraCQLUnit.getSession(); BoundStatement countStmt = session.prepare("SELECT COUNT(*) FROM load_balancer_targets;").bind(); PreparedStatement stateStmt = session.prepare("SELECT state FROM load_balancer_targets WHERE load_balancer_id = ? AND ip_address = ?;"); assertThat(session.execute(countStmt).one().getLong(0)).isEqualTo(0); LoadBalancerTarget target = new LoadBalancerTarget("lb-1", "task-1", "1.1.1.1"); CassandraLoadBalancerStore store = getInitdStore(); store.addOrUpdateTargets(target.withState(LoadBalancerTarget.State.REGISTERED)).block(); assertThat(session.execute(countStmt).one().getLong(0)).isEqualTo(1); Row registered = session.execute(stateStmt.bind("lb-1", "1.1.1.1")).one(); assertThat(registered.getString("state")).isEqualTo("REGISTERED"); store.addOrUpdateTargets(target.withState(LoadBalancerTarget.State.DEREGISTERED)).block(); assertThat(session.execute(countStmt).one().getLong(0)).isEqualTo(1); Row deregistered = session.execute(stateStmt.bind("lb-1", "1.1.1.1")).one(); assertThat(deregistered.getString("state")).isEqualTo("DEREGISTERED"); }
Example #22
Source File: DBasicNumericIO.java From blueflood with Apache License 2.0 | 6 votes |
/** * * @param metric * @param granularity * @return */ @Override protected BoundStatement getBoundStatementForMetric(IMetric metric, Granularity granularity) { Object metricValue = metric.getMetricValue(); if ( ! (metricValue instanceof BasicRollup) ) { throw new InvalidDataException( String.format("getBoundStatementForMetric(locator=%s, granularity=%s): metric value %s is not type BasicRollup", metric.getLocator(), granularity, metric.getMetricValue().getClass().getSimpleName()) ); } PreparedStatement statement = metricsCFPreparedStatements.basicGranToInsertStatement.get(granularity); return statement.bind( metric.getLocator().toString(), metric.getCollectionTime(), serDes.serialize( (BasicRollup) metric.getMetricValue() ), metric.getTtlInSeconds() ); }
Example #23
Source File: CassandraClusterServiceDao.java From arcusplatform with Apache License 2.0 | 6 votes |
@Override public ClusterServiceRecord heartbeat(ClusterServiceRecord record) throws ClusterServiceDaoException { try(Timer.Context timer = ClusterServiceMetrics.heartbeatTimer.time()) { Instant instant = clock.instant(); Date now = new Date(instant.toEpochMilli()); BoundStatement bs = heartbeat.bind(now, record.getService(), record.getMemberId(), record.getHost(), new Date(record.getRegistered().toEpochMilli())); ResultSet rs = session.execute( bs ); if(!rs.wasApplied()) { ClusterServiceMetrics.clusterIdLostCounter.inc(); throw new ClusterIdLostException("Another service has taken the member id"); } ClusterServiceRecord copy = record.copy(); copy.setLastHeartbeat(instant); return copy; } }
Example #24
Source File: CassandraSessionImpl.java From ignite with Apache License 2.0 | 6 votes |
/** * Tunes CQL statement execution options (consistency level, fetch option and etc.). * * @param statement Statement. * @return Modified statement. */ private Statement tuneStatementExecutionOptions(Statement statement) { String qry = ""; if (statement instanceof BoundStatement) qry = ((BoundStatement)statement).preparedStatement().getQueryString().trim().toLowerCase(); else if (statement instanceof PreparedStatement) qry = ((PreparedStatement)statement).getQueryString().trim().toLowerCase(); boolean readStatement = qry.startsWith("select"); boolean writeStatement = statement instanceof Batch || statement instanceof BatchStatement || qry.startsWith("insert") || qry.startsWith("delete") || qry.startsWith("update"); if (readStatement && readConsistency != null) statement.setConsistencyLevel(readConsistency); if (writeStatement && writeConsistency != null) statement.setConsistencyLevel(writeConsistency); if (fetchSize != null) statement.setFetchSize(fetchSize); return statement; }
Example #25
Source File: CassandraOAuthDAO.java From arcusplatform with Apache License 2.0 | 6 votes |
@Override public void updateTokens(String appId, String access, String refresh, UUID person) { Preconditions.checkNotNull(appId, "appId is required"); Preconditions.checkNotNull(access, "access is required"); Preconditions.checkNotNull(refresh, "refresh is required"); Preconditions.checkNotNull(person, "person is required"); BoundStatement stmt = bindTokenInsert(insertAccess, appId, access, Type.ACCESS, person); ResultSet rs = session.execute(stmt); checkApplied(rs, stmt); if(refresh != null) { stmt = bindTokenInsert(insertRefresh, appId, refresh, Type.REFRESH, person); rs = session.execute(stmt); checkApplied(rs, stmt); } stmt = bindPersonWhere(updatePersonTokens, appId, person); stmt.setString(PersonOAuthCols.access.name(), access); stmt.setString(PersonOAuthCols.refresh.name(), refresh); rs = session.execute(stmt); checkApplied(rs, stmt); }
Example #26
Source File: CassandraPreparedStatement.java From cassandra-jdbc-wrapper with Apache License 2.0 | 6 votes |
CassandraPreparedStatement(CassandraConnection con, String cql, int rsType, int rsConcurrency, int rsHoldability ) throws SQLException { super(con,cql,rsType,rsConcurrency,rsHoldability); if (LOG.isTraceEnabled()) LOG.trace("CQL: " + this.cql); try { stmt = this.connection.getSession().prepare(cql); this.statement = new BoundStatement(stmt); batchStatements = Lists.newArrayList(); count = cql.length() - cql.replace("?", "").length(); } catch (Exception e) { throw new SQLTransientException(e); } }
Example #27
Source File: PreferencesDAOImpl.java From arcusplatform with Apache License 2.0 | 5 votes |
@Override public void deletePref(UUID personId, UUID placeId, String prefKey) { BoundStatement boundStatement = new BoundStatement(deletePrefStatement) .setString(0, prefKey) .setUUID(Cols.PERSON_ID, personId) .setUUID(Cols.PLACE_ID, placeId); try (Context context = deletePrefTimer.time()) { session.execute(boundStatement); } }
Example #28
Source File: IncidentDao.java From glowroot with Apache License 2.0 | 5 votes |
@Override public List<ResolvedIncident> readResolvedIncidents(long from) throws Exception { BoundStatement boundStatement = readRecentResolvedIncidentsPS.bind(); boundStatement.setTimestamp(0, new Date(from)); ResultSet results = session.read(boundStatement); List<ResolvedIncident> resolvedIncidents = new ArrayList<>(); for (Row row : results) { int i = 0; long resolveTime = checkNotNull(row.getTimestamp(i++)).getTime(); String agentRollupId = checkNotNull(row.getString(i++)); AlertCondition condition = AlertCondition.parseFrom(checkNotNull(row.getBytes(i++))); AlertSeverity severity = AlertSeverity .valueOf(checkNotNull(row.getString(i++)).toUpperCase(Locale.ENGLISH)); AlertNotification notification = AlertNotification.parseFrom(checkNotNull(row.getBytes(i++))); long openTime = checkNotNull(row.getTimestamp(i++)).getTime(); resolvedIncidents.add(ImmutableResolvedIncident.builder() .agentRollupId(agentRollupId) .openTime(openTime) .resolveTime(resolveTime) .condition(condition) .severity(severity) .notification(notification) .build()); } return resolvedIncidents; }
Example #29
Source File: SchemaUpgrade.java From glowroot with Apache License 2.0 | 5 votes |
private void rewriteHeartbeatTablePart2() throws Exception { if (!tableExists("heartbeat_temp")) { // previously failed mid-upgrade prior to updating schema version return; } logger.info("rewriting heartbeat table (part 2)..."); Map<String, V09AgentRollup> v09AgentRollups = getV09AgentRollupsFromAgentRollupTable(); dropTableIfExists("heartbeat"); session.createTableWithTWCS("create table if not exists heartbeat (agent_id varchar," + " central_capture_time timestamp, primary key (agent_id, central_capture_time))", HeartbeatDao.EXPIRATION_HOURS); PreparedStatement insertPS = session.prepare("insert into heartbeat (agent_id," + " central_capture_time) values (?, ?) using ttl ?"); int ttl = Ints.saturatedCast(HOURS.toSeconds(HeartbeatDao.EXPIRATION_HOURS)); ResultSet results = session.read("select agent_id, central_capture_time from heartbeat_temp"); Queue<ListenableFuture<?>> futures = new ArrayDeque<>(); for (Row row : results) { String v09AgentRollupId = row.getString(0); V09AgentRollup v09AgentRollup = v09AgentRollups.get(v09AgentRollupId); if (v09AgentRollup == null) { // v09AgentRollupId was manually deleted (via the UI) from the agent_rollup // table in which case its parent is no longer known and best to ignore continue; } Date centralCaptureDate = checkNotNull(row.getTimestamp(1)); int adjustedTTL = Common.getAdjustedTTL(ttl, centralCaptureDate.getTime(), clock); BoundStatement boundStatement = insertPS.bind(); int i = 0; boundStatement.setString(i++, v09AgentRollup.agentRollupId()); boundStatement.setTimestamp(i++, centralCaptureDate); boundStatement.setInt(i++, adjustedTTL); futures.add(session.writeAsync(boundStatement)); waitForSome(futures); } MoreFutures.waitForAll(futures); dropTableIfExists("heartbeat_temp"); logger.info("rewriting heartbeat table (part 2) - complete"); }
Example #30
Source File: CassandraSessionDAO.java From arcusplatform with Apache License 2.0 | 5 votes |
@Override public void delete(Session session) { PreparedStatement ps = prepareDeleteStatement(); BoundStatement bs = new BoundStatement(ps); bs.bind(session.getId()); cassandraSession.execute(bs); }