com.datastax.driver.core.LocalDate Java Examples

The following examples show how to use com.datastax.driver.core.LocalDate. 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: CassandraRowMapperFn.java    From DataflowTemplates with Apache License 2.0 6 votes vote down vote up
/**
 * Most primitivies are represented the same way in Beam and Cassandra however there are a few
 * that differ. This method converts the native representation of timestamps, uuids, varint, dates
 * and IPs to a format which works for the Beam Schema.
 *
 * <p>Dates and Timestamps are returned as DateTime objects whilst UUIDs are converted to Strings.
 * Varint is converted into BigDecimal. The rest simply pass through as they are.
 *
 * @param value The object value as retrieved from Cassandra.
 * @param typeName The Cassandra schema type.
 * @see org.apache.beam.sdk.schemas.Schema.FieldType
 * @return The corresponding representation that works in the Beam schema.
 */
private Object toBeamObject(Object value, DataType typeName) {
  if (typeName == null || typeName.getName() == null) {
    throw new UnsupportedOperationException(
        "Unspecified Cassandra data type, cannot convert to beam row primitive.");
  }
  switch (typeName.getName()) {
    case TIMESTAMP:
      return new DateTime(value);
    case UUID:
      return ((UUID) value).toString();
    case VARINT:
      return new BigDecimal((BigInteger) value);
    case TIMEUUID:
      return ((UUID) value).toString();
    case DATE:
      LocalDate ld = (LocalDate) value;
      return new DateTime(ld.getYear(), ld.getMonth(), ld.getDay(), 0, 0);
    case INET:
      return ((InetAddress) value).getHostAddress();
    default:
      return value;
  }
}
 
Example #2
Source File: CassandraEnumerator.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Convert an object into the expected internal representation.
 *
 * @param obj Object to convert, if needed
 */
private Object convertToEnumeratorObject(Object obj) {
  if (obj instanceof ByteBuffer) {
    ByteBuffer buf = (ByteBuffer) obj;
    byte [] bytes = new byte[buf.remaining()];
    buf.get(bytes, 0, bytes.length);
    return new ByteString(bytes);
  } else if (obj instanceof LocalDate) {
    // converts dates to the expected numeric format
    return ((LocalDate) obj).getMillisSinceEpoch()
        / DateTimeUtils.MILLIS_PER_DAY;
  } else if (obj instanceof Date) {
    return ((Date) obj).toInstant().toEpochMilli();
  } else if (obj instanceof LinkedHashSet) {
    // MULTISET is handled as an array
    return ((LinkedHashSet) obj).toArray();
  } else if (obj instanceof TupleValue) {
    // STRUCT can be handled as an array
    final TupleValue tupleValue = (TupleValue) obj;
    int numComponents = tupleValue.getType().getComponentTypes().size();
    return IntStream.range(0, numComponents)
        .mapToObj(i ->
            tupleValue.get(i,
                CassandraSchema.CODEC_REGISTRY.codecFor(
                    tupleValue.getType().getComponentTypes().get(i)))
        ).map(this::convertToEnumeratorObject)
        .toArray();
  }

  return obj;
}
 
Example #3
Source File: DateSettableDataSetter.java    From SimpleFlatMapper with MIT License 5 votes vote down vote up
@Override
public void set(SettableByIndexData target, LocalDate value) throws Exception {
    if (value == null) {
        target.setToNull(index);
    } else {
        target.setDate(index, value);
    }
}
 
Example #4
Source File: CassandraTestHelper.java    From cassandra-jdbc-driver with Apache License 2.0 5 votes vote down vote up
public Class replaceDataType(Class clazz, Object value) {
    if (LocalDate.class.equals(clazz)) {
        clazz = Date.class;
    } else if (Short.class.equals(clazz) || Byte.class.equals(clazz)) {
        clazz = Integer.class;
    } else if (value instanceof Date && Long.class.equals(clazz)) {
        clazz = Date.class;
    }

    return clazz;
}
 
