下面列出了com.datastax.driver.core.BoundStatement#setUUID ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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);
}
}
protected Statement prepareUpsert(SceneDefinition sd, Date ts) {
BoundStatement bs = upsert.bind();
bs.setUUID(Column.PLACE_ID.columnName(), sd.getPlaceId());
bs.setInt(Column.ID.columnName(), sd.getSequenceId());
bs.setTimestamp(Column.CREATED.columnName(), sd.getCreated());
bs.setTimestamp(Column.MODIFIED.columnName(), sd.getModified());
bs.setString(Column.NAME.columnName(), sd.getName());
bs.setString(Column.DESCRIPTION.columnName(), sd.getDescription());
bs.setSet(Column.TAGS.columnName(), sd.getTags());
bs.setString(SceneColumn.TEMPLATE.columnName(), sd.getTemplate());
bs.setBool(SceneColumn.SATISFIABLE.columnName(), sd.isSatisfiable());
bs.setBool(SceneColumn.NOTIFICATION.columnName(), sd.isNotification());
bs.setTimestamp(SceneColumn.LAST_FIRE_TIME.columnName(), sd.getLastFireTime());
bs.setString(SceneColumn.LAST_FIRE_STATE.columnName(), sd.getLastFireState());
bs.setBool(SceneColumn.ENABLED.columnName(),sd.isEnabled());
if(sd.getAction() != null) {
bs.setBytes(ActionColumn.ACTION.columnName(), ByteBuffer.wrap(sd.getAction()));
}
else {
bs.setBytes(ActionColumn.ACTION.columnName(), ByteBuffer.wrap(new byte [] {}));
}
return bs;
}
private void renameConfigTable() throws Exception {
if (!tableExists("config")) {
// previously failed mid-upgrade prior to updating schema version
return;
}
session.createTableWithLCS("create table if not exists agent_config (agent_rollup_id"
+ " varchar, config blob, config_update boolean, config_update_token uuid,"
+ " primary key (agent_rollup_id))");
ResultSet results = session.read("select agent_rollup_id, config,"
+ " config_update, config_update_token from config");
PreparedStatement insertPS =
session.prepare("insert into agent_config (agent_rollup_id, config, config_update,"
+ " config_update_token) values (?, ?, ?, ?)");
for (Row row : results) {
BoundStatement boundStatement = insertPS.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);
}
dropTableIfExists("config");
}
private void addDefaultGaugeNameToUiConfigs() throws Exception {
PreparedStatement insertPS = session.prepare("insert into agent_config (agent_rollup_id,"
+ " config, config_update, config_update_token) values (?, ?, ?, ?)");
ResultSet results = session.read("select agent_rollup_id, config from agent_config");
for (Row row : results) {
String agentRollupId = row.getString(0);
AgentConfig oldAgentConfig;
try {
oldAgentConfig = AgentConfig.parseFrom(checkNotNull(row.getBytes(1)));
} catch (InvalidProtocolBufferException e) {
logger.error(e.getMessage(), e);
continue;
}
AgentConfig agentConfig = oldAgentConfig.toBuilder()
.setUiDefaultsConfig(oldAgentConfig.getUiDefaultsConfig().toBuilder()
.addAllDefaultGaugeName(ConfigDefaults.UI_DEFAULTS_GAUGE_NAMES))
.build();
BoundStatement boundStatement = insertPS.bind();
int i = 0;
boundStatement.setString(i++, agentRollupId);
boundStatement.setBytes(i++, ByteBuffer.wrap(agentConfig.toByteArray()));
boundStatement.setBool(i++, true);
boundStatement.setUUID(i++, UUIDs.random());
session.write(boundStatement);
}
}
@Override
public void cancel(Invitation invitation) {
Preconditions.checkNotNull(invitation, "invitation is required");
try(Context timer = cancelTimer.time()) {
BatchStatement stmt = new BatchStatement();
BoundStatement tblDel = new BoundStatement(delete);
tblDel.setString(Column.code.name(), invitation.getCode());
stmt.add(tblDel);
BoundStatement placeIdxDel = new BoundStatement(deletePlaceIdx);
placeIdxDel.setString(Column.code.name(), invitation.getCode());
placeIdxDel.setUUID(Column.placeId.name(), UUID.fromString(invitation.getPlaceId()));
stmt.add(placeIdxDel);
if(invitation.getInviteeId() != null) {
BoundStatement personIdxDel = new BoundStatement(deletePersonIdx);
personIdxDel.setString(Column.code.name(), invitation.getCode());
personIdxDel.setUUID(Column.inviteeId.name(), UUID.fromString(invitation.getInviteeId()));
stmt.add(personIdxDel);
}
session.execute(stmt);
}
}
public Map<String, ProactiveCreds> credentialsForPlace(UUID placeId) {
try(Timer.Context ctxt = credentialsForPlaceTimer.time()) {
BoundStatement stmt = new BoundStatement(findByPlaceId);
stmt.setUUID(Columns.placeId.name(), placeId);
ResultSet rs = session.execute(stmt);
return rs.all().stream()
.collect(Collectors.toMap(
row -> row.getString(Columns.assistant.name()),
row -> new ProactiveCreds(row.getString(Columns.access.name()), row.getTimestamp(Columns.accessExpiry.name()), row.getString(Columns.refresh.name()))
)
);
}
}
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);
}
}
@Override
public void upsert(AlarmIncident incident) {
PreparedStatement pStmt = incident.isCleared() ? upsertWithTtl : upsert;
BoundStatement bound = new BoundStatement(pStmt);
bound.setUUID(Column.placeid.name(), incident.getPlaceId());
bound.setUUID(Column.incidentid.name(), incident.getId());
bound.setString(Column.alertstate.name(), incident.getAlertState().name());
if(incident.getPlatformAlertState() == null) {
bound.setString(Column.platformstate.name(), incident.getAlertState().name());
}
else {
bound.setString(Column.platformstate.name(), incident.getPlatformAlertState().name());
}
if(incident.getHubAlertState() == null) {
bound.setToNull(Column.hubstate.name());
}
else {
bound.setString(Column.hubstate.name(), incident.getHubAlertState().name());
}
bound.setSet(Column.activealerts.name(), incident.getActiveAlerts());
bound.setSet(Column.additionalalerts.name(), incident.getAdditionalAlerts().stream().map(AlertType::name).collect(Collectors.toSet()));
bound.setString(Column.alert.name(), incident.getAlert().name());
bound.setString(Column.cancelledby.name(), incident.getCancelledBy() == null ? null : incident.getCancelledBy().getRepresentation());
bound.setTimestamp(Column.prealertendtime.name(), incident.getPrealertEndTime());
bound.setTimestamp(Column.endtime.name(), incident.getEndTime());
bound.setString(Column.monitoringstate.name(), incident.getMonitoringState().name());
bound.setList(Column.tracker.name(), incident.getTracker().stream().map((te) -> JSON.toJson(te.toMap())).collect(Collectors.toList()));
bound.setBool(Column.mockincident.name(), incident.isMockIncident());
bound.setBool(Column.monitored.name(), incident.isMonitored());
bound.setBool(Column.confirmed.name(), incident.isConfirmed());
session.execute(bound);
}
private void rewriteAgentConfigTablePart2() throws Exception {
if (!tableExists("agent_config_temp")) {
// previously failed mid-upgrade prior to updating schema version
return;
}
dropTableIfExists("agent_config");
session.createTableWithLCS("create table if not exists agent_config (agent_rollup_id"
+ " varchar, config blob, config_update boolean, config_update_token uuid, primary"
+ " key (agent_rollup_id))");
PreparedStatement insertPS = session.prepare("insert into agent_config"
+ " (agent_rollup_id, config, config_update, config_update_token) values"
+ " (?, ?, ?, ?)");
Map<String, V09AgentRollup> v09AgentRollups = getV09AgentRollupsFromAgentRollupTable();
ResultSet results = session.read("select agent_rollup_id, config, config_update,"
+ " config_update_token from agent_config_temp");
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;
}
BoundStatement boundStatement = insertPS.bind();
boundStatement.setString(0, v09AgentRollup.agentRollupId());
boundStatement.setBytes(1, row.getBytes(1));
boundStatement.setBool(2, row.getBool(2));
boundStatement.setUUID(3, row.getUUID(3));
session.write(boundStatement);
}
dropTableIfExists("agent_config_temp");
}
@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()));
}
@Override
public ScheduledCommand schedule(
UUID placeId,
Address schedulerAddress,
Date scheduledTime,
OptionalLong validForMs
) {
Date expiresAt = new Date(System.currentTimeMillis() + validForMs.orElse(defaultExpirationTimeMs));
PartitionOffset offset = getPartitionOffsetFor(placeId, scheduledTime);
BoundStatement statement = upsertCommand.bind();
statement.setInt(ScheduledEventTable.Columns.PARTITION_ID, offset.getPartition().getId());
statement.setTimestamp(ScheduledEventTable.Columns.TIME_BUCKET, offset.getOffset());
statement.setTimestamp(ScheduledEventTable.Columns.SCHEDULED_TIME, scheduledTime);
statement.setUUID(ScheduledEventTable.Columns.PLACE_ID, placeId);
statement.setString(ScheduledEventTable.Columns.SCHEDULER, schedulerAddress.getRepresentation());
session.execute(statement);
ScheduledCommand command = new ScheduledCommand();
command.setOffset(offset);
command.setPlaceId(placeId);
command.setScheduledTime(scheduledTime);
command.setSchedulerAddress(schedulerAddress);
command.setExpirationTime(expiresAt);
return command;
}
private void insertIndexes(String placeId, String inviteeId, String token) {
BatchStatement batch = new BatchStatement();
BoundStatement placeIdx = new BoundStatement(insertPlaceIdx);
placeIdx.setUUID(Column.placeId.name(), UUID.fromString(placeId));
placeIdx.setString(Column.code.name(), token);
batch.add(placeIdx);
if(inviteeId != null) {
batch.add(bindInsertPersonIdx(UUID.fromString(inviteeId), token));
}
session.execute(batch);
}
public void markUpdated(String agentId, UUID configUpdateToken) throws Exception {
BoundStatement boundStatement = markUpdatedPS.bind();
int i = 0;
boundStatement.setString(i++, agentId);
boundStatement.setUUID(i++, configUpdateToken);
session.update(boundStatement);
}
@Override
public List<Invitation> listForPlace(UUID placeId) {
Preconditions.checkNotNull(placeId, "placeId is required");
try(Context timer = listForPlaceTimer.time()) {
BoundStatement stmt = new BoundStatement(selectCodesForPlace);
stmt.setUUID(Column.placeId.name(), placeId);
return listByIndex(stmt, (r) -> { return true; });
}
}
@Override
public ListenableFuture<List<TsKvEntry>> findAllLatest(EntityId entityId) {
BoundStatement stmt = getFindAllLatestStmt().bind();
stmt.setString(0, entityId.getEntityType().name());
stmt.setUUID(1, entityId.getId());
log.debug("Generated query [{}] for entityType {} and entityId {}", stmt, entityId.getEntityType(), entityId.getId());
return getFuture(executeAsyncRead(stmt), rs -> convertResultToTsKvEntryList(rs.all()));
}
private BoundStatement bindPersonInsert(String appId, UUID person, Map<String,String> attrs) {
attrs = attrs == null ? ImmutableMap.of() : attrs;
BoundStatement bound = new BoundStatement(upsertPerson);
bound.setUUID(PersonOAuthCols.person.name(), person);
bound.setString(PersonOAuthCols.appid.name(), appId);
bound.setMap(PersonOAuthCols.attrs.name(), attrs);
return bound;
}
@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);
}
@Override
public Invitation insert(Invitation invitation) {
Preconditions.checkNotNull(invitation, "invitation is required");
try(Context timer = insertTimer.time()) {
for(int i = 0; i < tokenRetries; i++) {
String token = generateToken();
Date created = new Date();
BoundStatement stmt = new BoundStatement(insert);
stmt.setString(Column.code.name(), token);
stmt.setUUID(Column.placeId.name(), UUID.fromString(invitation.getPlaceId()));
stmt.setString(Column.placeName.name(), invitation.getPlaceName());
stmt.setString(Column.streetAddress1.name(), invitation.getStreetAddress1());
stmt.setString(Column.streetAddress2.name(), invitation.getStreetAddress2());
stmt.setString(Column.city.name(), invitation.getCity());
stmt.setString(Column.stateProv.name(), invitation.getStateProv());
stmt.setString(Column.zipCode.name(), invitation.getZipCode());
stmt.setUUID(Column.inviteeId.name(), invitation.getInviteeId() == null ? null : UUID.fromString(invitation.getInviteeId()));
stmt.setString(Column.inviteeEmail.name(), invitation.getInviteeEmail().toLowerCase());
stmt.setString(Column.inviteeFirstName.name(), invitation.getInviteeFirstName());
stmt.setString(Column.inviteeLastName.name(), invitation.getInviteeLastName());
stmt.setUUID(Column.invitorId.name(), UUID.fromString(invitation.getInvitorId()));
stmt.setString(Column.invitorFirstName.name(), invitation.getInvitorFirstName());
stmt.setString(Column.invitorLastName.name(), invitation.getInvitorLastName());
stmt.setUUID(Column.placeOwnerId.name(), UUID.fromString(invitation.getPlaceOwnerId()));
stmt.setString(Column.placeOwnerFirstName.name(), invitation.getPlaceOwnerFirstName());
stmt.setString(Column.placeOwnerLastName.name(), invitation.getPlaceOwnerLastName());
stmt.setTimestamp(Column.created.name(), created);
stmt.setTimestamp(Column.accepted.name(), null);
stmt.setTimestamp(Column.rejected.name(), null);
stmt.setString(Column.rejectReason.name(), invitation.getRejectReason());
stmt.setString(Column.relationship.name(), invitation.getRelationship());
stmt.setString(Column.invitationText.name(), invitation.getInvitationText());
stmt.setString(Column.personalizedGreeting.name(), invitation.getPersonalizedGreeting());
ResultSet rs = session.execute(stmt);
if(rs.wasApplied()) {
insertIndexes(invitation.getPlaceId(), invitation.getInviteeId(), token);
invitation.setCode(token);
invitation.setCreated(created);
return invitation;
}
}
invitationCodeConflictCounter.inc();
throw new ErrorEventException(Errors.CODE_GENERIC, "unique token could not be found after " + tokenRetries + " attempts");
}
}
private BoundStatement bindPersonWhere(PreparedStatement stmt, String appId, UUID person) {
BoundStatement bound = new BoundStatement(stmt);
bound.setString(PersonOAuthCols.appid.name(), appId);
bound.setUUID(PersonOAuthCols.person.name(), person);
return bound;
}
@Override
@SuppressWarnings("unchecked")
protected Statement setStatementParameters(PreparedStatement updateCommand, Object tuple) throws DriverException
{
final BoundStatement boundStmnt = new BoundStatement(updateCommand);
final int size = columnDataTypes.size();
for (int i = 0; i < size; i++) {
final DataType type = columnDataTypes.get(i);
switch (type.getName()) {
case UUID:
final UUID id = ((Getter<Object, UUID>)getters.get(i)).get(tuple);
boundStmnt.setUUID(i, id);
break;
case ASCII:
case VARCHAR:
case TEXT:
final String ascii = ((Getter<Object, String>)getters.get(i)).get(tuple);
boundStmnt.setString(i, ascii);
break;
case BOOLEAN:
final boolean bool = ((GetterBoolean<Object>)getters.get(i)).get(tuple);
boundStmnt.setBool(i, bool);
break;
case INT:
final int intValue = ((GetterInt<Object>)getters.get(i)).get(tuple);
boundStmnt.setInt(i, intValue);
break;
case BIGINT:
case COUNTER:
final long longValue = ((GetterLong<Object>)getters.get(i)).get(tuple);
boundStmnt.setLong(i, longValue);
break;
case FLOAT:
final float floatValue = ((GetterFloat<Object>)getters.get(i)).get(tuple);
boundStmnt.setFloat(i, floatValue);
break;
case DOUBLE:
final double doubleValue = ((GetterDouble<Object>)getters.get(i)).get(tuple);
boundStmnt.setDouble(i, doubleValue);
break;
case DECIMAL:
final BigDecimal decimal = ((Getter<Object, BigDecimal>)getters.get(i)).get(tuple);
boundStmnt.setDecimal(i, decimal);
break;
case SET:
Set<?> set = ((Getter<Object, Set<?>>)getters.get(i)).get(tuple);
boundStmnt.setSet(i, set);
break;
case MAP:
final Map<?,?> map = ((Getter<Object, Map<?,?>>)getters.get(i)).get(tuple);
boundStmnt.setMap(i, map);
break;
case LIST:
final List<?> list = ((Getter<Object, List<?>>)getters.get(i)).get(tuple);
boundStmnt.setList(i, list);
break;
case TIMESTAMP:
final Date date = ((Getter<Object, Date>)getters.get(i)).get(tuple);
boundStmnt.setDate(i, LocalDate.fromMillisSinceEpoch(date.getTime()));
break;
default:
throw new RuntimeException("unsupported data type " + type.getName());
}
}
return boundStmnt;
}