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

The following examples show how to use com.datastax.driver.core.Row. 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: 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 2
Source Project: glowroot   Source File: SyntheticResultDaoImpl.java    License: Apache License 2.0 6 votes vote down vote up
private ListenableFuture<?> rollupOne(int rollupLevel, String agentRollupId,
        String syntheticMonitorId, long from, long to, int adjustedTTL) throws Exception {
    BoundStatement boundStatement = readResultForRollupPS.get(rollupLevel - 1).bind();
    int i = 0;
    boundStatement.setString(i++, agentRollupId);
    boundStatement.setString(i++, syntheticMonitorId);
    boundStatement.setTimestamp(i++, new Date(from));
    boundStatement.setTimestamp(i++, new Date(to));
    ListenableFuture<ResultSet> future = session.readAsyncWarnIfNoRows(boundStatement,
            "no synthetic result table records found for agentRollupId={},"
                    + " syntheticMonitorId={}, from={}, to={}, level={}",
            agentRollupId, syntheticMonitorId, from, to, rollupLevel);
    return MoreFutures.rollupAsync(future, asyncExecutor, new DoRollup() {
        @Override
        public ListenableFuture<?> execute(Iterable<Row> rows) throws Exception {
            return rollupOneFromRows(rollupLevel, agentRollupId, syntheticMonitorId, to,
                    adjustedTTL, rows);
        }
    });
}
 
Example 3
Source Project: localization_nifi   Source File: CassandraQueryTestUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static Row createRow(String user_id, String first_name, String last_name, Set<String> emails,
                            List<String> top_places, Map<Date, String> todo, boolean registered,
                            float scale, double metric) {
    Row row = mock(Row.class);
    when(row.getString(0)).thenReturn(user_id);
    when(row.getString(1)).thenReturn(first_name);
    when(row.getString(2)).thenReturn(last_name);
    when(row.getSet(eq(3), any(TypeToken.class))).thenReturn(emails);
    when(row.getList(eq(4), any(TypeToken.class))).thenReturn(top_places);
    when(row.getMap(eq(5), any(TypeToken.class), any(TypeToken.class))).thenReturn(todo);
    when(row.getBool(6)).thenReturn(registered);
    when(row.getFloat(7)).thenReturn(scale);
    when(row.getDouble(8)).thenReturn(metric);

    return row;
}
 
Example 4
Source Project: cassandra-reaper   Source File: CassandraStorage.java    License: 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 5
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 6
Source Project: eventapis   Source File: BaseCassandraViewQuery.java    License: Apache License 2.0 6 votes vote down vote up
private E queryEntityInternal(String entityId, Select select, E previousEntity) throws EventStoreException {

        E currentEntity = previousEntity;
        List<Row> entityEventDatas = cassandraSession.execute(select, PagingIterable::all);
        for (Row entityEventData : entityEventDatas) {
            EntityEvent entityEvent = convertToEntityEvent(entityEventData);
            if (entityEvent.getStatus() == EventState.CREATED) {
                EntityFunctionSpec<E, ?> functionSpec = functionMap.get(entityEvent.getEventType());
                if (functionSpec != null) {
                    EntityEventWrapper eventWrapper = new EntityEventWrapper<>(functionSpec.getQueryType(), objectMapper, entityEvent);
                    EntityFunction<E, ?> entityFunction = functionSpec.getEntityFunction();
                    currentEntity = (E) entityFunction.apply(currentEntity, eventWrapper);
                } else
                    log.trace("Function Spec is not available for " + entityEvent.getEventType() + " EntityId:" + entityId + " Table:" + tableName);
            }
            if (currentEntity != null) {
                currentEntity.setId(entityId);
                currentEntity.setVersion(entityEvent.getEventKey().getVersion());
            }
        }
        return (currentEntity == null || currentEntity.getId() == null) ? null : currentEntity;
    }
 
Example 7
Source Project: arcusplatform   Source File: SetAccountOwner.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 * FROM authorization_grant").all();
   BatchStatement batch = new BatchStatement();
   rows.forEach((r) -> {
      if(r.getBool("accountowner")) {
         batch.add(new BoundStatement(stmt)
            .setUUID("owner", r.getUUID("entityId"))
            .setUUID("id", r.getUUID("accountid")));
      }
   });

   context.getSession().execute(batch);
}
 