Example #5
Source File: CassandraPageSink.java    From presto with Apache License 2.0 5 votes vote down vote up
public CassandraPageSink(
        CassandraSession cassandraSession,
        ProtocolVersion protocolVersion,
        String schemaName,
        String tableName,
        List<String> columnNames,
        List<Type> columnTypes,
        boolean generateUuid)
{
    this.cassandraSession = requireNonNull(cassandraSession, "cassandraSession");
    requireNonNull(schemaName, "schemaName is null");
    requireNonNull(tableName, "tableName is null");
    requireNonNull(columnNames, "columnNames is null");
    this.columnTypes = ImmutableList.copyOf(requireNonNull(columnTypes, "columnTypes is null"));
    this.generateUuid = generateUuid;

    if (protocolVersion.toInt() <= ProtocolVersion.V3.toInt()) {
        this.toCassandraDate = value -> DATE_FORMATTER.print(TimeUnit.DAYS.toMillis(value));
    }
    else {
        this.toCassandraDate = value -> LocalDate.fromDaysSinceEpoch(toIntExact(value));
    }

    Insert insert = insertInto(validSchemaName(schemaName), validTableName(tableName));
    if (generateUuid) {
        insert.value(ID_COLUMN_NAME, bindMarker());
    }
    for (int i = 0; i < columnNames.size(); i++) {
        String columnName = columnNames.get(i);
        checkArgument(columnName != null, "columnName is null at position: %s", i);
        insert.value(validColumnName(columnName), bindMarker());
    }
    this.insert = cassandraSession.prepare(insert);
}
 
Example #6
Source File: CassandraPOJOOutputOperator.java    From attic-apex-malhar with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected Statement setStatementParameters(PreparedStatement updateCommand, Object tuple) throws DriverException
{
  final BoundStatement boundStmnt = new BoundStatement(updateCommand);
  final int size = columnDataTypes.size();
  for (int i = 0; i < size; i++) {
    final DataType type = columnDataTypes.get(i);
    switch (type.getName()) {
      case UUID:
        final UUID id = ((Getter<Object, UUID>)getters.get(i)).get(tuple);
        boundStmnt.setUUID(i, id);
        break;
      case ASCII:
      case VARCHAR:
      case TEXT:
        final String ascii = ((Getter<Object, String>)getters.get(i)).get(tuple);
        boundStmnt.setString(i, ascii);
        break;
      case BOOLEAN:
        final boolean bool = ((GetterBoolean<Object>)getters.get(i)).get(tuple);
        boundStmnt.setBool(i, bool);
        break;
      case INT:
        final int intValue = ((GetterInt<Object>)getters.get(i)).get(tuple);
        boundStmnt.setInt(i, intValue);
        break;
      case BIGINT:
      case COUNTER:
        final long longValue = ((GetterLong<Object>)getters.get(i)).get(tuple);
        boundStmnt.setLong(i, longValue);
        break;
      case FLOAT:
        final float floatValue = ((GetterFloat<Object>)getters.get(i)).get(tuple);
        boundStmnt.setFloat(i, floatValue);
        break;
      case DOUBLE:
        final double doubleValue = ((GetterDouble<Object>)getters.get(i)).get(tuple);
        boundStmnt.setDouble(i, doubleValue);
        break;
      case DECIMAL:
        final BigDecimal decimal = ((Getter<Object, BigDecimal>)getters.get(i)).get(tuple);
        boundStmnt.setDecimal(i, decimal);
        break;
      case SET:
        Set<?> set = ((Getter<Object, Set<?>>)getters.get(i)).get(tuple);
        boundStmnt.setSet(i, set);
        break;
      case MAP:
        final Map<?,?> map = ((Getter<Object, Map<?,?>>)getters.get(i)).get(tuple);
        boundStmnt.setMap(i, map);
        break;
      case LIST:
        final List<?> list = ((Getter<Object, List<?>>)getters.get(i)).get(tuple);
        boundStmnt.setList(i, list);
        break;
      case TIMESTAMP:
        final Date date = ((Getter<Object, Date>)getters.get(i)).get(tuple);
        boundStmnt.setDate(i, LocalDate.fromMillisSinceEpoch(date.getTime()));
        break;
      default:
        throw new RuntimeException("unsupported data type " + type.getName());
    }
  }
  return boundStmnt;
}
 
Example #7
Source File: MockRow.java    From hawkular-metrics with Apache License 2.0 4 votes vote down vote up
@Override
public LocalDate getDate(String name) {
    throw new UnsupportedOperationException();
}
 
Example #8
Source File: MockRow.java    From hawkular-metrics with Apache License 2.0 4 votes vote down vote up
@Override
public LocalDate getDate(int i) {
    throw new UnsupportedOperationException();
}
 
Example #9
Source File: DatastaxDateGetter.java    From SimpleFlatMapper with MIT License 4 votes vote down vote up
@Override
public LocalDate get(GettableByIndexData target) throws Exception {
    return target.getDate(index);
}
 
