Java Code Examples for com.datastax.driver.core.Row#getBool()

The following examples show how to use com.datastax.driver.core.Row#getBool() . 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: CassandraCqlIncrementalState.java    From storm-cassandra-cql with Apache License 2.0 5 votes vote down vote up
private boolean applyUpdate(Statement updateStatement, Long txid) {
    LOG.debug("APPLYING [{}]", updateStatement.toString());
    ResultSet results = clientFactory.getSession().execute(updateStatement);
    Row row = results.one();
    if (row != null) {
        return row.getBool("[applied]");
    } else {
        return true;
    }
}
 
Example 2
Source File: RoleDao.java    From glowroot with Apache License 2.0 5 votes vote down vote up
void insertIfNotExists(RoleConfig roleConfig) throws Exception {
    BoundStatement boundStatement = insertIfNotExistsPS.bind();
    bindInsert(boundStatement, roleConfig);
    ResultSet results = session.update(boundStatement);
    Row row = checkNotNull(results.one());
    boolean applied = row.getBool("[applied]");
    if (applied) {
        roleConfigCache.invalidate(roleConfig.name());
        allRoleConfigsCache.invalidate(ALL_ROLES_SINGLE_CACHE_KEY);
    } else {
        throw new DuplicateRoleNameException();
    }
}
 
Example 3
Source File: SchemaUpgrade.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private Map<String, V09AgentRollup> getV09AgentRollupsFromAgentRollupTable() throws Exception {
    Map<String, V09AgentRollup> v09AgentRollupIds = new HashMap<>();
    ResultSet results = session.read("select agent_rollup_id, parent_agent_rollup_id, agent"
            + " from agent_rollup where one = 1");
    for (Row row : results) {
        int i = 0;
        String v09AgentRollupId = checkNotNull(row.getString(i++));
        String v09ParentAgentRollupId = row.getString(i++);
        boolean agent = row.getBool(i++);
        boolean hasRollup = v09ParentAgentRollupId != null;
        String agentRollupId;
        if (agent) {
            if (v09ParentAgentRollupId == null) {
                agentRollupId = v09AgentRollupId;
            } else {
                agentRollupId =
                        v09ParentAgentRollupId.replace("/", "::") + "::" + v09AgentRollupId;
            }
        } else {
            agentRollupId = v09AgentRollupId.replace("/", "::") + "::";
        }
        v09AgentRollupIds.put(v09AgentRollupId, ImmutableV09AgentRollup.builder()
                .agent(agent)
                .hasRollup(hasRollup)
                .agentRollupId(agentRollupId)
                .v09AgentRollupId(v09AgentRollupId)
                .v09ParentAgentRollupId(v09ParentAgentRollupId)
                .build());
    }
    return v09AgentRollupIds;
}
 
Example 4
Source File: CentralConfigDao.java    From glowroot with Apache License 2.0 5 votes vote down vote up
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();
    }
}
 
Example 5
Source File: CentralConfigDao.java    From glowroot with Apache License 2.0 5 votes vote down vote up
void write(String key, Object config, String priorVersion) throws Exception {
    BoundStatement boundStatement = readPS.bind();
    boundStatement.bind(key);
    ResultSet results = session.read(boundStatement);
    Row row = results.one();
    if (row == null) {
        writeIfNotExists(key, config);
        return;
    }
    String currValue = checkNotNull(row.getString(0));
    Object currConfig = readValue(key, currValue);
    if (!Versions.getJsonVersion(currConfig).equals(priorVersion)) {
        throw new OptimisticLockException();
    }
    String newValue = mapper.writeValueAsString(config);
    boundStatement = updatePS.bind();
    int i = 0;
    boundStatement.setString(i++, newValue);
    boundStatement.setString(i++, key);
    boundStatement.setString(i++, currValue);
    results = session.update(boundStatement);
    row = checkNotNull(results.one());
    boolean applied = row.getBool("[applied]");
    if (applied) {
        centralConfigCache.invalidate(key);
    } else {
        throw new OptimisticLockException();
    }
}
 
