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

The following examples show how to use com.datastax.driver.core.Row#getList() . 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: CassandraLoader.java    From swblocks-decisiontree with Apache License 2.0 6 votes vote down vote up
private Set<ValueGroupChange> getValueGroupChange(final Row row) {
    final String type = row.getString("vgchangetype");
    if (type != null && Type.valueOf(type) != Type.NONE) {
        final ValueGroup group =
                new ValueGroup(row.getUUID("vgid"), row.getString("vgname"),
                        row.getList("vgdrivers", String.class),
                        new DateRange(row.get("vgstart", Instant.class), row.get("vgend", Instant.class)));

        final String driver = row.getString("vgdrivername");
        if (driver != null && !driver.isEmpty()) {
            group.setNewRuleData(driver, row.getList("vgrulecodes", UUID.class));
        }

        return Collections.singleton(new ValueGroupChange(Type.valueOf(type), group));
    }

    return Collections.emptySet();
}
 
Example 2
Source File: ListTest.java    From jmeter-cassandra with Apache License 2.0 6 votes vote down vote up
@Test
public void testInsertPreparedthelist() {
    CassandraSampler cs = new CassandraSampler();

    cs.setProperty("sessionName",TESTSESSION);
    cs.setProperty("consistencyLevel", AbstractCassandaTestElement.ONE);
    cs.setProperty("resultVariable","rv");
    cs.setProperty("queryType", AbstractCassandaTestElement.PREPARED);
    cs.setProperty("queryArguments", "\"" + EXPECTED + "\"");
    cs.setProperty("query", "INSERT INTO " + TABLE + " (key,thelist) VALUES (2, ?)");

    TestBeanHelper.prepare(cs);

    SampleResult res = cs.sample(new Entry());
    assertTrue(res.isSuccessful(), res.getResponseMessage());

    // See if the value matches
    Row row = session.execute("select thelist from " + KEYSPACE + "." + TABLE + " where key = 2").one();
    List<String> thelist = row.getList(0, String.class);
    assertTrue(thelist.contains("one"));
    assertTrue(thelist.contains("two"));
    assertTrue(thelist.contains("three"));
    assertEquals(3, thelist.size());
}
 
Example 3
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 4
Source File: RangeUtils.java    From deep-spark with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the token ranges that will be mapped to Spark partitions.
 *
 * @param config the Deep configuration object.
 * @return the list of computed token ranges.
 */
public static List<DeepTokenRange> getSplitsBySize(
        CassandraDeepJobConfig config) {

    IPartitioner p = getPartitioner(config);
    AbstractType tokenValidator = p.getTokenValidator();

    Pair<Session, String> sessionWithHost = CassandraClientProvider
            .getSession(config.getHost(), config, false);

    String query = new StringBuilder("CALCULATE SPLITS FROM ")
            .append(config.getKeyspace()).append(".")
            .append(config.getTable()).append(" ESTIMATING ")
            .append(config.getSplitSize()).toString();
    ResultSet rSet = sessionWithHost.left.execute(query);

    List<DeepTokenRange> tokens = new ArrayList<>();

    for (Row row : rSet.all()) {
        Comparable startToken = (Comparable) tokenValidator.compose(row
                .getBytesUnsafe("start_token"));
        Comparable endToken = (Comparable) tokenValidator.compose(row
                .getBytesUnsafe("end_token"));
        List<String> replicas = new ArrayList<>();
        for (InetAddress addres : row.getList("preferred_locations",
                InetAddress.class)) {
            replicas.add(addres.getHostName());
        }
        tokens.add(new DeepTokenRange(startToken, endToken, replicas));
    }
    return tokens;
}
 