Example #10
Source File: DataTypeHelper.java    From SimpleFlatMapper with MIT License 4 votes vote down vote up
public static Class<?> asJavaClass(DataType.Name name) {
    if (name == null) return null;
    switch (name) {
        case ASCII:
            return String.class;
        case BIGINT:
            return Long.class;
        case BLOB:
            return ByteBuffer.class;
        case BOOLEAN:
            return Boolean.class;
        case COUNTER:
            return Long.class;
        case DECIMAL:
            return BigDecimal.class;
        case DOUBLE:
            return Double.class;
        case FLOAT:
            return Float.class;
        case INET:
            return InetAddress.class;
        case INT:
            return Integer.class;
        case LIST:
            return List.class;
        case MAP:
            return Map.class;
        case SET:
            return Set.class;
        case TEXT:
            return String.class;
        case TIMESTAMP:
            return Date.class;
        case TIMEUUID:
            return UUID.class;
        case UUID:
            return UUID.class;
        case VARCHAR:
            return String.class;
        case VARINT:
            return BigInteger.class;
        case UDT:
            return UDTValue.class;
        case TUPLE:
            return TupleValue.class;
        case CUSTOM:
            return ByteBuffer.class;
        case DATE:
            return LocalDate.class;
        case TIME:
            return Long.class;
        case SMALLINT:
            return Short.class;
        case TINYINT:
            return Byte.class;
    }

    return null;
}
 
Example #11
Source File: TestCassandraTarget.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Test
public void testWriteSingleRecord() throws InterruptedException, StageException {
  final String tableName = "test.trips";
  List<CassandraFieldMappingConfig> fieldMappings = ImmutableList.of(
      new CassandraFieldMappingConfig("[0]", "driver_id"),
      new CassandraFieldMappingConfig("[1]", "trip_id"),
      new CassandraFieldMappingConfig("[2]", "time"),
      new CassandraFieldMappingConfig("[3]", "x"),
      new CassandraFieldMappingConfig("[4]", "y"),
      new CassandraFieldMappingConfig("[5]", "dt"),
      new CassandraFieldMappingConfig("[6]", "ts"),
      new CassandraFieldMappingConfig("[7]", "time_id"),
      new CassandraFieldMappingConfig("[8]", "unique_id")
  );

  CassandraTargetConfig conf = new CassandraTargetConfig();
  conf.contactPoints.add(cassandra.getContainerIpAddress());
  conf.port = cassandra.getMappedPort(CASSANDRA_NATIVE_PORT);
  conf.protocolVersion = ProtocolVersion.V4;
  conf.authProviderOption = AuthProviderOption.NONE;
  conf.compression = CassandraCompressionCodec.NONE;
  conf.columnNames = fieldMappings;
  conf.qualifiedTableName = tableName;

  Target target = new CassandraTarget(conf);
  TargetRunner targetRunner = new TargetRunner.Builder(CassandraDTarget.class, target).build();

  long now = System.currentTimeMillis();
  LocalDate dt = LocalDate.fromMillisSinceEpoch(now);
  Date ts = new Date();

  Record record = RecordCreator.create();
  List<Field> fields = new ArrayList<>();
  fields.add(Field.create(1));
  fields.add(Field.create(2));
  fields.add(Field.create(3));
  fields.add(Field.create(4.0));
  fields.add(Field.create(5.0));
  fields.add(Field.create(Field.Type.DATE, new Date(dt.getMillisSinceEpoch())));
  fields.add(Field.create(Field.Type.DATETIME, ts));
  fields.add(Field.create(SAMPLE_TIMEUUID));
  fields.add(Field.create(SAMPLE_UUID));
  record.set(Field.create(fields));

  List<Record> singleRecord = ImmutableList.of(record);
  targetRunner.runInit();
  targetRunner.runWrite(singleRecord);

  // Should not be any error records.
  Assert.assertTrue(targetRunner.getErrorRecords().isEmpty());
  Assert.assertTrue(targetRunner.getErrors().isEmpty());

  targetRunner.runDestroy();

  ResultSet resultSet = session.execute("SELECT * FROM test.trips");
  List<Row> allRows = resultSet.all();
  Assert.assertEquals(1, allRows.size());

  Row row = allRows.get(0);
  Assert.assertEquals(1, row.getInt("driver_id"));
  Assert.assertEquals(2, row.getInt("trip_id"));
  Assert.assertEquals(3, row.getInt("time"));
  Assert.assertEquals(4.0, row.getDouble("x"), EPSILON);
  Assert.assertEquals(5.0, row.getDouble("y"), EPSILON);
  Assert.assertEquals(dt, row.getDate("dt"));
  Assert.assertEquals(ts, row.getTimestamp("ts"));
  Assert.assertEquals(SAMPLE_TIMEUUID, row.getUUID("time_id").toString());
  Assert.assertEquals(SAMPLE_UUID, row.getUUID("unique_id").toString());
}
 
