com.datastax.driver.core.Row Java Examples

The following examples show how to use com.datastax.driver.core.Row. 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: SetAccountOwner.java    From arcusplatform with 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 #2
Source File: CassandraStorage.java    From cassandra-reaper with 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 #3
Source File: AggregateDaoImpl.java    From glowroot with 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 #4
Source File: InsertStatementHandlerTest.java    From scalardb with 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 #5
Source File: SyntheticResultDaoImpl.java    From glowroot with 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 #6
Source File: HubDAOImpl.java    From arcusplatform with 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 #7
Source File: SchemaUpgrade.java    From glowroot with 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 #8
Source File: CassandraFactory.java    From database-transform-tool with 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 #9
Source File: CassandraQueryTestUtil.java    From localization_nifi with 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 #10
Source File: CassandraTables.java    From hugegraph with 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 #11
Source File: CqlMetaDaoImplNew.java    From staash with 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 #12
Source File: Cassandra2xDefaultMapDAO.java    From cumulusrdf with 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 #13
Source File: CQL2CSV.java    From cqlkit with 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 File: HubDAOImpl.java    From arcusplatform with 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 #15
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 #16
Source File: SetPersonHasLoginFlag.java    From arcusplatform with 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 #17
Source File: CassandraKeyUtils.java    From DataflowTemplates with 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 #18
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 #19
Source File: SchemaUpgrade.java    From glowroot with 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 #20
Source File: BaseCassandraViewQuery.java    From eventapis with 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 #21
Source File: CaseController.java    From skywalking with Apache License 2.0 5 votes vote down vote up
private void executeAsync(Session session) {
    logger.info("execute in async");

    ResultSetFuture createKeyspaceDataResultSetFuture = session.executeAsync(CREATE_KEYSPACE_SQL);
    ResultSet createKeyspaceDataResultSet = createKeyspaceDataResultSetFuture.getUninterruptibly();
    logger.info("CREATE KEYSPACE result: " + createKeyspaceDataResultSet.toString());

    ResultSetFuture createTableDataResultSetFuture = session.executeAsync(CREATE_TABLE_SQL);
    ResultSet createTableDataResultSet = createTableDataResultSetFuture.getUninterruptibly();
    logger.info("CREATE TABLE result: " + createTableDataResultSet.toString());

    PreparedStatement insertDataPreparedStatement = session.prepare(INSERT_DATA_SQL);
    ResultSetFuture insertDataResultSetFuture = session.executeAsync(insertDataPreparedStatement.bind("101", "foobar"));
    ResultSet insertDataResultSet = insertDataResultSetFuture.getUninterruptibly();
    logger.info("INSERT result: " + insertDataResultSet.toString());

    PreparedStatement selectDataPreparedStatement = session.prepare(SELECT_DATA_SQL);
    ResultSetFuture resultSetFuture = session.executeAsync(selectDataPreparedStatement.bind("101"));
    ResultSet resultSet = resultSetFuture.getUninterruptibly();
    Row row = resultSet.one();
    logger.info("SELECT result: id: {}, value: {}", row.getString("id"), row.getString("value"));

    PreparedStatement deleteDataPreparedStatement = session.prepare(DELETE_DATA_SQL);
    ResultSetFuture deleteDataResultSetFuture = session.executeAsync(deleteDataPreparedStatement.bind("101"));
    ResultSet deleteDataResultSet = deleteDataResultSetFuture.getUninterruptibly();
    logger.info("DELETE result: " + deleteDataResultSet.toString());

    ResultSetFuture dropTableDataResultSetFuture = session.executeAsync(DROP_TABLE_SQL);
    ResultSet dropTableDataResultSet = dropTableDataResultSetFuture.getUninterruptibly();
    logger.info("DROP TABLE result: " + dropTableDataResultSet.toString());

    ResultSetFuture dropKeyspaceDataResultSetFuture = session.executeAsync(DROP_KEYSPACE);
    ResultSet dropKeyspaceDataResultSet = dropKeyspaceDataResultSetFuture.getUninterruptibly();
    logger.info("DROP KEYSPACE result: " + dropKeyspaceDataResultSet.toString());
}
 
Example #22
Source File: SchemaUpgrade.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private void rewriteResolvedIncidentTablePart1() throws Exception {
    if (!tableExists("resolved_incident")) {
        // must be upgrading all the way from a glowroot version prior to resolved_incident
        return;
    }
    dropTableIfExists("resolved_incident_temp");
    session.updateSchemaWithRetry("create table if not exists resolved_incident_temp (one int,"
            + " resolve_time timestamp, agent_rollup_id varchar, condition blob, severity"
            + " varchar, notification blob, open_time timestamp, primary key (one,"
            + " resolve_time, agent_rollup_id, condition)) with clustering order by"
            + " (resolve_time desc)");
    PreparedStatement insertTempPS = session.prepare("insert into resolved_incident_temp"
            + " (one, resolve_time, agent_rollup_id, condition, severity, notification,"
            + " open_time) values (1, ?, ?, ?, ?, ?, ?)");
    ResultSet results = session.read("select resolve_time, agent_rollup_id, condition,"
            + " severity, notification, open_time from resolved_incident where one = 1");
    for (Row row : results) {
        BoundStatement boundStatement = insertTempPS.bind();
        boundStatement.setTimestamp(0, row.getTimestamp(0));
        boundStatement.setString(1, row.getString(1));
        boundStatement.setBytes(2, row.getBytes(2));
        boundStatement.setString(3, row.getString(3));
        boundStatement.setBytes(4, row.getBytes(4));
        boundStatement.setTimestamp(5, row.getTimestamp(5));
        session.write(boundStatement);
    }
}
 
