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

The following examples show how to use com.datastax.driver.core.Row#getInt() . 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: MobileDeviceDAOImpl.java    From arcusplatform with 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 File: CassandraStorage.java    From copper-engine with Apache License 2.0 6 votes vote down vote up
private WorkflowInstance row2WorkflowInstance(Row row) {
    final WorkflowInstance cw = new WorkflowInstance();
    cw.id = row.getString("ID");
    cw.ppoolId = row.getString("PPOOL_ID");
    cw.prio = row.getInt("PRIO");
    cw.creationTS = row.getTimestamp("CREATION_TS");
    cw.timeout = row.getTimestamp("TIMEOUT");
    cw.waitMode = toWaitMode(row.getString("WAIT_MODE"));
    cw.serializedWorkflow = new SerializedWorkflow();
    cw.serializedWorkflow.setData(row.getString("DATA"));
    cw.serializedWorkflow.setObjectState(row.getString("OBJECT_STATE"));
    cw.cid2ResponseMap = toResponseMap(row.getString("RESPONSE_MAP_JSON"));
    cw.state = ProcessingState.valueOf(row.getString("STATE"));
    cw.lastModTS = row.getTimestamp("LAST_MOD_TS");
    cw.classname = row.getString("CLASSNAME");
    return cw;
}
 
Example 3
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 4
Source File: SchemaUpgrade.java    From glowroot with Apache License 2.0 6 votes vote down vote up
private static @Nullable Integer getSchemaVersion(Session session) throws Exception {
    ResultSet results =
            session.read("select schema_version from schema_version where one = 1");
    Row row = results.one();
    if (row != null) {
        return row.getInt(0);
    }
    TableMetadata agentTable = session.getTable("agent");
    if (agentTable != null && agentTable.getColumn("system_info") != null) {
        // special case, this is glowroot version 0.9.1, the only version supporting upgrades
        // prior to schema_version table
        return 1;
    }
    // new installation
    return null;
}
 
Example 5
Source File: RawMetricMapper.java    From realtime-analytics with GNU General Public License v2.0 6 votes vote down vote up
public RawNumericMetric map(Row row) {
    RawNumericMetric metricRow =  new RawNumericMetric(row.getString(0), row.getString(1), row.getDate(2).getTime(), row.getInt(3));
    ColumnDefinitions columeDef = row.getColumnDefinitions();
    List<Definition> columeDefList = columeDef.asList();
    Map<String, String> tagMap = new HashMap<String, String>();
    for(Definition def: columeDefList){
        if(def.getName().startsWith("tag_")){
            tagMap.put(def.getName(), row.getString(def.getName()));
        }
    }
    
    if(tagMap.size()>0){
        metricRow.setTagMap(tagMap);
    }
    return metricRow;
}
 
Example 6
Source File: BaseCassandraViewQuery.java    From eventapis with Apache License 2.0 6 votes vote down vote up
@Override
public List<E> queryByOpId(String opId, Function<String, E> findOne) throws EventStoreException {
    Select select = QueryBuilder.select(CassandraEventRecorder.ENTITY_ID, CassandraEventRecorder.VERSION).from(tableNameByOps);
    select.where(QueryBuilder.eq(CassandraEventRecorder.OP_ID, opId));
    List<Row> entityEventDatas = cassandraSession.execute(select, PagingIterable::all);
    Map<String, E> resultList = new HashMap<>();
    for (Row entityEvent : entityEventDatas) {
        String entityId = entityEvent.getString(CassandraEventRecorder.ENTITY_ID);
        int version = entityEvent.getInt(CassandraEventRecorder.VERSION);
        E snapshot = findOne.apply(entityId);
        E newEntity = null;
        if (snapshot == null || snapshot.getVersion() > version) {
            newEntity = queryEntity(entityId);
        } else if (snapshot.getVersion() < version) {
            newEntity = queryEntity(entityId, version, snapshot);
        } else {
            log.debug("Up-to-date Snapshot:" + snapshot);
        }
        if (!resultList.containsKey(entityId)) {
            if (newEntity != null)
                resultList.put(entityId, newEntity);
        }

    }
    return new ArrayList<>(resultList.values());
}
 
