use of com.datastax.oss.driver.api.core.ProtocolVersion in project java-driver by datastax.
the class GraphConversions method createCustomPayload.
public static Map<String, ByteBuffer> createCustomPayload(GraphStatement<?> statement, GraphProtocol subProtocol, DriverExecutionProfile config, InternalDriverContext context, GraphBinaryModule graphBinaryModule) {
ProtocolVersion protocolVersion = context.getProtocolVersion();
NullAllowingImmutableMap.Builder<String, ByteBuffer> payload = NullAllowingImmutableMap.builder();
Map<String, ByteBuffer> statementOptions = statement.getCustomPayload();
payload.putAll(statementOptions);
final String graphLanguage;
// Don't override anything that's already provided at the statement level
if (!statementOptions.containsKey(GRAPH_LANG_OPTION_KEY)) {
graphLanguage = statement instanceof ScriptGraphStatement ? LANGUAGE_GROOVY : LANGUAGE_BYTECODE;
payload.put(GRAPH_LANG_OPTION_KEY, TypeCodecs.TEXT.encode(graphLanguage, protocolVersion));
} else {
graphLanguage = TypeCodecs.TEXT.decode(statementOptions.get(GRAPH_LANG_OPTION_KEY), protocolVersion);
Preconditions.checkNotNull(graphLanguage, "A null value was set for the graph-language custom payload key.");
}
if (!isSystemQuery(statement, config)) {
if (!statementOptions.containsKey(GRAPH_NAME_OPTION_KEY)) {
String graphName = statement.getGraphName();
if (graphName == null) {
graphName = config.getString(DseDriverOption.GRAPH_NAME, null);
}
if (graphName != null) {
payload.put(GRAPH_NAME_OPTION_KEY, TypeCodecs.TEXT.encode(graphName, protocolVersion));
}
}
if (!statementOptions.containsKey(GRAPH_SOURCE_OPTION_KEY)) {
String traversalSource = statement.getTraversalSource();
if (traversalSource == null) {
traversalSource = config.getString(DseDriverOption.GRAPH_TRAVERSAL_SOURCE, null);
}
if (traversalSource != null) {
payload.put(GRAPH_SOURCE_OPTION_KEY, TypeCodecs.TEXT.encode(traversalSource, protocolVersion));
}
}
}
// the payload allows null entry values so doing a get directly here and checking for null
final ByteBuffer payloadInitialProtocol = statementOptions.get(GRAPH_RESULTS_OPTION_KEY);
if (payloadInitialProtocol == null) {
Preconditions.checkNotNull(subProtocol);
payload.put(GRAPH_RESULTS_OPTION_KEY, TypeCodecs.TEXT.encode(subProtocol.toInternalCode(), protocolVersion));
} else {
subProtocol = GraphProtocol.fromString(TypeCodecs.TEXT.decode(payloadInitialProtocol, protocolVersion));
}
if (subProtocol.isGraphBinary() && graphLanguage.equals(LANGUAGE_BYTECODE)) {
Object bytecodeQuery = bytecodeToSerialize(statement);
try {
Buffer bytecodeByteBuf = graphBinaryModule.serialize(bytecodeQuery);
payload.put(GRAPH_BINARY_QUERY_OPTION_KEY, bytecodeByteBuf.nioBuffer());
bytecodeByteBuf.release();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
if (!statementOptions.containsKey(GRAPH_READ_CONSISTENCY_LEVEL_OPTION_KEY)) {
ConsistencyLevel readCl = statement.getReadConsistencyLevel();
String readClString = readCl != null ? readCl.name() : config.getString(DseDriverOption.GRAPH_READ_CONSISTENCY_LEVEL, null);
if (readClString != null) {
payload.put(GRAPH_READ_CONSISTENCY_LEVEL_OPTION_KEY, TypeCodecs.TEXT.encode(readClString, protocolVersion));
}
}
if (!statementOptions.containsKey(GRAPH_WRITE_CONSISTENCY_LEVEL_OPTION_KEY)) {
ConsistencyLevel writeCl = statement.getWriteConsistencyLevel();
String writeClString = writeCl != null ? writeCl.name() : config.getString(DseDriverOption.GRAPH_WRITE_CONSISTENCY_LEVEL, null);
if (writeClString != null) {
payload.put(GRAPH_WRITE_CONSISTENCY_LEVEL_OPTION_KEY, TypeCodecs.TEXT.encode(writeClString, protocolVersion));
}
}
if (!statementOptions.containsKey(GRAPH_TIMEOUT_OPTION_KEY)) {
Duration timeout = statement.getTimeout();
if (timeout == null) {
timeout = config.getDuration(DseDriverOption.GRAPH_TIMEOUT, Duration.ZERO);
}
if (timeout != null && !timeout.isZero()) {
payload.put(GRAPH_TIMEOUT_OPTION_KEY, TypeCodecs.BIGINT.encode(timeout.toMillis(), protocolVersion));
}
}
return payload.build();
}
use of com.datastax.oss.driver.api.core.ProtocolVersion in project java-driver by datastax.
the class Conversions method toMessage.
public static Message toMessage(Statement<?> statement, DriverExecutionProfile config, InternalDriverContext context) {
ConsistencyLevelRegistry consistencyLevelRegistry = context.getConsistencyLevelRegistry();
ConsistencyLevel consistency = statement.getConsistencyLevel();
int consistencyCode = (consistency == null) ? consistencyLevelRegistry.nameToCode(config.getString(DefaultDriverOption.REQUEST_CONSISTENCY)) : consistency.getProtocolCode();
int pageSize = statement.getPageSize();
if (pageSize <= 0) {
pageSize = config.getInt(DefaultDriverOption.REQUEST_PAGE_SIZE);
}
ConsistencyLevel serialConsistency = statement.getSerialConsistencyLevel();
int serialConsistencyCode = (serialConsistency == null) ? consistencyLevelRegistry.nameToCode(config.getString(DefaultDriverOption.REQUEST_SERIAL_CONSISTENCY)) : serialConsistency.getProtocolCode();
long timestamp = statement.getQueryTimestamp();
if (timestamp == Statement.NO_DEFAULT_TIMESTAMP) {
timestamp = context.getTimestampGenerator().next();
}
CodecRegistry codecRegistry = context.getCodecRegistry();
ProtocolVersion protocolVersion = context.getProtocolVersion();
ProtocolVersionRegistry protocolVersionRegistry = context.getProtocolVersionRegistry();
CqlIdentifier keyspace = statement.getKeyspace();
int nowInSeconds = statement.getNowInSeconds();
if (nowInSeconds != Statement.NO_NOW_IN_SECONDS && !protocolVersionRegistry.supports(protocolVersion, DefaultProtocolFeature.NOW_IN_SECONDS)) {
throw new IllegalArgumentException("Can't use nowInSeconds with protocol " + protocolVersion);
}
if (statement instanceof SimpleStatement) {
SimpleStatement simpleStatement = (SimpleStatement) statement;
List<Object> positionalValues = simpleStatement.getPositionalValues();
Map<CqlIdentifier, Object> namedValues = simpleStatement.getNamedValues();
if (!positionalValues.isEmpty() && !namedValues.isEmpty()) {
throw new IllegalArgumentException("Can't have both positional and named values in a statement.");
}
if (keyspace != null && !protocolVersionRegistry.supports(protocolVersion, DefaultProtocolFeature.PER_REQUEST_KEYSPACE)) {
throw new IllegalArgumentException("Can't use per-request keyspace with protocol " + protocolVersion);
}
QueryOptions queryOptions = new QueryOptions(consistencyCode, encode(positionalValues, codecRegistry, protocolVersion), encode(namedValues, codecRegistry, protocolVersion), false, pageSize, statement.getPagingState(), serialConsistencyCode, timestamp, (keyspace == null) ? null : keyspace.asInternal(), nowInSeconds);
return new Query(simpleStatement.getQuery(), queryOptions);
} else if (statement instanceof BoundStatement) {
BoundStatement boundStatement = (BoundStatement) statement;
if (!protocolVersionRegistry.supports(protocolVersion, DefaultProtocolFeature.UNSET_BOUND_VALUES)) {
ensureAllSet(boundStatement);
}
boolean skipMetadata = boundStatement.getPreparedStatement().getResultSetDefinitions().size() > 0;
QueryOptions queryOptions = new QueryOptions(consistencyCode, boundStatement.getValues(), Collections.emptyMap(), skipMetadata, pageSize, statement.getPagingState(), serialConsistencyCode, timestamp, null, nowInSeconds);
PreparedStatement preparedStatement = boundStatement.getPreparedStatement();
ByteBuffer id = preparedStatement.getId();
ByteBuffer resultMetadataId = preparedStatement.getResultMetadataId();
return new Execute(Bytes.getArray(id), (resultMetadataId == null) ? null : Bytes.getArray(resultMetadataId), queryOptions);
} else if (statement instanceof BatchStatement) {
BatchStatement batchStatement = (BatchStatement) statement;
if (!protocolVersionRegistry.supports(protocolVersion, DefaultProtocolFeature.UNSET_BOUND_VALUES)) {
ensureAllSet(batchStatement);
}
if (keyspace != null && !protocolVersionRegistry.supports(protocolVersion, DefaultProtocolFeature.PER_REQUEST_KEYSPACE)) {
throw new IllegalArgumentException("Can't use per-request keyspace with protocol " + protocolVersion);
}
List<Object> queriesOrIds = new ArrayList<>(batchStatement.size());
List<List<ByteBuffer>> values = new ArrayList<>(batchStatement.size());
for (BatchableStatement<?> child : batchStatement) {
if (child instanceof SimpleStatement) {
SimpleStatement simpleStatement = (SimpleStatement) child;
if (simpleStatement.getNamedValues().size() > 0) {
throw new IllegalArgumentException(String.format("Batch statements cannot contain simple statements with named values " + "(offending statement: %s)", simpleStatement.getQuery()));
}
queriesOrIds.add(simpleStatement.getQuery());
values.add(encode(simpleStatement.getPositionalValues(), codecRegistry, protocolVersion));
} else if (child instanceof BoundStatement) {
BoundStatement boundStatement = (BoundStatement) child;
queriesOrIds.add(Bytes.getArray(boundStatement.getPreparedStatement().getId()));
values.add(boundStatement.getValues());
} else {
throw new IllegalArgumentException("Unsupported child statement: " + child.getClass().getName());
}
}
return new Batch(batchStatement.getBatchType().getProtocolCode(), queriesOrIds, values, consistencyCode, serialConsistencyCode, timestamp, (keyspace == null) ? null : keyspace.asInternal(), nowInSeconds);
} else {
throw new IllegalArgumentException("Unsupported statement type: " + statement.getClass().getName());
}
}
use of com.datastax.oss.driver.api.core.ProtocolVersion in project java-driver by datastax.
the class CqlPrepareHandler method toPrepareMessage.
@NonNull
private Prepare toPrepareMessage(PrepareRequest request) {
ProtocolVersion protocolVersion = context.getProtocolVersion();
ProtocolVersionRegistry registry = context.getProtocolVersionRegistry();
CqlIdentifier keyspace = request.getKeyspace();
if (keyspace != null && !registry.supports(protocolVersion, DefaultProtocolFeature.PER_REQUEST_KEYSPACE)) {
throw new IllegalArgumentException("Can't use per-request keyspace with protocol " + protocolVersion);
}
return new Prepare(request.getQuery(), (keyspace == null) ? null : keyspace.asInternal());
}
use of com.datastax.oss.driver.api.core.ProtocolVersion in project java-driver by datastax.
the class ChannelFactory method connect.
@VisibleForTesting
CompletionStage<DriverChannel> connect(EndPoint endPoint, DriverChannelOptions options, NodeMetricUpdater nodeMetricUpdater) {
CompletableFuture<DriverChannel> resultFuture = new CompletableFuture<>();
ProtocolVersion currentVersion;
boolean isNegotiating;
List<ProtocolVersion> attemptedVersions = new CopyOnWriteArrayList<>();
if (this.protocolVersion != null) {
currentVersion = protocolVersion;
isNegotiating = false;
} else {
currentVersion = context.getProtocolVersionRegistry().highestNonBeta();
isNegotiating = true;
}
connect(endPoint, options, nodeMetricUpdater, currentVersion, isNegotiating, attemptedVersions, resultFuture);
return resultFuture;
}
use of com.datastax.oss.driver.api.core.ProtocolVersion in project java-driver by datastax.
the class DefaultProtocolVersionRegistry method highestCommon.
@Override
public ProtocolVersion highestCommon(Collection<Node> nodes) {
if (nodes == null || nodes.isEmpty()) {
throw new IllegalArgumentException("Expected at least one node");
}
// Start with all non-beta versions (beta versions are always forced, and we don't call this
// method if the version was forced).
Set<ProtocolVersion> candidates = new LinkedHashSet<>();
for (ProtocolVersion version : allVersions) {
if (!version.isBeta()) {
candidates.add(version);
}
}
// Keep an unfiltered copy in case we need to throw an exception below
ImmutableList<ProtocolVersion> initialCandidates = ImmutableList.copyOf(candidates);
// For each node, remove the versions it doesn't support
for (Node node : nodes) {
// We can't trust the Cassandra version reported by DSE to infer the maximum OSS protocol
// supported. For example DSE 6 reports release_version 4.0-SNAPSHOT, but only supports OSS
// protocol v4 (while Cassandra 4 will support v5). So we treat DSE separately.
Version dseVersion = (Version) node.getExtras().get(DseNodeProperties.DSE_VERSION);
if (dseVersion != null) {
LOG.debug("[{}] Node {} reports DSE version {}", logPrefix, node.getEndPoint(), dseVersion);
dseVersion = dseVersion.nextStable();
if (dseVersion.compareTo(DSE_4_7_0) < 0) {
throw new UnsupportedProtocolVersionException(node.getEndPoint(), String.format("Node %s reports DSE version %s, " + "but the driver only supports 4.7.0 and above", node.getEndPoint(), dseVersion), initialCandidates);
} else if (dseVersion.compareTo(DSE_5_0_0) < 0) {
// DSE 4.7.x, 4.8.x
removeHigherThan(DefaultProtocolVersion.V3, null, candidates);
} else if (dseVersion.compareTo(DSE_5_1_0) < 0) {
// DSE 5.0
removeHigherThan(DefaultProtocolVersion.V4, null, candidates);
} else if (dseVersion.compareTo(DSE_6_0_0) < 0) {
// DSE 5.1
removeHigherThan(DefaultProtocolVersion.V4, DseProtocolVersion.DSE_V1, candidates);
} else if (dseVersion.compareTo(DSE_7_0_0) < 0) {
// DSE 6
removeHigherThan(DefaultProtocolVersion.V4, DseProtocolVersion.DSE_V2, candidates);
} else {
// DSE 7.0
removeHigherThan(DefaultProtocolVersion.V5, DseProtocolVersion.DSE_V2, candidates);
}
} else {
// not DSE
Version cassandraVersion = node.getCassandraVersion();
if (cassandraVersion == null) {
LOG.warn("[{}] Node {} reports neither DSE version nor Cassandra version, " + "ignoring it from optimal protocol version computation", logPrefix, node.getEndPoint());
continue;
}
cassandraVersion = cassandraVersion.nextStable();
LOG.debug("[{}] Node {} reports Cassandra version {}", logPrefix, node.getEndPoint(), cassandraVersion);
if (cassandraVersion.compareTo(Version.V2_1_0) < 0) {
throw new UnsupportedProtocolVersionException(node.getEndPoint(), String.format("Node %s reports Cassandra version %s, " + "but the driver only supports 2.1.0 and above", node.getEndPoint(), cassandraVersion), ImmutableList.of(DefaultProtocolVersion.V3, DefaultProtocolVersion.V4));
} else if (cassandraVersion.compareTo(Version.V2_2_0) < 0) {
// 2.1.0
removeHigherThan(DefaultProtocolVersion.V3, null, candidates);
} else if (cassandraVersion.compareTo(Version.V4_0_0) < 0) {
// 2.2, 3.x
removeHigherThan(DefaultProtocolVersion.V4, null, candidates);
} else {
// 4.0
removeHigherThan(DefaultProtocolVersion.V5, null, candidates);
}
}
}
// If we have versions left, return the highest one
ProtocolVersion max = null;
for (ProtocolVersion candidate : candidates) {
if (max == null || max.getCode() < candidate.getCode()) {
max = candidate;
}
}
if (max == null) {
// Note: with the current algorithm, this never happens
throw new UnsupportedProtocolVersionException(null, String.format("Could not determine a common protocol version, " + "enable DEBUG logs for '%s' for more details", LOG.getName()), initialCandidates);
} else {
return max;
}
}
Aggregations