Example #12
Source File: LocalDateAsDateCodec.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Override
protected LocalDate serialize(Date d) { return LocalDate.fromMillisSinceEpoch(d.getTime()); }
 
Example #13
Source File: LocalDateAsDateCodec.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Override
protected Date deserialize(LocalDate localDate) { return new Date(localDate.getMillisSinceEpoch()); }
 
Example #14
Source File: CassandraDependenciesJob.java    From zipkin-dependencies with Apache License 2.0 4 votes vote down vote up
public void run() {
  long microsLower = day * 1000;
  long microsUpper = (day * 1000) + TimeUnit.DAYS.toMicros(1) - 1;

  log.info(
      "Running Dependencies job for {}: {} ≤ Span.timestamp {}",
      dateStamp,
      microsLower,
      microsUpper);

  SparkContext sc = new SparkContext(conf);
  try {
    JavaRDD<DependencyLink> links = flatMapToLinksByTraceId(
      javaFunctions(sc).cassandraTable(keyspace, "span"), microsUpper, microsLower, inTest
    ).values()
      .mapToPair(l -> Tuple2.apply(Tuple2.apply(l.parent(), l.child()), l))
      .reduceByKey((l, r) -> DependencyLink.newBuilder()
        .parent(l.parent())
        .child(l.child())
        .callCount(l.callCount() + r.callCount())
        .errorCount(l.errorCount() + r.errorCount())
        .build())
      .values();
    if (links.isEmpty()) {
      log.info("No dependency links could be processed from spans in table {}/span", keyspace);
      return;
    }
    log.info("Saving dependency links for {} to {}.dependency", dateStamp, keyspace);
    CassandraConnector.apply(conf)
        .withSessionDo(new AbstractFunction1<Session, Void>() {
          @Override
          public Void apply(Session session) {
            PreparedStatement prepared =
                session.prepare(QueryBuilder.insertInto(keyspace, "dependency")
                    .value("day", QueryBuilder.bindMarker("day"))
                    .value("parent", QueryBuilder.bindMarker("parent"))
                    .value("child", QueryBuilder.bindMarker("child"))
                    .value("calls", QueryBuilder.bindMarker("calls"))
                    .value("errors", QueryBuilder.bindMarker("errors")));

            for (DependencyLink link : links.collect()) {
              BoundStatement bound = prepared.bind()
                  .setDate("day", LocalDate.fromMillisSinceEpoch(day))
                  .setString("parent", link.parent())
                  .setString("child", link.child())
                  .setLong("calls", link.callCount());
              if (link.errorCount() > 0L) {
                bound.setLong("errors", link.errorCount());
              }
              session.execute(bound);
            }
            return null;
          }
        });
  } finally {
    sc.stop();
  }
}
 
