Java Code Examples for com.datastax.driver.core.ResultSet#isExhausted()

The following examples show how to use com.datastax.driver.core.ResultSet#isExhausted() . 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: TraceDaoImpl.java    From glowroot with Apache License 2.0 6 votes vote down vote up
private List<Trace.SharedQueryText> readSharedQueryTextsUsingPS(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);
    List<Trace.SharedQueryText> sharedQueryTexts = new ArrayList<>();
    while (!results.isExhausted()) {
        Row row = results.one();
        int i = 0;
        String truncatedText = checkNotNull(row.getString(i++));
        String truncatedEndText = row.getString(i++);
        String fullTextSha1 = row.getString(i++);
        Trace.SharedQueryText.Builder sharedQueryText = Trace.SharedQueryText.newBuilder();
        if (fullTextSha1 == null) {
            sharedQueryText.setFullText(truncatedText);
        } else {
            sharedQueryText.setFullTextSha1(fullTextSha1)
                    .setTruncatedText(truncatedText)
                    .setTruncatedEndText(checkNotNull(truncatedEndText));
        }
        sharedQueryTexts.add(sharedQueryText.build());
    }
    return sharedQueryTexts;
}
 
Example 2
Source File: CassandraVideoV2Dao.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
private void repairIfNeeded(VideoMetadata metadata) {
	if(metadata != null && metadata.isInProgress()) {
		try {
			ResultSet rs = session.execute(recordingTable.select(metadata.getRecordingId()));
			if(rs.isExhausted()) {
				logger.warn("Can't load recording data for recording [{}]", metadata);
				return;
			}
			
			VideoRecording rec = VideoUtil.recMaterializeRecording( rs, metadata.getRecordingId() );
			if(rec.isRecordingFinished()) {
				logger.debug("Repairing completed recording [{}]", metadata.getRecordingId());
				metadata.setDuration(rec.duration);
				metadata.setSize(rec.size);
				if(!metadata.isStream()) {						
					complete(metadata.getPlaceId(), metadata.getRecordingId(), metadata.getExpiration(), VideoV2Util.createActualTTL(metadata.getRecordingId(), metadata.getExpiration()), rec.duration, rec.size);
				}
			}
		}
		catch(Exception e) {
			logger.warn("Unable to load recording data for [{}] in order to attempt repair", metadata.getRecordingId(), e);
		}
	}
	
}
 
Example 3
Source File: CassandraVideoV2Dao.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
private void addDeleteStatements(BatchStatement stmt, UUID placeId, UUID recordingId, boolean isFavorite, Date purgeTime, int purgePartitionId) {
	boolean expired = false;
	long expiration = 0;
	if(isFavorite) {
		//check to see if data in the normal table has expired
		BoundStatement bs = recordingMetadataTable.selectRecording(recordingId);
		ResultSet rs = session.execute(bs);
		if(!rs.isExhausted()) {
			expiration = rs.one().getLong(VideoMetadataV2Table.COL_EXPIRATION);
		}else{
			expired = true;
		}
	}
	if(!expired) {					
		long actualTtlInSeconds = VideoV2Util.createActualTTL(recordingId, expiration);		
		// Recording metadata Table Mutations
		stmt.add(recordingMetadataTable.insertField(recordingId, expiration, actualTtlInSeconds, MetadataAttribute.DELETED, Boolean.TRUE.toString()));
		// Recording Place Index Mutations
		stmt.add(placeRecordingIndex.insertDeleted(placeId, recordingId, expiration, actualTtlInSeconds));
		stmt.add(placeRecordingIndex.deleteVideo(placeId, recordingId, PlaceRecordingIndexV2Table.Type.RECORDING));
		stmt.add(placeRecordingIndex.deleteVideo(placeId, recordingId, PlaceRecordingIndexV2Table.Type.STREAM));					
	}

}
 
Example 4
Source File: SchemaUpgrade.java    From glowroot with Apache License 2.0 6 votes vote down vote up
private Map<String, String> getSyntheticMonitorDisplays(PreparedStatement readAgentConfig,
        String agentRollupId) throws Exception {
    BoundStatement boundStatement = readAgentConfig.bind();
    boundStatement.setString(0, agentRollupId);
    ResultSet results = session.read(boundStatement);
    if (results.isExhausted()) {
        return ImmutableMap.of();
    }
    AgentConfig agentConfig;
    try {
        Row row = checkNotNull(results.one());
        agentConfig = AgentConfig.parseFrom(checkNotNull(row.getBytes(0)));
    } catch (InvalidProtocolBufferException e) {
        logger.error(e.getMessage(), e);
        return ImmutableMap.of();
    }
    Map<String, String> syntheticMonitorDisplays = new HashMap<>();
    for (SyntheticMonitorConfig config : agentConfig.getSyntheticMonitorConfigList()) {
        syntheticMonitorDisplays.put(config.getId(),
                MoreConfigDefaults.getDisplayOrDefault(config));
    }
    return syntheticMonitorDisplays;
}
 