Example 6
Source File: UserDao.java    From glowroot with Apache License 2.0 5 votes vote down vote up
void insertIfNotExists(UserConfig userConfig) throws Exception {
    BoundStatement boundStatement = insertIfNotExistsPS.bind();
    bindInsert(boundStatement, userConfig);
    ResultSet results = session.update(boundStatement);
    Row row = checkNotNull(results.one());
    boolean applied = row.getBool("[applied]");
    if (applied) {
        allUserConfigsCache.invalidate(ALL_USERS_SINGLE_CACHE_KEY);
    } else {
        throw new DuplicateUsernameException();
    }
}
 
Example 7
Source File: CassandraZuulRouteStore.java    From zuul-route-cassandra-spring-cloud-starter with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public ZuulProperties.ZuulRoute mapRow(Row row, int rowNum) throws DriverException {

    return new ZuulProperties.ZuulRoute(
            row.getString("id"),
            row.getString("path"),
            row.getString("service_id"),
            row.getString("url"),
            row.getBool("strip_prefix"),
            row.getBool("retryable")
    );
}
 
Example 8
Source File: CassandraStorage.java    From cassandra-reaper with Apache License 2.0 5 votes vote down vote up
private static DiagEventSubscription createDiagEventSubscription(Row row) {
  return new DiagEventSubscription(
      Optional.of(row.getUUID("id")),
      row.getString("cluster"),
      Optional.of(row.getString("description")),
      row.getSet("nodes", String.class),
      row.getSet("events", String.class),
      row.getBool("export_sse"),
      row.getString("export_file_logger"),
      row.getString("export_http_endpoint"));
}
 
Example 9
Source File: CassandraStorage.java    From cassandra-reaper with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<RepairUnit> getRepairUnit(RepairUnit.Builder params) {
  // brute force again
  RepairUnit repairUnit = null;
  Statement stmt = new SimpleStatement(SELECT_REPAIR_UNIT);
  stmt.setIdempotent(Boolean.TRUE);
  ResultSet results = session.execute(stmt);
  for (Row repairUnitRow : results) {
    if (repairUnitRow.getString("cluster_name").equals(params.clusterName)
        && repairUnitRow.getString("keyspace_name").equals(params.keyspaceName)
        && repairUnitRow.getSet("column_families", String.class).equals(params.columnFamilies)
        && repairUnitRow.getBool("incremental_repair") == params.incrementalRepair
        && repairUnitRow.getSet("nodes", String.class).equals(params.nodes)
        && repairUnitRow.getSet("datacenters", String.class).equals(params.datacenters)
        && repairUnitRow
            .getSet("blacklisted_tables", String.class)
            .equals(params.blacklistedTables)
        && repairUnitRow.getInt("repair_thread_count") == params.repairThreadCount) {

      repairUnit = RepairUnit.builder()
          .clusterName(repairUnitRow.getString("cluster_name"))
          .keyspaceName(repairUnitRow.getString("keyspace_name"))
          .columnFamilies(repairUnitRow.getSet("column_families", String.class))
          .incrementalRepair(repairUnitRow.getBool("incremental_repair"))
          .nodes(repairUnitRow.getSet("nodes", String.class))
          .datacenters(repairUnitRow.getSet("datacenters", String.class))
          .blacklistedTables(repairUnitRow.getSet("blacklisted_tables", String.class))
          .repairThreadCount(repairUnitRow.getInt("repair_thread_count"))
          .build(repairUnitRow.getUUID("id"));
      // exit the loop once we find a match
      break;
    }
  }

  return Optional.ofNullable(repairUnit);
}
 
Example 10
Source File: AggregatePartitionsFunction.java    From iotplatform with Apache License 2.0 5 votes vote down vote up
private Boolean getBooleanValue(Row row) {
    if (aggregation == Aggregation.MIN || aggregation == Aggregation.MAX) {
        return row.getBool(BOOL_POS);
    } else {
        return null;
    }
}
 
Example 11
Source File: HttpPrimeBatchIntegrationTest.java    From simulacron with Apache License 2.0 5 votes vote down vote up
private void assertResult(ResultSet set) {
  List<Row> results = set.all();
  assertThat(1).isEqualTo(results.size());
  Row row1 = results.get(0);
  boolean column1 = row1.getBool("applied");
  assertThat(column1).isTrue();
}
 