Example #15
Source File: CassandraPreparedStatementTest.java    From cassandra-jdbc-driver with Apache License 2.0 4 votes vote down vote up
@Test(groups = {"unit", "server"})
public void testInsertMaps() {
    String cql = "insert into test_drive.map_data_type(id,id_uuid,binary_data,date_date,date_time," +
            "date_timestamp,id_timeuuid,net_inet,num_big_integer,num_decimal,num_double,num_float,num_int," +
            "num_small_int,num_tiny_int,num_varint,str_ascii,str_text,str_varchar,true_or_false)\n" +
            "values(5d19b3b2-a889-4913-81ec-164e5845cf36,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

    try {
        java.sql.PreparedStatement s = conn.prepareStatement(cql);
        assertTrue(s instanceof CassandraPreparedStatement);

        CassandraDataTypeConverters c = ((CassandraPreparedStatement) s).getDataTypeConverters();
        int index = 1;
        s.setObject(index++, Maps.newHashMap(UUID.randomUUID(), UUID.randomUUID()));
        //s.setObject(index++, Lists.newArrayList(ByteBuffer.wrap(new byte[]{1, 2, 3})));
        s.setObject(index++, Maps.newHashMap(new byte[]{1, 2, 3}, new byte[]{1, 2, 3}));
        //s.setObject(index++, Lists.newArrayList("2017-01-01"));
        s.setObject(index++, Maps.newHashMap(
                CassandraTestHelper.getInstance().replaceParameter(
                        LocalDate.fromMillisSinceEpoch(System.currentTimeMillis()), Date.class),
                CassandraTestHelper.getInstance().replaceParameter(
                        LocalDate.fromMillisSinceEpoch(System.currentTimeMillis()), Date.class)));
        //s.setObject(index++, Lists.newArrayList("11:50:30"));
        //s.setObject(index++, Lists.newArrayList(LocalTime.now().getMillisOfDay() * 1000000L));
        s.setObject(index++, Maps.newHashMap(
                CassandraTestHelper.getInstance().replaceParameter(
                        new Time(LocalTime.now().toDateTimeToday().getMillis()), Time.class),
                CassandraTestHelper.getInstance().replaceParameter(
                        new Time(LocalTime.now().toDateTimeToday().getMillis()), Time.class)));
        //s.setObject(index++, Lists.newArrayList("2017-02-02 11:50:30.123"));
        s.setObject(index++, Maps.newHashMap(LocalDateTime.now().toDate(),
                LocalDateTime.now().toDate()));
        // or you'll likely end up with error like the following:
        // com.datastax.driver.core.exceptions.InvalidTypeException: xxx is not a Type 1 (time-based) UUID
        s.setObject(index++, Maps.newHashMap(((CassandraPreparedStatement) s)
                        .getDataTypeConverters().defaultValueOf(UUID.class),
                ((CassandraPreparedStatement) s).getDataTypeConverters().defaultValueOf(UUID.class)));
        s.setObject(index++, Maps.newHashMap(InetAddress.getByName("192.168.10.11"),
                InetAddress.getByName("192.168.10.11")));
        s.setObject(index++, Maps.newHashMap(Long.MAX_VALUE, Long.MAX_VALUE));
        s.setObject(index++, Maps.newHashMap(new BigDecimal("33333333333333333333333333333333333"),
                new BigDecimal("33333333333333333333333333333333333")));
        s.setObject(index++, Maps.newHashMap(Double.MAX_VALUE, Double.MAX_VALUE));
        s.setObject(index++, Maps.newHashMap(Float.MAX_VALUE, Float.MAX_VALUE));
        s.setObject(index++, Maps.newHashMap(Integer.MAX_VALUE, Integer.MAX_VALUE));
        s.setObject(index++, Maps.newHashMap(
                CassandraTestHelper.getInstance().replaceParameter(Short.MAX_VALUE, Short.class),
                CassandraTestHelper.getInstance().replaceParameter(Short.MAX_VALUE, Short.class)));
        s.setObject(index++, Maps.newHashMap(
                CassandraTestHelper.getInstance().replaceParameter(Byte.MAX_VALUE, Byte.class),
                CassandraTestHelper.getInstance().replaceParameter(Byte.MAX_VALUE, Byte.class)));
        s.setObject(index++, Maps.newHashMap(new BigInteger("2222222222222222222222222222222222"),
                new BigInteger("2222222222222222222222222222222222")));
        s.setObject(index++, Maps.newHashMap("ascii", "ascii"));
        s.setObject(index++, Maps.newHashMap("text", "text"));
        s.setObject(index++, Maps.newHashMap("varchar", "varchar"));
        s.setObject(index++, Maps.newHashMap(true, true));

        assertFalse(s.execute());
        assertNull(s.getResultSet());
        assertEquals(s.getUpdateCount(), 1);

        s.close();
    } catch (Exception e) {
        e.printStackTrace();
        fail("Error occurred during testing: " + e.getMessage());
    }
}
 
