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

The following examples show how to use com.datastax.driver.core.ResultSet#one() . 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: CassandraQueryExecutor.java    From arcusplatform with Apache License 2.0 7 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 2
Source File: CassandraStorage.java    From copper-engine with Apache License 2.0 6 votes vote down vote up
@Override
public int countWorkflowInstances(WorkflowInstanceFilter filter) throws Exception {
    final StringBuilder query = new StringBuilder();
    final List<Object> values = new ArrayList<>();
    query.append("SELECT COUNT(*) AS COUNT_NUMBER FROM COP_WORKFLOW_INSTANCE");
    appendQueryBase(query, values, filter);
    query.append(" ALLOW FILTERING");
    final String cqlQuery = query.toString();
    logger.info("queryWorkflowInstances - cqlQuery = {}", cqlQuery);
    final ResultSet resultSet = session.execute(cqlQuery, values.toArray());
    Row row;
    while ((row = resultSet.one()) != null) {
        return row.getInt("COUNT_NUMBER");
    }
    throw new SQLException("Failed to get result of CQL request for counting workflow instances");
}
 
Example 3
Source File: TestMain.java    From copper-engine with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    int counter = 0;
    CassandraSessionManagerImpl sessionManagerImpl = new CassandraSessionManagerImpl(Arrays.asList("nuc1.scoop-gmbh.de", "nuc2.scoop-gmbh.de"), null, "copper_red");
    sessionManagerImpl.startup();
    try {
        Session session = sessionManagerImpl.getSession();
        PreparedStatement stmt = session.prepare("SELECT ID FROM COP_WORKFLOW_INSTANCE");
        long startTS = System.currentTimeMillis();
        ResultSet rs = session.execute(stmt.bind().setConsistencyLevel(ConsistencyLevel.TWO).setFetchSize(20));
        Row row = null;
        while ((row = rs.one()) != null) {
            System.out.println(row.getString("ID"));
            counter++;
        }
        long et = System.currentTimeMillis() - startTS;
        System.out.println(et);
    } catch (Exception e) {
        e.printStackTrace();
    }
    sessionManagerImpl.shutdown();
    System.out.println(counter);
}
 
Example 4
Source File: AdaptiveResultSetTest.java    From emodb with Apache License 2.0 6 votes vote down vote up
private String verifyNextRow(ResultSet rs) {
    String rowid = null;
    for (int col=0; col < 137; col++) {
        Row row = rs.one();
        assertNotNull(row);

        if (rowid == null) {
            rowid = row.get("rowid", TypeCodec.varchar());
        } else {
            assertEquals(row.get("rowid", TypeCodec.varchar()), rowid);
        }

        assertEquals((long) row.get("col", TypeCodec.bigint()), col);
        assertEquals( row.get("data", TypeCodec.blob()).asIntBuffer().get(), col);
    }

    return rowid;
}
 
Example 5
Source File: BaseCassandraCRUDDao.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
protected PagedResults<T> doList(BoundStatement select, int limit) {
   List<T> result = new ArrayList<>(limit);
   select.setFetchSize(limit + 1);

   ResultSet rs = session.execute( select );
   Row row = rs.one();
   for(int i=0; i<limit && row != null; i++) {
      try {
         T entity = buildEntity(row);
         result.add(entity);
      }
      catch(Exception e) {
         logger.warn("Unable to deserialize row {}", row, e);
      }
      row = rs.one();
   }
   if(row == null) {
      return PagedResults.newPage(result);
   }
   else {
      return PagedResults.newPage(result, String.valueOf(getIdFromRow(row)));
   }
}
 
Example 6
Source File: CQLService.java    From Doradus with Apache License 2.0 6 votes vote down vote up
@Override
public List<String> getRows(String storeName, String continuationToken, int count) {
    String tableName = storeToCQLName(storeName);
    Set<String> rows = new HashSet<String>();
    //unfortunately I don't know how to get one record per row in CQL so we'll read everything
    //and find out the rows
    ResultSet rs = executeQuery(Query.SELECT_ROWS_RANGE, tableName);
    while(true) {
        Row r = rs.one();
        if(r == null) break;
        String key = r.getString("key");
        if(continuationToken != null && continuationToken.compareTo(key) >= 0) {
            continue;
        }
        rows.add(key);
    }
    List<String> result = new ArrayList<>(rows);
    Collections.sort(result);
    if(result.size() > count) {
        result = new ArrayList<>(result.subList(0,  count));
    }
    return result;
}
 
Example 7
Source File: SchemaUpgrade.java    From glowroot with Apache License 2.0 6 votes vote down vote up
private void sortOfFixWebConfig() throws Exception {
    ResultSet results =
            session.read("select value from central_config where key = 'web'");
    Row row = results.one();
    if (row == null) {
        return;
    }
    String webConfigText = row.getString(0);
    if (webConfigText == null) {
        return;
    }
    JsonNode jsonNode = mapper.readTree(webConfigText);
    if (jsonNode == null || !jsonNode.isObject()) {
        return;
    }
    ObjectNode webConfigNode = (ObjectNode) jsonNode;
    if (webConfigNode.has("host")) {
        // remove 'web' config row which has 'smtp' config (old 'web' config row is lost)
        session.read("delete from central_config where key = 'web'");
    }
}
 
