com.datastax.driver.core.TypeCodec Java Examples

The following examples show how to use com.datastax.driver.core.TypeCodec. 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: UserUpsertOperator.java    From attic-apex-malhar with Apache License 2.0 7 votes vote down vote up
@Override
public Map<String, TypeCodec> getCodecsForUserDefinedTypes()
{
  Map<String, TypeCodec> allCodecs = new HashMap<>();
  CodecRegistry codecRegistry = cluster.getConfiguration().getCodecRegistry();

  UserType addressType = cluster.getMetadata().getKeyspace(getConnectionStateManager().getKeyspaceName())
      .getUserType("address");
  TypeCodec<UDTValue> addressTypeCodec = codecRegistry.codecFor(addressType);
  AddressCodec addressCodec = new AddressCodec(addressTypeCodec, Address.class);
  allCodecs.put("currentaddress", addressCodec);

  UserType userFullNameType = cluster.getMetadata().getKeyspace(getConnectionStateManager().getKeyspaceName())
      .getUserType("fullname");
  TypeCodec<UDTValue> userFullNameTypeCodec = codecRegistry.codecFor(userFullNameType);
  FullNameCodec fullNameCodec = new FullNameCodec(userFullNameTypeCodec, FullName.class);
  allCodecs.put("username", fullNameCodec);

  return allCodecs;
}
 
Example #2
Source File: CQL2CQL.java    From cqlkit with Apache License 2.0 6 votes vote down vote up
@Override
protected String map(Row row) {

    Matcher matcher = pattern.matcher(template);
    StringBuffer result = new StringBuffer();
    for (int i = 0; i < definitions.length; i++) {
        Object value = row.getObject(i);
        String key = definitions[i].getName();
        DataType type = definitions[i].getType();

        matcher.find();
        TypeCodec<Object> typeCodec = CodecRegistry.DEFAULT_INSTANCE.codecFor(type);
        matcher.appendReplacement(result, typeCodec.format(value));
    }

    matcher.appendTail(result);
    return result.toString();
}
 
Example #3
Source File: AbstractUpsertOutputOperator.java    From attic-apex-malhar with Apache License 2.0 6 votes vote down vote up
private void registerCodecs()
{
  complexTypeCodecs = getCodecsForUserDefinedTypes();
  if (complexTypeCodecs != null) {
    CodecRegistry registry = cluster.getConfiguration().getCodecRegistry();
    if (cluster.getConfiguration().getProtocolOptions().getProtocolVersion().toInt() < 4) {
      LOG.error("Custom codecs are not supported for protocol version < 4");
      throw new RuntimeException("Custom codecs are not supported for protocol version < 4");
    }
    for (String typeCodecStr : complexTypeCodecs.keySet()) {
      TypeCodec codec = complexTypeCodecs.get(typeCodecStr);
      registry.register(codec);
      userDefinedTypesClass.put(typeCodecStr, codec.getJavaType().getRawType());
    }
  } else {
    complexTypeCodecs = new HashMap<>();
  }
}
 
Example #4
Source File: AdaptiveResultSetTest.java    From emodb with Apache License 2.0 6 votes vote down vote up
private String verifyNextRow(ResultSet rs) {
    String rowid = null;
    for (int col=0; col < 137; col++) {
        Row row = rs.one();
        assertNotNull(row);

        if (rowid == null) {
            rowid = row.get("rowid", TypeCodec.varchar());
        } else {
            assertEquals(row.get("rowid", TypeCodec.varchar()), rowid);
        }

        assertEquals((long) row.get("col", TypeCodec.bigint()), col);
        assertEquals( row.get("data", TypeCodec.blob()).asIntBuffer().get(), col);
    }

    return rowid;
}
 
Example #5
Source File: RowRead.java    From geowave with Apache License 2.0 6 votes vote down vote up
public CassandraRow result() {
  if ((partitionKey != null) && (sortKey != null)) {
    final BoundStatement boundRead = new BoundStatement(preparedRead);
    boundRead.set(
        CassandraField.GW_SORT_KEY.getBindMarkerName(),
        ByteBuffer.wrap(sortKey),
        ByteBuffer.class);
    boundRead.set(
        CassandraField.GW_ADAPTER_ID_KEY.getBindMarkerName(),
        internalAdapterId,
        TypeCodec.smallInt());
    boundRead.set(
        CassandraField.GW_PARTITION_ID_KEY.getBindMarkerName(),
        ByteBuffer.wrap(partitionKey),
        ByteBuffer.class);
    try (CloseableIterator<CassandraRow> it = operations.executeQuery(boundRead)) {
      if (it.hasNext()) {
        // there should only be one entry with this index
        return it.next();
      }
    }
  }
  return null;
}
 