Example #16
Source File: CassandraPreparedStatementTest.java    From cassandra-jdbc-driver with Apache License 2.0 4 votes vote down vote up
@Test(groups = {"unit", "server"})
public void testInsertSets() {
    String cql = "insert into test_drive.set_data_type(id,id_uuid,binary_data,date_date,date_time," +
            "date_timestamp,id_timeuuid,net_inet,num_big_integer,num_decimal,num_double,num_float,num_int," +
            "num_small_int,num_tiny_int,num_varint,str_ascii,str_text,str_varchar,true_or_false)\n" +
            "values(5d19b3b2-a889-4913-81ec-164e5845cf36,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

    try {
        java.sql.PreparedStatement s = conn.prepareStatement(cql);
        assertTrue(s instanceof CassandraPreparedStatement);

        CassandraDataTypeConverters c = ((CassandraPreparedStatement) s).getDataTypeConverters();
        int index = 1;
        s.setObject(index++, Sets.newHashSet(UUID.randomUUID()));
        //s.setObject(index++, Lists.newArrayList(ByteBuffer.wrap(new byte[]{1, 2, 3})));
        s.setObject(index++, Sets.newHashSet(new byte[]{1, 2, 3}));
        //s.setObject(index++, Lists.newArrayList("2017-01-01"));
        s.setObject(index++, Sets.newHashSet(
                CassandraTestHelper.getInstance().replaceParameter(
                        LocalDate.fromMillisSinceEpoch(System.currentTimeMillis()), Date.class)));
        //s.setObject(index++, Lists.newArrayList("11:50:30"));
        //s.setObject(index++, Lists.newArrayList(LocalTime.now().getMillisOfDay() * 1000000L));
        s.setObject(index++, Sets.newHashSet(
                CassandraTestHelper.getInstance().replaceParameter(
                        new Time(LocalTime.now().toDateTimeToday().getMillis()), Time.class)));
        //s.setObject(index++, Lists.newArrayList("2017-02-02 11:50:30.123"));
        s.setObject(index++, Sets.newHashSet(LocalDateTime.now().toDate()));
        // or you'll likely end up with error like the following:
        // com.datastax.driver.core.exceptions.InvalidTypeException: xxx is not a Type 1 (time-based) UUID
        s.setObject(index++, Sets.newHashSet(((CassandraPreparedStatement) s)
                .getDataTypeConverters().defaultValueOf(UUID.class)));
        s.setObject(index++, Sets.newHashSet(InetAddress.getByName("192.168.10.11")));
        s.setObject(index++, Sets.newHashSet(Long.MAX_VALUE));
        s.setObject(index++, Sets.newHashSet(new BigDecimal("33333333333333333333333333333333333")));
        s.setObject(index++, Sets.newHashSet(Double.MAX_VALUE));
        s.setObject(index++, Sets.newHashSet(Float.MAX_VALUE));
        s.setObject(index++, Sets.newHashSet(Integer.MAX_VALUE));
        s.setObject(index++, Sets.newHashSet(
                CassandraTestHelper.getInstance().replaceParameter(Short.MAX_VALUE, Short.class)));
        s.setObject(index++, Sets.newHashSet(
                CassandraTestHelper.getInstance().replaceParameter(Byte.MAX_VALUE, Byte.class)));
        s.setObject(index++, Sets.newHashSet(new BigInteger("2222222222222222222222222222222222")));
        s.setObject(index++, Sets.newHashSet("ascii"));
        s.setObject(index++, Sets.newHashSet("text"));
        s.setObject(index++, Sets.newHashSet("varchar"));
        s.setObject(index++, Sets.newHashSet(true));

        assertFalse(s.execute());
        assertNull(s.getResultSet());
        assertEquals(s.getUpdateCount(), 1);

        s.close();
    } catch (Exception e) {
        e.printStackTrace();
        fail("Error occurred during testing: " + e.getMessage());
    }
}
 
Example #17
Source File: CassandraPreparedStatementTest.java    From cassandra-jdbc-driver with Apache License 2.0 4 votes vote down vote up
@Test(groups = {"unit", "server"})
public void testInsertLists() {
    String cql = "insert into test_drive.list_data_type(id,id_uuid,binary_data,date_date,date_time," +
            "date_timestamp,id_timeuuid,net_inet,num_big_integer,num_decimal,num_double,num_float,num_int," +
            "num_small_int,num_tiny_int,num_varint,str_ascii,str_text,str_varchar,true_or_false)\n" +
            "values(5d19b3b2-a889-4913-81ec-164e5845cf36,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

    try {
        java.sql.PreparedStatement s = conn.prepareStatement(cql);
        assertTrue(s instanceof CassandraPreparedStatement);

        CassandraDataTypeConverters c = ((CassandraPreparedStatement) s).getDataTypeConverters();
        int index = 1;
        s.setObject(index++, Lists.newArrayList(UUID.randomUUID()));
        //s.setObject(index++, Lists.newArrayList(ByteBuffer.wrap(new byte[]{1, 2, 3})));
        s.setObject(index++, Lists.newArrayList(new byte[]{1, 2, 3}));
        //s.setObject(index++, Lists.newArrayList("2017-01-01"));
        s.setObject(index++, Lists.newArrayList(
                CassandraTestHelper.getInstance().replaceParameter(
                        LocalDate.fromMillisSinceEpoch(System.currentTimeMillis()), Date.class)));
        //s.setObject(index++, Lists.newArrayList("11:50:30"));
        //s.setObject(index++, Lists.newArrayList(LocalTime.now().getMillisOfDay() * 1000000L));
        s.setObject(index++, Lists.newArrayList(
                CassandraTestHelper.getInstance().replaceParameter(
                        new Time(LocalTime.now().toDateTimeToday().getMillis()), Time.class)));
        //s.setObject(index++, Lists.newArrayList("2017-02-02 11:50:30.123"));
        s.setObject(index++, Lists.newArrayList(LocalDateTime.now().toDate()));
        // or you'll likely end up with error like the following:
        // com.datastax.driver.core.exceptions.InvalidTypeException: xxx is not a Type 1 (time-based) UUID
        s.setObject(index++, Lists.newArrayList(((CassandraPreparedStatement) s)
                .getDataTypeConverters().defaultValueOf(UUID.class)));
        s.setObject(index++, Lists.newArrayList(InetAddress.getByName("192.168.10.11")));
        s.setObject(index++, Lists.newArrayList(Long.MAX_VALUE));
        s.setObject(index++, Lists.newArrayList(new BigDecimal("33333333333333333333333333333333333")));
        s.setObject(index++, Lists.newArrayList(Double.MAX_VALUE));
        s.setObject(index++, Lists.newArrayList(Float.MAX_VALUE));
        s.setObject(index++, Lists.newArrayList(Integer.MAX_VALUE));
        s.setObject(index++, Lists.newArrayList(
                CassandraTestHelper.getInstance().replaceParameter(Short.MAX_VALUE, Short.class)));
        s.setObject(index++, Lists.newArrayList(
                CassandraTestHelper.getInstance().replaceParameter(Byte.MAX_VALUE, Byte.class)));
        s.setObject(index++, Lists.newArrayList(new BigInteger("2222222222222222222222222222222222")));
        s.setObject(index++, Lists.newArrayList("ascii"));
        s.setObject(index++, Lists.newArrayList("text"));
        s.setObject(index++, Lists.newArrayList("varchar"));
        s.setObject(index++, Lists.newArrayList(true));

        assertFalse(s.execute());
        assertNull(s.getResultSet());
        assertEquals(s.getUpdateCount(), 1);

        s.close();
    } catch (Exception e) {
        e.printStackTrace();
        fail("Error occurred during testing: " + e.getMessage());
    }
}
 