Example 12
Source File: PlaceDAOImpl.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public boolean getUpdateFlag(UUID placeId) {
   Preconditions.checkArgument(placeId != null, "The place id cannot be null");
   BoundStatement statement = new BoundStatement(getUpdateFlag);
   ResultSet resultSet;
   try(Context ctxt = getUpdateFlagTimer.time()) {
      resultSet = session.execute(statement.bind(placeId));
   }
   Row row = resultSet.one();
   return row.getBool(UPDATEFLAG);
}
 
Example 13
Source File: PersonDAOImpl.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public boolean getUpdateFlag(UUID personId) {
   Preconditions.checkArgument(personId != null, "The person id cannot be null");
   BoundStatement statement = new BoundStatement(getUpdateFlag);
   ResultSet resultSet;
   try(Context ctxt = getUpdateFlagTimer.time()) {
      resultSet = session.execute(statement.bind(personId));
   }
   Row row = resultSet.one();
   return row.getBool(UPDATEFLAG);
}
 
Example 14
Source File: GenerateTimeZoneId.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public void execute(ExecutionContext context, boolean autoRollback) throws CommandExecutionException {
   Session session = context.getSession();
   PreparedStatement update = session.prepare(UPDATE_PLACE);
   
   ResultSet rs = context.getSession().execute(SELECT);
   for(Row row: rs) {
      UUID placeId = row.getUUID("id");
      String tzName = row.getString("tzName");
      if(StringUtils.isEmpty(tzName)) {
         continue;
      }

      logger.debug("Attmempting to repair timzone [{}]...", tzName);
      Double offset = row.getDouble("tzOffset");
      Boolean usesDst = row.getBool("tzUsesDst");
      
      TimeZone tz;
      try {
         tz = TimeZones.guessTimezone(tzName, offset, usesDst);
      }
      catch(Exception e) {
         logger.warn("Unable to determine timezone for place [{}]", placeId, e);
         continue;
      }

      logger.info("Found timezone [{}] for name [{}]", tz.getID(), tzName);
      BoundStatement bs = update.bind(
            tz.getID(), 
            tzName, 
            TimeZones.getOffsetAsHours(tz.getRawOffset()), 
            tz.useDaylightTime(),
            placeId
      );
      session.execute(bs);
   }
}
 
Example 15
Source File: AbstractCassandraProcessor.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
protected static Object getCassandraObject(Row row, int i, DataType dataType) {
    if (dataType.equals(DataType.blob())) {
        return row.getBytes(i);

    } else if (dataType.equals(DataType.varint()) || dataType.equals(DataType.decimal())) {
        // Avro can't handle BigDecimal and BigInteger as numbers - it will throw an
        // AvroRuntimeException such as: "Unknown datum type: java.math.BigDecimal: 38"
        return row.getObject(i).toString();

    } else if (dataType.equals(DataType.cboolean())) {
        return row.getBool(i);

    } else if (dataType.equals(DataType.cint())) {
        return row.getInt(i);

    } else if (dataType.equals(DataType.bigint())
            || dataType.equals(DataType.counter())) {
        return row.getLong(i);

    } else if (dataType.equals(DataType.ascii())
            || dataType.equals(DataType.text())
            || dataType.equals(DataType.varchar())) {
        return row.getString(i);

    } else if (dataType.equals(DataType.cfloat())) {
        return row.getFloat(i);

    } else if (dataType.equals(DataType.cdouble())) {
        return row.getDouble(i);

    } else if (dataType.equals(DataType.timestamp())) {
        return row.getTimestamp(i);

    } else if (dataType.equals(DataType.date())) {
        return row.getDate(i);

    } else if (dataType.equals(DataType.time())) {
        return row.getTime(i);

    } else if (dataType.isCollection()) {

        List<DataType> typeArguments = dataType.getTypeArguments();
        if (typeArguments == null || typeArguments.size() == 0) {
            throw new IllegalArgumentException("Column[" + i + "] " + dataType.getName()
                    + " is a collection but no type arguments were specified!");
        }
        // Get the first type argument, to be used for lists and sets (and the first in a map)
        DataType firstArg = typeArguments.get(0);
        TypeCodec firstCodec = codecRegistry.codecFor(firstArg);
        if (dataType.equals(DataType.set(firstArg))) {
            return row.getSet(i, firstCodec.getJavaType());
        } else if (dataType.equals(DataType.list(firstArg))) {
            return row.getList(i, firstCodec.getJavaType());
        } else {
            // Must be an n-arg collection like map
            DataType secondArg = typeArguments.get(1);
            TypeCodec secondCodec = codecRegistry.codecFor(secondArg);
            if (dataType.equals(DataType.map(firstArg, secondArg))) {
                return row.getMap(i, firstCodec.getJavaType(), secondCodec.getJavaType());
            }
        }

    } else {
        // The different types that we support are numbers (int, long, double, float),
        // as well as boolean values and Strings. Since Avro doesn't provide
        // timestamp types, we want to convert those to Strings. So we will cast anything other
        // than numbers or booleans to strings by using the toString() method.
        return row.getObject(i).toString();
    }
    return null;
}
 