Example 5
Source File: FullQueryTextDao.java    From glowroot with Apache License 2.0 6 votes vote down vote up
private @Nullable String getFullTextUsingPS(String agentRollupId, String fullTextSha1,
        PreparedStatement readCheckPS) throws Exception {
    BoundStatement boundStatement = readCheckPS.bind();
    boundStatement.setString(0, agentRollupId);
    boundStatement.setString(1, fullTextSha1);
    ResultSet results = session.read(boundStatement);
    if (results.isExhausted()) {
        return null;
    }
    boundStatement = readPS.bind();
    boundStatement.setString(0, fullTextSha1);
    results = session.read(boundStatement);
    Row row = results.one();
    if (row == null) {
        return null;
    }
    return row.getString(0);
}
 
Example 6
Source File: CassandraMessageDAO.java    From james-project with Apache License 2.0 6 votes vote down vote up
private Mono<MessageRepresentation>
message(ResultSet rows, CassandraMessageId cassandraMessageId, FetchType fetchType) {
    if (rows.isExhausted()) {
        return Mono.empty();
    }

    Row row = rows.one();
    return buildContentRetriever(fetchType, row).map(content ->
        new MessageRepresentation(
            cassandraMessageId,
            row.getTimestamp(INTERNAL_DATE),
            row.getLong(FULL_CONTENT_OCTETS),
            row.getInt(BODY_START_OCTET),
            new SharedByteArrayInputStream(content),
            getPropertyBuilder(row),
            hasAttachment(row),
            getAttachments(row).collect(Guavate.toImmutableList())));
}
 
Example 7
Source File: CassandraTransactionalStore.java    From attic-apex-malhar with Apache License 2.0 6 votes vote down vote up
@Override
public long getCommittedWindowId(String appId, int operatorId)
{
  try {
    BoundStatement boundStatement = new BoundStatement(lastWindowFetchCommand);
    lastWindowFetchStatement = boundStatement.bind(appId,operatorId);
    long lastWindow = -1;
    ResultSet resultSet = session.execute(lastWindowFetchStatement);
    if (!resultSet.isExhausted()) {
      lastWindow = resultSet.one().getLong(0);
    }
    lastWindowFetchCommand.disableTracing();
    return lastWindow;
  } catch (DriverException ex) {
    throw new RuntimeException(ex);
  }
}
 
Example 8
Source File: CassandraAppHandoffDao.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public Optional<SessionHandoff> validate(String token) {
	try(Timer.Context ctx = validateToken.time()) {
		BoundStatement bs = selectToken.bind( token );
		ResultSet result = session.execute( bs );
		if(result.isExhausted()) {
			logger.debug("No token exists for [{}]", token);
			return Optional.empty();
		}
		SessionHandoff handoff = translate(result.one());
		UUID personId = handoff.getPersonId();
		bs = clearToken.bind(personId, token);
		result = session.execute( bs );
		if(!result.wasApplied()) {
			logger.debug("Token [{}] has already been used / invalidated", token);
			return Optional.empty();
		}
		return Optional.of(handoff);
	}
}
 
Example 9
Source File: CassandraMemoryDAO.java    From modernmt with Apache License 2.0 5 votes vote down vote up
/**
 * This method retrieves from the Cassandra DB
 * all the Memory objects the ids of which
 * are contained in a given collection
 *
 * @param ids the collection of ids of the Memories to retrieve
 * @return the Memory objects the ids of which are contained in the passed id collection
 * @throws PersistenceException
 */
@Override
public Map<Long, Memory> retrieve(Collection<Long> ids) throws PersistenceException {
    Map<Long, Memory> map = new HashMap<>(ids.size());

    /*if the list is empty, return an empty map*/
    if (ids.isEmpty())
        return map;

    ArrayList<Long> list = new ArrayList<>(ids.size());
    list.addAll(ids);
    BuiltStatement statement = QueryBuilder.
            select().
            from(CassandraDatabase.MEMORIES_TABLE).
            where(QueryBuilder.in("id", list));

    /*execute the query*/
    ResultSet result = CassandraUtils.checkedExecute(connection, statement);

    /*create the Memory objects from the rows*/
    while (!result.isExhausted()) {
        Memory memory = read(result.one());
        map.put(memory.getId(), memory);
    }

    return map;
}
 