Example 5
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 6
Source File: AbstractUpsertOutputOperatorCodecsTest.java    From attic-apex-malhar with Apache License 2.0 4 votes vote down vote up
@Test
public void testForListAppend() throws Exception
{
  User aUser = new User();
  String userId = "user" + System.currentTimeMillis();
  aUser.setUserid(userId);
  FullName fullName = new FullName("first1" + System.currentTimeMillis(), "last1" + System.currentTimeMillis());
  aUser.setUsername(fullName);
  Address address = new Address("street1", "city1", 13, null);
  aUser.setCurrentaddress(address);
  Set<String> emails = new HashSet<>();
  emails.add(new String("1"));
  emails.add(new String("2"));
  aUser.setEmails(emails);
  List<Integer> topScores = new ArrayList<>();
  topScores.add(1);
  topScores.add(2);
  aUser.setTopScores(topScores);
  UpsertExecutionContext<User> originalEntry = new UpsertExecutionContext<>();
  originalEntry.setPayload(aUser);

  UpsertExecutionContext<User> subsequentUpdateForTopScores = new UpsertExecutionContext<>();
  subsequentUpdateForTopScores.setListPlacementStyle(
      UpsertExecutionContext.ListPlacementStyle.APPEND_TO_EXISTING_LIST);
  subsequentUpdateForTopScores.setCollectionMutationStyle(
      UpsertExecutionContext.CollectionMutationStyle.ADD_TO_EXISTING_COLLECTION);
  subsequentUpdateForTopScores.setNullHandlingMutationStyle(
      UpsertExecutionContext.NullHandlingMutationStyle.IGNORE_NULL_COLUMNS);
  User oldUser = new User();
  oldUser.setUserid(userId);
  List<Integer> topScoresAppended = new ArrayList<>();
  topScoresAppended.add(3);
  oldUser.setTopScores(topScoresAppended);
  subsequentUpdateForTopScores.setPayload(oldUser);
  userUpsertOperator.beginWindow(1);
  userUpsertOperator.input.process(originalEntry);
  userUpsertOperator.input.process(subsequentUpdateForTopScores);
  userUpsertOperator.endWindow();

  ResultSet results = userUpsertOperator.session.execute(
      "SELECT * FROM unittests.users WHERE userid = '" + userId + "'");
  List<Row> rows = results.all();
  Row userRow = rows.get(0);
  List<Integer> topScoresEntry = userRow.getList("top_scores", Integer.class);
  assertEquals(3, topScoresEntry.size());
  assertEquals("" + 3, "" + topScoresEntry.get(2));
}
 
Example 7
Source File: AbstractUpsertOutputOperatorCodecsTest.java    From attic-apex-malhar with Apache License 2.0 4 votes vote down vote up
@Test
public void testForListPrepend() throws Exception
{
  User aUser = new User();
  String userId = "user" + System.currentTimeMillis();
  aUser.setUserid(userId);
  FullName fullName = new FullName("first1" + System.currentTimeMillis(), "last1" + System.currentTimeMillis());
  aUser.setUsername(fullName);
  List<Integer> topScores = new ArrayList<>();
  topScores.add(1);
  topScores.add(2);
  aUser.setTopScores(topScores);
  UpsertExecutionContext<User> originalEntry = new UpsertExecutionContext<>();
  originalEntry.setPayload(aUser);

  UpsertExecutionContext<User> subsequentUpdateForTopScores = new UpsertExecutionContext<>();
  subsequentUpdateForTopScores.setListPlacementStyle(
      UpsertExecutionContext.ListPlacementStyle.PREPEND_TO_EXISTING_LIST);
  subsequentUpdateForTopScores.setCollectionMutationStyle(
      UpsertExecutionContext.CollectionMutationStyle.ADD_TO_EXISTING_COLLECTION);
  subsequentUpdateForTopScores.setNullHandlingMutationStyle(
      UpsertExecutionContext.NullHandlingMutationStyle.IGNORE_NULL_COLUMNS);
  User oldUser = new User();
  oldUser.setUserid(userId);
  List<Integer> topScoresAppended = new ArrayList<>();
  topScoresAppended.add(3);
  oldUser.setTopScores(topScoresAppended);
  subsequentUpdateForTopScores.setPayload(oldUser);
  userUpsertOperator.beginWindow(2);
  userUpsertOperator.input.process(originalEntry);
  userUpsertOperator.input.process(subsequentUpdateForTopScores);
  userUpsertOperator.endWindow();

  ResultSet results = userUpsertOperator.session.execute(
      "SELECT * FROM unittests.users WHERE userid = '" + userId + "'");
  List<Row> rows = results.all();
  Row userRow = rows.get(0);
  List<Integer> topScoresEntry = userRow.getList("top_scores", Integer.class);
  assertEquals(3, topScoresEntry.size());
  assertEquals("" + 3, "" + topScoresEntry.get(0));
}
 