Example 16
Source File: AbstractCassandraProcessor.java    From nifi with Apache License 2.0 4 votes vote down vote up
protected static Object getCassandraObject(Row row, int i, DataType dataType) {
    if (dataType.equals(DataType.blob())) {
        return row.getBytes(i);

    } else if (dataType.equals(DataType.varint()) || dataType.equals(DataType.decimal())) {
        // Avro can't handle BigDecimal and BigInteger as numbers - it will throw an
        // AvroRuntimeException such as: "Unknown datum type: java.math.BigDecimal: 38"
        return row.getObject(i).toString();

    } else if (dataType.equals(DataType.cboolean())) {
        return row.getBool(i);

    } else if (dataType.equals(DataType.cint())) {
        return row.getInt(i);

    } else if (dataType.equals(DataType.bigint())
            || dataType.equals(DataType.counter())) {
        return row.getLong(i);

    } else if (dataType.equals(DataType.ascii())
            || dataType.equals(DataType.text())
            || dataType.equals(DataType.varchar())) {
        return row.getString(i);

    } else if (dataType.equals(DataType.cfloat())) {
        return row.getFloat(i);

    } else if (dataType.equals(DataType.cdouble())) {
        return row.getDouble(i);

    } else if (dataType.equals(DataType.timestamp())) {
        return row.getTimestamp(i);

    } else if (dataType.equals(DataType.date())) {
        return row.getDate(i);

    } else if (dataType.equals(DataType.time())) {
        return row.getTime(i);

    } else if (dataType.isCollection()) {

        List<DataType> typeArguments = dataType.getTypeArguments();
        if (typeArguments == null || typeArguments.size() == 0) {
            throw new IllegalArgumentException("Column[" + i + "] " + dataType.getName()
                    + " is a collection but no type arguments were specified!");
        }
        // Get the first type argument, to be used for lists and sets (and the first in a map)
        DataType firstArg = typeArguments.get(0);
        TypeCodec firstCodec = codecRegistry.codecFor(firstArg);
        if (dataType.equals(DataType.set(firstArg))) {
            return row.getSet(i, firstCodec.getJavaType());
        } else if (dataType.equals(DataType.list(firstArg))) {
            return row.getList(i, firstCodec.getJavaType());
        } else {
            // Must be an n-arg collection like map
            DataType secondArg = typeArguments.get(1);
            TypeCodec secondCodec = codecRegistry.codecFor(secondArg);
            if (dataType.equals(DataType.map(firstArg, secondArg))) {
                return row.getMap(i, firstCodec.getJavaType(), secondCodec.getJavaType());
            }
        }

    } else {
        // The different types that we support are numbers (int, long, double, float),
        // as well as boolean values and Strings. Since Avro doesn't provide
        // timestamp types, we want to convert those to Strings. So we will cast anything other
        // than numbers or booleans to strings by using the toString() method.
        return row.getObject(i).toString();
    }
    return null;
}
 