Example 8
Source Project: DataflowTemplates   Source File: CassandraKeyUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This method returns a sorted map containing the columns that make up the (compound) primary key
 * in cassandra.
 *
 * <p>Each key in return value contains a name of a column in the cassandra key. The value for
 * each corresponding key in the map denotes the order in the Cassandra key.
 *
 * <p>Example, given the table:
 *
 * <p>create table mytable ( key_part_one int, key_part_two int, data boolean, PRIMARY
 * KEY(key_part_one, key_part_two) );
 *
 * <p>The method would return the following map:
 *
 * <p>"key_part_one", 0 "key_part_two", 1
 *
 * @param session the session to the Cassandra cluster.
 * @param keyspace they keyspace to query
 * @param table the table to query
 * @return see method description.
 */
static Map<String, Integer> primaryKeyOrder(Session session, String keyspace, String table) {
  HashMap<String, Integer> returnValue = new HashMap<>();
  Statement select = primarykeyCQL(keyspace, table);
  ResultSet rs = session.execute(select.toString());

  TreeMap<String, String> sortedMap = new TreeMap<>();
  for (Row row : rs) {
    String columnName = row.get(COLUMN_NAME_COLUMN, String.class);
    String kind = row.get(KIND_COLUMN, String.class);
    String position = row.get(POSITION_COLUMN, Integer.class).toString();
    if (kind.equals("clustering")) {
      sortedMap.put("clustering_" + position, columnName);
    } else {
      sortedMap.put(position, columnName);
    }
  }

  List<String> sortedKeyset = new ArrayList<>(sortedMap.keySet());
  for (int i = 0; i < sortedKeyset.size(); i++) {
    returnValue.put(sortedMap.get(sortedKeyset.get(i)), i);
  }

  return returnValue;
}
 
Example 9
Source Project: arcusplatform   Source File: SetPersonHasLoginFlag.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, email FROM person").all();

   BatchStatement batch = new BatchStatement();

   rows.forEach((r) -> {
      batch.add(new BoundStatement(stmt)
         .setBool("hasLogin", !StringUtils.isBlank(r.getString("email")))
         .setUUID("id", r.getUUID("id")));
   });

   context.getSession().execute(batch);
}
 
Example 10
Source Project: arcusplatform   Source File: HubDAOImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void populateEntity(Row row, Hub entity) {
   entity.setState(row.getString(HubEntityColumns.STATE));
   entity.setAccount(row.getUUID(HubEntityColumns.ACCOUNT_ID));
   entity.setPlace(row.getUUID(HubEntityColumns.PLACE_ID));
   entity.setCaps(row.getSet(HubEntityColumns.CAPS, String.class));
   entity.setName(row.getString(HubEntityColumns.NAME));
   entity.setVendor(row.getString(HubEntityColumns.VENDOR));
   entity.setModel(row.getString(HubEntityColumns.MODEL));
   entity.setSerialNum(row.getString(HubEntityColumns.SERIAL_NUM));
   entity.setHardwarever(row.getString(HubEntityColumns.HARDWARE_VER));
   entity.setMac(row.getString(HubEntityColumns.MAC_ADDRESS));
   entity.setMfgInfo(row.getString(HubEntityColumns.MFG_INFO));
   entity.setFirmwareGroup(row.getString(HubEntityColumns.FIRMWARE_GROUP));
   entity.setOsver(row.getString(HubEntityColumns.OS_VER));
   entity.setAgentver(row.getString(HubEntityColumns.AGENT_VER));
   entity.setBootloaderVer(row.getString(HubEntityColumns.BOOTLOADER_VER));
   entity.setRegistrationState(row.getString(HubEntityColumns.REGISTRATIONSTATE));
   entity.setLastDeviceAddRemove(row.getUUID(HubEntityColumns.LAST_DEVICE_ADD_REMOVE));
   entity.setLastReset(row.getUUID(HubEntityColumns.LAST_RESET));
   entity.setDisallowCell(row.getBool(HubEntityColumns.DISALLOW_CELL));
   entity.setDisallowCellReason(row.getString(HubEntityColumns.DISALLOW_CELL_REASON));

}
 
Example 11
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 12
Source Project: staash   Source File: CqlMetaDaoImplNew.java    License: Apache License 2.0 6 votes vote down vote up
public Map<String, JsonObject> runQuery(String key, String col) {
    // TODO Auto-generated method stub
    ResultSet rs;
    if (col!=null && !col.equals("*")) {
        rs = session
            .execute("select column1, value from "+MetaConstants.META_KEY_SPACE+"."+MetaConstants.META_COLUMN_FAMILY+ " where key='"+key+"' and column1='"+col+"';");
    }
    else {
        rs = session
                .execute("select column1, value from "+MetaConstants.META_KEY_SPACE+"."+MetaConstants.META_COLUMN_FAMILY+ " where key='"+key+"';");
    }
    List<Row> rows = rs.all();
    Map<String,JsonObject> storageMap = new HashMap<String,JsonObject>();
    for (Row row : rows) {
        String field = row.getString(0);
        JsonObject val = new JsonObject(row.getString(1));
        storageMap.put(field, val);
    }
    return storageMap;
}
 
