com.datastax.driver.core.CodecRegistry Java Examples

The following examples show how to use com.datastax.driver.core.CodecRegistry. 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: CassandraAbstractDao.java    From iotplatform with Apache License 2.0 6 votes vote down vote up
protected Session getSession() {
    if (session == null) {
        session = cluster.getSession();
        defaultReadLevel = cluster.getDefaultReadConsistencyLevel();
        defaultWriteLevel = cluster.getDefaultWriteConsistencyLevel();
        CodecRegistry registry = session.getCluster().getConfiguration().getCodecRegistry();
        registerCodecIfNotFound(registry, new JsonCodec());
        registerCodecIfNotFound(registry, new DeviceCredentialsTypeCodec());
        registerCodecIfNotFound(registry, new AuthorityCodec());
        registerCodecIfNotFound(registry, new ComponentLifecycleStateCodec());
        registerCodecIfNotFound(registry, new ComponentTypeCodec());
        registerCodecIfNotFound(registry, new ComponentScopeCodec());
        registerCodecIfNotFound(registry, new EntityTypeCodec());
    }
    return session;
}
 
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: 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 #5
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 #6
Source File: Clauses.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
@Override
void appendTo(StringBuilder sb, List<Object> variables,
              CodecRegistry codecRegistry) {
    // NOTE: '(? AND ?)' is not supported by Cassandra:
    // SyntaxError: line xx missing ')' at 'AND'
    // sb.append("(");
    this.left.appendTo(sb, variables, codecRegistry);
    sb.append(" ");
    sb.append(this.op);
    sb.append(" ");
    this.right.appendTo(sb, variables, codecRegistry);
    // sb.append(")");
}
 
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: CqlDeltaIterator.java    From emodb with Apache License 2.0 5 votes vote down vote up
public CqlDeltaIterator(Iterator<Row> iterator, final int blockIndex, final int changeIdIndex, final int contentIndex, boolean reversed, int prefixLength,
                        ProtocolVersion protocolVersion, CodecRegistry codecRegistry, String rowKey) {
    super(iterator, reversed, prefixLength, rowKey);
    _blockIndex = blockIndex;
    _changeIdIndex = changeIdIndex;
    _contentIndex = contentIndex;
    _protocolVersion = protocolVersion;
    _codecRegistry = codecRegistry;
}
 
Example #9
Source File: CassandraStorage.java    From cassandra-reaper with Apache License 2.0 5 votes vote down vote up
public CassandraStorage(
    UUID reaperInstanceId,
    ReaperApplicationConfiguration config,
    Environment environment) throws ReaperException {

  this.reaperInstanceId = reaperInstanceId;
  CassandraFactory cassandraFactory = config.getCassandraFactory();
  overrideQueryOptions(cassandraFactory);
  overrideRetryPolicy(cassandraFactory);
  overridePoolingOptions(cassandraFactory);

  // https://docs.datastax.com/en/developer/java-driver/3.5/manual/metrics/#metrics-4-compatibility
  cassandraFactory.setJmxEnabled(false);
  if (!CassandraStorage.UNINITIALISED.compareAndSet(true, false)) {
    // If there's been a past connection attempt, metrics are already registered
    cassandraFactory.setMetricsEnabled(false);
  }

  cassandra = cassandraFactory.build(environment);
  if (config.getActivateQueryLogger()) {
    cassandra.register(QueryLogger.builder().build());
  }
  CodecRegistry codecRegistry = cassandra.getConfiguration().getCodecRegistry();
  codecRegistry.register(new DateTimeCodec());
  session = cassandra.connect(config.getCassandraFactory().getKeyspace());

  version = cassandra.getMetadata().getAllHosts()
      .stream()
      .map(h -> h.getCassandraVersion())
      .min(VersionNumber::compareTo)
      .get();

  initializeAndUpgradeSchema(cassandra, session, config, version);
  prepareStatements();
}
 
Example #10
Source File: CassandraTarget.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private Cluster getCluster() throws StageException {
  RemoteEndpointAwareJdkSSLOptions sslOptions = null;

  if (conf.tlsConfig.isEnabled()) {
    // Not certain why we need the downcast here, but we do
    sslOptions = (RemoteEndpointAwareJdkSSLOptions)RemoteEndpointAwareJdkSSLOptions.builder()
        .withSSLContext(conf.tlsConfig.getSslContext())
        .build();
  }

  SocketOptions socketOptions = new SocketOptions();
  socketOptions.setConnectTimeoutMillis(conf.connectionTimeout);
  socketOptions.setReadTimeoutMillis(conf.readTimeout);

  QueryOptions queryOptions = new QueryOptions();
  queryOptions.setConsistencyLevel(conf.consistencyLevel);

  Cluster cluster = Cluster.builder()
      .addContactPoints(contactPoints)
      .withSSL(sslOptions)
      // If authentication is disabled on the C* cluster, this method has no effect.
      .withAuthProvider(getAuthProvider())
      .withProtocolVersion(conf.protocolVersion)
      .withPort(conf.port)
      .withCodecRegistry(new CodecRegistry().register(SDC_CODECS))
      .withSocketOptions(socketOptions)
      .withQueryOptions(queryOptions)
      .build();

  if (conf.logSlowQueries) {
    QueryLogger queryLogger = QueryLogger.builder()
        .withConstantThreshold(conf.slowQueryThreshold)
        .build();
    cluster.register(queryLogger);
  }
  return cluster;
}
 
Example #11
Source File: CassandraMetricBatch.java    From monasca-persister with Apache License 2.0 5 votes vote down vote up
public CassandraMetricBatch(Metadata metadata, ProtocolOptions protocol, CodecRegistry codec,
    TokenAwarePolicy lbPolicy, int batchLimit) {
  this.protocol = protocol;
  this.codec = codec;
  this.metadata = metadata;
  this.policy = lbPolicy;
  metricQueries = new HashMap<>();
  this.batchLimit = batchLimit;

  metricQueries = new HashMap<>();
  dimensionQueries = new HashMap<>();
  dimensionMetricQueries = new HashMap<>();
  metricDimensionQueries = new HashMap<>();
  measurementQueries = new HashMap<>();
}
 
Example #12
Source File: WrappedPreparedStatement.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override public CodecRegistry getCodecRegistry() {
    return st.getCodecRegistry();
}
 
Example #13
Source File: CassandraCluster.java    From monasca-persister with Apache License 2.0 4 votes vote down vote up
public CodecRegistry getCodecRegistry() {
  return cluster.getConfiguration().getCodecRegistry();
}