Example 17
Source File: GuicedCassandraSessionDAO.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
private Session hydrateSession(UUID id, Row row) {
	UUID rowId = row.getUUID(Columns.ID);
	if (id.equals(rowId)) {
		Date start = row.getTimestamp(Columns.START);
		// If this is null, then the row is a tombstone.
		if (start != null) {
			ByteBuffer buffer = row.getBytes(Columns.SERIALIZED);
			// If the buffer has anything, then it is an old style serialized session.
			if (buffer != null && buffer.remaining() > 0) {
				byte[] bytes = new byte[buffer.remaining()];
            buffer.get(bytes);
            return serializer.deserialize(bytes);
			}
			else {
				// New style session. Read the fields and create a session.
             Date stop = row.getTimestamp(Columns.STOP);
             Date lastAccess = row.getTimestamp(Columns.LAST_ACCESS);
				long timeout = row.getLong(Columns.TIMEOUT);
				boolean expired = row.getBool(Columns.EXPIRED);
				String host = row.getString(Columns.HOST);
				
				// Read the attributes
				Map<String, String> serialized_attrs = row.getMap(Columns.ATTRIBUTES, String.class, String.class);
				Map<Object, Object> attributes = new HashMap<>();
				for (Map.Entry<String, String> entry : serialized_attrs.entrySet()) {
					String json = entry.getValue();
					if (json != null && !json.isEmpty()) {
						attributes.put(entry.getKey(), deserializeAttribute(entry.getKey(), json));
					}
				}
				
				// Create and populate the session.
				SimpleSession session = new SimpleSession();
				session.setId(rowId);
				session.setStartTimestamp(start);
				session.setStopTimestamp(stop);
				session.setLastAccessTime(lastAccess);
				session.setTimeout(timeout);
				session.setExpired(expired);
				session.setHost(host);
				session.setAttributes(attributes);
				
				return session;
			}
		}
	}
	return null;
}
 
Example 18
Source File: SchemaUpgrade.java    From glowroot with Apache License 2.0 4 votes vote down vote up
private void populateTraceTtSlowCountAndPointPartialPart1() throws Exception {
    logger.info("populating trace_tt_slow_count_partial and trace_tt_slow_point_partial tables"
            + " - this could take several minutes on large data sets...");
    CentralStorageConfig storageConfig = getCentralStorageConfig(session);
    dropTableIfExists("trace_tt_slow_count_partial");
    dropTableIfExists("trace_tt_slow_point_partial");
    session.createTableWithTWCS("create table if not exists trace_tt_slow_count_partial"
            + " (agent_rollup varchar, transaction_type varchar, capture_time timestamp,"
            + " agent_id varchar, trace_id varchar, primary key ((agent_rollup,"
            + " transaction_type), capture_time, agent_id, trace_id))",
            storageConfig.traceExpirationHours(), false, true);
    session.createTableWithTWCS("create table if not exists trace_tt_slow_point_partial"
            + " (agent_rollup varchar, transaction_type varchar, capture_time timestamp,"
            + " agent_id varchar, trace_id varchar, duration_nanos bigint, error boolean,"
            + " headline varchar, user varchar, attributes blob, primary key ((agent_rollup,"
            + " transaction_type), capture_time, agent_id, trace_id))",
            storageConfig.traceExpirationHours(), false, true);
    PreparedStatement insertCountPartialPS = session.prepare("insert into"
            + " trace_tt_slow_count_partial (agent_rollup, transaction_type, capture_time,"
            + " agent_id, trace_id) values (?, ?, ?, ?, ?) using ttl ?");
    PreparedStatement insertPointPartialPS = session.prepare("insert into"
            + " trace_tt_slow_point_partial (agent_rollup, transaction_type, capture_time,"
            + " agent_id, trace_id, duration_nanos, error, headline, user, attributes) values"
            + " (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) using ttl ?");
    int ttl = getCentralStorageConfig(session).getTraceTTL();
    ResultSet results = session.read("select agent_rollup, transaction_type, capture_time,"
            + " agent_id, trace_id, duration_nanos, error, headline, user, attributes, partial"
            + " from trace_tt_slow_point");
    Queue<ListenableFuture<?>> futures = new ArrayDeque<>();
    Stopwatch stopwatch = Stopwatch.createStarted();
    int rowCount = 0;
    for (Row row : results) {
        if (!row.getBool(10)) { // partial
            // unfortunately cannot use "where partial = true allow filtering" in the query
            // above as that leads to ReadTimeoutException
            continue;
        }
        BoundStatement boundStatement = insertCountPartialPS.bind();
        int i = 0;
        copyString(row, boundStatement, i++); // agent_rollup
        copyString(row, boundStatement, i++); // transaction_type
        Date captureDate = checkNotNull(row.getTimestamp(i));
        int adjustedTTL = Common.getAdjustedTTL(ttl, captureDate.getTime(), clock);
        copyTimestamp(row, boundStatement, i++); // capture_time
        copyString(row, boundStatement, i++); // agent_id
        copyString(row, boundStatement, i++); // trace_id
        boundStatement.setInt(i++, adjustedTTL);
        futures.add(session.writeAsync(boundStatement));

        boundStatement = insertPointPartialPS.bind();
        i = 0;
        copyString(row, boundStatement, i++); // agent_rollup
        copyString(row, boundStatement, i++); // transaction_type
        copyTimestamp(row, boundStatement, i++); // capture_time
        copyString(row, boundStatement, i++); // agent_id
        copyString(row, boundStatement, i++); // trace_id
        copyLong(row, boundStatement, i++); // duration_nanos
        copyBool(row, boundStatement, i++); // error
        copyString(row, boundStatement, i++); // headline
        copyString(row, boundStatement, i++); // user
        copyBytes(row, boundStatement, i++); // attributes
        boundStatement.setInt(i++, adjustedTTL);
        futures.add(session.writeAsync(boundStatement));

        rowCount++;
        if (stopwatch.elapsed(SECONDS) > 60) {
            logger.info("processed {} records", rowCount);
            stopwatch.reset().start();
        }
        waitForSome(futures);
    }
    MoreFutures.waitForAll(futures);
    logger.info("populating trace_tt_slow_count_partial and trace_tt_slow_point_partial tables"
            + " - complete");
}
 