Example #6
Source File: ClusterCassandraConnectionFactory.java    From embedded-cassandra with Apache License 2.0 5 votes vote down vote up
private Cluster createCluster(Cassandra cassandra) {
	SocketOptions socketOptions = new SocketOptions();
	socketOptions.setConnectTimeoutMillis(30000);
	socketOptions.setReadTimeoutMillis(30000);
	int port = cassandra.getPort();
	int sslPort = cassandra.getSslPort();
	Cluster.Builder builder = Cluster.builder().addContactPoints(cassandra.getAddress())
			.withPort(isSslEnabled() && sslPort != -1 ? sslPort : port)
			.withSocketOptions(socketOptions);
	if (!isMetricsEnabled()) {
		builder.withoutMetrics();
	}
	if (!isJmxEnabled()) {
		builder.withoutJMXReporting();
	}
	String username = getUsername();
	String password = getPassword();
	if (username != null && password != null) {
		builder.withCredentials(username, password);
	}
	if (isSslEnabled()) {
		RemoteEndpointAwareJdkSSLOptions.Builder sslOptionsBuilder = RemoteEndpointAwareJdkSSLOptions.builder();
		if (getKeystore() != null || getTruststore() != null) {
			sslOptionsBuilder.withSSLContext(getSslContext());
		}
		List<String> cipherSuites = getCipherSuites();
		if (!cipherSuites.isEmpty()) {
			sslOptionsBuilder.withCipherSuites(cipherSuites.toArray(new String[0]));
		}
		builder.withSSL(sslOptionsBuilder.build());
	}
	List<TypeCodec<?>> typeCodecs = getTypeCodecs();
	if (!typeCodecs.isEmpty()) {
		builder.withCodecRegistry(new CodecRegistry().register(typeCodecs));
	}
	this.clusterBuilderCustomizers.forEach(customizer -> customizer.accept(builder));
	return builder.build();
}
 
Example #7
Source File: CassandraAbstractDao.java    From iotplatform with Apache License 2.0 5 votes vote down vote up
private void registerCodecIfNotFound(CodecRegistry registry, TypeCodec<?> codec) {
    try {
        registry.codecFor(codec.getCqlType(), codec.getJavaType());
    } catch (CodecNotFoundException e) {
        registry.register(codec);
    }
}
 
Example #8
Source File: BatchedRangeRead.java    From geowave with Apache License 2.0 5 votes vote down vote up
public CloseableIterator<T> results() {
  final List<BoundStatement> statements = new ArrayList<>();
  for (final SinglePartitionQueryRanges r : ranges) {
    final byte[] partitionKey = CassandraUtils.getCassandraSafePartitionKey(r.getPartitionKey());
    for (final ByteArrayRange range : r.getSortKeyRanges()) {
      final BoundStatement boundRead = new BoundStatement(preparedRead);
      final byte[] start = range.getStart() != null ? range.getStart() : new byte[0];
      final byte[] end =
          range.getEnd() != null ? range.getEndAsNextPrefix()
              : new byte[] {
                  (byte) 0xFF,
                  (byte) 0xFF,
                  (byte) 0xFF,
                  (byte) 0xFF,
                  (byte) 0xFF,
                  (byte) 0xFF,
                  (byte) 0xFF};
      boundRead.set(
          CassandraField.GW_SORT_KEY.getLowerBoundBindMarkerName(),
          ByteBuffer.wrap(start),
          ByteBuffer.class);

      boundRead.set(
          CassandraField.GW_SORT_KEY.getUpperBoundBindMarkerName(),
          ByteBuffer.wrap(end),
          ByteBuffer.class);
      boundRead.set(
          CassandraField.GW_PARTITION_ID_KEY.getBindMarkerName(),
          ByteBuffer.wrap(partitionKey),
          ByteBuffer.class);

      boundRead.set(
          CassandraField.GW_ADAPTER_ID_KEY.getBindMarkerName(),
          Arrays.asList(ArrayUtils.toObject(adapterIds)),
          TypeCodec.list(TypeCodec.smallInt()));
      statements.add(boundRead);
    }
  }
  return executeQueryAsync(statements.toArray(new BoundStatement[] {}));
}
 