Example 13
Source Project: cqlkit   Source File: CQL2CSV.java    License: Apache License 2.0 6 votes vote down vote up
@Override
    protected String map(Row row) {
        StringBuffer stringBuffer = new StringBuffer();
        try {
            CSVPrinter csvPrinter = new CSVPrinter(stringBuffer, csvFormat);

            if (lineNumberEnabled) {
                csvPrinter.print(lineNumber.getAndIncrement());
            }

            for (int i = 0; i < definitions.length; i++) {
                String value = RowUtils.toString(definitions[i].getType(), row.getObject(i));
                csvPrinter.print(value);
            }

//            if (isRangeQuery) {
//                Token t = row.getPartitionKeyToken();
//                String token = String.format("%.2f%%", (((Long) t.getValue() >> 48) + 32768) / 65535f * 100);
//                csvPrinter.print(token);
//            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return stringBuffer.toString();
    }
 
Example 14
Source Project: hugegraph   Source File: CassandraTables.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void delete(CassandraSessionPool.Session session,
                   CassandraBackendEntry.Row entry) {
    /*
     * TODO: Delete edge by label
     * Need to implement the framework that can delete with query
     * which contains id or condition.
     */

    // Let super class do delete if not deleting edge by label
    List<Object> idParts = this.idColumnValue(entry.id());
    if (idParts.size() > 1 || entry.columns().size() > 0) {
        super.delete(session, entry);
        return;
    }

    // The only element is label
    this.deleteEdgesByLabel(session, entry.id());
}
 
Example 15
Source Project: arcusplatform   Source File: HubDAOImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Set<String> findHubIdsByAccount(UUID accountId) {
   Set<String> hubIds = new HashSet<String>();
   if (accountId != null) {
      BoundStatement boundStatement = new BoundStatement(findIdsByAccount);
      ResultSet resultSet;
      try(Context ctxt = findHubIdsByAccountTimer.time()) {
     	 resultSet = session.execute(boundStatement.bind(accountId));
      }

      List<Row> rows = resultSet.all();
      for (Row row : rows) {
         hubIds.add(row.getString("hubid"));
      }
   }
   return hubIds;
}
 
Example 16
Source Project: scalardb   Source File: InsertStatementHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void handle_PutWithoutConditionButNoMutationApplied_ShouldThrowProperExecutionException()
    throws ExecutionException {
  // Arrange
  put = preparePutWithClusteringKey();
  put.withCondition(new PutIfNotExists());
  spy = prepareSpiedInsertStatementHandler();

  ResultSet results = mock(ResultSet.class);
  Row row = mock(Row.class);
  when(results.one()).thenReturn(row);
  when(row.getBool(0)).thenReturn(false);
  doReturn(results).when(spy).execute(bound, put);

  // Act Assert
  assertThatThrownBy(
          () -> {
            spy.handle(put);
          })
      .isInstanceOf(NoMutationException.class);
}
 
Example 17
Source Project: glowroot   Source File: AggregateDaoImpl.java    License: Apache License 2.0 6 votes vote down vote up
private ListenableFuture<?> rollupTransactionSummaryFromChildren(RollupParams rollup,
        AggregateQuery query, Collection<String> childAgentRollupIds,
        Multimap<String, String> transactionNames) throws Exception {
    Map<String, ListenableFuture<ResultSet>> futures =
            getRowsForSummaryRollupFromChildren(query, childAgentRollupIds, summaryTable, true);
    Map<String, MutableSummary> summaries = new HashMap<>();
    for (Map.Entry<String, ListenableFuture<ResultSet>> entry : futures.entrySet()) {
        String childAgentRollupId = entry.getKey();
        ResultSet results = entry.getValue().get();
        for (Row row : results) {
            String transactionName = mergeRowIntoSummaries(row, summaries);
            transactionNames.put(transactionName, childAgentRollupId);
        }
    }
    return insertTransactionSummaries(rollup, query, summaries);
}
 
Example 18
Source Project: cassandra-reaper   Source File: CassandraStorage.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Cluster deleteCluster(String clusterName) {
  getRepairSchedulesForCluster(clusterName).forEach(schedule -> deleteRepairSchedule(schedule.getId()));
  session.executeAsync(deleteRepairRunByClusterPrepStmt.bind(clusterName));

  getEventSubscriptions(clusterName)
      .stream()
      .filter(subscription -> subscription.getId().isPresent())
      .forEach(subscription -> deleteEventSubscription(subscription.getId().get()));

  Statement stmt = new SimpleStatement(SELECT_REPAIR_UNIT);
  stmt.setIdempotent(true);
  ResultSet results = session.execute(stmt);
  for (Row row : results) {
    if (row.getString("cluster_name").equals(clusterName)) {
      UUID id = row.getUUID("id");
      session.executeAsync(deleteRepairUnitPrepStmt.bind(id));
    }
  }
  Cluster cluster = getCluster(clusterName);
  session.execute(deleteClusterPrepStmt.bind(clusterName));
  return cluster;
}
 
Example 19
Source Project: database-transform-tool   Source File: CassandraFactory.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 描述: 查询数据库表名[未实现]
 * 时间: 2017年11月15日 上午11:29:59
 * @author yi.zhang
 * @return 返回表
 */
@Deprecated
public List<String> queryTables(){
	try {
		List<String> tables = new ArrayList<String>();
		String useQuery = "describe tables";
		ResultSet rs = session.execute(useQuery);
		for (Row row : rs.all()) {
			String table = row.getString(1);
			tables.add(table);
		}
		return tables;
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return null;
}
 
Example 20
Source Project: copper-engine   Source File: CassandraStorage.java    License: 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 21
Source Project: glowroot   Source File: SchemaUpgrade.java    License: Apache License 2.0 5 votes vote down vote up
private void rewriteOpenIncidentTablePart2() throws Exception {
    if (!tableExists("open_incident_temp")) {
        // previously failed mid-upgrade prior to updating schema version
        return;
    }
    dropTableIfExists("open_incident");
    session.createTableWithLCS("create table if not exists open_incident (one int,"
            + " agent_rollup_id varchar, condition blob, severity varchar, notification blob,"
            + " open_time timestamp, primary key (one, agent_rollup_id, condition, severity))");
    PreparedStatement insertPS = session.prepare("insert into open_incident (one,"
            + " agent_rollup_id, condition, severity, notification, open_time) values"
            + " (1, ?, ?, ?, ?, ?)");
    Map<String, V09AgentRollup> v09AgentRollups = getV09AgentRollupsFromAgentRollupTable();
    ResultSet results = session.read("select agent_rollup_id, condition, severity,"
            + " notification, open_time from open_incident_temp where one = 1");
    for (Row row : results) {
        String v09AgentRollupId = row.getString(0);
        V09AgentRollup v09AgentRollup = v09AgentRollups.get(v09AgentRollupId);
        if (v09AgentRollup == null) {
            // v09AgentRollupId was manually deleted (via the UI) from the agent_rollup
            // table in which case its parent is no longer known and best to ignore
            continue;
        }
        BoundStatement boundStatement = insertPS.bind();
        boundStatement.setString(0, v09AgentRollup.agentRollupId());
        boundStatement.setBytes(1, row.getBytes(1));
        boundStatement.setString(2, row.getString(2));
        boundStatement.setBytes(3, row.getBytes(3));
        boundStatement.setTimestamp(4, row.getTimestamp(4));
        session.write(boundStatement);
    }
    dropTableIfExists("open_incident_temp");
}
 
Example 22
Source Project: twissandra-j   Source File: CassandraTweetRepository.java    License: Apache License 2.0 5 votes vote down vote up
public List<String> getFollowers(String username) {
	ResultSet queryResult = execute("SELECT following FROM followers WHERE username = '%s'", username);
	List<String> followers = new ArrayList<String>();
	
	for (Row row : queryResult)
		followers.add(row.getString("following"));
	
	return followers;
}
 
Example 23
Source Project: arcusplatform   Source File: PlacePurgeRecordingTable.java    License: Apache License 2.0 5 votes vote down vote up
public PlacePurgeRecord buildEntity(Row row) {
	PurgeMode mode = PurgeMode.ALL;
	if(!row.isNull(COL_MODE)) {
		mode = PurgeMode.valueOf(row.getString(COL_MODE));
	}
	return new PlacePurgeRecord(row.getUUID(COL_PLACEID), row.getTimestamp(COL_DELETE_TIME), mode);
	
}
 
Example 24
Source Project: glowroot   Source File: TraceAttributeNameDao.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, List<String>> load(String agentRollupId) throws Exception {
    BoundStatement boundStatement = readPS.bind();
    boundStatement.setString(0, agentRollupId);
    ResultSet results = session.read(boundStatement);
    ListMultimap<String, String> traceAttributeNames = ArrayListMultimap.create();
    for (Row row : results) {
        int i = 0;
        String transactionType = checkNotNull(row.getString(i++));
        String traceAttributeName = checkNotNull(row.getString(i++));
        traceAttributeNames.put(transactionType, traceAttributeName);
    }
    return Multimaps.asMap(traceAttributeNames);
}
 
Example 25
Source Project: james-project   Source File: CassandraMessageDAO.java    License: Apache License 2.0 5 votes vote down vote up
private Mono<byte[]> buildContentRetriever(FetchType fetchType, Row row) {
    switch (fetchType) {
        case Full:
            return getFullContent(row);
        case Headers:
            return getHeaderContent(row);
        case Body:
            return getBodyContent(row)
                .map(data -> Bytes.concat(new byte[row.getInt(BODY_START_OCTET)], data));
        case Metadata:
            return Mono.just(EMPTY_BYTE_ARRAY);
        default:
            throw new RuntimeException("Unknown FetchType " + fetchType);
    }
}
 
Example 26
Source Project: glowroot   Source File: Tools.java    License: Apache License 2.0 5 votes vote down vote up
private Set<TtPartitionKey> getPartitionKeys(int rollupLevel, String thresholdComparator,
        Date threshold) throws Exception {
    ResultSet results = session.read("select agent_rollup, transaction_type, capture_time"
            + " from aggregate_tt_summary_rollup_" + rollupLevel);
    Multimap<String, String> transactionTypes = HashMultimap.create();
    for (Row row : results) {
        int i = 0;
        String agentRollupId = checkNotNull(row.getString(i++));
        String transactionType = checkNotNull(row.getString(i++));
        Date captureTime = checkNotNull(row.getTimestamp(i++));
        if (thresholdComparator.equals("<")) {
            if (captureTime.getTime() < threshold.getTime()) {
                transactionTypes.put(agentRollupId, transactionType);
            }
        } else if (thresholdComparator.equals(">")) {
            if (captureTime.getTime() > threshold.getTime()) {
                transactionTypes.put(agentRollupId, transactionType);
            }
        } else {
            throw new IllegalStateException(
                    "Unexpected threshold comparator: " + thresholdComparator);
        }
    }
    Set<TtPartitionKey> ttPartitionKeys = new HashSet<>();
    for (Map.Entry<String, String> entry : transactionTypes.entries()) {
        ttPartitionKeys.add(ImmutableTtPartitionKey.builder()
                .agentRollupId(entry.getKey())
                .transactionType(entry.getValue())
                .build());
    }
    return ttPartitionKeys;
}
 
Example 27
Source Project: staash   Source File: QueryUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static String formatQueryResult(CqlStatementResult rs, String cfname) {
    // TODO Auto-generated method stub
    String value = "";
    JsonObject response = new JsonObject();
    ColumnFamily<String, String> cf = ColumnFamily
            .newColumnFamily(cfname, StringSerializer.get(),
                    StringSerializer.get());
    Rows<String, String> rows = rs.getRows(cf);
    int rcount = 1;
    for (com.netflix.astyanax.model.Row<String, String> row : rows) {
        ColumnList<String> columns = row.getColumns();
        Collection<String> colnames = columns.getColumnNames();
        String rowStr = "";
        String colStr = "";
        if (colnames.contains("key") && colnames.contains("column1")) {
        	colStr = colStr + columns.getDateValue("column1", null).toGMTString();
        	rowStr = rowStr + columns.getStringValue("value", null); 
        	response.putString(colStr, rowStr);
        } else {
            JsonObject rowObj = new JsonObject();
         for (String colName:colnames) {
             //colStr = colStr+colname+",";
            value = columns.getStringValue(colName, null);
            //rowStr=rowStr+value+",";
            rowObj.putString(colName, value);
         }
         //rowobj.putString("columns", colStr);
         //rowobj.putString("values", rowStr);
         response.putObject(""+rcount++, rowObj);
        }
    }
    return response.toString();
    
}
 
Example 28
Source Project: flink   Source File: CassandraInputFormat.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public OUT nextRecord(OUT reuse) throws IOException {
	final Row item = resultSet.one();
	for (int i = 0; i < reuse.getArity(); i++) {
		reuse.setField(item.getObject(i), i);
	}
	return reuse;
}
 
Example 29
Source Project: glowroot   Source File: RoleDao.java    License: 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 30
Source Project: newts   Source File: CassandraSearcher.java    License: Apache License 2.0 5 votes vote down vote up
private Collection<String> getMetricNamesFromResults(ResultSetFuture results) throws InterruptedException, ExecutionException {
    List<String> metricNames = Lists.newArrayList();

    for (Row row : results.get()) {
        metricNames.add(row.getString(Schema.C_METRICS_NAME));
    }

    return metricNames;
}