Example 19
Source File: SchemaUpgrade.java    From glowroot with Apache License 2.0 4 votes vote down vote up
private void populateTraceTnSlowCountAndPointPartialPart1() throws Exception {
    logger.info("populating trace_tn_slow_count_partial and trace_tn_slow_point_partial tables"
            + " - this could take several minutes on large data sets...");
    CentralStorageConfig storageConfig = getCentralStorageConfig(session);
    dropTableIfExists("trace_tn_slow_count_partial");
    dropTableIfExists("trace_tn_slow_point_partial");
    session.createTableWithTWCS("create table if not exists trace_tn_slow_count_partial"
            + " (agent_rollup varchar, transaction_type varchar, transaction_name varchar,"
            + " capture_time timestamp, agent_id varchar, trace_id varchar, primary key"
            + " ((agent_rollup, transaction_type, transaction_name), capture_time, agent_id,"
            + " trace_id))", storageConfig.traceExpirationHours(), false, true);
    session.createTableWithTWCS("create table if not exists trace_tn_slow_point_partial"
            + " (agent_rollup varchar, transaction_type varchar, transaction_name varchar,"
            + " capture_time timestamp, agent_id varchar, trace_id varchar, duration_nanos"
            + " bigint, error boolean, headline varchar, user varchar, attributes blob, primary"
            + " key ((agent_rollup, transaction_type, transaction_name), capture_time,"
            + " agent_id, trace_id))", storageConfig.traceExpirationHours(), false, true);
    PreparedStatement insertCountPartialPS = session.prepare("insert into"
            + " trace_tn_slow_count_partial (agent_rollup, transaction_type, transaction_name,"
            + " capture_time, agent_id, trace_id) values (?, ?, ?, ?, ?, ?) using ttl ?");
    PreparedStatement insertPointPartialPS = session.prepare("insert into"
            + " trace_tn_slow_point_partial (agent_rollup, transaction_type, transaction_name,"
            + " capture_time, agent_id, trace_id, duration_nanos, error, headline, user,"
            + " attributes) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) using ttl ?");
    int ttl = getCentralStorageConfig(session).getTraceTTL();
    ResultSet results = session.read("select agent_rollup, transaction_type,"
            + " transaction_name, capture_time, agent_id, trace_id, duration_nanos, error,"
            + " headline, user, attributes, partial from trace_tn_slow_point");
    Queue<ListenableFuture<?>> futures = new ArrayDeque<>();
    Stopwatch stopwatch = Stopwatch.createStarted();
    int rowCount = 0;
    for (Row row : results) {
        if (!row.getBool(11)) { // partial
            // unfortunately cannot use "where partial = true allow filtering" in the query
            // above as that leads to ReadTimeoutException
            continue;
        }
        BoundStatement boundStatement = insertCountPartialPS.bind();
        int i = 0;
        copyString(row, boundStatement, i++); // agent_rollup
        copyString(row, boundStatement, i++); // transaction_type
        copyString(row, boundStatement, i++); // transaction_name
        Date captureDate = checkNotNull(row.getTimestamp(i));
        int adjustedTTL = Common.getAdjustedTTL(ttl, captureDate.getTime(), clock);
        copyTimestamp(row, boundStatement, i++); // capture_time
        copyString(row, boundStatement, i++); // agent_id
        copyString(row, boundStatement, i++); // trace_id
        boundStatement.setInt(i++, adjustedTTL);
        futures.add(session.writeAsync(boundStatement));

        boundStatement = insertPointPartialPS.bind();
        i = 0;
        copyString(row, boundStatement, i++); // agent_rollup
        copyString(row, boundStatement, i++); // transaction_type
        copyString(row, boundStatement, i++); // transaction_name
        copyTimestamp(row, boundStatement, i++); // capture_time
        copyString(row, boundStatement, i++); // agent_id
        copyString(row, boundStatement, i++); // trace_id
        copyLong(row, boundStatement, i++); // duration_nanos
        copyBool(row, boundStatement, i++); // error
        copyString(row, boundStatement, i++); // headline
        copyString(row, boundStatement, i++); // user
        copyBytes(row, boundStatement, i++); // attributes
        boundStatement.setInt(i++, adjustedTTL);
        futures.add(session.writeAsync(boundStatement));

        rowCount++;
        if (stopwatch.elapsed(SECONDS) > 60) {
            logger.info("processed {} records", rowCount);
            stopwatch.reset().start();
        }
        waitForSome(futures);
    }
    MoreFutures.waitForAll(futures);
    logger.info("populating trace_tn_slow_count_partial and trace_tn_slow_point_partial tables"
            + " - complete");
}
 