Example 10
Source File: RoleDao.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<RoleConfig> load(String name) throws Exception {
    BoundStatement boundStatement = readOnePS.bind();
    boundStatement.setString(0, name);
    ResultSet results = session.read(boundStatement);
    if (results.isExhausted()) {
        return Optional.absent();
    }
    Row row = results.one();
    if (!results.isExhausted()) {
        throw new IllegalStateException("Multiple role records for name: " + name);
    }
    return Optional.of(buildRole(row));
}
 
Example 11
Source File: AbstractCassandraInputOperator.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
/**
 * This executes the query to retrieve result from database.
 * It then converts each row into tuple and emit that into output port.
 */
@Override
public void emitTuples()
{
  String query = queryToRetrieveData();
  logger.debug("select statement: {}", query);

  SimpleStatement stmt = new SimpleStatement(query);
  stmt.setFetchSize(fetchSize);
  try {
    if (nextPageState != null) {
      stmt.setPagingState(nextPageState);
    }
    ResultSet result = store.getSession().execute(stmt);
    nextPageState = result.getExecutionInfo().getPagingState();

    if (!result.isExhausted()) {
      for (Row row : result) {
        T tuple = getTuple(row);
        emit(tuple);
      }
    } else {
      // No rows available wait for some time before retrying so as to not continuously slam the database
      Thread.sleep(waitForDataTimeout);
    }
  } catch (Exception ex) {
    store.disconnect();
    DTThrowable.rethrow(ex);
  }
}
 
Example 12
Source File: CassandraSyncIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public void transactionMarker() throws Exception {
    ResultSet results = session.execute("SELECT * FROM test.users where id = 12345");
    if (results.isExhausted()) {
        return;
    }
    for (Row row : results) {
        row.getInt("id");
    }
}
 
Example 13
Source File: CassandraStorage.java    From cassandra-reaper with Apache License 2.0 5 votes vote down vote up
@Override
public String listOperations(String clusterName, OpType operationType, String host) {
  ResultSet operations
      = session.execute(
          listOperationsForNodePrepStmt.bind(
              clusterName, operationType.getName(), DateTime.now().toString(HOURLY_FORMATTER), host));
  return operations.isExhausted()
      ? "[]"
      : operations.one().getString("data");
}
 
Example 14
Source File: CassandraIOTest.java    From beam with Apache License 2.0 5 votes vote down vote up
@Override
public Iterator map(ResultSet resultSet) {
  if (!resultSet.isExhausted()) {
    resultSet.iterator().forEachRemaining(r -> counter.getAndIncrement());
  }
  return Collections.emptyIterator();
}
 
Example 15
Source File: CassandraOperations.java    From geowave with Apache License 2.0 5 votes vote down vote up
public boolean deleteRow(
    final String tableName,
    final GeoWaveRow row,
    final String... additionalAuthorizations) {
  boolean exhausted = true;
  for (int i = 0; i < row.getFieldValues().length; i++) {
    final ResultSet rs =
        session.execute(
            QueryBuilder.delete().from(gwNamespace, getCassandraSafeName(tableName)).where(
                QueryBuilder.eq(
                    CassandraField.GW_PARTITION_ID_KEY.getFieldName(),
                    ByteBuffer.wrap(
                        CassandraUtils.getCassandraSafePartitionKey(row.getPartitionKey())))).and(
                            QueryBuilder.eq(
                                CassandraField.GW_SORT_KEY.getFieldName(),
                                ByteBuffer.wrap(row.getSortKey()))).and(
                                    QueryBuilder.eq(
                                        CassandraField.GW_ADAPTER_ID_KEY.getFieldName(),
                                        row.getAdapterId())).and(
                                            QueryBuilder.eq(
                                                CassandraField.GW_DATA_ID_KEY.getFieldName(),
                                                ByteBuffer.wrap(row.getDataId()))).and(
                                                    QueryBuilder.eq(
                                                        CassandraField.GW_FIELD_VISIBILITY_KEY.getFieldName(),
                                                        ByteBuffer.wrap(
                                                            row.getFieldValues()[i].getVisibility()))));
    exhausted &= rs.isExhausted();
  }

  return !exhausted;
}
 
Example 16
Source File: CassandraVideoV2Dao.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private VideoRecording retrieveVideoRecordingFromTable(AbstractRecordingV2Table table, UUID recordingId) {
	BoundStatement select = table.select(recordingId);
	ResultSet rs = session.execute(select);
	if(rs.isExhausted()) {
		return null;
	}else{
		return VideoUtil.recMaterializeRecording(rs, recordingId);
	}
}
 