Example 8
Source File: PlaceDAOImpl.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public UUID getAccountById(UUID placeId) {
   BoundStatement bs = getAccountById.bind(placeId);
   ResultSet rs = session.execute(bs);
   Row row = rs.one();
   return (row != null) ? row.getUUID(PlaceEntityColumns.ACCOUNT_ID) : null;
}
 
Example 9
Source File: PlaceDAOImpl.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
  @Nullable
public String getPopulationById(UUID placeId) {
  	BoundStatement bs = getPopulationById.bind(placeId);
     ResultSet rs = session.execute(bs);
     Row row = rs.one();
     return (row != null) ? row.getString(PlaceEntityColumns.POPULATION) : null;
}
 
Example 10
Source File: CassandraContainerTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
private void testInitScript(CassandraContainer cassandraContainer) {
    ResultSet resultSet = performQuery(cassandraContainer, "SELECT * FROM keySpaceTest.catalog_category");
    assertTrue("Query was not applied", resultSet.wasApplied());
    Row row = resultSet.one();
    assertEquals("Inserted row is not in expected state", 1, row.getLong(0));
    assertEquals("Inserted row is not in expected state", "test_category", row.getString(1));
}
 
Example 11
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 12
Source File: TraceDaoImpl.java    From glowroot with Apache License 2.0 5 votes vote down vote up
public @Nullable Profile readMainThreadProfileUsingPS(String agentId, String traceId,
        PreparedStatement readPS) throws Exception {
    BoundStatement boundStatement = readPS.bind();
    boundStatement.setString(0, agentId);
    boundStatement.setString(1, traceId);
    ResultSet results = session.read(boundStatement);
    Row row = results.one();
    if (row == null) {
        return null;
    }
    return Profile.parseFrom(checkNotNull(row.getBytes(0)));
}
 
Example 13
Source File: TransferLogSerializationImpl.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@Override
public Result<TransferLog> getAllTransferLogs(PagingState pagingState, int fetchSize ) {

    Statement query = QueryBuilder.select().all().from(TABLE_TRANSFER_LOG);

    query.setFetchSize( fetchSize );
    if ( pagingState != null ) {
        query.setPagingState( pagingState );
    }

    ResultSet rs = cassandraClient.getApplicationSession().execute( query );
    final PagingState newPagingState = rs.getExecutionInfo().getPagingState();

    final List<TransferLog> transferLogs = new ArrayList<>();
    int numReturned = rs.getAvailableWithoutFetching();
    for ( int i=0; i<numReturned; i++ ) {
        Row row = rs.one();
        TransferLog tlog = new TransferLog(
                row.getString( COLUMN_QUEUE_NAME ),
                row.getString( COLUMN_SOURCE_REGION ),
                row.getString( COLUMN_DEST_REGION ),
                row.getUUID( COLUMN_MESSAGE_ID ),
                row.getLong( COLUMN_TRANSFER_TIME ));
        transferLogs.add( tlog );
    }

    return new Result<TransferLog>() {

        @Override
        public PagingState getPagingState() {
            return newPagingState;
        }

        @Override
        public List<TransferLog> getEntities() {
            return transferLogs;
        }
    };
}
 
Example 14
Source File: CassandraPersistentActorRepository.java    From elasticactors with Apache License 2.0 5 votes vote down vote up
private Row internalGet(final ShardKey shard,final String actorId) {
    // log a warning when we exceed the readExecutionThreshold
    final long startTime = currentTimeMillis();
    try {
        ResultSet resultSet = executeWithRetry(cassandraSession, selectStatement.bind(clusterName, shard.toString(), actorId), logger);
        return resultSet.one();
    } finally {
        final long endTime = currentTimeMillis();
        if((endTime - startTime) > readExecutionThresholdMillis) {
            logger.warn("Cassandra read operation took {} msecs for actorId [{}] on shard [{}]", (endTime - startTime), actorId, shard);
        }
    }
}
 
Example 15
Source File: CassandraLoader.java    From swblocks-decisiontree with Apache License 2.0 5 votes vote down vote up
/**
 * Loads a {@link DecisionTreeRuleSet} from Cassandra using the defined keyspace.
 *
 * @return {@link Result} indicating if the load succeeded, storing any exception if the load failed.
 */
