下面列出了com.datastax.driver.core.BoundStatement#setString ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private AsyncFunction<List<Long>, List<ResultSet>> getFetchChunksAsyncFunction(EntityId entityId, String key, Aggregation aggregation, long startTs, long endTs) {
return partitions -> {
try {
PreparedStatement proto = getFetchStmt(aggregation);
List<ResultSetFuture> futures = new ArrayList<>(partitions.size());
for (Long partition : partitions) {
log.trace("Fetching data for partition [{}] for entityType {} and entityId {}", partition, entityId.getEntityType(), entityId.getId());
BoundStatement stmt = proto.bind();
stmt.setString(0, entityId.getEntityType().name());
stmt.setUUID(1, entityId.getId());
stmt.setString(2, key);
stmt.setLong(3, partition);
stmt.setLong(4, startTs);
stmt.setLong(5, endTs);
log.debug("Generated query [{}] for entityType {} and entityId {}", stmt, entityId.getEntityType(), entityId.getId());
futures.add(executeAsyncRead(stmt));
}
return Futures.allAsList(futures);
} catch (Throwable e) {
log.error("Failed to fetch data", e);
throw e;
}
};
}
private ListenableFuture<?> rollupOneFromChildren(int rollupLevel, String agentRollupId,
String gaugeName, Collection<String> childAgentRollupIds, long captureTime,
int adjustedTTL) throws Exception {
List<ListenableFuture<ResultSet>> futures = new ArrayList<>();
for (String childAgentRollupId : childAgentRollupIds) {
BoundStatement boundStatement = readValueForRollupFromChildPS.bind();
int i = 0;
boundStatement.setString(i++, childAgentRollupId);
boundStatement.setString(i++, gaugeName);
boundStatement.setTimestamp(i++, new Date(captureTime));
futures.add(session.readAsyncWarnIfNoRows(boundStatement, "no gauge value table"
+ " records found for agentRollupId={}, gaugeName={}, captureTime={}, level={}",
childAgentRollupId, gaugeName, captureTime, rollupLevel));
}
return MoreFutures.rollupAsync(futures, asyncExecutor, new DoRollup() {
@Override
public ListenableFuture<?> execute(Iterable<Row> rows) throws Exception {
return rollupOneFromRows(rollupLevel, agentRollupId, gaugeName, captureTime,
adjustedTTL, rows);
}
});
}
private void addAgentOneTable() throws Exception {
if (!tableExists("agent_rollup")) {
// previously failed mid-upgrade prior to updating schema version
return;
}
session.createTableWithLCS("create table if not exists agent_one (one int, agent_id"
+ " varchar, agent_rollup varchar, primary key (one, agent_id))");
ResultSet results = session.read("select agent_rollup from agent_rollup");
PreparedStatement insertPS =
session.prepare("insert into agent_one (one, agent_id) values (1, ?)");
for (Row row : results) {
BoundStatement boundStatement = insertPS.bind();
boundStatement.setString(0, row.getString(0));
session.write(boundStatement);
}
dropTableIfExists("agent_rollup");
}
private Iterator<com.datastax.driver.core.Row> cassandraSelect(Context context, Resource resource,
Timestamp start, Timestamp end) {
List<Future<ResultSet>> futures = Lists.newArrayList();
Duration resourceShard = m_contextConfigurations.getResourceShard(context);
Timestamp lower = start.stepFloor(resourceShard);
Timestamp upper = end.stepFloor(resourceShard);
for (Timestamp partition : new IntervalGenerator(lower, upper, resourceShard)) {
BoundStatement bindStatement = m_selectStatement.bind();
bindStatement.setString(SchemaConstants.F_CONTEXT, context.getId());
bindStatement.setInt(SchemaConstants.F_PARTITION, (int) partition.asSeconds());
bindStatement.setString(SchemaConstants.F_RESOURCE, resource.getId());
bindStatement.setTimestamp("start", start.asDate());
bindStatement.setTimestamp("end", end.asDate());
// Use the context specific consistency level
bindStatement.setConsistencyLevel(m_contextConfigurations.getReadConsistency(context));
futures.add(m_session.executeAsync(bindStatement));
}
return new ConcurrentResultWrapper(futures);
}
@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);
}
private static void addValue(KvEntry kvEntry, BoundStatement stmt, int column) {
switch (kvEntry.getDataType()) {
case BOOLEAN:
stmt.setBool(column, kvEntry.getBooleanValue().get().booleanValue());
break;
case STRING:
stmt.setString(column, kvEntry.getStrValue().get());
break;
case LONG:
stmt.setLong(column, kvEntry.getLongValue().get().longValue());
break;
case DOUBLE:
stmt.setDouble(column, kvEntry.getDoubleValue().get().doubleValue());
break;
}
}
public void remove(UUID placeId, String assistant) {
try(Timer.Context ctxt = removeTimer.time()) {
BoundStatement stmt = new BoundStatement(delete);
stmt.setUUID(Columns.placeId.name(), placeId);
stmt.setString(Columns.assistant.name(), assistant);
session.execute(stmt);
}
}
public @Nullable Profile readMainThreadProfileUsingPS(String agentId, String traceId,
PreparedStatement readPS) throws Exception {
BoundStatement boundStatement = readPS.bind();
boundStatement.setString(0, agentId);
boundStatement.setString(1, traceId);
ResultSet results = session.read(boundStatement);
Row row = results.one();
if (row == null) {
return null;
}
return Profile.parseFrom(checkNotNull(row.getBytes(0)));
}
@Override
public void updateVariables(CompositeId<UUID, Integer> id, Map<String, Object> variables, Date modified) {
BoundStatement bs = updateVariables.bind();
bs.setUUID(Column.PLACE_ID.columnName(), id.getPrimaryId());
bs.setInt(Column.ID.columnName(), id.getSecondaryId());
bs.setString(RuleColumn.VARIABLES.columnName(), JSON.toJson(variables));
bs.setTimestamp(Column.MODIFIED.columnName(),modified);
ResultSet rs = session.execute(bs);
if(!rs.wasApplied()) {
throw new IllegalStateException(String.format("Unable to update rule variables. Rule [%s] has been modified since read",id));
}
}
private void writeIfNotExists(String key, Object config) throws Exception {
String initialValue = mapper.writeValueAsString(config);
BoundStatement boundStatement = insertIfNotExistsPS.bind();
int i = 0;
boundStatement.setString(i++, key);
boundStatement.setString(i++, initialValue);
ResultSet results = session.update(boundStatement);
Row row = checkNotNull(results.one());
boolean applied = row.getBool("[applied]");
if (applied) {
centralConfigCache.invalidate(key);
} else {
throw new OptimisticLockException();
}
}
@Override
public void remove(final IntervalCollectionEvent event) {
/*
* The event indicates something was removed from the collection, there are to cases:
* - the collection is empty -> remove the whole entry
* - the collection has still other elements -> upsert the collection
*/
if (event.getCollection().isEmpty()) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Removing IntervalCollection: " + event.getKey());
}
if (this.delete == null) {
this.delete = getSession().prepare(QueryBuilder.delete()
.from(this.keySpace, this.columnFamily)
.where(eq(KEY_COLUMN, QueryBuilder.bindMarker())));
}
final BoundStatement boundStmt = new BoundStatement(this.delete);
boundStmt.setString(0, event.getKey());
getSession().execute(boundStmt);
} else {
upsert(event);
}
}
private CompletionStage<List<BoundStatement>> processTransferEvent(String status, TransferEvent event) {
String transferId = event.getTransferId().getId();
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
String source = null;
String destination = null;
String amount = event.getTransferDetails().getAmount().toString();
if (event.getTransferDetails().getSource() instanceof Account.Portfolio) {
source = ((Account.Portfolio) event.getTransferDetails().getSource()).getPortfolioId().getId();
} else {
source = "Savings";
}
if (event.getTransferDetails().getDestination() instanceof Account.Portfolio) {
destination = ((Account.Portfolio) event.getTransferDetails().getDestination()).getPortfolioId().getId();
} else {
destination = "Savings";
}
BoundStatement bindWriteTransfers = writeTransfers.bind();
bindWriteTransfers.setString("transferId", transferId);
bindWriteTransfers.setString("status", status);
bindWriteTransfers.setString("dateTime", timestamp.toString());
bindWriteTransfers.setString("source", source);
bindWriteTransfers.setString("destination", destination);
bindWriteTransfers.setString("amount", amount);
return completedStatements(Arrays.asList(bindWriteTransfers));
}
public void store(String v09AgentId, String v09AgentRollupId) throws Exception {
BoundStatement boundStatement = insertPS.bind();
int i = 0;
boundStatement.setString(i++, v09AgentId);
boundStatement.setString(i++, v09AgentRollupId);
session.write(boundStatement);
agentRollupIdsCache.invalidate(SINGLE_CACHE_KEY);
}
private void updateSmtpConfig() throws Exception {
ResultSet results =
session.read("select value from central_config where key = 'smtp'");
Row row = results.one();
if (row == null) {
return;
}
String smtpConfigText = row.getString(0);
if (smtpConfigText == null) {
return;
}
JsonNode jsonNode = mapper.readTree(smtpConfigText);
if (jsonNode == null || !jsonNode.isObject()) {
return;
}
ObjectNode smtpConfigNode = (ObjectNode) jsonNode;
JsonNode sslNode = smtpConfigNode.remove("ssl");
if (sslNode != null && sslNode.isBoolean() && sslNode.asBoolean()) {
smtpConfigNode.put("connectionSecurity", "ssl-tls");
}
String updatedWebConfigText = mapper.writeValueAsString(smtpConfigNode);
PreparedStatement preparedStatement =
session.prepare("insert into central_config (key, value) values ('smtp', ?)");
BoundStatement boundStatement = preparedStatement.bind();
boundStatement.setString(0, updatedWebConfigText);
session.write(boundStatement);
}
@Override
public ListenableFuture<TsKvEntry> findLatest(EntityId entityId, String key) {
BoundStatement stmt = getFindLatestStmt().bind();
stmt.setString(0, entityId.getEntityType().name());
stmt.setUUID(1, entityId.getId());
stmt.setString(2, key);
log.debug("Generated query [{}] for entityType {} and entityId {}", stmt, entityId.getEntityType(), entityId.getId());
return getFuture(executeAsyncRead(stmt), rs -> convertResultToTsKvEntry(key, rs.one()));
}
private void updateEncryptedPasswordAttributeName(String key, PreparedStatement readPS,
PreparedStatement insertPS) throws Exception {
BoundStatement boundStatement = readPS.bind();
boundStatement.setString(0, key);
ResultSet results = session.read(boundStatement);
Row row = results.one();
if (row == null) {
return;
}
String configText = row.getString(0);
if (configText == null) {
return;
}
JsonNode jsonNode = mapper.readTree(configText);
if (jsonNode == null || !jsonNode.isObject()) {
return;
}
ObjectNode objectNode = (ObjectNode) jsonNode;
JsonNode passwordNode = objectNode.remove("password");
if (passwordNode != null) {
objectNode.set("encryptedPassword", passwordNode);
}
String updatedConfigText = mapper.writeValueAsString(objectNode);
boundStatement = insertPS.bind();
boundStatement.setString(0, key);
boundStatement.setString(1, updatedConfigText);
session.write(boundStatement);
}
@Override
public Invitation find(String code) {
Preconditions.checkNotNull(code, "code is required");
try(Context timer = findTimer.time()) {
BoundStatement stmt = new BoundStatement(select);
stmt.setString(Column.code.name(), StringUtils.lowerCase(code));
return build(session.execute(stmt).one());
}
}
private ResultSetFuture fetchResourceAttributes(Context context, String resourceId, ConsistencyLevel readConsistency) {
BoundStatement bindStatement = m_selectAttributesStatement.bind();
bindStatement.setString(Schema.C_ATTRS_CONTEXT, context.getId());
bindStatement.setString(Schema.C_ATTRS_RESOURCE, resourceId);
bindStatement.setConsistencyLevel(readConsistency);
return m_session.executeAsync(bindStatement);
}
@Override
public void store(String agentRollupId, String syntheticMonitorId,
String syntheticMonitorDisplay, long captureTime, long durationNanos,
@Nullable String errorMessage) throws Exception {
int ttl = getTTLs().get(0);
long maxCaptureTime = 0;
BoundStatement boundStatement = insertResultPS.get(0).bind();
maxCaptureTime = Math.max(captureTime, maxCaptureTime);
int adjustedTTL = Common.getAdjustedTTL(ttl, captureTime, clock);
int i = 0;
boundStatement.setString(i++, agentRollupId);
boundStatement.setString(i++, syntheticMonitorId);
boundStatement.setTimestamp(i++, new Date(captureTime));
boundStatement.setDouble(i++, durationNanos);
boundStatement.setLong(i++, 1);
if (errorMessage == null) {
boundStatement.setToNull(i++);
} else {
Stored.ErrorInterval errorInterval = Stored.ErrorInterval.newBuilder()
.setFrom(captureTime)
.setTo(captureTime)
.setCount(1)
.setMessage(errorMessage)
.setDoNotMergeToTheLeft(false)
.setDoNotMergeToTheRight(false)
.build();
boundStatement.setBytes(i++, Messages.toByteBuffer(ImmutableList.of(errorInterval)));
}
boundStatement.setInt(i++, adjustedTTL);
List<Future<?>> futures = new ArrayList<>();
futures.add(session.writeAsync(boundStatement));
futures.addAll(syntheticMonitorIdDao.insert(agentRollupId, captureTime, syntheticMonitorId,
syntheticMonitorDisplay));
// wait for success before inserting "needs rollup" records
MoreFutures.waitForAll(futures);
// insert into synthetic_needs_rollup_1
List<RollupConfig> rollupConfigs = configRepository.getRollupConfigs();
long intervalMillis = rollupConfigs.get(1).intervalMillis();
long rollupCaptureTime = CaptureTimes.getRollup(captureTime, intervalMillis);
int needsRollupAdjustedTTL =
Common.getNeedsRollupAdjustedTTL(adjustedTTL, configRepository.getRollupConfigs());
boundStatement = insertNeedsRollup.get(0).bind();
i = 0;
boundStatement.setString(i++, agentRollupId);
boundStatement.setTimestamp(i++, new Date(rollupCaptureTime));
boundStatement.setUUID(i++, UUIDs.timeBased());
boundStatement.setSet(i++, ImmutableSet.of(syntheticMonitorId));
boundStatement.setInt(i++, needsRollupAdjustedTTL);
session.write(boundStatement);
}
void delete(String username) throws Exception {
BoundStatement boundStatement = deletePS.bind();
boundStatement.setString(0, username);
session.write(boundStatement);
allUserConfigsCache.invalidate(ALL_USERS_SINGLE_CACHE_KEY);
}