Example 20
Source File: TraceDaoImpl.java    From glowroot with Apache License 2.0 4 votes vote down vote up
private static List<TracePoint> processPoints(ResultSet results, TracePointFilter filter,
        boolean partial, boolean errorPoints) throws IOException {
    List<TracePoint> tracePoints = new ArrayList<>();
    for (Row row : results) {
        int i = 0;
        String agentId = checkNotNull(row.getString(i++));
        String traceId = checkNotNull(row.getString(i++));
        long captureTime = checkNotNull(row.getTimestamp(i++)).getTime();
        if (partial) {
            // real_capture_time is only present for data written starting with 0.13.1
            Date realCaptureTime = row.getTimestamp(i++);
            if (realCaptureTime != null) {
                captureTime = realCaptureTime.getTime();
            }
        }
        long durationNanos = row.getLong(i++);
        boolean error = errorPoints || row.getBool(i++);
        // error points are defined by having an error message, so safe to checkNotNull
        String errorMessage = errorPoints ? checkNotNull(row.getString(i++)) : "";
        // headline is null for data inserted prior to 0.9.7
        String headline = Strings.nullToEmpty(row.getString(i++));
        String user = Strings.nullToEmpty(row.getString(i++));
        ByteBuffer attributeBytes = row.getBytes(i++);
        List<Trace.Attribute> attrs =
                Messages.parseDelimitedFrom(attributeBytes, Trace.Attribute.parser());
        Map<String, List<String>> attributes = attrs.stream().collect(
                Collectors.toMap(Trace.Attribute::getName, Trace.Attribute::getValueList));
        if (filter.matchesDuration(durationNanos)
                && filter.matchesHeadline(headline)
                && filter.matchesError(errorMessage)
                && filter.matchesUser(user)
                && filter.matchesAttributes(attributes)) {
            tracePoints.add(ImmutableTracePoint.builder()
                    .agentId(agentId)
                    .traceId(traceId)
                    .captureTime(captureTime)
                    .durationNanos(durationNanos)
                    .partial(partial)
                    .error(error)
                    .checkLiveTraces(false)
                    .build());
        }
    }
    return tracePoints;
}