Example 7
Source File: CassandraImportJobDAO.java    From modernmt with Apache License 2.0 6 votes vote down vote up
/**
 * This method reads a row returned by a query
 * to the importjobs table in the Cassandra DB
 * and creates a new ImportJob object from its fields
 *
 * @param row a row retrieved from the importjobs table
 * @return the new ImportJob object obtained by the row
 */
private static ImportJob read(Row row) {
    long id = row.getLong("id");
    long memory = row.getLong("memory");
    int size = row.getInt("size");
    long begin = row.getLong("begin");
    long end = row.getLong("end");
    short dataChannel = row.getShort("data_channel");

    ImportJob job = new ImportJob();
    job.setId(id);
    job.setMemory(memory);
    job.setSize(size);
    job.setBegin(begin);
    job.setEnd(end);
    job.setDataChannel(dataChannel);

    return job;
}
 
Example 8
Source File: CassandraStorage.java    From cassandra-reaper with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<RepairSegment> getSegmentsWithState(UUID runId, State segmentState) {
  Collection<RepairSegment> segments = Lists.newArrayList();

  Statement statement = null != getRepairSegmentsByRunIdAndStatePrepStmt
      ? getRepairSegmentsByRunIdAndStatePrepStmt.bind(runId, segmentState.ordinal())
      // legacy mode for Cassandra-2 backends
      : getRepairSegmentsByRunIdPrepStmt.bind(runId);

  if (State.STARTED == segmentState) {
    statement = statement.setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM);
  }
  for (Row segmentRow : session.execute(statement)) {
    if (segmentRow.getInt("segment_state") == segmentState.ordinal()) {
      segments.add(createRepairSegmentFromRow(segmentRow));
    }
  }
  return segments;
}
 
Example 9
Source File: CassandraAsyncIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public void transactionMarker() throws Exception {
    ResultSet results =
            session.executeAsync("SELECT * FROM test.users where id = 12345").get();
    for (Row row : results) {
        row.getInt("id");
    }
}
 
Example 10
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");
    for (Row row : results) {
        row.getInt("id");
    }
}
 
Example 11
Source File: CassandraAsyncIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public void transactionMarker() throws Exception {
    ResultSetFuture future = session.executeAsync("SELECT * FROM test.users");
    ResultSet results = future.get();
    for (Row row : results) {
        row.getInt("id");
    }
}
 
Example 12
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 13
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");
    for (Row row : results) {
        row.getInt("id");
    }
}
 
Example 14
Source File: HadoopFormatIOCassandraTest.java    From beam with Apache License 2.0 4 votes vote down vote up
@Override
public String apply(Row input) {
  return input.getInt("id") + "|" + input.getString("scientist");
}
 
Example 15
Source File: CassandraStorage.java    From copper-engine with Apache License 2.0 4 votes vote down vote up
private void resume(final String wfId, final HybridDBStorageAccessor internalStorageAccessor) throws Exception {
    logger.trace("resume(wfId={})", wfId);

    final ResultSet rs = session.execute(preparedStatements.get(CQL_SEL_WORKFLOW_INSTANCE).bind(wfId));
    final Row row = rs.one();
    if (row == null) {
        logger.warn("No workflow instance {} found - deleting row in COP_WFI_ID", wfId);
        session.executeAsync(preparedStatements.get(CQL_DEL_WFI_ID).bind(wfId));
        return;
    }

    final String ppoolId = row.getString("PPOOL_ID");
    final int prio = row.getInt("PRIO");
    final WaitMode waitMode = toWaitMode(row.getString("WAIT_MODE"));
    final Map<String, String> responseMap = toResponseMap(row.getString("RESPONSE_MAP_JSON"));
    final ProcessingState state = ProcessingState.valueOf(row.getString("STATE"));
    final Date timeout = row.getTimestamp("TIMEOUT");
    final boolean timeoutOccured = timeout != null && timeout.getTime() <= System.currentTimeMillis();

    if (state == ProcessingState.ERROR || state == ProcessingState.INVALID) {
        return;
    }

    if (state == ProcessingState.ENQUEUED) {
        internalStorageAccessor.enqueue(wfId, ppoolId, prio);
        return;
    }

    if (responseMap != null) {
        final List<String> missingResponseCorrelationIds = new ArrayList<String>();
        int numberOfAvailableResponses = 0;
        for (Entry<String, String> e : responseMap.entrySet()) {
            final String correlationId = e.getKey();
            final String response = e.getValue();
            internalStorageAccessor.registerCorrelationId(correlationId, wfId);
            if (response != null) {
                numberOfAvailableResponses++;
            }
            else {
                missingResponseCorrelationIds.add(correlationId);
            }
        }
        boolean modified = false;
        if (!missingResponseCorrelationIds.isEmpty()) {
            // check for early responses
            for (String cid : missingResponseCorrelationIds) {
                String earlyResponse = readEarlyResponse(cid);
                if (earlyResponse != null) {
                    responseMap.put(cid, earlyResponse);
                    numberOfAvailableResponses++;
                    modified = true;
                }
            }
        }
        if (modified || timeoutOccured) {
            final ProcessingState newState = (timeoutOccured || numberOfAvailableResponses == responseMap.size() || (numberOfAvailableResponses == 1 && waitMode == WaitMode.FIRST)) ? ProcessingState.ENQUEUED : ProcessingState.WAITING;
            final String responseMapJson = jsonMapper.toJSON(responseMap);
            session.execute(preparedStatements.get(CQL_UPD_WORKFLOW_INSTANCE_STATE_AND_RESPONSE_MAP).bind(newState.name(), responseMapJson, wfId));
            if (newState == ProcessingState.ENQUEUED) {
                internalStorageAccessor.enqueue(wfId, ppoolId, prio);
            }
        }

    }
}
 