Example 8
Source File: AbstractUpsertOutputOperatorCodecsTest.java    From attic-apex-malhar with Apache License 2.0 4 votes vote down vote up
@Test
public void testForListAppendAndIfExists() throws Exception
{
  User aUser = new User();
  String userId = "user" + System.currentTimeMillis();
  aUser.setUserid(userId);
  FullName fullName = new FullName("first" + System.currentTimeMillis(), "last" + System.currentTimeMillis());
  aUser.setUsername(fullName);
  Address address = new Address("street1", "city1", 13, null);
  aUser.setCurrentaddress(address);
  Set<String> emails = new HashSet<>();
  emails.add(new String("1"));
  emails.add(new String("2"));
  aUser.setEmails(emails);
  List<Integer> topScores = new ArrayList<>();
  topScores.add(1);
  topScores.add(2);
  aUser.setTopScores(topScores);
  UpsertExecutionContext<User> originalEntry = new UpsertExecutionContext<>();
  originalEntry.setPayload(aUser);

  UpsertExecutionContext<User> subsequentUpdateForTopScores = new UpsertExecutionContext<>();
  subsequentUpdateForTopScores.setListPlacementStyle(
      UpsertExecutionContext.ListPlacementStyle.APPEND_TO_EXISTING_LIST);
  subsequentUpdateForTopScores.setCollectionMutationStyle(
      UpsertExecutionContext.CollectionMutationStyle.ADD_TO_EXISTING_COLLECTION);
  subsequentUpdateForTopScores.setNullHandlingMutationStyle(
      UpsertExecutionContext.NullHandlingMutationStyle.IGNORE_NULL_COLUMNS);
  subsequentUpdateForTopScores.setUpdateOnlyIfPrimaryKeyExists(true);
  User oldUser = new User();
  oldUser.setUserid(userId + System.currentTimeMillis());
  List<Integer> topScoresAppended = new ArrayList<>();
  topScoresAppended.add(3);
  oldUser.setTopScores(topScoresAppended);
  subsequentUpdateForTopScores.setPayload(oldUser);
  userUpsertOperator.beginWindow(5);
  userUpsertOperator.input.process(originalEntry);
  userUpsertOperator.input.process(subsequentUpdateForTopScores);
  userUpsertOperator.endWindow();

  ResultSet results = userUpsertOperator.session.execute(
      "SELECT * FROM unittests.users WHERE userid = '" + userId + "'");
  List<Row> rows = results.all();
  Row userRow = rows.get(0);
  List<Integer> topScoresEntry = userRow.getList("top_scores", Integer.class);
  assertEquals(2, topScoresEntry.size());
  assertEquals("" + 2, "" + topScoresEntry.get(1));
}
 
Example 9
Source File: CassandraMessageDAO.java    From james-project with Apache License 2.0 4 votes vote down vote up
private Stream<MessageAttachmentRepresentation> getAttachments(Row row) {
    List<UDTValue> udtValues = row.getList(ATTACHMENTS, UDTValue.class);
    return attachmentByIds(udtValues);
}
 
Example 10
Source File: CassandraMessageDAO.java    From james-project with Apache License 2.0 4 votes vote down vote up
private boolean hasAttachment(Row row) {
    List<UDTValue> udtValues = row.getList(ATTACHMENTS, UDTValue.class);
    return !udtValues.isEmpty();
}
 
Example 11
Source File: AbstractCassandraProcessor.java    From 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;
}