Example 17
Source File: CassandraVideoV2Dao.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private VideoMetadata retrieveMetadataFrom(AbstractVideoMetadataV2Table table, UUID recordingId, boolean repair) {
	BoundStatement bs = table.selectRecording(recordingId);
	ResultSet rs = session.execute(bs);
	VideoMetadata datum = null;
	if(!rs.isExhausted()) {
		//found it in table
		datum = Iterables.getFirst( table.materialize(rs), null );
		if(repair) {
			repairIfNeeded(datum);
		}
	}
	return datum;
}
 
Example 18
Source File: SchemaVersionChecker.java    From hawkular-metrics with Apache License 2.0 4 votes vote down vote up
public void waitForSchemaUpdates(Session session, String keyspace, long delay, int maxRetries)
        throws InterruptedException {
    String configId = "org.hawkular.metrics";
    String configName = "schema-version";
    int retries = 0;
    PreparedStatement getVersion = null;
    SchemaService schemaService = new SchemaService(session, keyspace);
    String version = schemaService.getSchemaVersion();

    while (maxRetries > retries) {
        try {
            if (getVersion == null) {
                getVersion = session.prepare("SELECT value FROM " + keyspace + ".sys_config " +
                        "WHERE config_id = ? AND name = ?");
            }
            ResultSet resultSet = session.execute(getVersion.bind(configId, configName));
            if (!resultSet.isExhausted()) {
                String schemaVersion = resultSet.one().getString(0);
                if(version.equals(schemaVersion)) {
                    logger.infof("Hawkular Metrics schema is up to date at version %s", version);
                    return;
                } else {
                    logger.infof("Hawkular Metrics schema version does not match," +
                                    " should be %s, present: %s, Trying again in %d ms",
                            version, schemaVersion, delay);

                }
            }
        } catch (Exception e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Version check failed", e);
            } else {
                logger.infof("Version check failed: %s", e.getMessage());
            }
            logger.infof("Trying again in %d ms", delay);
        }
        retries++;
        Thread.sleep(delay);
    }

    throw new SchemaVersionCheckException("Version check unsuccessful after " + maxRetries + " attempts");
}
 
Example 19
Source File: TraceDaoImpl.java    From glowroot with Apache License 2.0 4 votes vote down vote up
private List<Trace.Entry> readEntriesUsingPS(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);
    List<Trace.Entry> entries = new ArrayList<>();
    while (!results.isExhausted()) {
        Row row = results.one();
        int i = 0;
        Trace.Entry.Builder entry = Trace.Entry.newBuilder()
                .setDepth(row.getInt(i++))
                .setStartOffsetNanos(row.getLong(i++))
                .setDurationNanos(row.getLong(i++))
                .setActive(row.getBool(i++));
        if (row.isNull(i + 1)) { // shared_query_text_index
            // message is null for trace entries added using addErrorEntry()
            entry.setMessage(Strings.nullToEmpty(row.getString(i++)));
            i++; // shared_query_text_index
            i++; // query_message_prefix
            i++; // query_message_suffix
        } else {
            i++; // message
            Trace.QueryEntryMessage queryEntryMessage = Trace.QueryEntryMessage.newBuilder()
                    .setSharedQueryTextIndex(row.getInt(i++))
                    .setPrefix(Strings.nullToEmpty(row.getString(i++)))
                    .setSuffix(Strings.nullToEmpty(row.getString(i++)))
                    .build();
            entry.setQueryEntryMessage(queryEntryMessage);
        }
        ByteBuffer detailBytes = row.getBytes(i++);
        if (detailBytes != null) {
            entry.addAllDetailEntry(
                    Messages.parseDelimitedFrom(detailBytes, Trace.DetailEntry.parser()));
        }
        ByteBuffer locationBytes = row.getBytes(i++);
        if (locationBytes != null) {
            entry.addAllLocationStackTraceElement(Messages.parseDelimitedFrom(locationBytes,
                    Proto.StackTraceElement.parser()));
        }
        ByteBuffer errorBytes = row.getBytes(i++);
        if (errorBytes != null) {
            entry.setError(Trace.Error.parseFrom(errorBytes));
        }
        entries.add(entry.build());
    }
    return entries;
}
 
Example 20
Source File: CassandraTweetRepository.java    From twissandra-j with Apache License 2.0 4 votes vote down vote up
private Row getOneRow(ResultSet result) {
	Row row = result.one();
	if (!result.isExhausted())
		throw new RuntimeException("ResultSet instance contained more than one row!");
	return row;
}