Example #23
Source File: PojoField.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Sets object field value from a {@link com.datastax.driver.core.Row} returned by Cassandra CQL statement.
 *
 * @param row {@link com.datastax.driver.core.Row}
 * @param obj object which field should be populated from {@link com.datastax.driver.core.Row}
 * @param serializer {@link org.apache.ignite.cache.store.cassandra.serializer.Serializer} to use.
 */
public void setValueFromRow(Row row, Object obj, Serializer serializer) {
    if (calculatedField())
        return;

    Object val = PropertyMappingHelper.getCassandraColumnValue(row, col, accessor.getFieldType(), serializer);

    accessor.setValue(obj, val);
}
 
Example #24
Source File: DatabaseTest.java    From cassandra-migration with MIT License 5 votes vote down vote up
private List<Row> loadMigrations(String tablePrefix) {
    Session session = cassandra.getCluster().connect(CassandraJUnitRule.TEST_KEYSPACE);
    if (tablePrefix == null || tablePrefix.isEmpty()) {
        return session.execute(
                new SimpleStatement("SELECT * FROM schema_migration;")).all();
    }
    return session.execute(
            new SimpleStatement(String.format("SELECT * FROM %s_schema_migration;", tablePrefix))).all();
}
 
Example #25
Source File: Functions.java    From hawkular-metrics with Apache License 2.0 5 votes vote down vote up
public static Tenant getTenant(Row row) {
    String tenantId = row.getString(0);
    Map<MetricType<?>, Integer> retentions = row.getMap(1, String.class, Integer.class).entrySet().stream()
            .collect(toMap(entry -> MetricType.fromTextCode(entry.getKey()), Map.Entry::getValue));

    return new Tenant(tenantId, retentions);
}
 
Example #26
Source File: AbstractUpsertOutputOperatorCompositePKTest.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
@Test
public void testForCompositeRowKeyBasedTable() throws Exception
{
  CompositePrimaryKeyRow aCompositeRowKey = new CompositePrimaryKeyRow();
  String userId = new String("user1" + System.currentTimeMillis());
  String employeeId = new String(userId + System.currentTimeMillis());
  int day = 1;
  int month = 12;
  int year = 2017;
  aCompositeRowKey.setDay(day);
  aCompositeRowKey.setMonth(month);
  aCompositeRowKey.setYear(year);
  aCompositeRowKey.setCurrentstatus("status" + System.currentTimeMillis());
  aCompositeRowKey.setUserid(userId);
  aCompositeRowKey.setEmployeeid(employeeId);
  UpsertExecutionContext<CompositePrimaryKeyRow> anUpdate = new UpsertExecutionContext<>();
  anUpdate.setPayload(aCompositeRowKey);
  compositePrimaryKeysOperator.beginWindow(12);
  compositePrimaryKeysOperator.input.process(anUpdate);
  compositePrimaryKeysOperator.endWindow();

  ResultSet results = compositePrimaryKeysOperator.session.execute(
      "SELECT * FROM unittests.userstatus WHERE userid = '" + userId + "' and day=" + day + " and month=" +
      month + " and year=" + year + " and employeeid='" + employeeId + "'");
  List<Row> rows = results.all();
  assertEquals(rows.size(), 1);
}
 
Example #27
Source File: SchemaUpgrade.java    From glowroot with 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 #28
Source File: CassandraMessageIdDAO.java    From james-project with Apache License 2.0 5 votes vote down vote up
private Flux<Row> selectFrom(CassandraId mailboxId, MessageUid uid, Limit limit) {
    return cassandraAsyncExecutor.executeRows(limit.getLimit()
        .map(limitAsInt -> selectUidGteLimited.bind()
            .setUUID(MAILBOX_ID, mailboxId.asUuid())
            .setLong(IMAP_UID, uid.asLong())
            .setInt(LIMIT, limitAsInt))
        .orElse(selectUidGte.bind()
            .setUUID(MAILBOX_ID, mailboxId.asUuid())
            .setLong(IMAP_UID, uid.asLong())));
}
 
Example #29
Source File: LowercaseLoginIndex.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 insert = session.prepare(INSERT_LOGIN);
   PreparedStatement delete = session.prepare(DELETE_LOGIN);
   
   ResultSet rs = context.getSession().execute(SELECT);
   for(Row row: rs) {
      String domain = row.getString("domain");
      String user_0_3 = row.getString("user_0_3");
      String user = row.getString("user");
      if(
            !domain.equals(domain.toLowerCase()) ||
            !user_0_3.equals(user_0_3.toLowerCase()) ||
            !user.equals(user.toLowerCase())
      ) {
         // TODO async this?
         logger.debug("Converting [{}] to lower case", user);
         BoundStatement bs = insert.bind(
               domain.toLowerCase(), 
               user_0_3.toLowerCase(), 
               user.toLowerCase(),
               row.getString("password"),
               row.getString("password_salt"),
               row.getUUID("personid")
         );
         if(session.execute(bs).wasApplied()) {
            session.execute( delete.bind(domain, user_0_3, user) );
         }
         else {
            logger.warn("Unable to convert [{}] to lower case", user);
         }
      }
   }
}
 
Example #30
Source File: CassandraTables.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
private static Statement setTtl(BuiltStatement statement,
                                CassandraBackendEntry.Row entry) {
    long ttl = entry.ttl();
    if (ttl != 0L) {
        int calcTtl = (int) Math.ceil(ttl / 1000D);
        Using usingTtl = QueryBuilder.ttl(calcTtl);
        if (statement instanceof Insert) {
            ((Insert) statement).using(usingTtl);
        } else {
            assert statement instanceof Update;
            ((Update) statement).using(usingTtl);
        }
    }
    return statement;
}