Example 16
Source File: CqlDeltaIterator.java    From emodb with Apache License 2.0 4 votes vote down vote up
@Override
protected int getBlock(Row row) {
    return row.getInt(_blockIndex);
}
 
Example 17
Source File: WordCountAndSourceMapper.java    From storm-cassandra-cql with Apache License 2.0 4 votes vote down vote up
@Override
public Number getValue(Row row) {
    return (Number) row.getInt(VALUE_NAME);
}
 
Example 18
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 19
Source File: CassandraOAuthDAO.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
private Pair<UUID, Integer> getPersonWith(String appId, String token, Type type) {
   Row r = session.execute(bindTokenCommon(personWith, appId, token, type)).one();
   return r == null ? null : new ImmutablePair<>(r.getUUID(OAuthCols.person.name()), r.getInt(TTL_COLUMN_NAME));
}
 
Example 20
Source File: CassandraHistoryLogDao.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
private HistoryLogEntry translate(HistoryLogEntryType type, Row row) {
   HistoryLogEntry event = new HistoryLogEntry();
   event.setType(type);
   switch(type) {
   case CRITICAL_PLACE_LOG:
   case DETAILED_PLACE_LOG:
      event.setId(row.getUUID(Columns.PLACE_ID));
      break;
   case DETAILED_PERSON_LOG:
      event.setId(row.getUUID(Columns.PERSON_ID));
      break;
   case DETAILED_DEVICE_LOG:
      event.setId(row.getUUID(Columns.DEVICE_ID));
      break;
   case DETAILED_HUB_LOG:
       event.setId(row.getString(Columns.HUB_ID));
       break;
   case DETAILED_RULE_LOG:
      ChildId id = new ChildId(
            row.getUUID(Columns.PLACE_ID),
            row.getInt(Columns.RULE_ID)
      );
      event.setId(id);
      break;
   case DETAILED_SUBSYSTEM_LOG:
      SubsystemId subsystemId = new SubsystemId(
            row.getUUID(Columns.PLACE_ID),
            row.getString(Columns.SUBSYSTEM)
      );
      event.setId(subsystemId);
      break;
   case DETAILED_ALARM_LOG:
   	event.setId(row.getUUID(Columns.INCIDENT_ID));
   	break;
   default:
      throw new IllegalArgumentException("Unsupported log type:" + event.getType());
   }
   event.setTimestamp(row.getUUID(Columns.TIMESTAMP));
   event.setMessageKey(row.getString(Columns.MESSAGE_KEY));
   event.setValues(row.getList(Columns.PARAMS, String.class));
   event.setSubjectAddress(row.getString(Columns.SUBJECT_ADDRESS));
   return event;
}