Example #18
Source File: CassandraPreparedStatementTest.java    From cassandra-jdbc-driver with Apache License 2.0 4 votes vote down vote up
@Test(groups = {"unit", "server"})
public void testDate() {
    String insertCql = "insert into test_drive.basic_data_type(id_uuid, date_date) values(?, ?)";
    String queryCql = "select date_date from test_drive.basic_data_type where id_uuid = ?";
    UUID id = UUID.randomUUID();
    String date = "2015-01-01";
    LocalDate ld = LocalDate.fromYearMonthDay(2015, 1, 1);
    Date d = Date.valueOf(date);
    org.joda.time.LocalDate jld = org.joda.time.LocalDate.fromDateFields(d);

    try {
        // set date by string
        java.sql.PreparedStatement s = conn.prepareStatement(insertCql);
        s.setObject(1, id);
        s.setObject(2, date);
        s.execute();
        s.close();

        s = conn.prepareStatement(queryCql);
        s.setObject(1, id);
        ResultSet rs = s.executeQuery();
        rs.next();
        assertEquals(CassandraTestHelper.getInstance().replaceResult(rs.getObject(1), LocalDate.class), ld);
        assertEquals(CassandraTestHelper.getInstance().replaceResult(rs.getString(1), LocalDate.class), date);
        assertEquals(rs.getDate(1), d);
        rs.close();
        s.close();

        // by LocalDate
        s = conn.prepareStatement(insertCql);
        s.setObject(1, id);
        s.setObject(2, CassandraTestHelper.getInstance().replaceParameter(ld, Date.class));
        s.execute();
        s.close();

        s = conn.prepareStatement(queryCql);
        s.setObject(1, id);
        rs = s.executeQuery();
        rs.next();
        assertEquals(CassandraTestHelper.getInstance().replaceResult(rs.getObject(1), LocalDate.class), ld);
        assertEquals(CassandraTestHelper.getInstance().replaceResult(rs.getString(1), LocalDate.class), date);
        assertEquals(rs.getDate(1), d);
        rs.close();
        s.close();

        // by date
        s = conn.prepareStatement(insertCql);
        s.setObject(1, id);
        s.setDate(2, d);
        s.execute();
        s.close();

        s = conn.prepareStatement(queryCql);
        s.setObject(1, id);
        rs = s.executeQuery();
        rs.next();
        assertEquals(CassandraTestHelper.getInstance().replaceResult(rs.getObject(1), LocalDate.class), ld);
        assertEquals(CassandraTestHelper.getInstance().replaceResult(rs.getString(1), LocalDate.class), date);
        assertEquals(rs.getDate(1), d);
        rs.close();
        s.close();

        // by Joda LocalDate
        s = conn.prepareStatement(insertCql);
        s.setObject(1, id);
        s.setObject(2, jld);
        s.execute();
        s.close();

        s = conn.prepareStatement(queryCql);
        s.setObject(1, id);
        rs = s.executeQuery();
        rs.next();
        assertEquals(CassandraTestHelper.getInstance().replaceResult(rs.getObject(1), LocalDate.class), ld);
        assertEquals(CassandraTestHelper.getInstance().replaceResult(rs.getString(1), LocalDate.class), date);
        assertEquals(rs.getDate(1), d);
        rs.close();
        s.close();
    } catch (Exception e) {
        e.printStackTrace();
        fail("Error occurred during testing: " + e.getMessage());
    }
}
 