Example #9
Source File: MockRow.java    From hawkular-metrics with Apache License 2.0 4 votes vote down vote up
@Override
public <T> T get(String name, TypeCodec<T> codec) {
    throw new UnsupportedOperationException();
}
 
Example #10
Source File: MockRow.java    From hawkular-metrics with Apache License 2.0 4 votes vote down vote up
@Override
public <T> T get(int i, TypeCodec<T> codec) {
    throw new UnsupportedOperationException();
}
 
Example #11
Source File: TimeUUIDAsStringCodec.java    From datacollector with Apache License 2.0 4 votes vote down vote up
public TimeUUIDAsStringCodec() {
  super(TypeCodec.timeUUID(), String.class);
}
 
Example #12
Source File: LocalDateAsDateCodec.java    From datacollector with Apache License 2.0 4 votes vote down vote up
public LocalDateAsDateCodec() {
  super(TypeCodec.date(), Date.class);
}
 
Example #13
Source File: UUIDAsStringCodec.java    From datacollector with Apache License 2.0 4 votes vote down vote up
public UUIDAsStringCodec() {
  super(TypeCodec.uuid(), String.class);
}
 
Example #14
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;
}
 
Example #15
Source File: FullNameCodec.java    From attic-apex-malhar with Apache License 2.0 4 votes vote down vote up
public FullNameCodec(TypeCodec<UDTValue> innerCodec, Class<FullName> javaType)
{
  super(innerCodec.getCqlType(), javaType);
  this.innerCodec = innerCodec;
  this.userType = (UserType)innerCodec.getCqlType();
}
 
Example #16
Source File: CompositePrimaryKeyUpdateOperator.java    From attic-apex-malhar with Apache License 2.0 4 votes vote down vote up
@Override
public Map<String, TypeCodec> getCodecsForUserDefinedTypes()
{
  return null;
}
 
Example #17
Source File: CounterColumnUpdatesOperator.java    From attic-apex-malhar with Apache License 2.0 4 votes vote down vote up
@Override
public Map<String, TypeCodec> getCodecsForUserDefinedTypes()
{
  return null;
}
 
Example #18
Source File: AddressCodec.java    From attic-apex-malhar with Apache License 2.0 4 votes vote down vote up
public AddressCodec(TypeCodec<UDTValue> innerCodec, Class<Address> javaType)
{
  super(innerCodec.getCqlType(), javaType);
  this.innerCodec = innerCodec;
  this.userType = (UserType)innerCodec.getCqlType();
}
 
Example #19
Source File: VideoUtil.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public static ByteBuffer toblob(String value) {
	return TypeCodec.varchar().serialize(value, ProtocolVersion.V3);
}
 
Example #20
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 #21
Source File: VideoUtil.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public static Date toDate(ByteBuffer value) {
	return (Date) TypeCodec.timestamp().deserialize(value, ProtocolVersion.V3);
}
 
Example #22
Source File: VideoUtil.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public static double todouble(ByteBuffer value) {
	return (double) TypeCodec.cdouble().deserialize(value, ProtocolVersion.V3);
}
 
Example #23
Source File: VideoUtil.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public static long tolong(ByteBuffer value) {
	return (long) TypeCodec.bigint().deserialize(value, ProtocolVersion.V3);
}
 
Example #24
Source File: VideoUtil.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public static int toint(ByteBuffer value) {
	return (int) TypeCodec.cint().deserialize(value, ProtocolVersion.V3);
}
 
Example #25
Source File: VideoUtil.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public static UUID touuid(ByteBuffer value) {
	return (UUID) TypeCodec.uuid().deserialize(value, ProtocolVersion.V3);
}
 
Example #26
Source File: VideoUtil.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public static String tostr(ByteBuffer value) {
	return (String) TypeCodec.varchar().deserialize(value, ProtocolVersion.V3);
}
 
Example #27
Source File: VideoUtil.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public static ByteBuffer toblob(double value) {
	return TypeCodec.cdouble().serialize(value, ProtocolVersion.V3);
}
 
Example #28
Source File: VideoUtil.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public static ByteBuffer toblob(Date value) {
	return TypeCodec.timestamp().serialize(value, ProtocolVersion.V3);
}
 
Example #29
Source File: VideoUtil.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public static ByteBuffer toblob(long value) {
	return TypeCodec.bigint().serialize(value, ProtocolVersion.V3);
}
 
Example #30
Source File: VideoUtil.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public static ByteBuffer toblob(int value) {
	return TypeCodec.cint().serialize(value, ProtocolVersion.V3);
}