@Override
public Result<DecisionTreeRuleSet> get() {
    try {
        ResultSet resultSet = this.session.execute(CQL_GET_RULESET_FROM_RULESETNAME,
                "DEFAULT", this.ruleSetName);
        EhSupport.ensure(!resultSet.isExhausted(), "RuleSet %s does not exist in %s.", this.ruleSetName,
                this.keyspace);

        final Row resultsRow = resultSet.one();
        final List<String> driverList = resultsRow.getList("drivers", String.class);
        final DriverCache driverCache = new DriverCache();

        resultSet = this.session.execute(CQL_GET_RULES_FOR_RULESET, this.ruleSetName);
        final Builder<RuleSetBuilder, DecisionTreeRuleSet> ruleSetBuilder = RuleSetBuilder.creator(driverList);
        ruleSetBuilder.with(RuleSetBuilder::setName, this.ruleSetName);
        ruleSetBuilder.with(RuleSetBuilder::groups, getValueGroupsForRuleSet(this.ruleSetName));
        ruleSetBuilder.with(RuleSetBuilder::setCache, driverCache);

        resultSet.iterator().forEachRemaining(row -> ruleSetBuilder.with(RuleSetBuilder::rule, RuleBuilder.creator()
                .with(RuleBuilder::cache, driverCache)
                .with(RuleBuilder::setId, row.get("id", UUID.class))
                .with(RuleBuilder::setCode, row.get("code", UUID.class))
                .with(RuleBuilder::start, row.get("start", Instant.class))
                .with(RuleBuilder::end, row.get("end", Instant.class))
                .with(RuleBuilder::input, row.getList("drivers", String.class))
                .with(RuleBuilder::output, row.getList("outputs", String.class))
        ));

        final DecisionTreeRuleSet loadedRuleSet = ruleSetBuilder.build();
        return Result.success(loadedRuleSet);
    } catch (final Exception exception) {
        return Result.failure(() -> exception);
    }
}
 
Example 16
Source File: CassandraEntityStoreMixin.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
private EntityState queryFor( BoundStatement statement, ModuleDescriptor module, EntityReference reference )
{
    ResultSet result = cluster.cassandraClientSession().execute( statement );
    Row row = result.one();
    if( row == null )
    {
        throw new EntityNotFoundException( reference );
    }
    return deserialize( row, module );
}
 
Example 17
Source File: TraceDaoImpl.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private Trace. /*@Nullable*/ Header readHeaderUsingPS(String agentId, String traceId,
        PreparedStatement readPS) throws Exception {
    BoundStatement boundStatement = readPS.bind();
    boundStatement.setString(0, agentId);
    boundStatement.setString(1, traceId);
    ResultSet results = session.read(boundStatement);
    Row row = results.one();
    if (row == null) {
        return null;
    }
    return Trace.Header.parseFrom(checkNotNull(row.getBytes(0)));
}
 
Example 18
Source File: CassandraSession.java    From presto with Apache License 2.0 5 votes vote down vote up
public VersionNumber getCassandraVersion()
{
    ResultSet result = executeWithSession(session -> session.execute("select release_version from system.local"));
    Row versionRow = result.one();
    if (versionRow == null) {
        throw new PrestoException(CASSANDRA_VERSION_ERROR, "The cluster version is not available. " +
                "Please make sure that the Cassandra cluster is up and running, " +
                "and that the contact points are specified correctly.");
    }
    return VersionNumber.parse(versionRow.getString("release_version"));
}
 
Example 19
Source File: CassandraIpcdDeviceDao.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@Override
public IpcdDevice findByProtocolAddress(String address) {
   ResultSet rs = session.execute(findById.bind(address));
   Row row = rs.one();
   return row != null ? toIpcdDevice(row) : null;
}
 
Example 20
Source File: CassandraStorage.java    From copper-engine with Apache License 2.0 4 votes vote down vote up
@Override
public void initialize(final HybridDBStorageAccessor internalStorageAccessor, int numberOfThreads) throws Exception {
    createSchema(session, cluster);

    prepareStatements();

    // TODO instead of blocking the startup until all active workflow instances are read and resumed, it is
    // sufficient to read just their existing IDs in COP_WFI_ID and resume them in the background while already
    // starting the engine an accepting new instances.

    if (numberOfThreads <= 0)
        numberOfThreads = 1;
    logger.info("Starting to initialize with {} threads ...", numberOfThreads);
    final ExecutorService execService = Executors.newFixedThreadPool(numberOfThreads);
    final long startTS = System.currentTimeMillis();
    final ResultSet rs = session.execute(preparedStatements.get(CQL_SEL_WFI_ID_ALL).bind().setFetchSize(500).setConsistencyLevel(ConsistencyLevel.ONE));
    int counter = 0;
    Row row;
    while ((row = rs.one()) != null) {
        counter++;
        final String wfId = row.getString("ID");
        execService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    resume(wfId, internalStorageAccessor);
                }
                catch (Exception e) {
                    logger.error("resume failed", e);
                }
            }
        });
    }
    logger.info("Read {} IDs in {} msec", counter, System.currentTimeMillis() - startTS);
    execService.shutdown();
    final boolean timeoutHappened = !execService.awaitTermination(initializationTimeoutSeconds, TimeUnit.SECONDS);
    if (timeoutHappened) {
        throw new CopperRuntimeException("initialize timed out!");
    }
    logger.info("Finished initialization - read {} rows in {} msec", counter, System.currentTimeMillis() - startTS);
    runtimeStatisticsCollector.submit("storage.init", counter, System.currentTimeMillis() - startTS, TimeUnit.MILLISECONDS);
}