Java Code Examples for com.datastax.driver.core.BoundStatement

The following examples show how to use com.datastax.driver.core.BoundStatement. These examples are extracted from open source projects. 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 Project: arcusplatform   Source File: MobileDeviceDAOImpl.java    License: Apache License 2.0 6 votes vote down vote up
@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 2
Source Project: glowroot   Source File: Session.java    License: Apache License 2.0 6 votes vote down vote up
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 3
Source Project: glowroot   Source File: AggregateDaoImpl.java    License: Apache License 2.0 6 votes vote down vote up
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 4
Source Project: geowave   Source File: RowRead.java    License: Apache License 2.0 6 votes vote down vote up
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 5
Source Project: arcusplatform   Source File: GuicedCassandraSessionDAO.java    License: Apache License 2.0 6 votes vote down vote up
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 6
Source Project: cumulusrdf   Source File: Cassandra2xDefaultMapDAO.java    License: Apache License 2.0 6 votes vote down vote up
@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 7
Source Project: glowroot   Source File: TraceDaoImpl.java    License: Apache License 2.0 6 votes vote down vote up
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 8
Source Project: arcusplatform   Source File: SetPrimaryPlace.java    License: Apache License 2.0 6 votes vote down vote up
@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 9
Source Project: glowroot   Source File: TraceDaoImpl.java    License: Apache License 2.0 6 votes vote down vote up
@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 10
Source Project: glowroot   Source File: TraceDaoImpl.java    License: Apache License 2.0 6 votes vote down vote up
@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 11
Source Project: glowroot   Source File: SchemaUpgrade.java    License: Apache License 2.0 6 votes vote down vote up
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 12
Source Project: arcusplatform   Source File: HubDAOImpl.java    License: Apache License 2.0 6 votes vote down vote up
@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 13
@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 14
Source Project: glowroot   Source File: TraceDaoImpl.java    License: Apache License 2.0 6 votes vote down vote up
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 15
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 16
Source Project: blueflood   Source File: DTimerIO.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 17
Source Project: glowroot   Source File: AggregateDaoImpl.java    License: Apache License 2.0 6 votes vote down vote up
@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 18
Source Project: glowroot   Source File: SchemaUpgrade.java    License: Apache License 2.0 6 votes vote down vote up
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 19
Source Project: arcusplatform   Source File: CassandraQueryExecutor.java    License: Apache License 2.0 6 votes vote down vote up
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 20
Source Project: yb-sample-apps   Source File: CassandraPersonalization.java    License: Apache License 2.0 6 votes vote down vote up
@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
@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 Project: blueflood   Source File: DBasicNumericIO.java    License: Apache License 2.0 6 votes vote down vote up
/**
 *
 * @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 Project: arcusplatform   Source File: CassandraClusterServiceDao.java    License: Apache License 2.0 6 votes vote down vote up
@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 Project: ignite   Source File: CassandraSessionImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 Project: arcusplatform   Source File: CassandraOAuthDAO.java    License: Apache License 2.0 6 votes vote down vote up
@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 Project: glowroot   Source File: IncidentDao.java    License: Apache License 2.0 6 votes vote down vote up
@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 27
Source Project: glowroot   Source File: TraceDaoImpl.java    License: Apache License 2.0 5 votes vote down vote up
private static void bindTraceQuery(BoundStatement boundStatement, String agentRollupId,
        TraceQuery query, boolean overall) {
    int i = 0;
    boundStatement.setString(i++, agentRollupId);
    boundStatement.setString(i++, query.transactionType());
    if (!overall) {
        boundStatement.setString(i++, query.transactionName());
    }
    boundStatement.setTimestamp(i++, new Date(query.from()));
    boundStatement.setTimestamp(i++, new Date(query.to()));
}
 
Example 28
@Override
public Completable updateStatusMessage(String policyRefId, String statusMessage) {
    return Observable.fromCallable(() -> {
        BoundStatement statement = updateStatusMessageStmt.bind(statusMessage, UUID.fromString(policyRefId));
        return storeHelper.execute(statement);
    }).flatMap(storeUpdated -> {
        AutoScalingPolicy autoScalingPolicy = policies.get(policyRefId);
        AutoScalingPolicy updatedPolicy = AutoScalingPolicy.newBuilder().withAutoScalingPolicy(autoScalingPolicy)
                .withStatusMessage(statusMessage).build();
        policies.put(policyRefId, updatedPolicy);
        updatePolicyCounter.increment();
        return storeUpdated;
    }).toCompletable();
}
 
Example 29
Source Project: glowroot   Source File: SchemaUpgrade.java    License: Apache License 2.0 5 votes vote down vote up
private void populateAgentConfigGeneral() throws Exception {
    if (!columnExists("agent_rollup", "display")) {
        // previously failed mid-upgrade prior to updating schema version
        return;
    }
    ResultSet results =
            session.read("select agent_rollup_id, display from agent_rollup where one = 1");
    PreparedStatement readConfigPS =
            session.prepare("select config from agent_config where agent_rollup_id = ?");
    PreparedStatement insertConfigPS =
            session.prepare("insert into agent_config (agent_rollup_id, config) values (?, ?)");
    for (Row row : results) {
        String agentRollupId = row.getString(0);
        String display = row.getString(1);
        if (display == null) {
            continue;
        }
        BoundStatement boundStatement = readConfigPS.bind();
        boundStatement.setString(0, agentRollupId);
        Row configRow = session.read(boundStatement).one();
        if (configRow == null) {
            logger.warn("could not find config for agent rollup id: {}", agentRollupId);
            continue;
        }
        AgentConfig agentConfig = AgentConfig.parseFrom(checkNotNull(configRow.getBytes(0)));
        AgentConfig updatedAgentConfig = agentConfig.toBuilder()
                .setGeneralConfig(GeneralConfig.newBuilder()
                        .setDisplay(display))
                .build();
        boundStatement = insertConfigPS.bind();
        boundStatement.setString(0, agentRollupId);
        boundStatement.setBytes(1, ByteBuffer.wrap(updatedAgentConfig.toByteArray()));
        session.write(boundStatement);
    }
    dropColumnIfExists("agent_rollup", "display");
}
 
Example 30
Source Project: arcusplatform   Source File: CassandraSessionDAO.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void delete(Session session) {
   PreparedStatement ps = prepareDeleteStatement();
   BoundStatement bs = new BoundStatement(ps);
   bs.bind(session.getId());
   cassandraSession.execute(bs);
}