Example #19
Source File: CassandraStatementTest.java    From cassandra-jdbc-driver with Apache License 2.0 4 votes vote down vote up
@Test(groups = {"unit", "server"}, dependsOnMethods = {"testInsertBasicData"})
public void testQueryBasicDataAsObject() {
    String cql = "select tbl.id_uuid,tbl.binary_data,tbl.date_date,tbl.date_time,tbl.date_timestamp," +
            "tbl.id_timeuuid,tbl.net_inet,tbl.num_big_integer,tbl.num_decimal,tbl.num_double,tbl.num_float," +
            "tbl.num_int,tbl.num_small_int,tbl.num_tiny_int,tbl.num_varint,tbl.str_ascii,tbl.str_text," +
            "tbl.str_varchar,tbl.true_or_false from \"test_drive\".\"basic_data_type\" tbl limit 1";

    try {
        java.sql.Statement s = conn.createStatement();
        assertTrue(s instanceof CassandraStatement);

        ResultSet rs = s.executeQuery(cql);
        assertTrue(rs instanceof CassandraResultSet);
        assertNotNull(rs);
        assertTrue(rs == s.getResultSet());

        while (rs.next()) { // only need to read one row
            int index = 1;
            validateObjectType(rs.getObject(index++), UUID.class);
            validateObjectType(rs.getObject(index++), ByteBuffer.class);
            validateObjectType(rs.getObject(index++), LocalDate.class);
            validateObjectType(rs.getObject(index++), Long.class);
            validateObjectType(rs.getObject(index++), java.util.Date.class);
            validateObjectType(rs.getObject(index++), UUID.class);
            validateObjectType(rs.getObject(index++), InetAddress.class);
            validateObjectType(rs.getObject(index++), Long.class);
            validateObjectType(rs.getObject(index++), BigDecimal.class);
            validateObjectType(rs.getObject(index++), Double.class);
            validateObjectType(rs.getObject(index++), Float.class);
            validateObjectType(rs.getObject(index++), Integer.class);
            validateObjectType(rs.getObject(index++), Short.class);
            validateObjectType(rs.getObject(index++), Byte.class);
            validateObjectType(rs.getObject(index++), BigInteger.class);
            validateObjectType(rs.getObject(index++), String.class);
            validateObjectType(rs.getObject(index++), String.class);
            validateObjectType(rs.getObject(index++), String.class);
            validateObjectType(rs.getObject(index++), Boolean.class);
        }

        rs.close();
        s.close();
    } catch (Exception e) {
        e.printStackTrace();
        fail("Error occurred during testing: " + e.getMessage());
    }
}
 
Example #20
Source File: CassandraType.java    From presto with Apache License 2.0 4 votes vote down vote up
public Object getJavaValue(Object prestoNativeValue)
{
    switch (this) {
        case ASCII:
        case TEXT:
        case VARCHAR:
            return ((Slice) prestoNativeValue).toStringUtf8();
        case BIGINT:
        case BOOLEAN:
        case DOUBLE:
        case COUNTER:
            return prestoNativeValue;
        case INET:
            return InetAddresses.forString(((Slice) prestoNativeValue).toStringUtf8());
        case INT:
        case SMALLINT:
        case TINYINT:
            return ((Long) prestoNativeValue).intValue();
        case FLOAT:
            // conversion can result in precision lost
            return intBitsToFloat(((Long) prestoNativeValue).intValue());
        case DECIMAL:
            // conversion can result in precision lost
            // Presto uses double for decimal, so to keep the floating point precision, convert it to string.
            // Otherwise partition id doesn't match
            return new BigDecimal(prestoNativeValue.toString());
        case TIMESTAMP:
            return new Date((Long) prestoNativeValue);
        case DATE:
            return LocalDate.fromDaysSinceEpoch(((Long) prestoNativeValue).intValue());
        case UUID:
        case TIMEUUID:
            return java.util.UUID.fromString(((Slice) prestoNativeValue).toStringUtf8());
        case BLOB:
        case CUSTOM:
            return ((Slice) prestoNativeValue).toStringUtf8();
        case VARINT:
            return new BigInteger(((Slice) prestoNativeValue).toStringUtf8());
        case SET:
        case LIST:
        case MAP:
        default:
            throw new IllegalStateException("Back conversion not implemented for " + this);
    }
}