diff --git a/.asf.yaml b/.asf.yaml new file mode 100644 index 00000000000..ac29efed9ff --- /dev/null +++ b/.asf.yaml @@ -0,0 +1,37 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +notifications: + commits: commits@cassandra.apache.org + issues: commits@cassandra.apache.org + pullrequests: pr@cassandra.apache.org + jira_options: link worklog + +github: + description: "Java Driver for Apache Cassandra®" + homepage: https://cassandra.apache.org/ + enabled_merge_buttons: + squash: false + merge: false + rebase: true + features: + wiki: false + issues: false + projects: false + autolink_jira: + - CASSANDRA + - CASSJAVA diff --git a/.snyk b/.snyk new file mode 100644 index 00000000000..a081b17225c --- /dev/null +++ b/.snyk @@ -0,0 +1,35 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# Snyk (https://snyk.io) policy file, patches or ignores known vulnerabilities. +version: v1.22.2 +# ignores vulnerabilities until expiry date; change duration by modifying expiry date +ignore: + SNYK-JAVA-ORGGRAALVMSDK-2767964: + - '*': + reason: cannot upgrade to graal-sdk 22.1.0+ until we move off Java8, which is slated for later this year + expires: 2024-01-10T00:00:00.000Z + created: 2023-06-21T00:00:00.000Z + SNYK-JAVA-ORGGRAALVMSDK-2769618: + - '*': + reason: cannot upgrade to graal-sdk 22.1.0+ until we move off Java8, which is slated for later this year + expires: 2024-01-10T00:00:00.000Z + created: 2023-06-21T00:00:00.000Z + SNYK-JAVA-ORGGRAALVMSDK-5457933: + - '*': + reason: cannot upgrade to graal-sdk 22.1.0+ until we move off Java8, which is slated for later this year + expires: 2024-01-10T00:00:00.000Z + created: 2023-06-21T00:00:00.000Z diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 7b868941bc3..00000000000 --- a/.travis.yml +++ /dev/null @@ -1,22 +0,0 @@ -language: java -dist: trusty -sudo: false -# see https://sormuras.github.io/blog/2018-03-20-jdk-matrix.html -matrix: - include: - # 8 - - env: JDK='OpenJDK 8' - jdk: openjdk8 - # 11 - - env: JDK='OpenJDK 11' - # switch to JDK 11 before running tests - before_script: . $TRAVIS_BUILD_DIR/ci/install-jdk.sh -F 11 -L GPL -before_install: - # Require JDK8 for compiling - - jdk_switcher use openjdk8 - - ./install-snapshots.sh -install: mvn install -DskipTests=true -Dmaven.javadoc.skip=true -B -V -script: mvn test -Djacoco.skip=true -Dmaven.test.failure.ignore=true -Dmaven.javadoc.skip=true -B -V -cache: - directories: - - $HOME/.m2 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 927c7a7aa8c..53857383cf2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,3 +1,22 @@ + + # Contributing guidelines ## Code formatting diff --git a/Jenkinsfile-asf b/Jenkinsfile-asf new file mode 100644 index 00000000000..4b5041903c1 --- /dev/null +++ b/Jenkinsfile-asf @@ -0,0 +1,81 @@ +#!groovy + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +pipeline { + agent { + label 'cassandra-small' + } + + triggers { + // schedules only run against release branches (i.e. 3.x, 4.x, 4.5.x, etc.) + cron(branchPatternCron().matcher(env.BRANCH_NAME).matches() ? '@weekly' : '') + } + + stages { + stage('Matrix') { + matrix { + axes { + axis { + name 'TEST_JAVA_VERSION' + values 'openjdk@1.8.0-292', 'openjdk@1.11.0-9', 'openjdk@1.17.0', 'openjdk@1.21.0' + } + axis { + name 'SERVER_VERSION' + values '3.11', + '4.0', + '4.1', + '5.0' + } + } + stages { + stage('Tests') { + agent { + label 'cassandra-medium' + } + steps { + script { + executeTests() + junit testResults: '**/target/surefire-reports/TEST-*.xml', allowEmptyResults: true + junit testResults: '**/target/failsafe-reports/TEST-*.xml', allowEmptyResults: true + } + } + } + } + } + } + } +} + +def executeTests() { + def testJavaMajorVersion = (TEST_JAVA_VERSION =~ /@(?:1\.)?(\d+)/)[0][1] + sh """ + container_id=\$(docker run -td -e TEST_JAVA_VERSION=${TEST_JAVA_VERSION} -e SERVER_VERSION=${SERVER_VERSION} -e TEST_JAVA_MAJOR_VERSION=${testJavaMajorVersion} -v \$(pwd):/home/docker/cassandra-java-driver apache.jfrog.io/cassan-docker/apache/cassandra-java-driver-testing-ubuntu2204 'sleep 2h') + docker exec --user root \$container_id bash -c \"sudo bash /home/docker/cassandra-java-driver/ci/create-user.sh docker \$(id -u) \$(id -g) /home/docker/cassandra-java-driver\" + docker exec --user docker \$container_id './cassandra-java-driver/ci/run-tests.sh' + ( nohup docker stop \$container_id >/dev/null 2>/dev/null & ) + """ +} + +// branch pattern for cron +// should match 3.x, 4.x, 4.5.x, etc +def branchPatternCron() { + ~'((\\d+(\\.[\\dx]+)+))' +} diff --git a/Jenkinsfile b/Jenkinsfile-datastax similarity index 66% rename from Jenkinsfile rename to Jenkinsfile-datastax index 95eb2aa20b0..602f33101ca 100644 --- a/Jenkinsfile +++ b/Jenkinsfile-datastax @@ -1,23 +1,52 @@ #!groovy +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ def initializeEnvironment() { - env.DRIVER_DISPLAY_NAME = 'CassandraⓇ Java Driver' + env.DRIVER_DISPLAY_NAME = 'Java Driver for Apache CassandraⓇ' env.DRIVER_METRIC_TYPE = 'oss' - if (env.GIT_URL.contains('riptano/java-driver')) { - env.DRIVER_DISPLAY_NAME = 'private ' + env.DRIVER_DISPLAY_NAME - env.DRIVER_METRIC_TYPE = 'oss-private' - } else if (env.GIT_URL.contains('java-dse-driver')) { - env.DRIVER_DISPLAY_NAME = 'DSE Java Driver' - env.DRIVER_METRIC_TYPE = 'dse' - } env.GIT_SHA = "${env.GIT_COMMIT.take(7)}" env.GITHUB_PROJECT_URL = "https://${GIT_URL.replaceFirst(/(git@|http:\/\/|https:\/\/)/, '').replace(':', '/').replace('.git', '')}" env.GITHUB_BRANCH_URL = "${GITHUB_PROJECT_URL}/tree/${env.BRANCH_NAME}" env.GITHUB_COMMIT_URL = "${GITHUB_PROJECT_URL}/commit/${env.GIT_COMMIT}" - env.MAVEN_HOME = "${env.HOME}/.mvn/apache-maven-3.3.9" + env.MAVEN_HOME = "${env.HOME}/.mvn/apache-maven-3.8.8" env.PATH = "${env.MAVEN_HOME}/bin:${env.PATH}" + + /* + * As of JAVA-3042 JAVA_HOME is always set to JDK8 and this is currently necessary for mvn compile and DSE Search/Graph. + * To facilitate testing with JDK11/17 we feed the appropriate JAVA_HOME into the maven build via commandline. + * + * Maven command-line flags: + * - -DtestJavaHome=/path/to/java/home: overrides JAVA_HOME for surefire/failsafe tests, defaults to environment JAVA_HOME. + * - -Ptest-jdk-N: enables profile for running tests with a specific JDK version (substitute N for 8/11/17). + * + * Note test-jdk-N is also automatically loaded based off JAVA_HOME SDK version so testing with an older SDK is not supported. + * + * Environment variables: + * - JAVA_HOME: Path to JDK used for mvn (all steps except surefire/failsafe), Cassandra, DSE. + * - JAVA8_HOME: Path to JDK8 used for Cassandra/DSE if ccm determines JAVA_HOME is not compatible with the chosen backend. + * - TEST_JAVA_HOME: PATH to JDK used for surefire/failsafe testing. + * - TEST_JAVA_VERSION: TEST_JAVA_HOME SDK version number [8/11/17], used to configure test-jdk-N profile in maven (see above) + */ + env.JAVA_HOME = sh(label: 'Get JAVA_HOME',script: '''#!/bin/bash -le . ${JABBA_SHELL} jabba which ${JABBA_VERSION}''', returnStdout: true).trim() @@ -25,12 +54,40 @@ def initializeEnvironment() { . ${JABBA_SHELL} jabba which 1.8''', returnStdout: true).trim() - sh label: 'Download Apache CassandraⓇ or DataStax Enterprise',script: '''#!/bin/bash -le + sh label: 'Download Apache CassandraⓇ, DataStax Enterprise or DataStax HCD ',script: '''#!/bin/bash -le . ${JABBA_SHELL} - jabba use ${JABBA_VERSION} + jabba use 1.8 . ${CCM_ENVIRONMENT_SHELL} ${SERVER_VERSION} ''' + if (env.SERVER_VERSION.split('-')[0] == 'dse') { + env.DSE_FIXED_VERSION = env.SERVER_VERSION.split('-')[1] + sh label: 'Update environment for DataStax Enterprise', script: '''#!/bin/bash -le + cat >> ${HOME}/environment.txt << ENVIRONMENT_EOF +CCM_CASSANDRA_VERSION=${DSE_FIXED_VERSION} # maintain for backwards compatibility +CCM_VERSION=${DSE_FIXED_VERSION} +CCM_SERVER_TYPE=dse +DSE_VERSION=${DSE_FIXED_VERSION} +CCM_BRANCH=${DSE_FIXED_VERSION} +DSE_BRANCH=${DSE_FIXED_VERSION} +ENVIRONMENT_EOF + ''' + } + + if (env.SERVER_VERSION.split('-')[0] == 'hcd') { + env.HCD_FIXED_VERSION = env.SERVER_VERSION.split('-')[1] + sh label: 'Update environment for DataStax HCD', script: '''#!/bin/bash -le + cat >> ${HOME}/environment.txt << ENVIRONMENT_EOF +CCM_CASSANDRA_VERSION=${HCD_FIXED_VERSION} # maintain for backwards compatibility +CCM_VERSION=${HCD_FIXED_VERSION} +CCM_SERVER_TYPE=hcd +HCD_VERSION=${HCD_FIXED_VERSION} +CCM_BRANCH=${HCD_FIXED_VERSION} +HCD_BRANCH=${HCD_FIXED_VERSION} +ENVIRONMENT_EOF + ''' + } + sh label: 'Display Java and environment information',script: '''#!/bin/bash -le # Load CCM environment variables set -o allexport @@ -38,7 +95,7 @@ def initializeEnvironment() { set +o allexport . ${JABBA_SHELL} - jabba use ${JABBA_VERSION} + jabba use 1.8 java -version mvn -v @@ -47,25 +104,32 @@ def initializeEnvironment() { } def buildDriver(jabbaVersion) { - withEnv(["BUILD_JABBA_VERSION=${jabbaVersion}"]) { - sh label: 'Build driver', script: '''#!/bin/bash -le - . ${JABBA_SHELL} - jabba use ${BUILD_JABBA_VERSION} + def buildDriverScript = '''#!/bin/bash -le - mvn -B -V install -DskipTests -Dmaven.javadoc.skip=true - ''' - } + . ${JABBA_SHELL} + jabba use '''+jabbaVersion+''' + + echo "Building with Java version '''+jabbaVersion+'''" + + mvn -B -V install -DskipTests -Dmaven.javadoc.skip=true + ''' + sh label: 'Build driver', script: buildDriverScript } def executeTests() { - sh label: 'Execute tests', script: '''#!/bin/bash -le + def testJavaHome = sh(label: 'Get TEST_JAVA_HOME',script: '''#!/bin/bash -le + . ${JABBA_SHELL} + jabba which ${JABBA_VERSION}''', returnStdout: true).trim() + def testJavaVersion = (JABBA_VERSION =~ /.*\.(\d+)/)[0][1] + + def executeTestScript = '''#!/bin/bash -le # Load CCM environment variables set -o allexport . ${HOME}/environment.txt set +o allexport . ${JABBA_SHELL} - jabba use ${JABBA_VERSION} + jabba use 1.8 if [ "${JABBA_VERSION}" != "1.8" ]; then SKIP_JAVADOCS=true @@ -79,17 +143,21 @@ def executeTests() { fi printenv | sort - mvn -B -V ${INTEGRATION_TESTS_FILTER_ARGUMENT} verify \ + mvn -B -V ${INTEGRATION_TESTS_FILTER_ARGUMENT} -T 1 verify \ + -Ptest-jdk-'''+testJavaVersion+''' \ + -DtestJavaHome='''+testJavaHome+''' \ -DfailIfNoTests=false \ -Dmaven.test.failure.ignore=true \ -Dmaven.javadoc.skip=${SKIP_JAVADOCS} \ -Dccm.version=${CCM_CASSANDRA_VERSION} \ - -Dccm.dse=${CCM_IS_DSE} \ + -Dccm.distribution=${CCM_SERVER_TYPE:cassandra} \ -Dproxy.path=${HOME}/proxy \ ${SERIAL_ITS_ARGUMENT} \ ${ISOLATED_ITS_ARGUMENT} \ ${PARALLELIZABLE_ITS_ARGUMENT} ''' + echo "Invoking Maven with parameters test-jdk-${testJavaVersion} and testJavaHome = ${testJavaHome}" + sh label: 'Execute tests', script: executeTestScript } def executeCodeCoverage() { @@ -133,25 +201,6 @@ ${status} after ${currentBuild.durationString - ' and counting'}""" } } -def submitCIMetrics(buildType) { - long durationMs = currentBuild.duration - long durationSec = durationMs / 1000 - long nowSec = (currentBuild.startTimeInMillis + durationMs) / 1000 - def branchNameNoPeriods = env.BRANCH_NAME.replaceAll('\\.', '_') - def durationMetric = "okr.ci.java.${env.DRIVER_METRIC_TYPE}.${buildType}.${branchNameNoPeriods} ${durationSec} ${nowSec}" - - timeout(time: 1, unit: 'MINUTES') { - withCredentials([string(credentialsId: 'lab-grafana-address', variable: 'LAB_GRAFANA_ADDRESS'), - string(credentialsId: 'lab-grafana-port', variable: 'LAB_GRAFANA_PORT')]) { - withEnv(["DURATION_METRIC=${durationMetric}"]) { - sh label: 'Send runtime metrics to labgrafana', script: '''#!/bin/bash -le - echo "${DURATION_METRIC}" | nc -q 5 ${LAB_GRAFANA_ADDRESS} ${LAB_GRAFANA_PORT} - ''' - } - } - } -} - def describePerCommitStage() { script { currentBuild.displayName = "Per-Commit build" @@ -175,7 +224,9 @@ def describeAdhocAndScheduledTestingStage() { // branch pattern for cron // should match 3.x, 4.x, 4.5.x, etc -def branchPatternCron = ~"((\\d+(\\.[\\dx]+)+))" +def branchPatternCron() { + ~"((\\d+(\\.[\\dx]+)+))" +} pipeline { agent none @@ -210,18 +261,17 @@ pipeline { ''') choice( name: 'ADHOC_BUILD_AND_EXECUTE_TESTS_SERVER_VERSION', - choices: ['2.1', // Legacy Apache CassandraⓇ - '2.2', // Legacy Apache CassandraⓇ - '3.0', // Previous Apache CassandraⓇ - '3.11', // Current Apache CassandraⓇ - '4.0', // Development Apache CassandraⓇ - 'dse-4.8', // Previous EOSL DataStax Enterprise - 'dse-5.0', // Long Term Support DataStax Enterprise - 'dse-5.1', // Legacy DataStax Enterprise - 'dse-6.0', // Previous DataStax Enterprise - 'dse-6.7', // Previous DataStax Enterprise - 'dse-6.8.0', // Current DataStax Enterprise - 'dse-6.8', // Development DataStax Enterprise + choices: ['4.0', // Previous Apache CassandraⓇ + '4.1', // Previous Apache CassandraⓇ + '5.0', // Current Apache CassandraⓇ + 'dse-4.8.16', // Previous EOSL DataStax Enterprise + 'dse-5.0.15', // Long Term Support DataStax Enterprise + 'dse-5.1.35', // Legacy DataStax Enterprise + 'dse-6.0.18', // Previous DataStax Enterprise + 'dse-6.7.17', // Previous DataStax Enterprise + 'dse-6.8.30', // Current DataStax Enterprise + 'dse-6.9.0', // Current DataStax Enterprise + 'hcd-1.0.0', // Current DataStax HCD 'ALL'], description: '''Apache Cassandra® and DataStax Enterprise server version to use for adhoc BUILD-AND-EXECUTE-TESTS builds @@ -232,63 +282,58 @@ pipeline { - - - - - - - - - - + + - - + + - - + + - + - + - + - + - + - - + + - - + + + + + +
Description
2.1Apache Cassandra® v2.1.x
2.2Apache Cassandra® v2.2.x
3.0Apache Cassandra® v3.0.x4.0Apache Cassandra® v4.0.x
3.11Apache Cassandra® v3.11.x4.1Apache Cassandra® v4.1.x
4.0Apache Cassandra® v4.x (CURRENTLY UNDER DEVELOPMENT)5.0Apache Cassandra® v5.0.x
dse-4.8dse-4.8.16 DataStax Enterprise v4.8.x (END OF SERVICE LIFE)
dse-5.0dse-5.0.15 DataStax Enterprise v5.0.x (Long Term Support)
dse-5.1dse-5.1.35 DataStax Enterprise v5.1.x
dse-6.0dse-6.0.18 DataStax Enterprise v6.0.x
dse-6.7dse-6.7.17 DataStax Enterprise v6.7.x
dse-6.8.0DataStax Enterprise v6.8.0dse-6.8.30DataStax Enterprise v6.8.x
dse-6.8DataStax Enterprise v6.8.x (CURRENTLY UNDER DEVELOPMENT)dse-6.9.0DataStax Enterprise v6.9.x
hcd-1.0.0DataStax HCD v1.0.x
''') choice( name: 'ADHOC_BUILD_AND_EXECUTE_TESTS_JABBA_VERSION', - choices: ['1.8', // Oracle JDK version 1.8 (current default) - 'openjdk@1.9', // OpenJDK version 9 - 'openjdk@1.10', // OpenJDK version 10 + choices: [ + '1.8', // Oracle JDK version 1.8 (current default) 'openjdk@1.11', // OpenJDK version 11 - 'openjdk@1.12', // OpenJDK version 12 - 'openjdk@1.13', // OpenJDK version 13 - 'openjdk@1.14'], // OpenJDK version 14 + 'openjdk@1.17', // OpenJDK version 17 + 'openjdk@1.21' // OpenJDK version 21 + ], description: '''JDK version to use for TESTING when running adhoc BUILD-AND-EXECUTE-TESTS builds. All builds will use JDK8 for building the driver @@ -301,29 +346,17 @@ pipeline { - - - - - - - - - - - - - - + + - - + +
1.8 Oracle JDK version 1.8 (Used for compiling regardless of choice)
openjdk@1.9OpenJDK version 9
openjdk@1.10OpenJDK version 10
openjdk@1.11 OpenJDK version 11
openjdk@1.12OpenJDK version 12
openjdk@1.13OpenJDK version 13openjdk@1.17OpenJDK version 17
openjdk@1.14OpenJDK version 14openjdk@1.21OpenJDK version 21
''') booleanParam( @@ -359,20 +392,17 @@ pipeline { triggers { // schedules only run against release branches (i.e. 3.x, 4.x, 4.5.x, etc.) - parameterizedCron(branchPatternCron.matcher(env.BRANCH_NAME).matches() ? """ - # Every weeknight (Monday - Friday) around 2:00 AM - ### JDK8 tests against 2.1, 3.0, DSE 4.8, DSE 5.0, DSE 5.1, DSE-6.0 and DSE 6.7 - H 2 * * 1-5 %CI_SCHEDULE=WEEKNIGHTS;CI_SCHEDULE_SERVER_VERSIONS=2.1 3.0 dse-4.8 dse-5.0 dse-5.1 dse-6.0 dse-6.7;CI_SCHEDULE_JABBA_VERSION=1.8 - ### JDK11 tests against 3.11, 4.0, DSE 6.7 and DSE 6.8.0 - H 2 * * 1-5 %CI_SCHEDULE=WEEKNIGHTS;CI_SCHEDULE_SERVER_VERSIONS=3.11 4.0 dse-6.7 dse-6.8.0;CI_SCHEDULE_JABBA_VERSION=openjdk@1.11 - # Every weekend (Sunday) around 12:00 PM noon - ### JDK14 tests against 3.11, 4.0, DSE 6.7, DSE 6.8.0 and DSE 6.8.X - H 12 * * 0 %CI_SCHEDULE=WEEKENDS;CI_SCHEDULE_SERVER_VERSIONS=3.11 4.0 dse-6.7 dse-6.8.0 dse-6.8;CI_SCHEDULE_JABBA_VERSION=openjdk@1.14 + parameterizedCron(branchPatternCron().matcher(env.BRANCH_NAME).matches() ? """ + # Every weekend (Saturday, Sunday) around 2:00 AM + H 2 * * 0 %CI_SCHEDULE=WEEKENDS;CI_SCHEDULE_SERVER_VERSIONS=4.0 4.1 5.0 dse-4.8.16 dse-5.0.15 dse-5.1.35 dse-6.0.18 dse-6.7.17;CI_SCHEDULE_JABBA_VERSION=1.8 + # Every weeknight (Monday - Friday) around 12:00 PM noon + H 12 * * 1-5 %CI_SCHEDULE=WEEKNIGHTS;CI_SCHEDULE_SERVER_VERSIONS=4.1 5.0 dse-6.8.30 dse-6.9.0 hcd-1.0.0;CI_SCHEDULE_JABBA_VERSION=openjdk@1.11 + H 12 * * 1-5 %CI_SCHEDULE=WEEKNIGHTS;CI_SCHEDULE_SERVER_VERSIONS=4.1 5.0 dse-6.8.30 dse-6.9.0 hcd-1.0.0;CI_SCHEDULE_JABBA_VERSION=openjdk@1.17 """ : "") } environment { - OS_VERSION = 'ubuntu/bionic64/java-driver' + OS_VERSION = 'ubuntu/focal64/java-driver' JABBA_SHELL = '/usr/lib/jabba/jabba.sh' CCM_ENVIRONMENT_SHELL = '/usr/local/bin/ccm_environment.sh' SERIAL_ITS_ARGUMENT = "-DskipSerialITs=${params.SKIP_SERIAL_ITS}" @@ -401,19 +431,24 @@ pipeline { axes { axis { name 'SERVER_VERSION' - values '3.11', // Latest stable Apache CassandraⓇ - '4.0', // Development Apache CassandraⓇ - 'dse-6.8.0' // Current DataStax Enterprise + values '4.0', // Previous Apache CassandraⓇ + '5.0', // Current Apache CassandraⓇ + 'dse-6.8.30', // Current DataStax Enterprise + 'dse-6.9.0', // Current DataStax Enterprise + 'hcd-1.0.0' // Current DataStax HCD + } + axis { + name 'JABBA_VERSION' + values '1.8', // jdk8 + 'openjdk@1.11', // jdk11 + 'openjdk@1.17', // jdk17 + 'openjdk@1.21' // jdk21 } } agent { label "${OS_VERSION}" } - environment { - // Per-commit builds are only going to run against JDK8 - JABBA_VERSION = '1.8' - } stages { stage('Initialize-Environment') { @@ -433,7 +468,7 @@ pipeline { } stage('Build-Driver') { steps { - buildDriver(env.JABBA_VERSION) + buildDriver('1.8') } } stage('Execute-Tests') { @@ -465,11 +500,6 @@ pipeline { } } post { - always { - node('master') { - submitCIMetrics('commit') - } - } aborted { notifySlack('aborted') } @@ -512,17 +542,17 @@ pipeline { axes { axis { name 'SERVER_VERSION' - values '2.1', // Legacy Apache CassandraⓇ - '3.0', // Previous Apache CassandraⓇ - '3.11', // Current Apache CassandraⓇ - '4.0', // Development Apache CassandraⓇ - 'dse-4.8', // Previous EOSL DataStax Enterprise - 'dse-5.0', // Last EOSL DataStax Enterprise - 'dse-5.1', // Legacy DataStax Enterprise - 'dse-6.0', // Previous DataStax Enterprise - 'dse-6.7', // Previous DataStax Enterprise - 'dse-6.8.0', // Current DataStax Enterprise - 'dse-6.8' // Development DataStax Enterprise + values '4.0', // Previous Apache CassandraⓇ + '4.1', // Previous Apache CassandraⓇ + '5.0', // Current Apache CassandraⓇ + 'dse-4.8.16', // Previous EOSL DataStax Enterprise + 'dse-5.0.15', // Last EOSL DataStax Enterprise + 'dse-5.1.35', // Legacy DataStax Enterprise + 'dse-6.0.18', // Previous DataStax Enterprise + 'dse-6.7.17', // Previous DataStax Enterprise + 'dse-6.8.30', // Current DataStax Enterprise + 'dse-6.9.0', // Current DataStax Enterprise + 'hcd-1.0.0' // Current DataStax HCD } } when { @@ -553,8 +583,7 @@ pipeline { } stage('Build-Driver') { steps { - // Jabba default should be a JDK8 for now - buildDriver('default') + buildDriver('1.8') } } stage('Execute-Tests') { diff --git a/LICENSE b/LICENSE index d6456956733..a157e31d058 100644 --- a/LICENSE +++ b/LICENSE @@ -200,3 +200,24 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +Apache Cassandra Java Driver bundles code and files from the following projects: + +JNR project +Copyright (C) 2008-2010 Wayne Meissner +This product includes software developed as part of the JNR project ( https://github.com/jnr/jnr-ffi )s. +see core/src/main/java/com/datastax/oss/driver/internal/core/os/CpuInfo.java + +Protocol Buffers +Copyright 2008 Google Inc. +This product includes software developed as part of the Protocol Buffers project ( https://developers.google.com/protocol-buffers/ ). +see core/src/main/java/com/datastax/oss/driver/internal/core/type/util/VIntCoding.java + +Guava +Copyright (C) 2007 The Guava Authors +This product includes software developed as part of the Guava project ( https://guava.dev ). +see core/src/main/java/com/datastax/oss/driver/internal/core/util/CountingIterator.java + +Copyright (C) 2018 Christian Stein +This product includes software developed by Christian Stein +see ci/install-jdk.sh diff --git a/LICENSE_binary b/LICENSE_binary new file mode 100644 index 00000000000..b59c6ec22bb --- /dev/null +++ b/LICENSE_binary @@ -0,0 +1,247 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +Apache Cassandra Java Driver bundles code and files from the following projects: + +JNR project +Copyright (C) 2008-2010 Wayne Meissner +This product includes software developed as part of the JNR project ( https://github.com/jnr/jnr-ffi )s. +see core/src/main/java/com/datastax/oss/driver/internal/core/os/CpuInfo.java + +Protocol Buffers +Copyright 2008 Google Inc. +This product includes software developed as part of the Protocol Buffers project ( https://developers.google.com/protocol-buffers/ ). +see core/src/main/java/com/datastax/oss/driver/internal/core/type/util/VIntCoding.java + +Guava +Copyright (C) 2007 The Guava Authors +This product includes software developed as part of the Guava project ( https://guava.dev ). +see core/src/main/java/com/datastax/oss/driver/internal/core/util/CountingIterator.java + +Copyright (C) 2018 Christian Stein +This product includes software developed by Christian Stein +see ci/install-jdk.sh + +This product bundles Java Native Runtime - POSIX 3.1.15, +which is available under the Eclipse Public License version 2.0. +see licenses/jnr-posix.txt + +This product bundles jnr-x86asm 1.0.2, +which is available under the MIT License. +see licenses/jnr-x86asm.txt + +This product bundles ASM 9.2: a very small and fast Java bytecode manipulation framework, +which is available under the 3-Clause BSD License. +see licenses/asm.txt + +This product bundles HdrHistogram 2.1.12: A High Dynamic Range (HDR) Histogram, +which is available under the 2-Clause BSD License. +see licenses/HdrHistogram.txt + +This product bundles The Simple Logging Facade for Java (SLF4J) API 1.7.26, +which is available under the MIT License. +see licenses/slf4j-api.txt + +This product bundles Reactive Streams 1.0.3, +which is available under the MIT License. +see licenses/reactive-streams.txt diff --git a/NOTICE.txt b/NOTICE.txt new file mode 100644 index 00000000000..8e27ae3e52f --- /dev/null +++ b/NOTICE.txt @@ -0,0 +1,5 @@ +Apache Cassandra Java Driver +Copyright 2012- The Apache Software Foundation + +This product includes software developed at The Apache Software +Foundation (http://www.apache.org/). diff --git a/NOTICE_binary.txt b/NOTICE_binary.txt new file mode 100644 index 00000000000..f6f11c298f6 --- /dev/null +++ b/NOTICE_binary.txt @@ -0,0 +1,249 @@ +Apache Cassandra Java Driver +Copyright 2012- The Apache Software Foundation + +This product includes software developed at The Apache Software +Foundation (http://www.apache.org/). + +This compiled product also includes Apache-licensed dependencies +that contain the following NOTICE information: + +================================================================== +io.netty:netty-handler NOTICE.txt +================================================================== +This product contains the extensions to Java Collections Framework which has +been derived from the works by JSR-166 EG, Doug Lea, and Jason T. Greene: + + * LICENSE: + * license/LICENSE.jsr166y.txt (Public Domain) + * HOMEPAGE: + * http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/ + * http://viewvc.jboss.org/cgi-bin/viewvc.cgi/jbosscache/experimental/jsr166/ + +This product contains a modified version of Robert Harder's Public Domain +Base64 Encoder and Decoder, which can be obtained at: + + * LICENSE: + * license/LICENSE.base64.txt (Public Domain) + * HOMEPAGE: + * http://iharder.sourceforge.net/current/java/base64/ + +This product contains a modified portion of 'Webbit', an event based +WebSocket and HTTP server, which can be obtained at: + + * LICENSE: + * license/LICENSE.webbit.txt (BSD License) + * HOMEPAGE: + * https://github.com/joewalnes/webbit + +This product contains a modified portion of 'SLF4J', a simple logging +facade for Java, which can be obtained at: + + * LICENSE: + * license/LICENSE.slf4j.txt (MIT License) + * HOMEPAGE: + * https://www.slf4j.org/ + +This product contains a modified portion of 'Apache Harmony', an open source +Java SE, which can be obtained at: + + * NOTICE: + * license/NOTICE.harmony.txt + * LICENSE: + * license/LICENSE.harmony.txt (Apache License 2.0) + * HOMEPAGE: + * https://archive.apache.org/dist/harmony/ + +This product contains a modified portion of 'jbzip2', a Java bzip2 compression +and decompression library written by Matthew J. Francis. It can be obtained at: + + * LICENSE: + * license/LICENSE.jbzip2.txt (MIT License) + * HOMEPAGE: + * https://code.google.com/p/jbzip2/ + +This product contains a modified portion of 'libdivsufsort', a C API library to construct +the suffix array and the Burrows-Wheeler transformed string for any input string of +a constant-size alphabet written by Yuta Mori. It can be obtained at: + + * LICENSE: + * license/LICENSE.libdivsufsort.txt (MIT License) + * HOMEPAGE: + * https://github.com/y-256/libdivsufsort + +This product contains a modified portion of Nitsan Wakart's 'JCTools', Java Concurrency Tools for the JVM, + which can be obtained at: + + * LICENSE: + * license/LICENSE.jctools.txt (ASL2 License) + * HOMEPAGE: + * https://github.com/JCTools/JCTools + +This product optionally depends on 'JZlib', a re-implementation of zlib in +pure Java, which can be obtained at: + + * LICENSE: + * license/LICENSE.jzlib.txt (BSD style License) + * HOMEPAGE: + * http://www.jcraft.com/jzlib/ + +This product optionally depends on 'Compress-LZF', a Java library for encoding and +decoding data in LZF format, written by Tatu Saloranta. It can be obtained at: + + * LICENSE: + * license/LICENSE.compress-lzf.txt (Apache License 2.0) + * HOMEPAGE: + * https://github.com/ning/compress + +This product optionally depends on 'lz4', a LZ4 Java compression +and decompression library written by Adrien Grand. It can be obtained at: + + * LICENSE: + * license/LICENSE.lz4.txt (Apache License 2.0) + * HOMEPAGE: + * https://github.com/yawkat/lz4-java + +This product optionally depends on 'lzma-java', a LZMA Java compression +and decompression library, which can be obtained at: + + * LICENSE: + * license/LICENSE.lzma-java.txt (Apache License 2.0) + * HOMEPAGE: + * https://github.com/jponge/lzma-java + +This product optionally depends on 'zstd-jni', a zstd-jni Java compression +and decompression library, which can be obtained at: + + * LICENSE: + * license/LICENSE.zstd-jni.txt (Apache License 2.0) + * HOMEPAGE: + * https://github.com/luben/zstd-jni + +This product contains a modified portion of 'jfastlz', a Java port of FastLZ compression +and decompression library written by William Kinney. It can be obtained at: + + * LICENSE: + * license/LICENSE.jfastlz.txt (MIT License) + * HOMEPAGE: + * https://code.google.com/p/jfastlz/ + +This product contains a modified portion of and optionally depends on 'Protocol Buffers', Google's data +interchange format, which can be obtained at: + + * LICENSE: + * license/LICENSE.protobuf.txt (New BSD License) + * HOMEPAGE: + * https://github.com/google/protobuf + +This product optionally depends on 'Bouncy Castle Crypto APIs' to generate +a temporary self-signed X.509 certificate when the JVM does not provide the +equivalent functionality. It can be obtained at: + + * LICENSE: + * license/LICENSE.bouncycastle.txt (MIT License) + * HOMEPAGE: + * https://www.bouncycastle.org/ + +This product optionally depends on 'Snappy', a compression library produced +by Google Inc, which can be obtained at: + + * LICENSE: + * license/LICENSE.snappy.txt (New BSD License) + * HOMEPAGE: + * https://github.com/google/snappy + +This product optionally depends on 'JBoss Marshalling', an alternative Java +serialization API, which can be obtained at: + + * LICENSE: + * license/LICENSE.jboss-marshalling.txt (Apache License 2.0) + * HOMEPAGE: + * https://github.com/jboss-remoting/jboss-marshalling + +This product optionally depends on 'Caliper', Google's micro- +benchmarking framework, which can be obtained at: + + * LICENSE: + * license/LICENSE.caliper.txt (Apache License 2.0) + * HOMEPAGE: + * https://github.com/google/caliper + +This product optionally depends on 'Apache Commons Logging', a logging +framework, which can be obtained at: + + * LICENSE: + * license/LICENSE.commons-logging.txt (Apache License 2.0) + * HOMEPAGE: + * https://commons.apache.org/logging/ + +This product optionally depends on 'Apache Log4J', a logging framework, which +can be obtained at: + + * LICENSE: + * license/LICENSE.log4j.txt (Apache License 2.0) + * HOMEPAGE: + * https://logging.apache.org/log4j/ + +This product optionally depends on 'Aalto XML', an ultra-high performance +non-blocking XML processor, which can be obtained at: + + * LICENSE: + * license/LICENSE.aalto-xml.txt (Apache License 2.0) + * HOMEPAGE: + * https://wiki.fasterxml.com/AaltoHome + +This product contains a modified version of 'HPACK', a Java implementation of +the HTTP/2 HPACK algorithm written by Twitter. It can be obtained at: + + * LICENSE: + * license/LICENSE.hpack.txt (Apache License 2.0) + * HOMEPAGE: + * https://github.com/twitter/hpack + +This product contains a modified version of 'HPACK', a Java implementation of +the HTTP/2 HPACK algorithm written by Cory Benfield. It can be obtained at: + + * LICENSE: + * license/LICENSE.hyper-hpack.txt (MIT License) + * HOMEPAGE: + * https://github.com/python-hyper/hpack/ + +This product contains a modified version of 'HPACK', a Java implementation of +the HTTP/2 HPACK algorithm written by Tatsuhiro Tsujikawa. It can be obtained at: + + * LICENSE: + * license/LICENSE.nghttp2-hpack.txt (MIT License) + * HOMEPAGE: + * https://github.com/nghttp2/nghttp2/ + +This product contains a modified portion of 'Apache Commons Lang', a Java library +provides utilities for the java.lang API, which can be obtained at: + + * LICENSE: + * license/LICENSE.commons-lang.txt (Apache License 2.0) + * HOMEPAGE: + * https://commons.apache.org/proper/commons-lang/ + + +This product contains the Maven wrapper scripts from 'Maven Wrapper', that provides an easy way to ensure a user has everything necessary to run the Maven build. + + * LICENSE: + * license/LICENSE.mvn-wrapper.txt (Apache License 2.0) + * HOMEPAGE: + * https://github.com/takari/maven-wrapper + +This product contains the dnsinfo.h header file, that provides a way to retrieve the system DNS configuration on MacOS. +This private header is also used by Apple's open source + mDNSResponder (https://opensource.apple.com/tarballs/mDNSResponder/). + + * LICENSE: + * license/LICENSE.dnsinfo.txt (Apple Public Source License 2.0) + * HOMEPAGE: + * https://www.opensource.apple.com/source/configd/configd-453.19/dnsinfo/dnsinfo.h + +This product optionally depends on 'Brotli4j', Brotli compression and +decompression for Java., which can be obtained at: + + * LICENSE: + * license/LICENSE.brotli4j.txt (Apache License 2.0) + * HOMEPAGE: + * https://github.com/hyperxpro/Brotli4j diff --git a/README.md b/README.md index fc8427f7f73..d8ef01d0964 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,12 @@ -# Datastax Java Driver for Apache Cassandra® +# Java Driver for Apache Cassandra® -[![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.datastax.oss/java-driver-core/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.datastax.oss/java-driver-core) +[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) +[![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.apache.cassandra/java-driver-core/badge.svg)](https://maven-badges.herokuapp.com/maven-central/org.apache.cassandra/java-driver-core) *If you're reading this on github.com, please note that this is the readme for the development version and that some features described here might not yet have been released. You can find the documentation for latest version through [DataStax Docs] or via the release tags, e.g. -[4.9.0](https://github.com/datastax/java-driver/tree/4.9.0).* +[4.17.0](https://github.com/datastax/java-driver/tree/4.17.0).* A modern, feature-rich and highly tunable Java client library for [Apache Cassandra®] \(2.1+) and [DataStax Enterprise] \(4.7+), and [DataStax Astra], using exclusively Cassandra's binary protocol @@ -13,29 +14,27 @@ and Cassandra Query Language (CQL) v3. [DataStax Docs]: http://docs.datastax.com/en/developer/java-driver/ [Apache Cassandra®]: http://cassandra.apache.org/ -[DataStax Enterprise]: https://www.datastax.com/products/datastax-enterprise -[DataStax Astra]: https://www.datastax.com/products/datastax-astra ## Getting the driver -The driver artifacts are published in Maven central, under the group id [com.datastax.oss]; there +The driver artifacts are published in Maven central, under the group id [org.apache.cassandra]; there are multiple modules, all prefixed with `java-driver-`. ```xml - com.datastax.oss + org.apache.cassandra java-driver-core ${driver.version} - com.datastax.oss + org.apache.cassandra java-driver-query-builder ${driver.version} - com.datastax.oss + org.apache.cassandra java-driver-mapper-runtime ${driver.version} @@ -47,7 +46,7 @@ dependency if you plan to use it. Refer to each module's manual for more details ([core](manual/core/), [query builder](manual/query_builder/), [mapper](manual/mapper)). -[com.datastax.oss]: http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.datastax.oss%22 +[org.apache.cassandra]: http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22org.apache.cassandra%22 ## Compatibility @@ -59,14 +58,9 @@ It requires Java 8 or higher. Disclaimer: Some DataStax/DataStax Enterprise products might partially work on big-endian systems, but DataStax does not officially support these systems. -## Connecting to DataStax Astra - -The driver comes with built-in support for Astra, DataStax's cloud-native Cassandra-as-a-service -offering. See the dedicated [manual page](manual/cloud/) for more details. - ## Migrating from previous versions -Java driver 4 is **not binary compatible** with previous versions. However, most of the concepts +Java Driver 4 is **not binary compatible** with previous versions. However, most of the concepts remain unchanged, and the new API will look very familiar to 2.x and 3.x users. See the [upgrade guide](upgrade_guide/) for details. @@ -77,22 +71,18 @@ See the [upgrade guide](upgrade_guide/) for details. * [API docs] * Bug tracking: [JIRA] * [Mailing list] -* Twitter: [@dsJavaDriver] tweets Java driver releases and important announcements (low frequency). - [@DataStaxEng] has more news, including other drivers, Cassandra, and DSE. * [Changelog] * [FAQ] -[API docs]: https://docs.datastax.com/en/drivers/java/4.9 -[JIRA]: https://datastax-oss.atlassian.net/browse/JAVA +[API docs]: https://docs.datastax.com/en/drivers/java/4.17 +[JIRA]: https://issues.apache.org/jira/issues/?jql=project%20%3D%20CASSJAVA%20ORDER%20BY%20key%20DESC [Mailing list]: https://groups.google.com/a/lists.datastax.com/forum/#!forum/java-driver-user -[@dsJavaDriver]: https://twitter.com/dsJavaDriver -[@DataStaxEng]: https://twitter.com/datastaxeng [Changelog]: changelog/ [FAQ]: faq/ ## License -© DataStax, Inc. +© The Apache Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -108,9 +98,8 @@ limitations under the License. ---- -DataStax is a registered trademark of DataStax, Inc. and its subsidiaries in the United States -and/or other countries. - Apache Cassandra, Apache, Tomcat, Lucene, Solr, Hadoop, Spark, TinkerPop, and Cassandra are trademarks of the [Apache Software Foundation](http://www.apache.org/) or its subsidiaries in Canada, the United States and/or other countries. + +Binary artifacts of this product bundle Java Native Runtime libraries, which is available under the Eclipse Public License version 2.0. diff --git a/bom/pom.xml b/bom/pom.xml index 7ee0bf21874..dd76153a9b1 100644 --- a/bom/pom.xml +++ b/bom/pom.xml @@ -1,13 +1,15 @@ + ## Changelog -### 4.10.0 (in progress) - +### 4.19.2 + +- [bug] CASSJAVA-116: Retry or Speculative Execution with RequestIdGenerator throws "Duplicate Key" + +### 4.19.1 + +- [improvement] CASSJAVA-97: Let users inject an ID for each request and write to the custom payload +- [improvement] CASSJAVA-92: Add Local DC to driver connection info and provide visibility with nodetool clientstats +- [bug] PR 2025: Eliminate lock in ConcurrencyLimitingRequestThrottler +- [improvement] CASSJAVA-89: Fix deprecated table configs in Cassandra 5 +- [improvement] PR 2028: Remove unnecessary locking in DefaultNettyOptions +- [improvement] CASSJAVA-102: Fix revapi spurious complaints about optional dependencies +- [improvement] PR 2013: Add SubnetAddressTranslator +- [improvement] CASSJAVA-68: Improve DefaultCodecRegistry.CacheKey#hashCode() to eliminate Object[] allocation +- [improvement] PR 1989: Bump Jackson version to la(te)st 2.13.x, 2.13.5 +- [improvement] CASSJAVA-76: Make guava an optional dependency of java-driver-guava-shaded +- [bug] PR 2035: Prevent long overflow in SNI address resolution +- [improvement] CASSJAVA-77: 4.x: Upgrade Netty to 4.1.119 +- [improvement] CASSJAVA-40: Driver testing against Java 21 +- [improvement] CASSJAVA-90: Update native-protocol +- [improvement] CASSJAVA-80: Support configuration to disable DNS reverse-lookups for SAN validation + +### 4.19.0 + +- [bug] JAVA-3055: Prevent PreparedStatement cache to be polluted if a request is cancelled. +- [bug] JAVA-3168: Copy node info for contact points on initial node refresh only from first match by endpoint +- [improvement] JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0) +- [improvement] CASSJAVA-53: Update Guava version used in cassandra-java-driver +- [improvement] JAVA-3118: Add support for vector data type in Schema Builder, QueryBuilder +- [bug] CASSJAVA-55: Remove setting "Host" header for metadata requests +- [bug] JAVA-3057: Allow decoding a UDT that has more fields than expected +- [improvement] CASSJAVA-52: Bring java-driver-shaded-guava into the repo as a submodule +- [bug] CASSJAVA-2: TableMetadata#describe produces invalid CQL when a type of a column is a vector +- [bug] JAVA-3051: Memory leak in DefaultLoadBalancingPolicy measurement of response times +- [improvement] CASSJAVA-14: Query builder support for NOT CQL syntax +- [bug] CASSJAVA-12: DefaultSslEngineFactory missing null check on close +- [improvement] CASSJAVA-46: Expose table extensions via schema builders +- [bug] PR 1938: Fix uncaught exception during graceful channel shutdown after exceeding max orphan ids +- [improvement] PR 1607: Annotate BatchStatement, Statement, SimpleStatement methods with CheckReturnValue +- [improvement] CASSJAVA-41: Reduce lock held duration in ConcurrencyLimitingRequestThrottler +- [bug] JAVA-3149: Async Query Cancellation Not Propagated To RequestThrottler +- [bug] JAVA-3167: CompletableFutures.allSuccessful() may return never completed future +- [bug] PR 1620: Don't return empty routing key when partition key is unbound +- [improvement] PR 1623: Limit calls to Conversions.resolveExecutionProfile +- [improvement] CASSJAVA-29: Update target Cassandra versions for integration tests, support new 5.0.x + +### 4.18.1 + +- [improvement] JAVA-3142: Ability to specify ordering of remote local dc's via new configuration for graceful automatic failovers +- [bug] CASSANDRA-19457: Object reference in Micrometer metrics prevent GC from reclaiming Session instances +- [improvement] CASSANDRA-19468: Don't swallow exception during metadata refresh +- [bug] CASSANDRA-19333: Fix data corruption in VectorCodec when using heap buffers +- [improvement] CASSANDRA-19290: Replace uses of AttributeKey.newInstance +- [improvement] CASSANDRA-19352: Support native_transport_(address|port) + native_transport_port_ssl for DSE 6.8 (4.x edition) +- [improvement] CASSANDRA-19180: Support reloading keystore in cassandra-java-driver + +### 4.18.0 + +- [improvement] PR 1689: Add support for publishing percentile time series for the histogram metrics (nparaddi-walmart) +- [improvement] JAVA-3104: Do not eagerly pre-allocate array when deserializing CqlVector +- [improvement] JAVA-3111: upgrade jackson-databind to 2.13.4.2 to address gradle dependency issue +- [improvement] PR 1617: Improve ByteBufPrimitiveCodec readBytes (chibenwa) +- [improvement] JAVA-3095: Fix CREATE keyword in vector search example in upgrade guide +- [improvement] JAVA-3100: Update jackson-databind to 2.13.4.1 and jackson-jaxrs-json-provider to 2.13.4 to address recent CVEs +- [improvement] JAVA-3089: Forbid wildcard imports + +### 4.17.0 + +- [improvement] JAVA-3070: Make CqlVector and CqlDuration serializable +- [improvement] JAVA-3085: Initialize c.d.o.d.i.core.util.Dependency at Graal native image build-time +- [improvement] JAVA-3061: CqlVector API improvements, add support for accessing vectors directly as float arrays +- [improvement] JAVA-3042: Enable automated testing for Java17 +- [improvement] JAVA-3050: Upgrade Netty to 4.1.94 + +### 4.16.0 + +- [improvement] JAVA-3058: Clear prepared statement cache on UDT type change event +- [improvement] JAVA-3060: Add vector type, codec + support for parsing CQL type +- [improvement] DOC-2813: Add error handling guidance linking to a helpful blog post +- [improvement] JAVA-3045: Fix GraalVM native image support for GraalVM 22.2 + +### 4.15.0 + +- [improvement] JAVA-3041: Update Guava session sample code to use ProgrammaticArguments +- [improvement] JAVA-3022: Implement AddressTranslator for AWS PrivateLink +- [bug] JAVA-3021: Update table SchemaBuilder page to replace withPrimaryKey with withPartitionKey +- [bug] JAVA-3005: Node list refresh behavior in 4.x is different from 3.x +- [bug] JAVA-3002: spring-boot app keeps connecting to IP of replaced node +- [improvement] JAVA-3023 Upgrade Netty to 4.1.77 +- [improvement] JAVA-2995: CodecNotFoundException doesn't extend DriverException + +### 4.14.1 + +- [improvement] JAVA-3013: Upgrade dependencies to address CVEs and other security issues, 4.14.1 edition +- [improvement] JAVA-2977: Update Netty to resolve higher-priority CVEs +- [improvement] JAVA-3003: Update jnr-posix to address CVE-2014-4043 + +### 4.14.0 + +- [bug] JAVA-2976: Support missing protocol v5 error codes CAS_WRITE_UNKNOWN, CDC_WRITE_FAILURE +- [bug] JAVA-2987: BasicLoadBalancingPolicy remote computation assumes local DC is up and live +- [bug] JAVA-2992: Include options into DefaultTableMetadata equals and hash methods +- [improvement] JAVA-2982: Switch Esri geometry lib to an optional dependency +- [improvement] JAVA-2959: Don't throw NoNodeAvailableException when all connections busy + +### 4.13.0 + +- [improvement] JAVA-2940: Add GraalVM native image build configurations +- [improvement] JAVA-2953: Promote ProgrammaticPlainTextAuthProvider to the public API and add + credentials hot-reload +- [improvement] JAVA-2951: Accept multiple node state listeners, schema change listeners and request + trackers + +Merged from 4.12.x: + +- [bug] JAVA-2949: Provide mapper support for CompletionStage> +- [bug] JAVA-2950: Remove reference to Reflection class from DependencyCheck + +### 4.12.1 + +Merged from 4.11.x: + +- [bug] JAVA-2949: Provide mapper support for CompletionStage> +- [bug] JAVA-2950: Remove reference to Reflection class from DependencyCheck + +### 4.12.0 + +- [improvement] JAVA-2935: Make GetEntity and SetEntity methods resilient to incomplete data +- [improvement] JAVA-2944: Upgrade MicroProfile Metrics to 3.0 + +Merged from 4.11.x: + +- [bug] JAVA-2932: Make DefaultDriverConfigLoader.close() resilient to terminated executors +- [bug] JAVA-2945: Reinstate InternalDriverContext.getNodeFilter method +- [bug] JAVA-2947: Release buffer after decoding multi-slice frame +- [bug] JAVA-2946: Make MapperResultProducerService instances be located with user-provided class loader +- [bug] JAVA-2942: GraphStatement.setConsistencyLevel() is not effective +- [bug] JAVA-2941: Cannot add a single static column with the alter table API +- [bug] JAVA-2943: Prevent session leak with wrong keyspace name +- [bug] JAVA-2938: OverloadedException message is misleading + +### 4.11.3 + +- [bug] JAVA-2949: Provide mapper support for CompletionStage> +- [bug] JAVA-2950: Remove reference to Reflection class from DependencyCheck + +### 4.11.2 + +- [bug] JAVA-2932: Make DefaultDriverConfigLoader.close() resilient to terminated executors +- [bug] JAVA-2945: Reinstate InternalDriverContext.getNodeFilter method +- [bug] JAVA-2947: Release buffer after decoding multi-slice frame +- [bug] JAVA-2946: Make MapperResultProducerService instances be located with user-provided class loader +- [bug] JAVA-2942: GraphStatement.setConsistencyLevel() is not effective +- [bug] JAVA-2941: Cannot add a single static column with the alter table API +- [bug] JAVA-2943: Prevent session leak with wrong keyspace name +- [bug] JAVA-2938: OverloadedException message is misleading + +### 4.11.1 + +- [bug] JAVA-2910: Add a configuration option to support strong values for prepared statements cache +- [bug] JAVA-2936: Support Protocol V6 +- [bug] JAVA-2934: Handle empty non-final pages in ReactiveResultSetSubscription + +### 4.11.0 + +- [improvement] JAVA-2930: Allow Micrometer to record histograms for timers +- [improvement] JAVA-2914: Transform node filter into a more flexible node distance evaluator +- [improvement] JAVA-2929: Revisit node-level metric eviction +- [new feature] JAVA-2830: Add mapper support for Java streams +- [bug] JAVA-2928: Generate counter increment/decrement constructs compatible with legacy C* + versions +- [new feature] JAVA-2872: Ability to customize metric names and tags +- [bug] JAVA-2925: Consider protocol version unsupported when server requires USE_BETA flag for it +- [improvement] JAVA-2704: Remove protocol v5 beta status, add v6-beta +- [improvement] JAVA-2916: Annotate generated classes with `@SuppressWarnings` +- [bug] JAVA-2927: Make Dropwizard truly optional +- [improvement] JAVA-2917: Include GraalVM substitutions for request processors and geo codecs +- [bug] JAVA-2918: Exclude invalid peers from schema agreement checks + +### 4.10.0 + +- [improvement] JAVA-2907: Switch Tinkerpop to an optional dependency +- [improvement] JAVA-2904: Upgrade Jackson to 2.12.0 and Tinkerpop to 3.4.9 +- [bug] JAVA-2911: Prevent control connection from scheduling too many reconnections +- [bug] JAVA-2902: Consider computed values when validating constructors for immutable entities +- [new feature] JAVA-2899: Re-introduce cross-DC failover in driver 4 +- [new feature] JAVA-2900: Re-introduce consistency downgrading retries +- [new feature] JAVA-2903: BlockHound integration +- [improvement] JAVA-2877: Allow skipping validation for individual mapped entities +- [improvement] JAVA-2871: Allow keyspace exclusions in the metadata, and exclude system keyspaces + by default +- [improvement] JAVA-2449: Use non-cryptographic random number generation in Uuids.random() +- [improvement] JAVA-2893: Allow duplicate keys in DefaultProgrammaticDriverConfigLoaderBuilder +- [documentation] JAVA-2894: Clarify usage of Statement.setQueryTimestamp +- [bug] JAVA-2889: Remove TypeSafe imports from DriverConfigLoader +- [bug] JAVA-2883: Use root locale explicitly when changing string case +- [bug] JAVA-2890: Fix off-by-one error in UdtCodec +- [improvement] JAVA-2905: Prevent new connections from using a protocol version higher than the negotiated one +- [bug] JAVA-2647: Handle token types in QueryBuilder.literal() +- [bug] JAVA-2887: Handle composite profiles with more than one key and/or backed by only one profile ### 4.9.0 @@ -500,28 +717,58 @@ changelog](https://docs.datastax.com/en/developer/java-driver-dse/latest/changel - [bug] JAVA-1499: Wait for load balancing policy at cluster initialization - [new feature] JAVA-1495: Add prepared statements -## 3.10.2 +## 3.11.5 +- [improvement] JAVA-3114: Shade io.dropwizard.metrics:metrics-core in shaded driver +- [improvement] JAVA-3115: SchemaChangeListener#onKeyspaceChanged can fire when keyspace has not changed if using SimpleStrategy replication + +## 3.11.4 +- [improvement] JAVA-3079: Upgrade Netty to 4.1.94, 3.x edition +- [improvement] JAVA-3082: Fix maven build for Apple-silicon +- [improvement] PR 1671: Fix LatencyAwarePolicy scale docstring + +## 3.11.3 + +- [improvement] JAVA-3023: Upgrade Netty to 4.1.77, 3.x edition + +## 3.11.2 + +- [improvement] JAVA-3008: Upgrade Netty to 4.1.75, 3.x edition +- [improvement] JAVA-2984: Upgrade Jackson to resolve high-priority CVEs + +## 3.11.1 + +- [bug] JAVA-2967: Support native transport peer information for DSE 6.8. +- [bug] JAVA-2976: Support missing protocol v5 error codes CAS_WRITE_UNKNOWN, CDC_WRITE_FAILURE. + +## 3.11.0 + +- [improvement] JAVA-2705: Remove protocol v5 beta status, add v6-beta. +- [bug] JAVA-2923: Detect and use Guava's new HostAndPort.getHost method. +- [bug] JAVA-2922: Switch to modern framing format inside a channel handler. +- [bug] JAVA-2924: Consider protocol version unsupported when server requires USE_BETA flag for it. + +### 3.10.2 - [bug] JAVA-2860: Avoid NPE if channel initialization crashes. -## 3.10.1 +### 3.10.1 - [bug] JAVA-2857: Fix NPE when built statements without parameters are logged at TRACE level. - [bug] JAVA-2843: Successfully parse DSE table schema in OSS driver. -## 3.10.0 +### 3.10.0 - [improvement] JAVA-2676: Don't reschedule flusher after empty runs - [new feature] JAVA-2772: Support new protocol v5 message format -## 3.9.0 +### 3.9.0 - [bug] JAVA-2627: Avoid logging error message including stack trace in request handler. - [new feature] JAVA-2706: Add now_in_seconds to protocol v5 query messages. - [improvement] JAVA-2730: Add support for Cassandra® 4.0 table options - [improvement] JAVA-2702: Transient Replication Support for Cassandra® 4.0 -## 3.8.0 +### 3.8.0 - [new feature] JAVA-2356: Support for DataStax Cloud API. - [improvement] JAVA-2483: Allow to provide secure bundle via URL. diff --git a/ci/create-user.sh b/ci/create-user.sh new file mode 100644 index 00000000000..fb193df9a00 --- /dev/null +++ b/ci/create-user.sh @@ -0,0 +1,60 @@ +#!/bin/bash +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +################################ +# +# Prep +# +################################ + +if [ "$1" == "-h" ]; then + echo "$0 [-h] " + echo " this script is used internally by other scripts in the same directory to create a user with the running host user's same uid and gid" + exit 1 +fi + +# arguments +username=$1 +uid=$2 +gid=$3 +BUILD_HOME=$4 + +################################ +# +# Main +# +################################ + +# disable git directory ownership checks +su ${username} -c "git config --global safe.directory '*'" + +if grep "^ID=" /etc/os-release | grep -q 'debian\|ubuntu' ; then + deluser docker + adduser --quiet --disabled-login --no-create-home --uid $uid --gecos ${username} ${username} + groupmod --non-unique -g $gid $username + gpasswd -a ${username} sudo >/dev/null +else + adduser --no-create-home --uid $uid ${username} +fi + +# sudo priviledges +echo "${username} ALL=(root) NOPASSWD:ALL" > /etc/sudoers.d/${username} +chmod 0440 /etc/sudoers.d/${username} + +# proper permissions +chown -R ${username}:${username} /home/docker +chmod og+wx ${BUILD_HOME} \ No newline at end of file diff --git a/ci/run-tests.sh b/ci/run-tests.sh new file mode 100755 index 00000000000..5268bdd7113 --- /dev/null +++ b/ci/run-tests.sh @@ -0,0 +1,12 @@ +#!/bin/bash -x + +. ~/.jabba/jabba.sh +. ~/env.txt +cd $(dirname "$(readlink -f "$0")")/.. +printenv | sort +mvn -B -V install -DskipTests -Dmaven.javadoc.skip=true +jabba use ${TEST_JAVA_VERSION} +# Find out the latest patch version of Cassandra +PATCH_SERVER_VERSION=$(curl -s https://downloads.apache.org/cassandra/ | grep -oP '(?<=href=\")[0-9]+\.[0-9]+\.[0-9]+(?=)' | sort -rV | uniq -w 3 | grep $SERVER_VERSION) +printenv | sort +mvn -B -V verify -T 1 -Ptest-jdk-${TEST_JAVA_MAJOR_VERSION} -DtestJavaHome=$(jabba which ${TEST_JAVA_VERSION}) -Dccm.version=${PATCH_SERVER_VERSION} -Dccm.dse=false -Dmaven.test.failure.ignore=true -Dmaven.javadoc.skip=true diff --git a/core-shaded/pom.xml b/core-shaded/pom.xml index 4d92a37736f..84cb4b15398 100644 --- a/core-shaded/pom.xml +++ b/core-shaded/pom.xml @@ -1,13 +1,15 @@ - com.datastax.oss + org.apache.cassandra java-driver-core + + + src/main/resources + + + ${project.basedir}/.. + + LICENSE + NOTICE_binary.txt + NOTICE.txt + + META-INF + + maven-shade-plugin @@ -137,31 +162,20 @@ - The core driver itself; it is not relocated but needs to be included. - All the dependencies we want to shade & relocate. --> - com.datastax.oss:java-driver-core + org.apache.cassandra:java-driver-core io.netty:* - com.esri.geometry:* - org.json:* - org.codehaus.jackson:* com.fasterxml.jackson.core:* + io.netty com.datastax.oss.driver.shaded.netty - - com.esri - com.datastax.oss.driver.shaded.esri - - - org.json - com.datastax.oss.driver.shaded.json - - - org.codehaus.jackson - com.datastax.oss.driver.shaded.codehaus.jackson - com.fasterxml.jackson com.datastax.oss.driver.shaded.fasterxml.jackson @@ -170,9 +184,11 @@ - com.datastax.oss:* + org.apache.cassandra:* - META-INF/** + + META-INF/MANIFEST.MF + META-INF/maven/** @@ -181,24 +197,6 @@ META-INF/** - - com.esri.geometry:* - - META-INF/** - - - - org.json:* - - META-INF/** - - - - org.codehaus.jackson:* - - META-INF/** - - com.fasterxml.jackson.core:* @@ -222,7 +220,7 @@ - com.datastax.oss + org.apache.cassandra java-driver-core-shaded jar ${project.build.outputDirectory} @@ -240,7 +238,7 @@ - com.datastax.oss + org.apache.cassandra java-driver-core-shaded jar sources @@ -251,32 +249,30 @@ + - maven-javadoc-plugin + com.google.code.maven-replacer-plugin + replacer + 1.5.3 - attach-javadocs + shade-graalvm-files + package - jar + replace - - ${project.build.directory}/shaded-sources - com.datastax.*.driver.internal*,com.datastax.oss.driver.shaded* - - - - org.jctools - jctools-core - 2.1.2 - - - + + false + ${project.build.directory}/classes/META-INF/native-image/com.datastax.oss/java-driver-core/reflection.json,${project.build.directory}/shaded-sources/META-INF/native-image/com.datastax.oss/java-driver-core/reflection.json + + + io.netty + com.datastax.oss.driver.shaded.netty + + + org.apache.felix @@ -302,7 +298,7 @@ !com.datastax.oss.driver.shaded.netty.*, !com.datastax.oss.driver.shaded.esri.*, !com.datastax.oss.driver.shaded.json.*, !com.datastax.oss.driver.shaded.codehaus.jackson.*, !com.datastax.oss.driver.shaded.fasterxml.jackson.*, + -->!com.datastax.oss.driver.shaded.netty.*, !com.datastax.oss.driver.shaded.fasterxml.jackson.*, jnr.*;resolution:=optional, com.esri.core.geometry.*;resolution:=optional,org.reactivestreams.*;resolution:=optional, org.apache.tinkerpop.*;resolution:=optional, org.javatuples.*;resolution:=optional, + -->jnr.*;resolution:=optional, com.esri.core.geometry.*;resolution:=optional,org.reactivestreams.*;resolution:=optional, org.apache.tinkerpop.*;resolution:=optional, org.javatuples.*;resolution:=optional, reactor.blockhound.*;resolution:=optional, !com.google.protobuf.*, !com.jcraft.jzlib.*, !com.ning.compress.*, !lzma.sdk.*, !net.jpountz.xxhash.*, !org.bouncycastle.*, !org.conscrypt.*, !org.apache.commons.logging.*, !org.apache.log4j.*, !org.apache.logging.log4j.*, !org.eclipse.jetty.*, !org.jboss.marshalling.*, !sun.misc.*, !sun.security.*, !com.barchart.udt.*, !com.fasterxml.aalto.*, !com.sun.nio.sctp.*, !gnu.io.*, !org.xml.sax.*, !org.w3c.dom.*, !reactor.blockhound.*, * + -->!com.google.protobuf.*, !com.jcraft.jzlib.*, !com.ning.compress.*, !lzma.sdk.*, !net.jpountz.xxhash.*, !org.bouncycastle.*, !org.conscrypt.*, !org.apache.commons.logging.*, !org.apache.log4j.*, !org.apache.logging.log4j.*, !org.eclipse.jetty.*, !org.jboss.marshalling.*, !sun.misc.*, !sun.security.*, !com.barchart.udt.*, !com.fasterxml.aalto.*, !com.sun.nio.sctp.*, !gnu.io.*, !org.xml.sax.*, !org.w3c.dom.*, !com.aayushatharva.brotli4j.*, !com.github.luben.zstd.*, * - com.datastax.oss.driver.api.core.*, com.datastax.oss.driver.internal.core.*, com.datastax.dse.driver.api.core.*, com.datastax.dse.driver.internal.core.*, com.datastax.oss.driver.shaded.netty.*, com.datastax.oss.driver.shaded.esri.*, com.datastax.oss.driver.shaded.json.*, com.datastax.oss.driver.shaded.codehaus.jackson.*, com.datastax.oss.driver.shaded.fasterxml.jackson.*, + com.datastax.oss.driver.api.core.*, com.datastax.oss.driver.internal.core.*, com.datastax.dse.driver.api.core.*, com.datastax.dse.driver.internal.core.*, com.datastax.oss.driver.shaded.netty.*, com.datastax.oss.driver.shaded.fasterxml.jackson.*, true diff --git a/core-shaded/src/assembly/shaded-jar.xml b/core-shaded/src/assembly/shaded-jar.xml index a7fffda6b65..449eb77bd1a 100644 --- a/core-shaded/src/assembly/shaded-jar.xml +++ b/core-shaded/src/assembly/shaded-jar.xml @@ -1,13 +1,15 @@ jnr.*;resolution:=optional, com.esri.core.geometry.*;resolution:=optional, org.reactivestreams.*;resolution:=optional, org.apache.tinkerpop.*;resolution:=optional, org.javatuples.*;resolution:=optional, * + -->jnr.*;resolution:=optional, com.esri.core.geometry.*;resolution:=optional, org.reactivestreams.*;resolution:=optional, org.apache.tinkerpop.*;resolution:=optional, org.javatuples.*;resolution:=optional, reactor.blockhound.*;resolution:=optional, * com.datastax.oss.driver.*.core.*, com.datastax.dse.driver.*.core.* diff --git a/core/revapi.json b/core/revapi.json index b42dd7ca74f..8c707659c13 100644 --- a/core/revapi.json +++ b/core/revapi.json @@ -1,5 +1,3 @@ -// Configures Revapi (https://revapi.org/getting-started.html) to check API compatibility between -// successive driver versions. { "revapi": { "java": { @@ -5028,8 +5026,2392 @@ }, { "code": "java.class.nonPublicPartOfAPI", - "new": "class com.fasterxml.jackson.databind.util.PrimitiveArrayBuilder.Node", + "new": "class com.fasterxml.jackson.databind.util.PrimitiveArrayBuilder.Node", "justification": "Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.field.enumConstantOrderChanged", + "old": "field com.fasterxml.jackson.annotation.JsonTypeInfo.Id.CUSTOM", + "new": "field com.fasterxml.jackson.annotation.JsonTypeInfo.Id.CUSTOM", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.field.serialVersionUIDUnchanged", + "old": "field com.fasterxml.jackson.core.Base64Variant.serialVersionUID", + "new": "field com.fasterxml.jackson.core.Base64Variant.serialVersionUID", + "serialVersionUID": "1", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.class.nonFinalClassInheritsFromNewClass", + "old": "class com.fasterxml.jackson.core.JsonGenerationException", + "new": "class com.fasterxml.jackson.core.JsonGenerationException", + "superClass": "com.fasterxml.jackson.core.JacksonException", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.class.nonFinalClassInheritsFromNewClass", + "old": "class com.fasterxml.jackson.core.JsonParseException", + "new": "class com.fasterxml.jackson.core.JsonParseException", + "superClass": "com.fasterxml.jackson.core.JacksonException", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.class.nonFinalClassInheritsFromNewClass", + "old": "class com.fasterxml.jackson.core.JsonProcessingException", + "new": "class com.fasterxml.jackson.core.JsonProcessingException", + "superClass": "com.fasterxml.jackson.core.JacksonException", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.class.nonPublicPartOfAPI", + "old": "class com.fasterxml.jackson.core.sym.ByteQuadsCanonicalizer.TableInfo", + "new": "class com.fasterxml.jackson.core.sym.ByteQuadsCanonicalizer.TableInfo", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.class.nonPublicPartOfAPI", + "old": "class com.fasterxml.jackson.core.sym.CharsToNameCanonicalizer.Bucket", + "new": "class com.fasterxml.jackson.core.sym.CharsToNameCanonicalizer.Bucket", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.class.nonPublicPartOfAPI", + "old": "class com.fasterxml.jackson.core.sym.CharsToNameCanonicalizer.TableInfo", + "new": "class com.fasterxml.jackson.core.sym.CharsToNameCanonicalizer.TableInfo", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.method.removed", + "old": "method java.lang.String[] com.fasterxml.jackson.databind.AnnotationIntrospector::findPropertiesToIgnore(com.fasterxml.jackson.databind.introspect.Annotated)", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.class.defaultSerializationChanged", + "old": "class com.fasterxml.jackson.databind.AnnotationIntrospector", + "new": "class com.fasterxml.jackson.databind.AnnotationIntrospector", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.field.serialVersionUIDUnchanged", + "old": "field com.fasterxml.jackson.databind.DeserializationConfig.serialVersionUID", + "new": "field com.fasterxml.jackson.databind.DeserializationConfig.serialVersionUID", + "serialVersionUID": "2", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.method.returnTypeChanged", + "old": "method void com.fasterxml.jackson.databind.DeserializationConfig::initialize(com.fasterxml.jackson.core.JsonParser)", + "new": "method com.fasterxml.jackson.core.JsonParser com.fasterxml.jackson.databind.DeserializationConfig::initialize(com.fasterxml.jackson.core.JsonParser)", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.method.returnTypeTypeParametersChanged", + "old": "method T com.fasterxml.jackson.databind.DeserializationConfig::introspect(com.fasterxml.jackson.databind.JavaType)", + "new": "method com.fasterxml.jackson.databind.BeanDescription com.fasterxml.jackson.databind.DeserializationConfig::introspect(com.fasterxml.jackson.databind.JavaType)", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.generics.formalTypeParameterRemoved", + "old": "method T com.fasterxml.jackson.databind.DeserializationConfig::introspect(com.fasterxml.jackson.databind.JavaType)", + "new": "method com.fasterxml.jackson.databind.BeanDescription com.fasterxml.jackson.databind.DeserializationConfig::introspect(com.fasterxml.jackson.databind.JavaType)", + "typeParameter": "T extends com.fasterxml.jackson.databind.BeanDescription", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.method.returnTypeTypeParametersChanged", + "old": "method T com.fasterxml.jackson.databind.DeserializationConfig::introspectForBuilder(com.fasterxml.jackson.databind.JavaType)", + "new": "method com.fasterxml.jackson.databind.BeanDescription com.fasterxml.jackson.databind.DeserializationConfig::introspectForBuilder(com.fasterxml.jackson.databind.JavaType)", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.generics.formalTypeParameterRemoved", + "old": "method T com.fasterxml.jackson.databind.DeserializationConfig::introspectForBuilder(com.fasterxml.jackson.databind.JavaType)", + "new": "method com.fasterxml.jackson.databind.BeanDescription com.fasterxml.jackson.databind.DeserializationConfig::introspectForBuilder(com.fasterxml.jackson.databind.JavaType)", + "typeParameter": "T extends com.fasterxml.jackson.databind.BeanDescription", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.method.returnTypeTypeParametersChanged", + "old": "method T com.fasterxml.jackson.databind.DeserializationConfig::introspectForCreation(com.fasterxml.jackson.databind.JavaType)", + "new": "method com.fasterxml.jackson.databind.BeanDescription com.fasterxml.jackson.databind.DeserializationConfig::introspectForCreation(com.fasterxml.jackson.databind.JavaType)", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.generics.formalTypeParameterRemoved", + "old": "method T com.fasterxml.jackson.databind.DeserializationConfig::introspectForCreation(com.fasterxml.jackson.databind.JavaType)", + "new": "method com.fasterxml.jackson.databind.BeanDescription com.fasterxml.jackson.databind.DeserializationConfig::introspectForCreation(com.fasterxml.jackson.databind.JavaType)", + "typeParameter": "T extends com.fasterxml.jackson.databind.BeanDescription", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.field.serialVersionUIDUnchanged", + "old": "field com.fasterxml.jackson.databind.DeserializationContext.serialVersionUID", + "new": "field com.fasterxml.jackson.databind.DeserializationContext.serialVersionUID", + "serialVersionUID": "1", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.method.finalMethodAddedToNonFinalClass", + "new": "method boolean com.fasterxml.jackson.databind.DeserializationContext::isEnabled(com.fasterxml.jackson.core.StreamReadCapability)", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.method.finalMethodAddedToNonFinalClass", + "new": "method boolean com.fasterxml.jackson.databind.JavaType::isRecordType()", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.class.nonFinalClassInheritsFromNewClass", + "old": "class com.fasterxml.jackson.databind.JsonMappingException", + "new": "class com.fasterxml.jackson.databind.JsonMappingException", + "superClass": "com.fasterxml.jackson.core.JacksonException", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.field.enumConstantOrderChanged", + "old": "field com.fasterxml.jackson.databind.MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS", + "new": "field com.fasterxml.jackson.databind.MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.field.enumConstantOrderChanged", + "old": "field com.fasterxml.jackson.databind.MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES", + "new": "field com.fasterxml.jackson.databind.MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.field.enumConstantOrderChanged", + "old": "field com.fasterxml.jackson.databind.MapperFeature.ACCEPT_CASE_INSENSITIVE_VALUES", + "new": "field com.fasterxml.jackson.databind.MapperFeature.ACCEPT_CASE_INSENSITIVE_VALUES", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.field.enumConstantOrderChanged", + "old": "field com.fasterxml.jackson.databind.MapperFeature.ALLOW_COERCION_OF_SCALARS", + "new": "field com.fasterxml.jackson.databind.MapperFeature.ALLOW_COERCION_OF_SCALARS", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.field.enumConstantOrderChanged", + "old": "field com.fasterxml.jackson.databind.MapperFeature.ALLOW_EXPLICIT_PROPERTY_RENAMING", + "new": "field com.fasterxml.jackson.databind.MapperFeature.ALLOW_EXPLICIT_PROPERTY_RENAMING", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.field.enumConstantOrderChanged", + "old": "field com.fasterxml.jackson.databind.MapperFeature.BLOCK_UNSAFE_POLYMORPHIC_BASE_TYPES", + "new": "field com.fasterxml.jackson.databind.MapperFeature.BLOCK_UNSAFE_POLYMORPHIC_BASE_TYPES", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.field.enumConstantOrderChanged", + "old": "field com.fasterxml.jackson.databind.MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS", + "new": "field com.fasterxml.jackson.databind.MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.field.enumConstantOrderChanged", + "old": "field com.fasterxml.jackson.databind.MapperFeature.DEFAULT_VIEW_INCLUSION", + "new": "field com.fasterxml.jackson.databind.MapperFeature.DEFAULT_VIEW_INCLUSION", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.field.enumConstantOrderChanged", + "old": "field com.fasterxml.jackson.databind.MapperFeature.IGNORE_DUPLICATE_MODULE_REGISTRATIONS", + "new": "field com.fasterxml.jackson.databind.MapperFeature.IGNORE_DUPLICATE_MODULE_REGISTRATIONS", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.field.enumConstantOrderChanged", + "old": "field com.fasterxml.jackson.databind.MapperFeature.IGNORE_MERGE_FOR_UNMERGEABLE", + "new": "field com.fasterxml.jackson.databind.MapperFeature.IGNORE_MERGE_FOR_UNMERGEABLE", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.field.enumConstantOrderChanged", + "old": "field com.fasterxml.jackson.databind.MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS", + "new": "field com.fasterxml.jackson.databind.MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.field.enumConstantOrderChanged", + "old": "field com.fasterxml.jackson.databind.MapperFeature.SORT_PROPERTIES_ALPHABETICALLY", + "new": "field com.fasterxml.jackson.databind.MapperFeature.SORT_PROPERTIES_ALPHABETICALLY", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.field.enumConstantOrderChanged", + "old": "field com.fasterxml.jackson.databind.MapperFeature.USE_BASE_TYPE_AS_DEFAULT_IMPL", + "new": "field com.fasterxml.jackson.databind.MapperFeature.USE_BASE_TYPE_AS_DEFAULT_IMPL", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.field.enumConstantOrderChanged", + "old": "field com.fasterxml.jackson.databind.MapperFeature.USE_STATIC_TYPING", + "new": "field com.fasterxml.jackson.databind.MapperFeature.USE_STATIC_TYPING", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.field.enumConstantOrderChanged", + "old": "field com.fasterxml.jackson.databind.MapperFeature.USE_STD_BEAN_NAMING", + "new": "field com.fasterxml.jackson.databind.MapperFeature.USE_STD_BEAN_NAMING", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.field.enumConstantOrderChanged", + "old": "field com.fasterxml.jackson.databind.MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME", + "new": "field com.fasterxml.jackson.databind.MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.field.serialVersionUIDUnchanged", + "old": "field com.fasterxml.jackson.databind.ObjectMapper.serialVersionUID", + "new": "field com.fasterxml.jackson.databind.ObjectMapper.serialVersionUID", + "serialVersionUID": "2", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.method.removed", + "old": "method java.lang.Object com.fasterxml.jackson.databind.ObjectMapper::_unwrapAndDeserialize(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext, com.fasterxml.jackson.databind.DeserializationConfig, com.fasterxml.jackson.databind.JavaType, com.fasterxml.jackson.databind.JsonDeserializer) throws java.io.IOException", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.method.finalMethodAddedToNonFinalClass", + "new": "method void com.fasterxml.jackson.databind.ObjectMapper::_writeValueAndClose(com.fasterxml.jackson.core.JsonGenerator, java.lang.Object) throws java.io.IOException", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.method.exception.runtimeAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::treeToValue(com.fasterxml.jackson.core.TreeNode, java.lang.Class) throws com.fasterxml.jackson.core.JsonProcessingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::treeToValue(com.fasterxml.jackson.core.TreeNode, java.lang.Class) throws java.lang.IllegalArgumentException, com.fasterxml.jackson.core.JsonProcessingException", + "exception": "java.lang.IllegalArgumentException", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.method.removed", + "old": "method java.lang.Object com.fasterxml.jackson.databind.ObjectReader::_unwrapAndDeserialize(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext, com.fasterxml.jackson.databind.JavaType, com.fasterxml.jackson.databind.JsonDeserializer) throws java.io.IOException", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.method.removed", + "old": "method void com.fasterxml.jackson.databind.ObjectWriter::_configAndWriteValue(com.fasterxml.jackson.core.JsonGenerator, java.lang.Object) throws java.io.IOException", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.method.returnTypeChanged", + "old": "method void com.fasterxml.jackson.databind.ObjectWriter::_configureGenerator(com.fasterxml.jackson.core.JsonGenerator)", + "new": "method com.fasterxml.jackson.core.JsonGenerator com.fasterxml.jackson.databind.ObjectWriter::_configureGenerator(com.fasterxml.jackson.core.JsonGenerator)", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.method.finalMethodAddedToNonFinalClass", + "new": "method void com.fasterxml.jackson.databind.ObjectWriter::_writeValueAndClose(com.fasterxml.jackson.core.JsonGenerator, java.lang.Object) throws java.io.IOException", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.field.serialVersionUIDChanged", + "new": "field com.fasterxml.jackson.databind.PropertyNamingStrategy.serialVersionUID", + "oldSerialVersionUID": "-5237220944964015475", + "newSerialVersionUID": "2", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.method.returnTypeTypeParametersChanged", + "old": "method T com.fasterxml.jackson.databind.SerializationConfig::introspect(com.fasterxml.jackson.databind.JavaType)", + "new": "method com.fasterxml.jackson.databind.BeanDescription com.fasterxml.jackson.databind.SerializationConfig::introspect(com.fasterxml.jackson.databind.JavaType)", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.generics.formalTypeParameterRemoved", + "old": "method T com.fasterxml.jackson.databind.SerializationConfig::introspect(com.fasterxml.jackson.databind.JavaType)", + "new": "method com.fasterxml.jackson.databind.BeanDescription com.fasterxml.jackson.databind.SerializationConfig::introspect(com.fasterxml.jackson.databind.JavaType)", + "typeParameter": "T extends com.fasterxml.jackson.databind.BeanDescription", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.field.serialVersionUIDUnchanged", + "old": "field com.fasterxml.jackson.databind.cfg.BaseSettings.serialVersionUID", + "new": "field com.fasterxml.jackson.databind.cfg.BaseSettings.serialVersionUID", + "serialVersionUID": "1", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.method.numberOfParametersChanged", + "old": "method void com.fasterxml.jackson.databind.cfg.BaseSettings::(com.fasterxml.jackson.databind.introspect.ClassIntrospector, com.fasterxml.jackson.databind.AnnotationIntrospector, com.fasterxml.jackson.databind.PropertyNamingStrategy, com.fasterxml.jackson.databind.type.TypeFactory, com.fasterxml.jackson.databind.jsontype.TypeResolverBuilder, java.text.DateFormat, com.fasterxml.jackson.databind.cfg.HandlerInstantiator, java.util.Locale, java.util.TimeZone, com.fasterxml.jackson.core.Base64Variant)", + "new": "method void com.fasterxml.jackson.databind.cfg.BaseSettings::(com.fasterxml.jackson.databind.introspect.ClassIntrospector, com.fasterxml.jackson.databind.AnnotationIntrospector, com.fasterxml.jackson.databind.PropertyNamingStrategy, com.fasterxml.jackson.databind.type.TypeFactory, com.fasterxml.jackson.databind.jsontype.TypeResolverBuilder, java.text.DateFormat, com.fasterxml.jackson.databind.cfg.HandlerInstantiator, java.util.Locale, java.util.TimeZone, com.fasterxml.jackson.core.Base64Variant, com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator, com.fasterxml.jackson.databind.introspect.AccessorNamingStrategy.Provider)", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.method.finalMethodAddedToNonFinalClass", + "new": "method com.fasterxml.jackson.databind.introspect.AccessorNamingStrategy.Provider com.fasterxml.jackson.databind.cfg.MapperConfig>::getAccessorNaming()", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.method.abstractMethodAdded", + "new": "method com.fasterxml.jackson.annotation.JsonIncludeProperties.Value com.fasterxml.jackson.databind.cfg.MapperConfig>::getDefaultPropertyInclusions(java.lang.Class, com.fasterxml.jackson.databind.introspect.AnnotatedClass)", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.field.serialVersionUIDUnchanged", + "old": "field com.fasterxml.jackson.databind.deser.DefaultDeserializationContext.serialVersionUID", + "new": "field com.fasterxml.jackson.databind.deser.DefaultDeserializationContext.serialVersionUID", + "serialVersionUID": "1", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.method.abstractMethodAdded", + "new": "method com.fasterxml.jackson.databind.deser.DefaultDeserializationContext com.fasterxml.jackson.databind.deser.DefaultDeserializationContext::createDummyInstance(com.fasterxml.jackson.databind.DeserializationConfig)", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.class.nonFinalClassInheritsFromNewClass", + "old": "class com.fasterxml.jackson.databind.deser.UnresolvedForwardReference", + "new": "class com.fasterxml.jackson.databind.deser.UnresolvedForwardReference", + "superClass": "com.fasterxml.jackson.core.JacksonException", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.method.removed", + "old": "method com.fasterxml.jackson.databind.introspect.AnnotatedParameter com.fasterxml.jackson.databind.deser.ValueInstantiator::getIncompleteParameter()", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.method.removed", + "old": "method void com.fasterxml.jackson.databind.deser.impl.BeanPropertyMap::(boolean, java.util.Collection)", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.method.numberOfParametersChanged", + "old": "method com.fasterxml.jackson.databind.deser.impl.BeanPropertyMap com.fasterxml.jackson.databind.deser.impl.BeanPropertyMap::construct(java.util.Collection, boolean)", + "new": "method com.fasterxml.jackson.databind.deser.impl.BeanPropertyMap com.fasterxml.jackson.databind.deser.impl.BeanPropertyMap::construct(com.fasterxml.jackson.databind.cfg.MapperConfig, java.util.Collection, java.util.Map>, boolean)", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.method.removed", + "old": "method void com.fasterxml.jackson.databind.deser.impl.BeanPropertyMap::replace(com.fasterxml.jackson.databind.deser.SettableBeanProperty)", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.method.abstractMethodAdded", + "new": "method com.fasterxml.jackson.databind.BeanDescription com.fasterxml.jackson.databind.introspect.ClassIntrospector::forDeserializationWithBuilder(com.fasterxml.jackson.databind.DeserializationConfig, com.fasterxml.jackson.databind.JavaType, com.fasterxml.jackson.databind.introspect.ClassIntrospector.MixInResolver, com.fasterxml.jackson.databind.BeanDescription)", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.method.numberOfParametersChanged", + "old": "method void com.fasterxml.jackson.databind.ser.BeanSerializer::(com.fasterxml.jackson.databind.ser.std.BeanSerializerBase, java.util.Set)", + "new": "method void com.fasterxml.jackson.databind.ser.BeanSerializer::(com.fasterxml.jackson.databind.ser.std.BeanSerializerBase, java.util.Set, java.util.Set)", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.method.removed", + "old": "method com.fasterxml.jackson.databind.ser.impl.PropertySerializerMap com.fasterxml.jackson.databind.ser.impl.PropertySerializerMap::emptyMap()", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.method.visibilityReduced", + "old": "method void com.fasterxml.jackson.databind.ser.std.BeanSerializerBase::(com.fasterxml.jackson.databind.ser.std.BeanSerializerBase, com.fasterxml.jackson.databind.ser.BeanPropertyWriter[], com.fasterxml.jackson.databind.ser.BeanPropertyWriter[])", + "new": "method void com.fasterxml.jackson.databind.ser.std.BeanSerializerBase::(com.fasterxml.jackson.databind.ser.std.BeanSerializerBase, com.fasterxml.jackson.databind.ser.BeanPropertyWriter[], com.fasterxml.jackson.databind.ser.BeanPropertyWriter[])", + "oldVisibility": "public", + "newVisibility": "protected", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.method.abstractMethodAdded", + "new": "method com.fasterxml.jackson.databind.ser.std.BeanSerializerBase com.fasterxml.jackson.databind.ser.std.BeanSerializerBase::withByNameInclusion(java.util.Set, java.util.Set)", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.method.abstractMethodAdded", + "new": "method com.fasterxml.jackson.databind.ser.std.BeanSerializerBase com.fasterxml.jackson.databind.ser.std.BeanSerializerBase::withProperties(com.fasterxml.jackson.databind.ser.BeanPropertyWriter[], com.fasterxml.jackson.databind.ser.BeanPropertyWriter[])", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.field.typeChanged", + "old": "field com.fasterxml.jackson.databind.type.TypeFactory._typeCache", + "new": "field com.fasterxml.jackson.databind.type.TypeFactory._typeCache", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.field.serialVersionUIDUnchanged", + "old": "field com.fasterxml.jackson.databind.type.TypeFactory.serialVersionUID", + "new": "field com.fasterxml.jackson.databind.type.TypeFactory.serialVersionUID", + "serialVersionUID": "1", + "justification": "JAVA-2904: Jackson upgraded to 2.12.0. Caused by the exposure of ObjectMapper as a parameter in ExtraTypeCodecs.json()" + }, + { + "code": "java.missing.newClass", + "new": "missing-class org.apache.tinkerpop.gremlin.process.remote.RemoteConnection", + "justification": "JAVA-2907: switched Tinkerpop dependency to optional" + }, + { + "code": "java.missing.newClass", + "new": "missing-class org.apache.tinkerpop.gremlin.process.traversal.P", + "justification": "JAVA-2907: switched Tinkerpop dependency to optional" + }, + { + "code": "java.missing.newClass", + "new": "missing-class org.apache.tinkerpop.gremlin.process.traversal.Path", + "justification": "JAVA-2907: switched Tinkerpop dependency to optional" + }, + { + "code": "java.missing.newClass", + "new": "missing-class org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal", + "justification": "JAVA-2907: switched Tinkerpop dependency to optional" + }, + { + "code": "java.missing.newClass", + "new": "missing-class org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource", + "justification": "JAVA-2907: switched Tinkerpop dependency to optional" + }, + { + "code": "java.missing.newClass", + "new": "missing-class org.apache.tinkerpop.gremlin.structure.Edge", + "justification": "JAVA-2907: switched Tinkerpop dependency to optional" + }, + { + "code": "java.missing.newClass", + "new": "missing-class org.apache.tinkerpop.gremlin.structure.Property", + "justification": "JAVA-2907: switched Tinkerpop dependency to optional" + }, + { + "code": "java.missing.newClass", + "new": "missing-class org.apache.tinkerpop.gremlin.structure.Vertex", + "justification": "JAVA-2907: switched Tinkerpop dependency to optional" + }, + { + "code": "java.missing.newClass", + "new": "missing-class org.apache.tinkerpop.gremlin.structure.VertexProperty", + "justification": "JAVA-2907: switched Tinkerpop dependency to optional" + }, + { + "code": "java.missing.oldClass", + "old": "missing-class org.apache.tinkerpop.gremlin.process.remote.RemoteConnection", + "new": "missing-class org.apache.tinkerpop.gremlin.process.remote.RemoteConnection", + "justification": "JAVA-2907: switched Tinkerpop dependency to optional" + }, + { + "code": "java.missing.oldClass", + "old": "missing-class org.apache.tinkerpop.gremlin.process.traversal.P", + "new": "missing-class org.apache.tinkerpop.gremlin.process.traversal.P", + "justification": "JAVA-2907: switched Tinkerpop dependency to optional" + }, + { + "code": "java.missing.oldClass", + "old": "missing-class org.apache.tinkerpop.gremlin.process.traversal.Path", + "new": "missing-class org.apache.tinkerpop.gremlin.process.traversal.Path", + "justification": "JAVA-2907: switched Tinkerpop dependency to optional" + }, + { + "code": "java.missing.oldClass", + "old": "missing-class org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal", + "new": "missing-class org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal", + "justification": "JAVA-2907: switched Tinkerpop dependency to optional" + }, + { + "code": "java.missing.oldClass", + "old": "missing-class org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource", + "new": "missing-class org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource", + "justification": "JAVA-2907: switched Tinkerpop dependency to optional" + }, + { + "code": "java.missing.oldClass", + "old": "missing-class org.apache.tinkerpop.gremlin.structure.Edge", + "new": "missing-class org.apache.tinkerpop.gremlin.structure.Edge", + "justification": "JAVA-2907: switched Tinkerpop dependency to optional" + }, + { + "code": "java.missing.oldClass", + "old": "missing-class org.apache.tinkerpop.gremlin.structure.Property", + "new": "missing-class org.apache.tinkerpop.gremlin.structure.Property", + "justification": "JAVA-2907: switched Tinkerpop dependency to optional" + }, + { + "code": "java.missing.oldClass", + "old": "missing-class org.apache.tinkerpop.gremlin.structure.Vertex", + "new": "missing-class org.apache.tinkerpop.gremlin.structure.Vertex", + "justification": "JAVA-2907: switched Tinkerpop dependency to optional" + }, + { + "code": "java.missing.oldClass", + "old": "missing-class org.apache.tinkerpop.gremlin.structure.VertexProperty", + "new": "missing-class org.apache.tinkerpop.gremlin.structure.VertexProperty", + "justification": "JAVA-2907: switched Tinkerpop dependency to optional" + }, + { + "code": "java.class.nonFinalClassInheritsFromNewClass", + "old": "class com.fasterxml.jackson.core.JsonGenerationException", + "new": "class com.fasterxml.jackson.core.JsonGenerationException", + "superClass": "com.fasterxml.jackson.core.exc.StreamWriteException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.field.serialVersionUIDChanged", + "old": "field com.fasterxml.jackson.core.JsonLocation.serialVersionUID", + "new": "field com.fasterxml.jackson.core.JsonLocation.serialVersionUID", + "oldSerialVersionUID": "1", + "newSerialVersionUID": "2", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.removed", + "old": "method java.lang.StringBuilder com.fasterxml.jackson.core.JsonLocation::_appendSourceDesc(java.lang.StringBuilder)", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.visibilityReduced", + "old": "method void com.fasterxml.jackson.core.exc.StreamReadException::(com.fasterxml.jackson.core.JsonParser, java.lang.String)", + "new": "method void com.fasterxml.jackson.core.exc.StreamReadException::(com.fasterxml.jackson.core.JsonParser, java.lang.String)", + "oldVisibility": "public", + "newVisibility": "protected", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.visibilityReduced", + "old": "method void com.fasterxml.jackson.core.exc.StreamReadException::(com.fasterxml.jackson.core.JsonParser, java.lang.String, com.fasterxml.jackson.core.JsonLocation)", + "new": "method void com.fasterxml.jackson.core.exc.StreamReadException::(com.fasterxml.jackson.core.JsonParser, java.lang.String, com.fasterxml.jackson.core.JsonLocation)", + "oldVisibility": "public", + "newVisibility": "protected", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.visibilityReduced", + "old": "method void com.fasterxml.jackson.core.exc.StreamReadException::(com.fasterxml.jackson.core.JsonParser, java.lang.String, java.lang.Throwable)", + "new": "method void com.fasterxml.jackson.core.exc.StreamReadException::(com.fasterxml.jackson.core.JsonParser, java.lang.String, java.lang.Throwable)", + "oldVisibility": "public", + "newVisibility": "protected", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.field.nowFinal", + "old": "field com.fasterxml.jackson.core.sym.ByteQuadsCanonicalizer._intern", + "new": "field com.fasterxml.jackson.core.sym.ByteQuadsCanonicalizer._intern", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.removed", + "old": "method void com.fasterxml.jackson.core.sym.CharsToNameCanonicalizer::reportTooManyCollisions(int)", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.abstractMethodAdded", + "new": "method java.util.List> com.fasterxml.jackson.databind.BeanDescription::getConstructorsWithMode()", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.abstractMethodAdded", + "new": "method java.util.List> com.fasterxml.jackson.databind.BeanDescription::getFactoryMethodsWithMode()", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.parameterTypeChanged", + "old": "parameter com.fasterxml.jackson.databind.DeserializationConfig com.fasterxml.jackson.databind.DeserializationConfig::_withMapperFeatures(===int===)", + "new": "parameter com.fasterxml.jackson.databind.DeserializationConfig com.fasterxml.jackson.databind.DeserializationConfig::_withMapperFeatures(===long===)", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.finalMethodAddedToNonFinalClass", + "new": "method com.fasterxml.jackson.databind.util.TokenBuffer com.fasterxml.jackson.databind.DeserializationContext::bufferForInputBuffering()", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.JsonDeserializer::deserialize(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext) throws java.io.IOException, com.fasterxml.jackson.core.JsonProcessingException", + "new": "method T com.fasterxml.jackson.databind.JsonDeserializer::deserialize(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext) throws java.io.IOException, com.fasterxml.jackson.core.JacksonException", + "exception": "com.fasterxml.jackson.core.JacksonException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.JsonDeserializer::deserialize(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext) throws java.io.IOException, com.fasterxml.jackson.core.JsonProcessingException", + "new": "method T com.fasterxml.jackson.databind.JsonDeserializer::deserialize(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext) throws java.io.IOException, com.fasterxml.jackson.core.JacksonException", + "exception": "com.fasterxml.jackson.core.JsonProcessingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.JsonDeserializer::deserialize(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext, T) throws java.io.IOException", + "new": "method T com.fasterxml.jackson.databind.JsonDeserializer::deserialize(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext, T) throws java.io.IOException, com.fasterxml.jackson.core.JacksonException", + "exception": "com.fasterxml.jackson.core.JacksonException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method java.lang.Object com.fasterxml.jackson.databind.JsonDeserializer::deserializeWithType(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext, com.fasterxml.jackson.databind.jsontype.TypeDeserializer) throws java.io.IOException", + "new": "method java.lang.Object com.fasterxml.jackson.databind.JsonDeserializer::deserializeWithType(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext, com.fasterxml.jackson.databind.jsontype.TypeDeserializer) throws java.io.IOException, com.fasterxml.jackson.core.JacksonException", + "exception": "com.fasterxml.jackson.core.JacksonException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method java.lang.Object com.fasterxml.jackson.databind.JsonDeserializer::deserializeWithType(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext, com.fasterxml.jackson.databind.jsontype.TypeDeserializer, T) throws java.io.IOException", + "new": "method java.lang.Object com.fasterxml.jackson.databind.JsonDeserializer::deserializeWithType(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext, com.fasterxml.jackson.databind.jsontype.TypeDeserializer, T) throws java.io.IOException, com.fasterxml.jackson.core.JacksonException", + "exception": "com.fasterxml.jackson.core.JacksonException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.class.nonFinalClassInheritsFromNewClass", + "old": "class com.fasterxml.jackson.databind.JsonMappingException", + "new": "class com.fasterxml.jackson.databind.JsonMappingException", + "superClass": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method com.fasterxml.jackson.databind.JsonDeserializer com.fasterxml.jackson.databind.ObjectMapper::_findRootDeserializer(com.fasterxml.jackson.databind.DeserializationContext, com.fasterxml.jackson.databind.JavaType) throws com.fasterxml.jackson.databind.JsonMappingException", + "new": "method com.fasterxml.jackson.databind.JsonDeserializer com.fasterxml.jackson.databind.ObjectMapper::_findRootDeserializer(com.fasterxml.jackson.databind.DeserializationContext, com.fasterxml.jackson.databind.JavaType) throws com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method com.fasterxml.jackson.databind.JsonDeserializer com.fasterxml.jackson.databind.ObjectMapper::_findRootDeserializer(com.fasterxml.jackson.databind.DeserializationContext, com.fasterxml.jackson.databind.JavaType) throws com.fasterxml.jackson.databind.JsonMappingException", + "new": "method com.fasterxml.jackson.databind.JsonDeserializer com.fasterxml.jackson.databind.ObjectMapper::_findRootDeserializer(com.fasterxml.jackson.databind.DeserializationContext, com.fasterxml.jackson.databind.JavaType) throws com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.removed", + "old": "method com.fasterxml.jackson.core.JsonToken com.fasterxml.jackson.databind.ObjectMapper::_initForReading(com.fasterxml.jackson.core.JsonParser) throws java.io.IOException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readTree(com.fasterxml.jackson.core.JsonParser) throws java.io.IOException, com.fasterxml.jackson.core.JsonProcessingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readTree(com.fasterxml.jackson.core.JsonParser) throws java.io.IOException", + "exception": "com.fasterxml.jackson.core.JsonProcessingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method com.fasterxml.jackson.databind.JsonNode com.fasterxml.jackson.databind.ObjectMapper::readTree(java.io.File) throws java.io.IOException, com.fasterxml.jackson.core.JsonProcessingException", + "new": "method com.fasterxml.jackson.databind.JsonNode com.fasterxml.jackson.databind.ObjectMapper::readTree(java.io.File) throws java.io.IOException", + "exception": "com.fasterxml.jackson.core.JsonProcessingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.exc.StreamReadException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.JsonParseException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.exc.StreamReadException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.JsonParseException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], int, int, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], int, int, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.exc.StreamReadException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], int, int, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], int, int, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], int, int, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], int, int, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.JsonParseException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], int, int, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], int, int, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], int, int, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], int, int, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.exc.StreamReadException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], int, int, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], int, int, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], int, int, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], int, int, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.JsonParseException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], int, int, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], int, int, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], int, int, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], int, int, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.exc.StreamReadException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], int, int, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], int, int, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], int, int, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], int, int, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.JsonParseException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], int, int, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], int, int, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.exc.StreamReadException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.JsonParseException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(byte[], java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.core.type.ResolvedType) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.core.type.ResolvedType) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.exc.StreamReadException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.core.type.ResolvedType) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.core.type.ResolvedType) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.core.type.ResolvedType) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.core.type.ResolvedType) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.JsonParseException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.core.type.ResolvedType) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.core.type.ResolvedType) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.exc.StreamReadException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.JsonParseException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.exc.StreamReadException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.JsonParseException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(com.fasterxml.jackson.core.JsonParser, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(com.fasterxml.jackson.core.JsonParser, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.exc.StreamReadException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(com.fasterxml.jackson.core.JsonParser, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(com.fasterxml.jackson.core.JsonParser, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(com.fasterxml.jackson.core.JsonParser, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(com.fasterxml.jackson.core.JsonParser, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.JsonParseException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(com.fasterxml.jackson.core.JsonParser, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(com.fasterxml.jackson.core.JsonParser, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.File, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.File, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.exc.StreamReadException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.File, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.File, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.File, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.File, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.JsonParseException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.File, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.File, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.File, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.File, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.exc.StreamReadException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.File, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.File, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.File, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.File, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.JsonParseException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.File, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.File, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.File, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.File, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.exc.StreamReadException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.File, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.File, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.File, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.File, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.JsonParseException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.File, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.File, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.InputStream, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.InputStream, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.exc.StreamReadException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.InputStream, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.InputStream, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.InputStream, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.InputStream, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.JsonParseException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.InputStream, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.InputStream, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.InputStream, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.InputStream, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.exc.StreamReadException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.InputStream, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.InputStream, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.InputStream, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.InputStream, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.JsonParseException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.InputStream, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.InputStream, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.InputStream, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.InputStream, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.exc.StreamReadException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.InputStream, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.InputStream, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.InputStream, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.InputStream, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.JsonParseException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.InputStream, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.InputStream, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.Reader, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.Reader, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.exc.StreamReadException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.Reader, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.Reader, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.Reader, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.Reader, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.JsonParseException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.Reader, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.Reader, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.Reader, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.Reader, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.exc.StreamReadException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.Reader, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.Reader, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.Reader, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.Reader, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.JsonParseException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.Reader, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.Reader, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.Reader, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.Reader, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.exc.StreamReadException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.Reader, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.Reader, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.Reader, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.Reader, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.JsonParseException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.Reader, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.io.Reader, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.net.URL, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.net.URL, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.exc.StreamReadException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.net.URL, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.net.URL, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.net.URL, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.net.URL, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.JsonParseException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.net.URL, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.net.URL, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.net.URL, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.net.URL, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.exc.StreamReadException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.net.URL, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.net.URL, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.net.URL, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.net.URL, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.JsonParseException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.net.URL, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.net.URL, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.net.URL, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.net.URL, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.exc.StreamReadException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.net.URL, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.net.URL, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.net.URL, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.net.URL, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.JsonParseException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.net.URL, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method T com.fasterxml.jackson.databind.ObjectMapper::readValue(java.net.URL, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamReadException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method com.fasterxml.jackson.databind.MappingIterator com.fasterxml.jackson.databind.ObjectMapper::readValues(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.core.type.ResolvedType) throws java.io.IOException, com.fasterxml.jackson.core.JsonProcessingException", + "new": "method com.fasterxml.jackson.databind.MappingIterator com.fasterxml.jackson.databind.ObjectMapper::readValues(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.core.type.ResolvedType) throws java.io.IOException", + "exception": "com.fasterxml.jackson.core.JsonProcessingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method com.fasterxml.jackson.databind.MappingIterator com.fasterxml.jackson.databind.ObjectMapper::readValues(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException, com.fasterxml.jackson.core.JsonProcessingException", + "new": "method com.fasterxml.jackson.databind.MappingIterator com.fasterxml.jackson.databind.ObjectMapper::readValues(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.core.type.TypeReference) throws java.io.IOException", + "exception": "com.fasterxml.jackson.core.JsonProcessingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method com.fasterxml.jackson.databind.MappingIterator com.fasterxml.jackson.databind.ObjectMapper::readValues(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException, com.fasterxml.jackson.core.JsonProcessingException", + "new": "method com.fasterxml.jackson.databind.MappingIterator com.fasterxml.jackson.databind.ObjectMapper::readValues(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.JavaType) throws java.io.IOException", + "exception": "com.fasterxml.jackson.core.JsonProcessingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method com.fasterxml.jackson.databind.MappingIterator com.fasterxml.jackson.databind.ObjectMapper::readValues(com.fasterxml.jackson.core.JsonParser, java.lang.Class) throws java.io.IOException, com.fasterxml.jackson.core.JsonProcessingException", + "new": "method com.fasterxml.jackson.databind.MappingIterator com.fasterxml.jackson.databind.ObjectMapper::readValues(com.fasterxml.jackson.core.JsonParser, java.lang.Class) throws java.io.IOException", + "exception": "com.fasterxml.jackson.core.JsonProcessingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method void com.fasterxml.jackson.databind.ObjectMapper::writeTree(com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.core.TreeNode) throws java.io.IOException, com.fasterxml.jackson.core.JsonProcessingException", + "new": "method void com.fasterxml.jackson.databind.ObjectMapper::writeTree(com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.core.TreeNode) throws java.io.IOException", + "exception": "com.fasterxml.jackson.core.JsonProcessingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method void com.fasterxml.jackson.databind.ObjectMapper::writeTree(com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.JsonNode) throws java.io.IOException, com.fasterxml.jackson.core.JsonProcessingException", + "new": "method void com.fasterxml.jackson.databind.ObjectMapper::writeTree(com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.JsonNode) throws java.io.IOException", + "exception": "com.fasterxml.jackson.core.JsonProcessingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method void com.fasterxml.jackson.databind.ObjectMapper::writeValue(com.fasterxml.jackson.core.JsonGenerator, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.JsonGenerationException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method void com.fasterxml.jackson.databind.ObjectMapper::writeValue(com.fasterxml.jackson.core.JsonGenerator, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamWriteException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.exc.StreamWriteException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method void com.fasterxml.jackson.databind.ObjectMapper::writeValue(com.fasterxml.jackson.core.JsonGenerator, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.JsonGenerationException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method void com.fasterxml.jackson.databind.ObjectMapper::writeValue(com.fasterxml.jackson.core.JsonGenerator, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamWriteException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method void com.fasterxml.jackson.databind.ObjectMapper::writeValue(com.fasterxml.jackson.core.JsonGenerator, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.JsonGenerationException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method void com.fasterxml.jackson.databind.ObjectMapper::writeValue(com.fasterxml.jackson.core.JsonGenerator, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamWriteException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.JsonGenerationException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method void com.fasterxml.jackson.databind.ObjectMapper::writeValue(com.fasterxml.jackson.core.JsonGenerator, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.JsonGenerationException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method void com.fasterxml.jackson.databind.ObjectMapper::writeValue(com.fasterxml.jackson.core.JsonGenerator, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamWriteException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method void com.fasterxml.jackson.databind.ObjectMapper::writeValue(java.io.File, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.JsonGenerationException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method void com.fasterxml.jackson.databind.ObjectMapper::writeValue(java.io.File, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamWriteException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.exc.StreamWriteException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method void com.fasterxml.jackson.databind.ObjectMapper::writeValue(java.io.File, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.JsonGenerationException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method void com.fasterxml.jackson.databind.ObjectMapper::writeValue(java.io.File, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamWriteException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method void com.fasterxml.jackson.databind.ObjectMapper::writeValue(java.io.File, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.JsonGenerationException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method void com.fasterxml.jackson.databind.ObjectMapper::writeValue(java.io.File, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamWriteException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.JsonGenerationException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method void com.fasterxml.jackson.databind.ObjectMapper::writeValue(java.io.File, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.JsonGenerationException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method void com.fasterxml.jackson.databind.ObjectMapper::writeValue(java.io.File, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamWriteException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method void com.fasterxml.jackson.databind.ObjectMapper::writeValue(java.io.OutputStream, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.JsonGenerationException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method void com.fasterxml.jackson.databind.ObjectMapper::writeValue(java.io.OutputStream, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamWriteException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.exc.StreamWriteException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method void com.fasterxml.jackson.databind.ObjectMapper::writeValue(java.io.OutputStream, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.JsonGenerationException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method void com.fasterxml.jackson.databind.ObjectMapper::writeValue(java.io.OutputStream, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamWriteException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method void com.fasterxml.jackson.databind.ObjectMapper::writeValue(java.io.OutputStream, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.JsonGenerationException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method void com.fasterxml.jackson.databind.ObjectMapper::writeValue(java.io.OutputStream, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamWriteException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.JsonGenerationException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method void com.fasterxml.jackson.databind.ObjectMapper::writeValue(java.io.OutputStream, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.JsonGenerationException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method void com.fasterxml.jackson.databind.ObjectMapper::writeValue(java.io.OutputStream, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamWriteException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method void com.fasterxml.jackson.databind.ObjectMapper::writeValue(java.io.Writer, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.JsonGenerationException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method void com.fasterxml.jackson.databind.ObjectMapper::writeValue(java.io.Writer, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamWriteException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.exc.StreamWriteException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method void com.fasterxml.jackson.databind.ObjectMapper::writeValue(java.io.Writer, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.JsonGenerationException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method void com.fasterxml.jackson.databind.ObjectMapper::writeValue(java.io.Writer, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamWriteException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method void com.fasterxml.jackson.databind.ObjectMapper::writeValue(java.io.Writer, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.JsonGenerationException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method void com.fasterxml.jackson.databind.ObjectMapper::writeValue(java.io.Writer, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamWriteException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.JsonGenerationException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method void com.fasterxml.jackson.databind.ObjectMapper::writeValue(java.io.Writer, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.JsonGenerationException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method void com.fasterxml.jackson.databind.ObjectMapper::writeValue(java.io.Writer, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamWriteException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method com.fasterxml.jackson.databind.JsonDeserializer com.fasterxml.jackson.databind.ObjectReader::_findRootDeserializer(com.fasterxml.jackson.databind.DeserializationContext) throws com.fasterxml.jackson.databind.JsonMappingException", + "new": "method com.fasterxml.jackson.databind.JsonDeserializer com.fasterxml.jackson.databind.ObjectReader::_findRootDeserializer(com.fasterxml.jackson.databind.DeserializationContext) throws com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method com.fasterxml.jackson.databind.JsonDeserializer com.fasterxml.jackson.databind.ObjectReader::_findRootDeserializer(com.fasterxml.jackson.databind.DeserializationContext) throws com.fasterxml.jackson.databind.JsonMappingException", + "new": "method com.fasterxml.jackson.databind.JsonDeserializer com.fasterxml.jackson.databind.ObjectReader::_findRootDeserializer(com.fasterxml.jackson.databind.DeserializationContext) throws com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method com.fasterxml.jackson.databind.JsonDeserializer com.fasterxml.jackson.databind.ObjectReader::_findTreeDeserializer(com.fasterxml.jackson.databind.DeserializationContext) throws com.fasterxml.jackson.databind.JsonMappingException", + "new": "method com.fasterxml.jackson.databind.JsonDeserializer com.fasterxml.jackson.databind.ObjectReader::_findTreeDeserializer(com.fasterxml.jackson.databind.DeserializationContext) throws com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method com.fasterxml.jackson.databind.JsonDeserializer com.fasterxml.jackson.databind.ObjectReader::_findTreeDeserializer(com.fasterxml.jackson.databind.DeserializationContext) throws com.fasterxml.jackson.databind.JsonMappingException", + "new": "method com.fasterxml.jackson.databind.JsonDeserializer com.fasterxml.jackson.databind.ObjectReader::_findTreeDeserializer(com.fasterxml.jackson.databind.DeserializationContext) throws com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method void com.fasterxml.jackson.databind.ObjectReader::_reportUndetectableSource(java.lang.Object) throws com.fasterxml.jackson.core.JsonParseException", + "new": "method void com.fasterxml.jackson.databind.ObjectReader::_reportUndetectableSource(java.lang.Object) throws com.fasterxml.jackson.core.exc.StreamReadException", + "exception": "com.fasterxml.jackson.core.exc.StreamReadException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method void com.fasterxml.jackson.databind.ObjectReader::_reportUndetectableSource(java.lang.Object) throws com.fasterxml.jackson.core.JsonParseException", + "new": "method void com.fasterxml.jackson.databind.ObjectReader::_reportUndetectableSource(java.lang.Object) throws com.fasterxml.jackson.core.exc.StreamReadException", + "exception": "com.fasterxml.jackson.core.JsonParseException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method void com.fasterxml.jackson.databind.ObjectReader::_reportUnkownFormat(com.fasterxml.jackson.databind.deser.DataFormatReaders, com.fasterxml.jackson.databind.deser.DataFormatReaders.Match) throws com.fasterxml.jackson.core.JsonProcessingException", + "new": "method void com.fasterxml.jackson.databind.ObjectReader::_reportUnkownFormat(com.fasterxml.jackson.databind.deser.DataFormatReaders, com.fasterxml.jackson.databind.deser.DataFormatReaders.Match) throws java.io.IOException", + "exception": "java.io.IOException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method void com.fasterxml.jackson.databind.ObjectReader::_reportUnkownFormat(com.fasterxml.jackson.databind.deser.DataFormatReaders, com.fasterxml.jackson.databind.deser.DataFormatReaders.Match) throws com.fasterxml.jackson.core.JsonProcessingException", + "new": "method void com.fasterxml.jackson.databind.ObjectReader::_reportUnkownFormat(com.fasterxml.jackson.databind.deser.DataFormatReaders, com.fasterxml.jackson.databind.deser.DataFormatReaders.Match) throws java.io.IOException", + "exception": "com.fasterxml.jackson.core.JsonProcessingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method void com.fasterxml.jackson.databind.ObjectWriter::writeValue(java.io.DataOutput, java.lang.Object) throws java.io.IOException", + "new": "method void com.fasterxml.jackson.databind.ObjectWriter::writeValue(java.io.DataOutput, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamWriteException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.exc.StreamWriteException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method void com.fasterxml.jackson.databind.ObjectWriter::writeValue(java.io.DataOutput, java.lang.Object) throws java.io.IOException", + "new": "method void com.fasterxml.jackson.databind.ObjectWriter::writeValue(java.io.DataOutput, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamWriteException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method void com.fasterxml.jackson.databind.ObjectWriter::writeValue(java.io.File, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.JsonGenerationException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method void com.fasterxml.jackson.databind.ObjectWriter::writeValue(java.io.File, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamWriteException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.exc.StreamWriteException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method void com.fasterxml.jackson.databind.ObjectWriter::writeValue(java.io.File, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.JsonGenerationException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method void com.fasterxml.jackson.databind.ObjectWriter::writeValue(java.io.File, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamWriteException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method void com.fasterxml.jackson.databind.ObjectWriter::writeValue(java.io.File, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.JsonGenerationException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method void com.fasterxml.jackson.databind.ObjectWriter::writeValue(java.io.File, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamWriteException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.JsonGenerationException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method void com.fasterxml.jackson.databind.ObjectWriter::writeValue(java.io.File, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.JsonGenerationException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method void com.fasterxml.jackson.databind.ObjectWriter::writeValue(java.io.File, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamWriteException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method void com.fasterxml.jackson.databind.ObjectWriter::writeValue(java.io.OutputStream, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.JsonGenerationException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method void com.fasterxml.jackson.databind.ObjectWriter::writeValue(java.io.OutputStream, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamWriteException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.exc.StreamWriteException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method void com.fasterxml.jackson.databind.ObjectWriter::writeValue(java.io.OutputStream, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.JsonGenerationException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method void com.fasterxml.jackson.databind.ObjectWriter::writeValue(java.io.OutputStream, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamWriteException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method void com.fasterxml.jackson.databind.ObjectWriter::writeValue(java.io.OutputStream, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.JsonGenerationException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method void com.fasterxml.jackson.databind.ObjectWriter::writeValue(java.io.OutputStream, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamWriteException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.JsonGenerationException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method void com.fasterxml.jackson.databind.ObjectWriter::writeValue(java.io.OutputStream, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.JsonGenerationException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method void com.fasterxml.jackson.databind.ObjectWriter::writeValue(java.io.OutputStream, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamWriteException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method void com.fasterxml.jackson.databind.ObjectWriter::writeValue(java.io.Writer, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.JsonGenerationException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method void com.fasterxml.jackson.databind.ObjectWriter::writeValue(java.io.Writer, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamWriteException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.exc.StreamWriteException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method void com.fasterxml.jackson.databind.ObjectWriter::writeValue(java.io.Writer, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.JsonGenerationException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method void com.fasterxml.jackson.databind.ObjectWriter::writeValue(java.io.Writer, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamWriteException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method void com.fasterxml.jackson.databind.ObjectWriter::writeValue(java.io.Writer, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.JsonGenerationException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method void com.fasterxml.jackson.databind.ObjectWriter::writeValue(java.io.Writer, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamWriteException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.core.JsonGenerationException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method void com.fasterxml.jackson.databind.ObjectWriter::writeValue(java.io.Writer, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.JsonGenerationException, com.fasterxml.jackson.databind.JsonMappingException", + "new": "method void com.fasterxml.jackson.databind.ObjectWriter::writeValue(java.io.Writer, java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.exc.StreamWriteException, com.fasterxml.jackson.databind.DatabindException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.field.serialVersionUIDUnchanged", + "old": "field com.fasterxml.jackson.databind.SerializationConfig.serialVersionUID", + "new": "field com.fasterxml.jackson.databind.SerializationConfig.serialVersionUID", + "serialVersionUID": "1", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.parameterTypeChanged", + "old": "parameter com.fasterxml.jackson.databind.SerializationConfig com.fasterxml.jackson.databind.SerializationConfig::_withMapperFeatures(===int===)", + "new": "parameter com.fasterxml.jackson.databind.SerializationConfig com.fasterxml.jackson.databind.SerializationConfig::_withMapperFeatures(===long===)", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.field.enumConstantOrderChanged", + "old": "field com.fasterxml.jackson.databind.SerializationFeature.EAGER_SERIALIZER_FETCH", + "new": "field com.fasterxml.jackson.databind.SerializationFeature.EAGER_SERIALIZER_FETCH", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.field.enumConstantOrderChanged", + "old": "field com.fasterxml.jackson.databind.SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS", + "new": "field com.fasterxml.jackson.databind.SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.field.enumConstantOrderChanged", + "old": "field com.fasterxml.jackson.databind.SerializationFeature.USE_EQUALITY_FOR_OBJECT_ID", + "new": "field com.fasterxml.jackson.databind.SerializationFeature.USE_EQUALITY_FOR_OBJECT_ID", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.field.enumConstantOrderChanged", + "old": "field com.fasterxml.jackson.databind.SerializationFeature.WRITE_BIGDECIMAL_AS_PLAIN", + "new": "field com.fasterxml.jackson.databind.SerializationFeature.WRITE_BIGDECIMAL_AS_PLAIN", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.field.enumConstantOrderChanged", + "old": "field com.fasterxml.jackson.databind.SerializationFeature.WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS", + "new": "field com.fasterxml.jackson.databind.SerializationFeature.WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.field.enumConstantOrderChanged", + "old": "field com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS", + "new": "field com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.field.enumConstantOrderChanged", + "old": "field com.fasterxml.jackson.databind.SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS", + "new": "field com.fasterxml.jackson.databind.SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.field.enumConstantOrderChanged", + "old": "field com.fasterxml.jackson.databind.SerializationFeature.WRITE_EMPTY_JSON_ARRAYS", + "new": "field com.fasterxml.jackson.databind.SerializationFeature.WRITE_EMPTY_JSON_ARRAYS", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.field.enumConstantOrderChanged", + "old": "field com.fasterxml.jackson.databind.SerializationFeature.WRITE_ENUMS_USING_INDEX", + "new": "field com.fasterxml.jackson.databind.SerializationFeature.WRITE_ENUMS_USING_INDEX", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.field.enumConstantOrderChanged", + "old": "field com.fasterxml.jackson.databind.SerializationFeature.WRITE_ENUMS_USING_TO_STRING", + "new": "field com.fasterxml.jackson.databind.SerializationFeature.WRITE_ENUMS_USING_TO_STRING", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.field.enumConstantOrderChanged", + "old": "field com.fasterxml.jackson.databind.SerializationFeature.WRITE_ENUM_KEYS_USING_INDEX", + "new": "field com.fasterxml.jackson.databind.SerializationFeature.WRITE_ENUM_KEYS_USING_INDEX", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.field.enumConstantOrderChanged", + "old": "field com.fasterxml.jackson.databind.SerializationFeature.WRITE_NULL_MAP_VALUES", + "new": "field com.fasterxml.jackson.databind.SerializationFeature.WRITE_NULL_MAP_VALUES", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.field.enumConstantOrderChanged", + "old": "field com.fasterxml.jackson.databind.SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED", + "new": "field com.fasterxml.jackson.databind.SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.finalMethodAddedToNonFinalClass", + "new": "method com.fasterxml.jackson.databind.util.TokenBuffer com.fasterxml.jackson.databind.SerializerProvider::bufferForValueConversion()", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.removed", + "old": "method java.lang.Class com.fasterxml.jackson.databind.SerializerProvider::getSerializationView()", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.field.typeChanged", + "old": "field com.fasterxml.jackson.databind.cfg.MapperConfig>._mapperFeatures", + "new": "field com.fasterxml.jackson.databind.cfg.MapperConfig>._mapperFeatures", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.field.serialVersionUIDUnchanged", + "old": "field com.fasterxml.jackson.databind.cfg.MapperConfig>.serialVersionUID", + "new": "field com.fasterxml.jackson.databind.cfg.MapperConfig>.serialVersionUID", + "serialVersionUID": "2", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.parameterTypeChanged", + "old": "parameter void com.fasterxml.jackson.databind.cfg.MapperConfig>::(com.fasterxml.jackson.databind.cfg.BaseSettings, ===int===)", + "new": "parameter void com.fasterxml.jackson.databind.cfg.MapperConfig>::(com.fasterxml.jackson.databind.cfg.BaseSettings, ===long===)", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.parameterTypeChanged", + "old": "parameter void com.fasterxml.jackson.databind.cfg.MapperConfig>::(com.fasterxml.jackson.databind.cfg.MapperConfig, ===int===)", + "new": "parameter void com.fasterxml.jackson.databind.cfg.MapperConfig>::(com.fasterxml.jackson.databind.cfg.MapperConfig, ===long===)", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method void com.fasterxml.jackson.databind.deser.BeanDeserializerBuilder::_fixAccess(java.util.Collection)", + "new": "method void com.fasterxml.jackson.databind.deser.BeanDeserializerBuilder::_fixAccess(java.util.Collection) throws com.fasterxml.jackson.databind.JsonMappingException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method void com.fasterxml.jackson.databind.deser.BeanDeserializerBuilder::addBackReferenceProperty(java.lang.String, com.fasterxml.jackson.databind.deser.SettableBeanProperty)", + "new": "method void com.fasterxml.jackson.databind.deser.BeanDeserializerBuilder::addBackReferenceProperty(java.lang.String, com.fasterxml.jackson.databind.deser.SettableBeanProperty) throws com.fasterxml.jackson.databind.JsonMappingException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method void com.fasterxml.jackson.databind.deser.BeanDeserializerBuilder::addInjectable(com.fasterxml.jackson.databind.PropertyName, com.fasterxml.jackson.databind.JavaType, com.fasterxml.jackson.databind.util.Annotations, com.fasterxml.jackson.databind.introspect.AnnotatedMember, java.lang.Object)", + "new": "method void com.fasterxml.jackson.databind.deser.BeanDeserializerBuilder::addInjectable(com.fasterxml.jackson.databind.PropertyName, com.fasterxml.jackson.databind.JavaType, com.fasterxml.jackson.databind.util.Annotations, com.fasterxml.jackson.databind.introspect.AnnotatedMember, java.lang.Object) throws com.fasterxml.jackson.databind.JsonMappingException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedAdded", + "old": "method com.fasterxml.jackson.databind.JsonDeserializer com.fasterxml.jackson.databind.deser.BeanDeserializerBuilder::build()", + "new": "method com.fasterxml.jackson.databind.JsonDeserializer com.fasterxml.jackson.databind.deser.BeanDeserializerBuilder::build() throws com.fasterxml.jackson.databind.JsonMappingException", + "exception": "com.fasterxml.jackson.databind.JsonMappingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.class.nonFinalClassInheritsFromNewClass", + "old": "class com.fasterxml.jackson.databind.deser.UnresolvedForwardReference", + "new": "class com.fasterxml.jackson.databind.deser.UnresolvedForwardReference", + "superClass": "com.fasterxml.jackson.databind.DatabindException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method void com.fasterxml.jackson.databind.deser.impl.PropertyValue::assign(java.lang.Object) throws java.io.IOException, com.fasterxml.jackson.core.JsonProcessingException", + "new": "method void com.fasterxml.jackson.databind.deser.impl.PropertyValue::assign(java.lang.Object) throws java.io.IOException", + "exception": "com.fasterxml.jackson.core.JsonProcessingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method void com.fasterxml.jackson.databind.node.BinaryNode::serialize(com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.SerializerProvider) throws java.io.IOException, com.fasterxml.jackson.core.JsonProcessingException", + "new": "method void com.fasterxml.jackson.databind.node.BinaryNode::serialize(com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.SerializerProvider) throws java.io.IOException", + "exception": "com.fasterxml.jackson.core.JsonProcessingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method void com.fasterxml.jackson.databind.node.BaseJsonNode::serialize(com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.SerializerProvider) throws java.io.IOException, com.fasterxml.jackson.core.JsonProcessingException @ com.fasterxml.jackson.databind.node.NumericNode", + "new": "method void com.fasterxml.jackson.databind.node.BaseJsonNode::serialize(com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.SerializerProvider) throws java.io.IOException @ com.fasterxml.jackson.databind.node.NumericNode", + "exception": "com.fasterxml.jackson.core.JsonProcessingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method void com.fasterxml.jackson.databind.node.BaseJsonNode::serialize(com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.SerializerProvider) throws java.io.IOException, com.fasterxml.jackson.core.JsonProcessingException @ com.fasterxml.jackson.databind.node.ValueNode", + "new": "method void com.fasterxml.jackson.databind.node.BaseJsonNode::serialize(com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.SerializerProvider) throws java.io.IOException @ com.fasterxml.jackson.databind.node.ValueNode", + "exception": "com.fasterxml.jackson.core.JsonProcessingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method void com.fasterxml.jackson.databind.ser.std.BeanSerializerBase::serializeFieldsFiltered(java.lang.Object, com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.SerializerProvider) throws java.io.IOException, com.fasterxml.jackson.core.JsonGenerationException", + "new": "method void com.fasterxml.jackson.databind.ser.std.BeanSerializerBase::serializeFieldsFiltered(java.lang.Object, com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.SerializerProvider) throws java.io.IOException", + "exception": "com.fasterxml.jackson.core.JsonGenerationException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.method.exception.checkedRemoved", + "old": "method void com.fasterxml.jackson.databind.type.TypeBase::serialize(com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.SerializerProvider) throws java.io.IOException, com.fasterxml.jackson.core.JsonProcessingException", + "new": "method void com.fasterxml.jackson.databind.type.TypeBase::serialize(com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.SerializerProvider) throws java.io.IOException", + "exception": "com.fasterxml.jackson.core.JsonProcessingException", + "justification": "Upgrade deps around JAVA-2977 to address outstanding CVEs" + }, + { + "code": "java.class.nonFinalClassInheritsFromNewClass", + "old": "class com.datastax.oss.driver.api.core.type.codec.CodecNotFoundException", + "new": "class com.datastax.oss.driver.api.core.type.codec.CodecNotFoundException", + "superClass": "com.datastax.oss.driver.api.core.DriverException", + "justification": "Make CodecNotFoundException to extend DriverException as all other driver exceptions do" + }, + { + "code": "java.class.removed", + "old": "class com.datastax.oss.driver.api.core.data.CqlVector", + "justification": "Refactoring in JAVA-3061" + }, + { + "code": "java.method.removed", + "old": "method com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.GettableById::getCqlVector(com.datastax.oss.driver.api.core.CqlIdentifier)", + "justification": "Refactoring in JAVA-3061" + }, + { + "code": "java.method.removed", + "old": "method com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.GettableByIndex::getCqlVector(int)", + "justification": "Refactoring in JAVA-3061" + }, + { + "code": "java.method.removed", + "old": "method com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.GettableByName::getCqlVector(java.lang.String)", + "justification": "Refactoring in JAVA-3061" + }, + { + "code": "java.method.removed", + "old": "method SelfT com.datastax.oss.driver.api.core.data.SettableById>::setCqlVector(com.datastax.oss.driver.api.core.CqlIdentifier, com.datastax.oss.driver.api.core.data.CqlVector)", + "justification": "Refactoring in JAVA-3061" + }, + { + "code": "java.method.removed", + "old": "method SelfT com.datastax.oss.driver.api.core.data.SettableByIndex>::setCqlVector(int, com.datastax.oss.driver.api.core.data.CqlVector)", + "justification": "Refactoring in JAVA-3061" + }, + { + "code": "java.method.removed", + "old": "method SelfT com.datastax.oss.driver.api.core.data.SettableByName>::setCqlVector(java.lang.String, com.datastax.oss.driver.api.core.data.CqlVector)", + "justification": "Refactoring in JAVA-3061" + }, + { + "code": "java.class.removed", + "old": "class com.datastax.oss.driver.api.core.type.CqlVectorType", + "justification": "Refactoring in JAVA-3061" + }, + { + "code": "java.method.returnTypeChanged", + "old": "method com.datastax.oss.driver.api.core.type.CqlVectorType com.datastax.oss.driver.api.core.type.DataTypes::vectorOf(com.datastax.oss.driver.api.core.type.DataType, int)", + "new": "method com.datastax.oss.driver.api.core.type.VectorType com.datastax.oss.driver.api.core.type.DataTypes::vectorOf(com.datastax.oss.driver.api.core.type.DataType, int)", + "justification": "Refactoring in JAVA-3061" + }, + { + "code": "java.method.parameterTypeChanged", + "old": "parameter com.datastax.oss.driver.api.core.type.codec.TypeCodec> com.datastax.oss.driver.api.core.type.codec.TypeCodecs::vectorOf(===com.datastax.oss.driver.api.core.type.CqlVectorType===, com.datastax.oss.driver.api.core.type.codec.TypeCodec)", + "new": "parameter com.datastax.oss.driver.api.core.type.codec.TypeCodec> com.datastax.oss.driver.api.core.type.codec.TypeCodecs::vectorOf(===com.datastax.oss.driver.api.core.type.VectorType===, com.datastax.oss.driver.api.core.type.codec.TypeCodec)", + "justification": "Refactoring in JAVA-3061" + }, + { + "code": "java.method.returnTypeTypeParametersChanged", + "old": "method com.datastax.oss.driver.api.core.type.codec.TypeCodec> com.datastax.oss.driver.api.core.type.codec.TypeCodecs::vectorOf(com.datastax.oss.driver.api.core.type.CqlVectorType, com.datastax.oss.driver.api.core.type.codec.TypeCodec)", + "new": "method com.datastax.oss.driver.api.core.type.codec.TypeCodec> com.datastax.oss.driver.api.core.type.codec.TypeCodecs::vectorOf(com.datastax.oss.driver.api.core.type.VectorType, com.datastax.oss.driver.api.core.type.codec.TypeCodec)", + "justification": "Refactoring in JAVA-3061" + }, + { + "code": "java.method.removed", + "old": "method com.datastax.oss.driver.api.core.type.reflect.GenericType> com.datastax.oss.driver.api.core.type.reflect.GenericType::vectorOf(com.datastax.oss.driver.api.core.type.reflect.GenericType)", + "justification": "Refactoring in JAVA-3061" + }, + { + "code": "java.class.removed", + "old": "class com.datastax.oss.driver.api.core.data.CqlVector.Builder", + "justification": "Refactorings in PR 1666" + }, + { + "code": "java.method.removed", + "old": "method com.datastax.oss.driver.api.core.data.CqlVector.Builder com.datastax.oss.driver.api.core.data.CqlVector::builder()", + "justification": "Refactorings in PR 1666" + }, + { + "code": "java.method.removed", + "old": "method java.lang.Iterable com.datastax.oss.driver.api.core.data.CqlVector::getValues()", + "justification": "Refactorings in PR 1666" + }, + { + "code": "java.generics.formalTypeParameterChanged", + "old": "class com.datastax.oss.driver.api.core.data.CqlVector", + "new": "class com.datastax.oss.driver.api.core.data.CqlVector", + "justification": "Refactorings in PR 1666" + }, + { + "code": "java.method.parameterTypeChanged", + "old": "parameter com.datastax.oss.driver.api.core.type.codec.TypeCodec> com.datastax.oss.driver.api.core.type.codec.TypeCodecs::vectorOf(===com.datastax.oss.driver.api.core.type.CqlVectorType===, com.datastax.oss.driver.api.core.type.codec.TypeCodec)", + "new": "parameter com.datastax.oss.driver.api.core.type.codec.TypeCodec> com.datastax.oss.driver.api.core.type.codec.TypeCodecs::vectorOf(===com.datastax.oss.driver.api.core.type.VectorType===, com.datastax.oss.driver.api.core.type.codec.TypeCodec)", + "justification": "Refactorings in PR 1666" + }, + { + "code": "java.method.parameterTypeParameterChanged", + "old": "parameter com.datastax.oss.driver.api.core.type.codec.TypeCodec> com.datastax.oss.driver.api.core.type.codec.TypeCodecs::vectorOf(com.datastax.oss.driver.api.core.type.CqlVectorType, ===com.datastax.oss.driver.api.core.type.codec.TypeCodec===)", + "new": "parameter com.datastax.oss.driver.api.core.type.codec.TypeCodec> com.datastax.oss.driver.api.core.type.codec.TypeCodecs::vectorOf(com.datastax.oss.driver.api.core.type.VectorType, ===com.datastax.oss.driver.api.core.type.codec.TypeCodec===)", + "justification": "Refactorings in PR 1666" + }, + { + "code": "java.method.returnTypeTypeParametersChanged", + "old": "method com.datastax.oss.driver.api.core.type.codec.TypeCodec> com.datastax.oss.driver.api.core.type.codec.TypeCodecs::vectorOf(com.datastax.oss.driver.api.core.type.CqlVectorType, com.datastax.oss.driver.api.core.type.codec.TypeCodec)", + "new": "method com.datastax.oss.driver.api.core.type.codec.TypeCodec> com.datastax.oss.driver.api.core.type.codec.TypeCodecs::vectorOf(com.datastax.oss.driver.api.core.type.VectorType, com.datastax.oss.driver.api.core.type.codec.TypeCodec)", + "justification": "Refactorings in PR 1666" + }, + { + "code": "java.generics.formalTypeParameterChanged", + "old": "method com.datastax.oss.driver.api.core.type.codec.TypeCodec> com.datastax.oss.driver.api.core.type.codec.TypeCodecs::vectorOf(com.datastax.oss.driver.api.core.type.CqlVectorType, com.datastax.oss.driver.api.core.type.codec.TypeCodec)", + "new": "method com.datastax.oss.driver.api.core.type.codec.TypeCodec> com.datastax.oss.driver.api.core.type.codec.TypeCodecs::vectorOf(com.datastax.oss.driver.api.core.type.VectorType, com.datastax.oss.driver.api.core.type.codec.TypeCodec)", + "justification": "Refactorings in PR 1666" + }, + { + "code": "java.method.parameterTypeParameterChanged", + "old": "parameter com.datastax.oss.driver.api.core.type.reflect.GenericType> com.datastax.oss.driver.api.core.type.reflect.GenericType::vectorOf(===com.datastax.oss.driver.api.core.type.reflect.GenericType===)", + "new": "parameter com.datastax.oss.driver.api.core.type.reflect.GenericType> com.datastax.oss.driver.api.core.type.reflect.GenericType::vectorOf(===com.datastax.oss.driver.api.core.type.reflect.GenericType===)", + "justification": "Refactorings in PR 1666" + }, + { + "code": "java.method.returnTypeTypeParametersChanged", + "old": "method com.datastax.oss.driver.api.core.type.reflect.GenericType> com.datastax.oss.driver.api.core.type.reflect.GenericType::vectorOf(com.datastax.oss.driver.api.core.type.reflect.GenericType)", + "new": "method com.datastax.oss.driver.api.core.type.reflect.GenericType> com.datastax.oss.driver.api.core.type.reflect.GenericType::vectorOf(com.datastax.oss.driver.api.core.type.reflect.GenericType)", + "justification": "Refactorings in PR 1666" + }, + { + "code": "java.generics.formalTypeParameterChanged", + "old": "method com.datastax.oss.driver.api.core.type.reflect.GenericType> com.datastax.oss.driver.api.core.type.reflect.GenericType::vectorOf(com.datastax.oss.driver.api.core.type.reflect.GenericType)", + "new": "method com.datastax.oss.driver.api.core.type.reflect.GenericType> com.datastax.oss.driver.api.core.type.reflect.GenericType::vectorOf(com.datastax.oss.driver.api.core.type.reflect.GenericType)", + "justification": "Refactorings in PR 1666" + }, + { + "code": "java.method.returnTypeChangedCovariantly", + "old": "method java.lang.Throwable java.lang.Throwable::fillInStackTrace() @ com.fasterxml.jackson.databind.deser.UnresolvedForwardReference", + "new": "method com.fasterxml.jackson.databind.deser.UnresolvedForwardReference com.fasterxml.jackson.databind.deser.UnresolvedForwardReference::fillInStackTrace()", + "justification": "Upgrade jackson-databind to 2.13.4.1 to address CVEs, API change cause: https://github.com/FasterXML/jackson-databind/issues/3419" + }, + { + "code": "java.annotation.added", + "old": "method SelfT com.datastax.oss.driver.api.core.cql.Statement>::setNowInSeconds(int) @ com.datastax.oss.driver.api.core.cql.BatchStatement", + "new": "method SelfT com.datastax.oss.driver.api.core.cql.Statement>::setNowInSeconds(int) @ com.datastax.oss.driver.api.core.cql.BatchStatement", + "annotation": "@edu.umd.cs.findbugs.annotations.CheckReturnValue", + "justification": "Annotate mutating methods with @CheckReturnValue" + }, + { + "code": "java.annotation.added", + "old": "method SelfT com.datastax.oss.driver.api.core.cql.Statement>::setNowInSeconds(int) @ com.datastax.oss.driver.api.core.cql.BatchableStatement>", + "new": "method SelfT com.datastax.oss.driver.api.core.cql.Statement>::setNowInSeconds(int) @ com.datastax.oss.driver.api.core.cql.BatchStatement", + "annotation": "@edu.umd.cs.findbugs.annotations.CheckReturnValue", + "justification": "Annotate mutating methods with @CheckReturnValue" + }, + { + "code": "java.annotation.added", + "old": "method SelfT com.datastax.oss.driver.api.core.cql.Statement>::setNowInSeconds(int) @ com.datastax.oss.driver.api.core.cql.BatchableStatement>", + "new": "method SelfT com.datastax.oss.driver.api.core.cql.Statement>::setNowInSeconds(int) @ com.datastax.oss.driver.api.core.cql.BatchableStatement>", + "annotation": "@edu.umd.cs.findbugs.annotations.CheckReturnValue", + "justification": "Annotate mutating methods with @CheckReturnValue" + }, + { + "code": "java.annotation.added", + "old": "method SelfT com.datastax.oss.driver.api.core.cql.Statement>::setNowInSeconds(int) @ com.datastax.oss.driver.api.core.cql.BoundStatement", + "new": "method SelfT com.datastax.oss.driver.api.core.cql.Statement>::setNowInSeconds(int) @ com.datastax.oss.driver.api.core.cql.BoundStatement", + "annotation": "@edu.umd.cs.findbugs.annotations.CheckReturnValue", + "justification": "Annotate mutating methods with @CheckReturnValue" + }, + { + "code": "java.annotation.added", + "old": "method SelfT com.datastax.oss.driver.api.core.cql.Statement>::setNowInSeconds(int) @ com.datastax.oss.driver.api.core.cql.SimpleStatement", + "new": "method SelfT com.datastax.oss.driver.api.core.cql.Statement>::setNowInSeconds(int) @ com.datastax.oss.driver.api.core.cql.SimpleStatement", + "annotation": "@edu.umd.cs.findbugs.annotations.CheckReturnValue", + "justification": "Annotate mutating methods with @CheckReturnValue" + }, + { + "code": "java.annotation.added", + "old": "method SelfT com.datastax.oss.driver.api.core.cql.Statement>::setNowInSeconds(int)", + "new": "method SelfT com.datastax.oss.driver.api.core.cql.Statement>::setNowInSeconds(int)", + "annotation": "@edu.umd.cs.findbugs.annotations.CheckReturnValue", + "justification": "Annotate mutating methods with @CheckReturnValue" + }, + { + "code": "java.annotation.added", + "old": "method com.datastax.oss.driver.api.core.cql.BatchStatement com.datastax.oss.driver.api.core.cql.BatchStatement::add(com.datastax.oss.driver.api.core.cql.BatchableStatement)", + "new": "method com.datastax.oss.driver.api.core.cql.BatchStatement com.datastax.oss.driver.api.core.cql.BatchStatement::add(com.datastax.oss.driver.api.core.cql.BatchableStatement)", + "annotation": "@edu.umd.cs.findbugs.annotations.CheckReturnValue", + "justification": "Annotate mutating methods with @CheckReturnValue" + }, + { + "code": "java.annotation.added", + "old": "method com.datastax.oss.driver.api.core.cql.BatchStatement com.datastax.oss.driver.api.core.cql.BatchStatement::addAll(com.datastax.oss.driver.api.core.cql.BatchableStatement[])", + "new": "method com.datastax.oss.driver.api.core.cql.BatchStatement com.datastax.oss.driver.api.core.cql.BatchStatement::addAll(com.datastax.oss.driver.api.core.cql.BatchableStatement[])", + "annotation": "@edu.umd.cs.findbugs.annotations.CheckReturnValue", + "justification": "Annotate mutating methods with @CheckReturnValue" + }, + { + "code": "java.annotation.added", + "old": "method com.datastax.oss.driver.api.core.cql.BatchStatement com.datastax.oss.driver.api.core.cql.BatchStatement::addAll(java.lang.Iterable>)", + "new": "method com.datastax.oss.driver.api.core.cql.BatchStatement com.datastax.oss.driver.api.core.cql.BatchStatement::addAll(java.lang.Iterable>)", + "annotation": "@edu.umd.cs.findbugs.annotations.CheckReturnValue", + "justification": "Annotate mutating methods with @CheckReturnValue" + }, + { + "code": "java.annotation.added", + "old": "method com.datastax.oss.driver.api.core.cql.BatchStatement com.datastax.oss.driver.api.core.cql.BatchStatement::clear()", + "new": "method com.datastax.oss.driver.api.core.cql.BatchStatement com.datastax.oss.driver.api.core.cql.BatchStatement::clear()", + "annotation": "@edu.umd.cs.findbugs.annotations.CheckReturnValue", + "justification": "Annotate mutating methods with @CheckReturnValue" + }, + { + "code": "java.annotation.added", + "old": "method com.datastax.oss.driver.api.core.cql.BatchStatement com.datastax.oss.driver.api.core.cql.BatchStatement::setBatchType(com.datastax.oss.driver.api.core.cql.BatchType)", + "new": "method com.datastax.oss.driver.api.core.cql.BatchStatement com.datastax.oss.driver.api.core.cql.BatchStatement::setBatchType(com.datastax.oss.driver.api.core.cql.BatchType)", + "annotation": "@edu.umd.cs.findbugs.annotations.CheckReturnValue", + "justification": "Annotate mutating methods with @CheckReturnValue" + }, + { + "code": "java.annotation.added", + "old": "method com.datastax.oss.driver.api.core.cql.BatchStatement com.datastax.oss.driver.api.core.cql.BatchStatement::setKeyspace(com.datastax.oss.driver.api.core.CqlIdentifier)", + "new": "method com.datastax.oss.driver.api.core.cql.BatchStatement com.datastax.oss.driver.api.core.cql.BatchStatement::setKeyspace(com.datastax.oss.driver.api.core.CqlIdentifier)", + "annotation": "@edu.umd.cs.findbugs.annotations.CheckReturnValue", + "justification": "JAVA-2161: Annotate mutating methods with @CheckReturnValue" + }, + { + "code": "java.annotation.added", + "old": "method com.datastax.oss.driver.api.core.cql.BatchStatement com.datastax.oss.driver.api.core.cql.BatchStatement::setKeyspace(java.lang.String)", + "new": "method com.datastax.oss.driver.api.core.cql.BatchStatement com.datastax.oss.driver.api.core.cql.BatchStatement::setKeyspace(java.lang.String)", + "annotation": "@edu.umd.cs.findbugs.annotations.CheckReturnValue", + "justification": "JAVA-2161: Annotate mutating methods with @CheckReturnValue" + }, + { + "code": "java.annotation.added", + "old": "method com.datastax.oss.driver.api.core.cql.SimpleStatement com.datastax.oss.driver.api.core.cql.SimpleStatement::setQuery(java.lang.String)", + "new": "method com.datastax.oss.driver.api.core.cql.SimpleStatement com.datastax.oss.driver.api.core.cql.SimpleStatement::setQuery(java.lang.String)", + "annotation": "@edu.umd.cs.findbugs.annotations.CheckReturnValue", + "justification": "Annotate mutating methods with @CheckReturnValue" + }, + { + "code": "java.annotation.added", + "old": "method com.datastax.oss.driver.api.core.cql.SimpleStatement com.datastax.oss.driver.api.core.cql.SimpleStatement::setKeyspace(com.datastax.oss.driver.api.core.CqlIdentifier)", + "new": "method com.datastax.oss.driver.api.core.cql.SimpleStatement com.datastax.oss.driver.api.core.cql.SimpleStatement::setKeyspace(com.datastax.oss.driver.api.core.CqlIdentifier)", + "annotation": "@edu.umd.cs.findbugs.annotations.CheckReturnValue", + "justification": "Annotate mutating methods with @CheckReturnValue" + }, + { + "code": "java.annotation.added", + "old": "method com.datastax.oss.driver.api.core.cql.SimpleStatement com.datastax.oss.driver.api.core.cql.SimpleStatement::setKeyspace(java.lang.String)", + "new": "method com.datastax.oss.driver.api.core.cql.SimpleStatement com.datastax.oss.driver.api.core.cql.SimpleStatement::setKeyspace(java.lang.String)", + "annotation": "@edu.umd.cs.findbugs.annotations.CheckReturnValue", + "justification": "Annotate mutating methods with @CheckReturnValue" + }, + { + "code": "java.annotation.added", + "old": "method com.datastax.oss.driver.api.core.cql.SimpleStatement com.datastax.oss.driver.api.core.cql.SimpleStatement::setPositionalValues(java.util.List)", + "new": "method com.datastax.oss.driver.api.core.cql.SimpleStatement com.datastax.oss.driver.api.core.cql.SimpleStatement::setPositionalValues(java.util.List)", + "annotation": "@edu.umd.cs.findbugs.annotations.CheckReturnValue", + "justification": "Annotate mutating methods with @CheckReturnValue" + }, + { + "code": "java.annotation.added", + "old": "method com.datastax.oss.driver.api.core.cql.SimpleStatement com.datastax.oss.driver.api.core.cql.SimpleStatement::setNamedValuesWithIds(java.util.Map)", + "new": "method com.datastax.oss.driver.api.core.cql.SimpleStatement com.datastax.oss.driver.api.core.cql.SimpleStatement::setNamedValuesWithIds(java.util.Map)", + "annotation": "@edu.umd.cs.findbugs.annotations.CheckReturnValue", + "justification": "Annotate mutating methods with @CheckReturnValue" + }, + { + "code": "java.annotation.added", + "old": "method com.datastax.oss.driver.api.core.cql.SimpleStatement com.datastax.oss.driver.api.core.cql.SimpleStatement::setNamedValues(java.util.Map)", + "new": "method com.datastax.oss.driver.api.core.cql.SimpleStatement com.datastax.oss.driver.api.core.cql.SimpleStatement::setNamedValues(java.util.Map)", + "annotation": "@edu.umd.cs.findbugs.annotations.CheckReturnValue", + "justification": "Annotate mutating methods with @CheckReturnValue" + }, + { + "code": "java.method.parameterTypeParameterChanged", + "old": "parameter com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.CqlVector::from(java.lang.String, ===com.datastax.oss.driver.api.core.type.codec.TypeCodec===)", + "new": "parameter com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.CqlVector::from(java.lang.String, ===com.datastax.oss.driver.api.core.type.codec.TypeCodec===)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.method.returnTypeTypeParametersChanged", + "old": "method com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.CqlVector::from(java.lang.String, com.datastax.oss.driver.api.core.type.codec.TypeCodec)", + "new": "method com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.CqlVector::from(java.lang.String, com.datastax.oss.driver.api.core.type.codec.TypeCodec)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.generics.formalTypeParameterChanged", + "old": "method com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.CqlVector::from(java.lang.String, com.datastax.oss.driver.api.core.type.codec.TypeCodec)", + "new": "method com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.CqlVector::from(java.lang.String, com.datastax.oss.driver.api.core.type.codec.TypeCodec)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.method.returnTypeChanged", + "old": "method T com.datastax.oss.driver.api.core.data.CqlVector::get(int)", + "new": "method T com.datastax.oss.driver.api.core.data.CqlVector::get(int)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.method.returnTypeTypeParametersChanged", + "old": "method java.util.Iterator com.datastax.oss.driver.api.core.data.CqlVector::iterator()", + "new": "method java.util.Iterator com.datastax.oss.driver.api.core.data.CqlVector::iterator()", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.method.parameterTypeChanged", + "old": "parameter com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.CqlVector::newInstance(===V[]===)", + "new": "parameter com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.CqlVector::newInstance(===V[]===)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.method.returnTypeTypeParametersChanged", + "old": "method com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.CqlVector::newInstance(V[])", + "new": "method com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.CqlVector::newInstance(V[])", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.generics.formalTypeParameterChanged", + "old": "method com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.CqlVector::newInstance(V[])", + "new": "method com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.CqlVector::newInstance(V[])", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.method.parameterTypeParameterChanged", + "old": "parameter com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.CqlVector::newInstance(===java.util.List===)", + "new": "parameter com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.CqlVector::newInstance(===java.util.List===)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.method.returnTypeTypeParametersChanged", + "old": "method com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.CqlVector::newInstance(java.util.List)", + "new": "method com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.CqlVector::newInstance(java.util.List)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.generics.formalTypeParameterChanged", + "old": "method com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.CqlVector::newInstance(java.util.List)", + "new": "method com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.CqlVector::newInstance(java.util.List)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.method.parameterTypeChanged", + "old": "parameter T com.datastax.oss.driver.api.core.data.CqlVector::set(int, ===T===)", + "new": "parameter T com.datastax.oss.driver.api.core.data.CqlVector::set(int, ===T===)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.method.returnTypeChanged", + "old": "method T com.datastax.oss.driver.api.core.data.CqlVector::set(int, T)", + "new": "method T com.datastax.oss.driver.api.core.data.CqlVector::set(int, T)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.method.returnTypeTypeParametersChanged", + "old": "method java.util.Spliterator java.lang.Iterable::spliterator() @ com.datastax.oss.driver.api.core.data.CqlVector", + "new": "method java.util.Spliterator java.lang.Iterable::spliterator() @ com.datastax.oss.driver.api.core.data.CqlVector", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.method.returnTypeTypeParametersChanged", + "old": "method java.util.stream.Stream com.datastax.oss.driver.api.core.data.CqlVector::stream()", + "new": "method java.util.stream.Stream com.datastax.oss.driver.api.core.data.CqlVector::stream()", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.method.returnTypeTypeParametersChanged", + "old": "method com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.CqlVector::subVector(int, int)", + "new": "method com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.CqlVector::subVector(int, int)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.class.noLongerImplementsInterface", + "old": "class com.datastax.oss.driver.api.core.data.CqlVector", + "new": "class com.datastax.oss.driver.api.core.data.CqlVector", + "interface": "java.lang.Iterable", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.generics.formalTypeParameterChanged", + "old": "class com.datastax.oss.driver.api.core.data.CqlVector", + "new": "class com.datastax.oss.driver.api.core.data.CqlVector", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.class.superTypeTypeParametersChanged", + "old": "class com.datastax.oss.driver.api.core.data.CqlVector", + "new": "class com.datastax.oss.driver.api.core.data.CqlVector", + "oldSuperType": "java.lang.Iterable", + "newSuperType": "java.lang.Iterable", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.method.parameterTypeParameterChanged", + "old": "parameter com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.GettableById::getVector(com.datastax.oss.driver.api.core.CqlIdentifier, ===java.lang.Class===)", + "new": "parameter com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.GettableById::getVector(com.datastax.oss.driver.api.core.CqlIdentifier, ===java.lang.Class===)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.method.returnTypeTypeParametersChanged", + "old": "method com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.GettableById::getVector(com.datastax.oss.driver.api.core.CqlIdentifier, java.lang.Class)", + "new": "method com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.GettableById::getVector(com.datastax.oss.driver.api.core.CqlIdentifier, java.lang.Class)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.generics.formalTypeParameterChanged", + "old": "method com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.GettableById::getVector(com.datastax.oss.driver.api.core.CqlIdentifier, java.lang.Class)", + "new": "method com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.GettableById::getVector(com.datastax.oss.driver.api.core.CqlIdentifier, java.lang.Class)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.method.parameterTypeParameterChanged", + "old": "parameter com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.GettableByIndex::getVector(int, ===java.lang.Class===)", + "new": "parameter com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.GettableByIndex::getVector(int, ===java.lang.Class===)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.method.returnTypeTypeParametersChanged", + "old": "method com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.GettableByIndex::getVector(int, java.lang.Class)", + "new": "method com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.GettableByIndex::getVector(int, java.lang.Class)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.generics.formalTypeParameterChanged", + "old": "method com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.GettableByIndex::getVector(int, java.lang.Class)", + "new": "method com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.GettableByIndex::getVector(int, java.lang.Class)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.method.parameterTypeParameterChanged", + "old": "parameter com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.GettableByName::getVector(java.lang.String, ===java.lang.Class===)", + "new": "parameter com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.GettableByName::getVector(java.lang.String, ===java.lang.Class===)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.method.returnTypeTypeParametersChanged", + "old": "method com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.GettableByName::getVector(java.lang.String, java.lang.Class)", + "new": "method com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.GettableByName::getVector(java.lang.String, java.lang.Class)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.generics.formalTypeParameterChanged", + "old": "method com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.GettableByName::getVector(java.lang.String, java.lang.Class)", + "new": "method com.datastax.oss.driver.api.core.data.CqlVector com.datastax.oss.driver.api.core.data.GettableByName::getVector(java.lang.String, java.lang.Class)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.method.parameterTypeParameterChanged", + "old": "parameter SelfT com.datastax.oss.driver.api.core.data.SettableById>::setVector(com.datastax.oss.driver.api.core.CqlIdentifier, ===com.datastax.oss.driver.api.core.data.CqlVector===, java.lang.Class)", + "new": "parameter SelfT com.datastax.oss.driver.api.core.data.SettableById>::setVector(com.datastax.oss.driver.api.core.CqlIdentifier, ===com.datastax.oss.driver.api.core.data.CqlVector===, java.lang.Class)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.method.parameterTypeParameterChanged", + "old": "parameter SelfT com.datastax.oss.driver.api.core.data.SettableById>::setVector(com.datastax.oss.driver.api.core.CqlIdentifier, com.datastax.oss.driver.api.core.data.CqlVector, ===java.lang.Class===)", + "new": "parameter SelfT com.datastax.oss.driver.api.core.data.SettableById>::setVector(com.datastax.oss.driver.api.core.CqlIdentifier, com.datastax.oss.driver.api.core.data.CqlVector, ===java.lang.Class===)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.generics.formalTypeParameterChanged", + "old": "method SelfT com.datastax.oss.driver.api.core.data.SettableById>::setVector(com.datastax.oss.driver.api.core.CqlIdentifier, com.datastax.oss.driver.api.core.data.CqlVector, java.lang.Class)", + "new": "method SelfT com.datastax.oss.driver.api.core.data.SettableById>::setVector(com.datastax.oss.driver.api.core.CqlIdentifier, com.datastax.oss.driver.api.core.data.CqlVector, java.lang.Class)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.method.parameterTypeParameterChanged", + "old": "parameter SelfT com.datastax.oss.driver.api.core.data.SettableByIndex>::setVector(int, ===com.datastax.oss.driver.api.core.data.CqlVector===, java.lang.Class)", + "new": "parameter SelfT com.datastax.oss.driver.api.core.data.SettableByIndex>::setVector(int, ===com.datastax.oss.driver.api.core.data.CqlVector===, java.lang.Class)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.method.parameterTypeParameterChanged", + "old": "parameter SelfT com.datastax.oss.driver.api.core.data.SettableByIndex>::setVector(int, com.datastax.oss.driver.api.core.data.CqlVector, ===java.lang.Class===)", + "new": "parameter SelfT com.datastax.oss.driver.api.core.data.SettableByIndex>::setVector(int, com.datastax.oss.driver.api.core.data.CqlVector, ===java.lang.Class===)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.generics.formalTypeParameterChanged", + "old": "method SelfT com.datastax.oss.driver.api.core.data.SettableByIndex>::setVector(int, com.datastax.oss.driver.api.core.data.CqlVector, java.lang.Class)", + "new": "method SelfT com.datastax.oss.driver.api.core.data.SettableByIndex>::setVector(int, com.datastax.oss.driver.api.core.data.CqlVector, java.lang.Class)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.method.parameterTypeParameterChanged", + "old": "parameter SelfT com.datastax.oss.driver.api.core.data.SettableByName>::setVector(java.lang.String, ===com.datastax.oss.driver.api.core.data.CqlVector===, java.lang.Class)", + "new": "parameter SelfT com.datastax.oss.driver.api.core.data.SettableByName>::setVector(java.lang.String, ===com.datastax.oss.driver.api.core.data.CqlVector===, java.lang.Class)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.method.parameterTypeParameterChanged", + "old": "parameter SelfT com.datastax.oss.driver.api.core.data.SettableByName>::setVector(java.lang.String, com.datastax.oss.driver.api.core.data.CqlVector, ===java.lang.Class===)", + "new": "parameter SelfT com.datastax.oss.driver.api.core.data.SettableByName>::setVector(java.lang.String, com.datastax.oss.driver.api.core.data.CqlVector, ===java.lang.Class===)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.generics.formalTypeParameterChanged", + "old": "method SelfT com.datastax.oss.driver.api.core.data.SettableByName>::setVector(java.lang.String, com.datastax.oss.driver.api.core.data.CqlVector, java.lang.Class)", + "new": "method SelfT com.datastax.oss.driver.api.core.data.SettableByName>::setVector(java.lang.String, com.datastax.oss.driver.api.core.data.CqlVector, java.lang.Class)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.method.parameterTypeParameterChanged", + "old": "parameter com.datastax.oss.driver.api.core.type.codec.TypeCodec> com.datastax.oss.driver.api.core.type.codec.TypeCodecs::vectorOf(com.datastax.oss.driver.api.core.type.VectorType, ===com.datastax.oss.driver.api.core.type.codec.TypeCodec===)", + "new": "parameter com.datastax.oss.driver.api.core.type.codec.TypeCodec> com.datastax.oss.driver.api.core.type.codec.TypeCodecs::vectorOf(com.datastax.oss.driver.api.core.type.VectorType, ===com.datastax.oss.driver.api.core.type.codec.TypeCodec===)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.method.returnTypeTypeParametersChanged", + "old": "method com.datastax.oss.driver.api.core.type.codec.TypeCodec> com.datastax.oss.driver.api.core.type.codec.TypeCodecs::vectorOf(com.datastax.oss.driver.api.core.type.VectorType, com.datastax.oss.driver.api.core.type.codec.TypeCodec)", + "new": "method com.datastax.oss.driver.api.core.type.codec.TypeCodec> com.datastax.oss.driver.api.core.type.codec.TypeCodecs::vectorOf(com.datastax.oss.driver.api.core.type.VectorType, com.datastax.oss.driver.api.core.type.codec.TypeCodec)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.generics.formalTypeParameterChanged", + "old": "method com.datastax.oss.driver.api.core.type.codec.TypeCodec> com.datastax.oss.driver.api.core.type.codec.TypeCodecs::vectorOf(com.datastax.oss.driver.api.core.type.VectorType, com.datastax.oss.driver.api.core.type.codec.TypeCodec)", + "new": "method com.datastax.oss.driver.api.core.type.codec.TypeCodec> com.datastax.oss.driver.api.core.type.codec.TypeCodecs::vectorOf(com.datastax.oss.driver.api.core.type.VectorType, com.datastax.oss.driver.api.core.type.codec.TypeCodec)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.method.parameterTypeParameterChanged", + "old": "parameter com.datastax.oss.driver.api.core.type.codec.TypeCodec> com.datastax.oss.driver.api.core.type.codec.TypeCodecs::vectorOf(int, ===com.datastax.oss.driver.api.core.type.codec.TypeCodec===)", + "new": "parameter com.datastax.oss.driver.api.core.type.codec.TypeCodec> com.datastax.oss.driver.api.core.type.codec.TypeCodecs::vectorOf(int, ===com.datastax.oss.driver.api.core.type.codec.TypeCodec===)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.method.returnTypeTypeParametersChanged", + "old": "method com.datastax.oss.driver.api.core.type.codec.TypeCodec> com.datastax.oss.driver.api.core.type.codec.TypeCodecs::vectorOf(int, com.datastax.oss.driver.api.core.type.codec.TypeCodec)", + "new": "method com.datastax.oss.driver.api.core.type.codec.TypeCodec> com.datastax.oss.driver.api.core.type.codec.TypeCodecs::vectorOf(int, com.datastax.oss.driver.api.core.type.codec.TypeCodec)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.generics.formalTypeParameterChanged", + "old": "method com.datastax.oss.driver.api.core.type.codec.TypeCodec> com.datastax.oss.driver.api.core.type.codec.TypeCodecs::vectorOf(int, com.datastax.oss.driver.api.core.type.codec.TypeCodec)", + "new": "method com.datastax.oss.driver.api.core.type.codec.TypeCodec> com.datastax.oss.driver.api.core.type.codec.TypeCodecs::vectorOf(int, com.datastax.oss.driver.api.core.type.codec.TypeCodec)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.method.parameterTypeParameterChanged", + "old": "parameter com.datastax.oss.driver.api.core.type.reflect.GenericType> com.datastax.oss.driver.api.core.type.reflect.GenericType::vectorOf(===com.datastax.oss.driver.api.core.type.reflect.GenericType===)", + "new": "parameter com.datastax.oss.driver.api.core.type.reflect.GenericType> com.datastax.oss.driver.api.core.type.reflect.GenericType::vectorOf(===com.datastax.oss.driver.api.core.type.reflect.GenericType===)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.method.returnTypeTypeParametersChanged", + "old": "method com.datastax.oss.driver.api.core.type.reflect.GenericType> com.datastax.oss.driver.api.core.type.reflect.GenericType::vectorOf(com.datastax.oss.driver.api.core.type.reflect.GenericType)", + "new": "method com.datastax.oss.driver.api.core.type.reflect.GenericType> com.datastax.oss.driver.api.core.type.reflect.GenericType::vectorOf(com.datastax.oss.driver.api.core.type.reflect.GenericType)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.generics.formalTypeParameterChanged", + "old": "method com.datastax.oss.driver.api.core.type.reflect.GenericType> com.datastax.oss.driver.api.core.type.reflect.GenericType::vectorOf(com.datastax.oss.driver.api.core.type.reflect.GenericType)", + "new": "method com.datastax.oss.driver.api.core.type.reflect.GenericType> com.datastax.oss.driver.api.core.type.reflect.GenericType::vectorOf(com.datastax.oss.driver.api.core.type.reflect.GenericType)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.method.parameterTypeParameterChanged", + "old": "parameter com.datastax.oss.driver.api.core.type.reflect.GenericType> com.datastax.oss.driver.api.core.type.reflect.GenericType::vectorOf(===java.lang.Class===)", + "new": "parameter com.datastax.oss.driver.api.core.type.reflect.GenericType> com.datastax.oss.driver.api.core.type.reflect.GenericType::vectorOf(===java.lang.Class===)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.method.returnTypeTypeParametersChanged", + "old": "method com.datastax.oss.driver.api.core.type.reflect.GenericType> com.datastax.oss.driver.api.core.type.reflect.GenericType::vectorOf(java.lang.Class)", + "new": "method com.datastax.oss.driver.api.core.type.reflect.GenericType> com.datastax.oss.driver.api.core.type.reflect.GenericType::vectorOf(java.lang.Class)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.generics.formalTypeParameterChanged", + "old": "method com.datastax.oss.driver.api.core.type.reflect.GenericType> com.datastax.oss.driver.api.core.type.reflect.GenericType::vectorOf(java.lang.Class)", + "new": "method com.datastax.oss.driver.api.core.type.reflect.GenericType> com.datastax.oss.driver.api.core.type.reflect.GenericType::vectorOf(java.lang.Class)", + "justification": "JAVA-3143: Extend driver vector support to arbitrary subtypes and fix handling of variable length types (OSS C* 5.0)" + }, + { + "code": "java.class.nonPublicPartOfAPI", + "old": "class com.datastax.oss.driver.internal.core.config.typesafe.TypesafeDriverExecutionProfile.Base", + "justification": "CASSJAVA-102: Fix spurious complaints about optional dependencies" + }, + { + "code": "java.class.nonPublicPartOfAPI", + "old": "class com.fasterxml.jackson.databind.type.TypeParser.MyTokenizer", + "justification": "CASSJAVA-102: Fix spurious complaints about optional dependencies" + }, + { + "code": "java.class.nonPublicPartOfAPI", + "old": "class org.apache.tinkerpop.shaded.jackson.databind.type.TypeParser.MyTokenizer", + "justification": "CASSJAVA-102: Fix spurious complaints about optional dependencies" + }, + { + "code": "java.class.externalClassExposedInAPI", + "justification": "CASSJAVA-102: Migrate revapi config into dedicated config files, ported from pom.xml" + }, + { + "code": "java.method.varargOverloadsOnlyDifferInVarargParameter", + "justification": "CASSJAVA-102: Migrate revapi config into dedicated config files, ported from pom.xml" + }, + { + "code": "java.method.addedToInterface", + "new": "method java.util.Optional com.datastax.oss.driver.api.core.context.DriverContext::getRequestIdGenerator()", + "justification": "CASSJAVA-97: Let users inject an ID for each request and write to the custom payload" } ] } diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/DseProtocolVersion.java b/core/src/main/java/com/datastax/dse/driver/api/core/DseProtocolVersion.java index 3d2a016f899..dc420970427 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/DseProtocolVersion.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/DseProtocolVersion.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/DseSession.java b/core/src/main/java/com/datastax/dse/driver/api/core/DseSession.java index d66487eb41c..8251aaf767c 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/DseSession.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/DseSession.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/DseSessionBuilder.java b/core/src/main/java/com/datastax/dse/driver/api/core/DseSessionBuilder.java index a8f2840895d..01e5f9f9125 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/DseSessionBuilder.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/DseSessionBuilder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/auth/BaseDseAuthenticator.java b/core/src/main/java/com/datastax/dse/driver/api/core/auth/BaseDseAuthenticator.java index dd595f20ee0..abd68b530b6 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/auth/BaseDseAuthenticator.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/auth/BaseDseAuthenticator.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/auth/DseGssApiAuthProviderBase.java b/core/src/main/java/com/datastax/dse/driver/api/core/auth/DseGssApiAuthProviderBase.java index 36fb0d5475c..48a0e5b0ef3 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/auth/DseGssApiAuthProviderBase.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/auth/DseGssApiAuthProviderBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/auth/DsePlainTextAuthProviderBase.java b/core/src/main/java/com/datastax/dse/driver/api/core/auth/DsePlainTextAuthProviderBase.java index 39ce47136d3..7c5ee23bd6c 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/auth/DsePlainTextAuthProviderBase.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/auth/DsePlainTextAuthProviderBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/auth/ProgrammaticDseGssApiAuthProvider.java b/core/src/main/java/com/datastax/dse/driver/api/core/auth/ProgrammaticDseGssApiAuthProvider.java index 1cb193fb726..64ee5265b5a 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/auth/ProgrammaticDseGssApiAuthProvider.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/auth/ProgrammaticDseGssApiAuthProvider.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/auth/ProxyAuthentication.java b/core/src/main/java/com/datastax/dse/driver/api/core/auth/ProxyAuthentication.java index a3756277e2a..a3624ba736d 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/auth/ProxyAuthentication.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/auth/ProxyAuthentication.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/config/DseDriverConfigLoader.java b/core/src/main/java/com/datastax/dse/driver/api/core/config/DseDriverConfigLoader.java index cda2acdaa27..2694b51ffca 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/config/DseDriverConfigLoader.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/config/DseDriverConfigLoader.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/config/DseDriverOption.java b/core/src/main/java/com/datastax/dse/driver/api/core/config/DseDriverOption.java index ac493719ef6..4d10501f6d2 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/config/DseDriverOption.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/config/DseDriverOption.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -247,6 +249,75 @@ public enum DseDriverOption implements DriverOption { *

Value-type: {@link java.time.Duration Duration} */ METRICS_NODE_GRAPH_MESSAGES_INTERVAL("advanced.metrics.node.graph-messages.refresh-interval"), + + /** + * The shortest latency that we expect to record for continuous requests. + * + *

Value-type: {@link java.time.Duration Duration} + */ + CONTINUOUS_PAGING_METRICS_SESSION_CQL_REQUESTS_LOWEST( + "advanced.metrics.session.continuous-cql-requests.lowest-latency"), + /** + * Optional service-level objectives to meet, as a list of latencies to track. + * + *

Value-type: {@link java.time.Duration Duration} + */ + CONTINUOUS_PAGING_METRICS_SESSION_CQL_REQUESTS_SLO( + "advanced.metrics.session.continuous-cql-requests.slo"), + + /** + * The shortest latency that we expect to record for graph requests. + * + *

Value-type: {@link java.time.Duration Duration} + */ + METRICS_SESSION_GRAPH_REQUESTS_LOWEST("advanced.metrics.session.graph-requests.lowest-latency"), + /** + * Optional service-level objectives to meet, as a list of latencies to track. + * + *

Value-type: {@link java.time.Duration Duration} + */ + METRICS_SESSION_GRAPH_REQUESTS_SLO("advanced.metrics.session.graph-requests.slo"), + + /** + * The shortest latency that we expect to record for graph requests. + * + *

Value-type: {@link java.time.Duration Duration} + */ + METRICS_NODE_GRAPH_MESSAGES_LOWEST("advanced.metrics.node.graph-messages.lowest-latency"), + /** + * Optional service-level objectives to meet, as a list of latencies to track. + * + *

Value-type: {@link java.time.Duration Duration} + */ + METRICS_NODE_GRAPH_MESSAGES_SLO("advanced.metrics.node.graph-messages.slo"), + /** + * Optional list of percentiles to publish for graph-requests metric. Produces an additional time + * series for each requested percentile. This percentile is computed locally, and so can't be + * aggregated with percentiles computed across other dimensions (e.g. in a different instance). + * + *

Value type: {@link java.util.List List}<{@link Double}> + */ + METRICS_SESSION_GRAPH_REQUESTS_PUBLISH_PERCENTILES( + "advanced.metrics.session.graph-requests.publish-percentiles"), + /** + * Optional list of percentiles to publish for node graph-messages metric. Produces an additional + * time series for each requested percentile. This percentile is computed locally, and so can't be + * aggregated with percentiles computed across other dimensions (e.g. in a different instance). + * + *

Value type: {@link java.util.List List}<{@link Double}> + */ + METRICS_NODE_GRAPH_MESSAGES_PUBLISH_PERCENTILES( + "advanced.metrics.node.graph-messages.publish-percentiles"), + /** + * Optional list of percentiles to publish for continuous paging requests metric. Produces an + * additional time series for each requested percentile. This percentile is computed locally, and + * so can't be aggregated with percentiles computed across other dimensions (e.g. in a different + * instance). + * + *

Value type: {@link java.util.List List}<{@link Double}> + */ + CONTINUOUS_PAGING_METRICS_SESSION_CQL_REQUESTS_PUBLISH_PERCENTILES( + "advanced.metrics.session.continuous-cql-requests.publish-percentiles"), ; private final String path; diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/cql/continuous/ContinuousAsyncResultSet.java b/core/src/main/java/com/datastax/dse/driver/api/core/cql/continuous/ContinuousAsyncResultSet.java index a9588be16a9..a9491ec2414 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/cql/continuous/ContinuousAsyncResultSet.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/cql/continuous/ContinuousAsyncResultSet.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/cql/continuous/ContinuousResultSet.java b/core/src/main/java/com/datastax/dse/driver/api/core/cql/continuous/ContinuousResultSet.java index d4473144c48..a333801a59a 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/cql/continuous/ContinuousResultSet.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/cql/continuous/ContinuousResultSet.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/cql/continuous/ContinuousSession.java b/core/src/main/java/com/datastax/dse/driver/api/core/cql/continuous/ContinuousSession.java index f98b0a5d1fa..1c647b33b92 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/cql/continuous/ContinuousSession.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/cql/continuous/ContinuousSession.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -30,9 +32,9 @@ /** * A session that has the ability to execute continuous paging queries. * - *

Continuous paging is a new method of streaming bulk amounts of records from Datastax - * Enterprise (DSE) to the Datastax Java Driver, available since DSE 5.1. It is mainly intended to - * be leveraged by Continuous paging is a new method of streaming bulk amounts of records from DataStax + * Enterprise (DSE) to the Java Driver, available since DSE 5.1. It is mainly intended to be + * leveraged by DSE * Analytics and Apache Spark™, or by any similar analytics tool that needs to read large * portions of a table in one single operation, as quick and reliably as possible. @@ -76,7 +78,7 @@ public interface ContinuousSession extends Session { * *

See {@link ContinuousSession} for more explanations about continuous paging. * - *

This feature is only available with Datastax Enterprise. Executing continuous queries + *

This feature is only available with DataStax Enterprise. Executing continuous queries * against an Apache Cassandra© cluster will result in a runtime error. * * @param statement the query to execute. @@ -99,7 +101,7 @@ default ContinuousResultSet executeContinuously(@NonNull Statement statement) * *

See {@link ContinuousSession} for more explanations about continuous paging. * - *

This feature is only available with Datastax Enterprise. Executing continuous queries + *

This feature is only available with DataStax Enterprise. Executing continuous queries * against an Apache Cassandra© cluster will result in a runtime error. * * @param statement the query to execute. diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/cql/continuous/reactive/ContinuousReactiveResultSet.java b/core/src/main/java/com/datastax/dse/driver/api/core/cql/continuous/reactive/ContinuousReactiveResultSet.java index 9eb68cf0399..6b645ad05bf 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/cql/continuous/reactive/ContinuousReactiveResultSet.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/cql/continuous/reactive/ContinuousReactiveResultSet.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/cql/continuous/reactive/ContinuousReactiveSession.java b/core/src/main/java/com/datastax/dse/driver/api/core/cql/continuous/reactive/ContinuousReactiveSession.java index 9661f9bf5a1..d00013731cb 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/cql/continuous/reactive/ContinuousReactiveSession.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/cql/continuous/reactive/ContinuousReactiveSession.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -51,7 +53,7 @@ public interface ContinuousReactiveSession extends Session { * *

See {@link ContinuousSession} for more explanations about continuous paging. * - *

This feature is only available with Datastax Enterprise. Executing continuous queries + *

This feature is only available with DataStax Enterprise. Executing continuous queries * against an Apache Cassandra® cluster will result in a runtime error. * * @param query the query to execute. @@ -68,7 +70,7 @@ default ContinuousReactiveResultSet executeContinuouslyReactive(@NonNull String * *

See {@link ContinuousSession} for more explanations about continuous paging. * - *

This feature is only available with Datastax Enterprise. Executing continuous queries + *

This feature is only available with DataStax Enterprise. Executing continuous queries * against an Apache Cassandra® cluster will result in a runtime error. * * @param statement the statement to execute. diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/cql/reactive/ReactiveQueryMetadata.java b/core/src/main/java/com/datastax/dse/driver/api/core/cql/reactive/ReactiveQueryMetadata.java index 5cd3445d6e3..55a898cd3ee 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/cql/reactive/ReactiveQueryMetadata.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/cql/reactive/ReactiveQueryMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/cql/reactive/ReactiveResultSet.java b/core/src/main/java/com/datastax/dse/driver/api/core/cql/reactive/ReactiveResultSet.java index 981cf309d4a..0e44dab8cab 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/cql/reactive/ReactiveResultSet.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/cql/reactive/ReactiveResultSet.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/cql/reactive/ReactiveRow.java b/core/src/main/java/com/datastax/dse/driver/api/core/cql/reactive/ReactiveRow.java index ff28ef2f575..c3b94689580 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/cql/reactive/ReactiveRow.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/cql/reactive/ReactiveRow.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/cql/reactive/ReactiveSession.java b/core/src/main/java/com/datastax/dse/driver/api/core/cql/reactive/ReactiveSession.java index 56adf116840..2fd8ffe41c2 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/cql/reactive/ReactiveSession.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/cql/reactive/ReactiveSession.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/cql/reactive/package-info.java b/core/src/main/java/com/datastax/dse/driver/api/core/cql/reactive/package-info.java index 3a138abd833..01a5f514aba 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/cql/reactive/package-info.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/cql/reactive/package-info.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/data/geometry/Geometry.java b/core/src/main/java/com/datastax/dse/driver/api/core/data/geometry/Geometry.java index 2244b9cd758..66a5708832e 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/data/geometry/Geometry.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/data/geometry/Geometry.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/data/geometry/LineString.java b/core/src/main/java/com/datastax/dse/driver/api/core/data/geometry/LineString.java index 84370ddafcd..7f77b3202a2 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/data/geometry/LineString.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/data/geometry/LineString.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/data/geometry/Point.java b/core/src/main/java/com/datastax/dse/driver/api/core/data/geometry/Point.java index 338de70625d..b064b3fb222 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/data/geometry/Point.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/data/geometry/Point.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/data/geometry/Polygon.java b/core/src/main/java/com/datastax/dse/driver/api/core/data/geometry/Polygon.java index 6f66f47042e..d793704defa 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/data/geometry/Polygon.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/data/geometry/Polygon.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/data/time/DateRange.java b/core/src/main/java/com/datastax/dse/driver/api/core/data/time/DateRange.java index fd17047b695..3dd48915dba 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/data/time/DateRange.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/data/time/DateRange.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/data/time/DateRangeBound.java b/core/src/main/java/com/datastax/dse/driver/api/core/data/time/DateRangeBound.java index 5d7427110cb..1621b8bf742 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/data/time/DateRangeBound.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/data/time/DateRangeBound.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/data/time/DateRangePrecision.java b/core/src/main/java/com/datastax/dse/driver/api/core/data/time/DateRangePrecision.java index db133a6846b..ce811466c38 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/data/time/DateRangePrecision.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/data/time/DateRangePrecision.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/graph/AsyncGraphResultSet.java b/core/src/main/java/com/datastax/dse/driver/api/core/graph/AsyncGraphResultSet.java index f1f871c67dd..995de53959b 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/graph/AsyncGraphResultSet.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/graph/AsyncGraphResultSet.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/graph/BatchGraphStatement.java b/core/src/main/java/com/datastax/dse/driver/api/core/graph/BatchGraphStatement.java index 8d48c1ff42a..2169dc5f053 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/graph/BatchGraphStatement.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/graph/BatchGraphStatement.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/graph/BatchGraphStatementBuilder.java b/core/src/main/java/com/datastax/dse/driver/api/core/graph/BatchGraphStatementBuilder.java index d83c9e89141..ac1b85bdc71 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/graph/BatchGraphStatementBuilder.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/graph/BatchGraphStatementBuilder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/graph/DseGraph.java b/core/src/main/java/com/datastax/dse/driver/api/core/graph/DseGraph.java index e9a46c8f5c9..dd1dbe95bc8 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/graph/DseGraph.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/graph/DseGraph.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/graph/DseGraphRemoteConnectionBuilder.java b/core/src/main/java/com/datastax/dse/driver/api/core/graph/DseGraphRemoteConnectionBuilder.java index 9f982ea3a11..c4210a5b3dd 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/graph/DseGraphRemoteConnectionBuilder.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/graph/DseGraphRemoteConnectionBuilder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/graph/FluentGraphStatement.java b/core/src/main/java/com/datastax/dse/driver/api/core/graph/FluentGraphStatement.java index 4f6a1be16be..051c6501c65 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/graph/FluentGraphStatement.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/graph/FluentGraphStatement.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/graph/FluentGraphStatementBuilder.java b/core/src/main/java/com/datastax/dse/driver/api/core/graph/FluentGraphStatementBuilder.java index 82d7f0132d9..59e588c564a 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/graph/FluentGraphStatementBuilder.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/graph/FluentGraphStatementBuilder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/graph/GraphExecutionInfo.java b/core/src/main/java/com/datastax/dse/driver/api/core/graph/GraphExecutionInfo.java index f15275356f2..758f6b358ed 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/graph/GraphExecutionInfo.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/graph/GraphExecutionInfo.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/graph/GraphNode.java b/core/src/main/java/com/datastax/dse/driver/api/core/graph/GraphNode.java index 7124b5225b7..97d48a6b04d 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/graph/GraphNode.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/graph/GraphNode.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/graph/GraphResultSet.java b/core/src/main/java/com/datastax/dse/driver/api/core/graph/GraphResultSet.java index 561cd21682b..d9c8d8fa460 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/graph/GraphResultSet.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/graph/GraphResultSet.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/graph/GraphSession.java b/core/src/main/java/com/datastax/dse/driver/api/core/graph/GraphSession.java index 2c022ff4d49..b985bc56353 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/graph/GraphSession.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/graph/GraphSession.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -49,7 +51,7 @@ public interface GraphSession extends Session { * configuration and schema. * * - *

This feature is only available with Datastax Enterprise. Executing graph queries against an + *

This feature is only available with DataStax Enterprise. Executing graph queries against an * Apache Cassandra® cluster will result in a runtime error. * * @see GraphResultSet @@ -67,7 +69,7 @@ default GraphResultSet execute(@NonNull GraphStatement graphStatement) { * Executes a graph statement asynchronously (the call returns as soon as the statement was sent, * generally before the result is available). * - *

This feature is only available with Datastax Enterprise. Executing graph queries against an + *

This feature is only available with DataStax Enterprise. Executing graph queries against an * Apache Cassandra® cluster will result in a runtime error. * * @see #execute(GraphStatement) diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/graph/GraphStatement.java b/core/src/main/java/com/datastax/dse/driver/api/core/graph/GraphStatement.java index b7f4d13ac2f..f770469b824 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/graph/GraphStatement.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/graph/GraphStatement.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/graph/GraphStatementBuilderBase.java b/core/src/main/java/com/datastax/dse/driver/api/core/graph/GraphStatementBuilderBase.java index 062e917cbcf..5cb48613cf5 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/graph/GraphStatementBuilderBase.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/graph/GraphStatementBuilderBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/graph/PagingEnabledOptions.java b/core/src/main/java/com/datastax/dse/driver/api/core/graph/PagingEnabledOptions.java index b38a75204e1..f59d0e50e93 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/graph/PagingEnabledOptions.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/graph/PagingEnabledOptions.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/graph/ScriptGraphStatement.java b/core/src/main/java/com/datastax/dse/driver/api/core/graph/ScriptGraphStatement.java index 412cf0e6aeb..2ad7aafc232 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/graph/ScriptGraphStatement.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/graph/ScriptGraphStatement.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/graph/ScriptGraphStatementBuilder.java b/core/src/main/java/com/datastax/dse/driver/api/core/graph/ScriptGraphStatementBuilder.java index 9a8d0d262eb..1985c58955f 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/graph/ScriptGraphStatementBuilder.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/graph/ScriptGraphStatementBuilder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -34,7 +36,7 @@ public class ScriptGraphStatementBuilder private String script; private Boolean isSystemQuery; - private Map queryParams; + private final Map queryParams; public ScriptGraphStatementBuilder() { this.queryParams = Maps.newHashMap(); diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/graph/predicates/CqlCollection.java b/core/src/main/java/com/datastax/dse/driver/api/core/graph/predicates/CqlCollection.java index a009925f357..fdbf3fbe397 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/graph/predicates/CqlCollection.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/graph/predicates/CqlCollection.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/graph/predicates/Geo.java b/core/src/main/java/com/datastax/dse/driver/api/core/graph/predicates/Geo.java index eb80aa7d14f..65dd84d0076 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/graph/predicates/Geo.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/graph/predicates/Geo.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/graph/predicates/Search.java b/core/src/main/java/com/datastax/dse/driver/api/core/graph/predicates/Search.java index 5e5a109f874..e285c118c8a 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/graph/predicates/Search.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/graph/predicates/Search.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/graph/reactive/ReactiveGraphNode.java b/core/src/main/java/com/datastax/dse/driver/api/core/graph/reactive/ReactiveGraphNode.java index 9c07364f9ca..ad7849633c6 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/graph/reactive/ReactiveGraphNode.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/graph/reactive/ReactiveGraphNode.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/graph/reactive/ReactiveGraphResultSet.java b/core/src/main/java/com/datastax/dse/driver/api/core/graph/reactive/ReactiveGraphResultSet.java index 403c436861c..a0e3231750e 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/graph/reactive/ReactiveGraphResultSet.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/graph/reactive/ReactiveGraphResultSet.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/graph/reactive/ReactiveGraphSession.java b/core/src/main/java/com/datastax/dse/driver/api/core/graph/reactive/ReactiveGraphSession.java index f4e3dff3f23..88f0e5def61 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/graph/reactive/ReactiveGraphSession.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/graph/reactive/ReactiveGraphSession.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/metadata/DseNodeProperties.java b/core/src/main/java/com/datastax/dse/driver/api/core/metadata/DseNodeProperties.java index 11dde63c235..88dbc164588 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/metadata/DseNodeProperties.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/metadata/DseNodeProperties.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseAggregateMetadata.java b/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseAggregateMetadata.java index 0555a61bb1b..609c64f7c15 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseAggregateMetadata.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseAggregateMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseColumnMetadata.java b/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseColumnMetadata.java index 0b6ed9ed5d6..62b5650697e 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseColumnMetadata.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseColumnMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseEdgeMetadata.java b/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseEdgeMetadata.java index 1a24a72e8b5..59ee8a277ff 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseEdgeMetadata.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseEdgeMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseFunctionMetadata.java b/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseFunctionMetadata.java index 32f897863ef..91298795959 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseFunctionMetadata.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseFunctionMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseGraphKeyspaceMetadata.java b/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseGraphKeyspaceMetadata.java index aebfb23753d..8978a8858f9 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseGraphKeyspaceMetadata.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseGraphKeyspaceMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseGraphTableMetadata.java b/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseGraphTableMetadata.java index e6e8f1dc5e5..8f340b3b447 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseGraphTableMetadata.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseGraphTableMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseIndexMetadata.java b/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseIndexMetadata.java index 7bda2fae326..ac4c1057fbf 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseIndexMetadata.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseIndexMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseKeyspaceMetadata.java b/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseKeyspaceMetadata.java index 3098bba1aa7..bc5cb002802 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseKeyspaceMetadata.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseKeyspaceMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseRelationMetadata.java b/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseRelationMetadata.java index 97ce6df7386..55b36cb7fe5 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseRelationMetadata.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseRelationMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseTableMetadata.java b/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseTableMetadata.java index 25d3cea0c02..a140f93bc2e 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseTableMetadata.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseTableMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseVertexMetadata.java b/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseVertexMetadata.java index db4b3b4f3fd..c08a7eb1d60 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseVertexMetadata.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseVertexMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseViewMetadata.java b/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseViewMetadata.java index 3af7594f606..0f68ea7e456 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseViewMetadata.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/metadata/schema/DseViewMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/metrics/DseNodeMetric.java b/core/src/main/java/com/datastax/dse/driver/api/core/metrics/DseNodeMetric.java index 2382ec0ba30..cf4b4d0aa18 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/metrics/DseNodeMetric.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/metrics/DseNodeMetric.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/metrics/DseSessionMetric.java b/core/src/main/java/com/datastax/dse/driver/api/core/metrics/DseSessionMetric.java index f39a0ee2165..79584f3c44a 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/metrics/DseSessionMetric.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/metrics/DseSessionMetric.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/servererrors/UnfitClientException.java b/core/src/main/java/com/datastax/dse/driver/api/core/servererrors/UnfitClientException.java index dee5d45061f..8bf4d80699d 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/servererrors/UnfitClientException.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/servererrors/UnfitClientException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/type/DseDataTypes.java b/core/src/main/java/com/datastax/dse/driver/api/core/type/DseDataTypes.java index d2c913bacd4..6003274e09a 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/type/DseDataTypes.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/type/DseDataTypes.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/api/core/type/codec/DseTypeCodecs.java b/core/src/main/java/com/datastax/dse/driver/api/core/type/codec/DseTypeCodecs.java index 13102b3e94b..fb0225970b4 100644 --- a/core/src/main/java/com/datastax/dse/driver/api/core/type/codec/DseTypeCodecs.java +++ b/core/src/main/java/com/datastax/dse/driver/api/core/type/codec/DseTypeCodecs.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/DseProtocolFeature.java b/core/src/main/java/com/datastax/dse/driver/internal/core/DseProtocolFeature.java index ce0f13eea41..95f245061d2 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/DseProtocolFeature.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/DseProtocolFeature.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/InsightsClientLifecycleListener.java b/core/src/main/java/com/datastax/dse/driver/internal/core/InsightsClientLifecycleListener.java index ddf4cbfee79..e4dd6f93bf7 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/InsightsClientLifecycleListener.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/InsightsClientLifecycleListener.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/auth/AuthUtils.java b/core/src/main/java/com/datastax/dse/driver/internal/core/auth/AuthUtils.java index 15efc152837..38f1644bcb7 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/auth/AuthUtils.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/auth/AuthUtils.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/auth/DseGssApiAuthProvider.java b/core/src/main/java/com/datastax/dse/driver/internal/core/auth/DseGssApiAuthProvider.java index be1b64fad7c..6ef6596a870 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/auth/DseGssApiAuthProvider.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/auth/DseGssApiAuthProvider.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -150,10 +152,6 @@ * } * } * - * - * @see Authenticating - * a DSE cluster with Kerberos */ @ThreadSafe public class DseGssApiAuthProvider extends DseGssApiAuthProviderBase { diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/auth/DsePlainTextAuthProvider.java b/core/src/main/java/com/datastax/dse/driver/internal/core/auth/DsePlainTextAuthProvider.java index e812dda211a..6cf82aef03e 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/auth/DsePlainTextAuthProvider.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/auth/DsePlainTextAuthProvider.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/auth/DseProgrammaticPlainTextAuthProvider.java b/core/src/main/java/com/datastax/dse/driver/internal/core/auth/DseProgrammaticPlainTextAuthProvider.java deleted file mode 100644 index a8feb1cd2ba..00000000000 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/auth/DseProgrammaticPlainTextAuthProvider.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.datastax.dse.driver.internal.core.auth; - -import com.datastax.oss.driver.internal.core.auth.ProgrammaticPlainTextAuthProvider; - -/** - * @deprecated The driver's default plain text providers now support both Apache Cassandra and DSE. - * This type was preserved for backward compatibility, but {@link - * ProgrammaticPlainTextAuthProvider} should be used instead. - */ -@Deprecated -public class DseProgrammaticPlainTextAuthProvider extends ProgrammaticPlainTextAuthProvider { - - public DseProgrammaticPlainTextAuthProvider( - String username, String password, String authorizationId) { - super(username, password, authorizationId); - } -} diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/DseConversions.java b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/DseConversions.java index 3a1eeda1d86..15aab143150 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/DseConversions.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/DseConversions.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousCqlRequestAsyncProcessor.java b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousCqlRequestAsyncProcessor.java index eea0b331e73..8a098bf2895 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousCqlRequestAsyncProcessor.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousCqlRequestAsyncProcessor.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousCqlRequestHandler.java b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousCqlRequestHandler.java index ca2631fae75..dd308c11854 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousCqlRequestHandler.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousCqlRequestHandler.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -20,6 +22,7 @@ import com.datastax.dse.driver.api.core.metrics.DseSessionMetric; import com.datastax.dse.driver.internal.core.cql.DseConversions; import com.datastax.dse.protocol.internal.response.result.DseRowsMetadata; +import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; import com.datastax.oss.driver.api.core.cql.ColumnDefinitions; import com.datastax.oss.driver.api.core.cql.ExecutionInfo; import com.datastax.oss.driver.api.core.cql.Row; @@ -27,6 +30,7 @@ import com.datastax.oss.driver.api.core.metrics.DefaultNodeMetric; import com.datastax.oss.driver.api.core.metrics.DefaultSessionMetric; import com.datastax.oss.driver.internal.core.context.InternalDriverContext; +import com.datastax.oss.driver.internal.core.cql.Conversions; import com.datastax.oss.driver.internal.core.cql.DefaultRow; import com.datastax.oss.driver.internal.core.session.DefaultSession; import com.datastax.oss.driver.internal.core.util.CountingIterator; @@ -45,13 +49,7 @@ */ @ThreadSafe public class ContinuousCqlRequestHandler - extends ContinuousRequestHandlerBase { - - private final Message message; - private final Duration firstPageTimeout; - private final Duration otherPagesTimeout; - private final int maxEnqueuedPages; - private final int maxPages; + extends ContinuousRequestHandlerBase, ContinuousAsyncResultSet> { ContinuousCqlRequestHandler( @NonNull Statement statement, @@ -68,14 +66,6 @@ public class ContinuousCqlRequestHandler DefaultSessionMetric.CQL_CLIENT_TIMEOUTS, DseSessionMetric.CONTINUOUS_CQL_REQUESTS, DefaultNodeMetric.CQL_MESSAGES); - message = DseConversions.toContinuousPagingMessage(statement, executionProfile, context); - firstPageTimeout = - executionProfile.getDuration(DseDriverOption.CONTINUOUS_PAGING_TIMEOUT_FIRST_PAGE); - otherPagesTimeout = - executionProfile.getDuration(DseDriverOption.CONTINUOUS_PAGING_TIMEOUT_OTHER_PAGES); - maxEnqueuedPages = - executionProfile.getInt(DseDriverOption.CONTINUOUS_PAGING_MAX_ENQUEUED_PAGES); - maxPages = executionProfile.getInt(DseDriverOption.CONTINUOUS_PAGING_MAX_PAGES); // NOTE that ordering of the following statement matters. // We should register this request after all fields have been initialized. throttler.register(this); @@ -89,40 +79,54 @@ protected Duration getGlobalTimeout() { @NonNull @Override - protected Duration getPageTimeout(int pageNumber) { - return pageNumber == 1 ? firstPageTimeout : otherPagesTimeout; + protected Duration getPageTimeout(@NonNull Statement statement, int pageNumber) { + DriverExecutionProfile executionProfile = + Conversions.resolveExecutionProfile(statement, context); + if (pageNumber == 1) { + return executionProfile.getDuration(DseDriverOption.CONTINUOUS_PAGING_TIMEOUT_FIRST_PAGE); + } else { + return executionProfile.getDuration(DseDriverOption.CONTINUOUS_PAGING_TIMEOUT_OTHER_PAGES); + } } @NonNull @Override - protected Duration getReviseRequestTimeout() { - return otherPagesTimeout; + protected Duration getReviseRequestTimeout(@NonNull Statement statement) { + DriverExecutionProfile executionProfile = + Conversions.resolveExecutionProfile(statement, context); + return executionProfile.getDuration(DseDriverOption.CONTINUOUS_PAGING_TIMEOUT_OTHER_PAGES); } @Override - protected int getMaxEnqueuedPages() { - return maxEnqueuedPages; + protected int getMaxEnqueuedPages(@NonNull Statement statement) { + DriverExecutionProfile executionProfile = + Conversions.resolveExecutionProfile(statement, context); + return executionProfile.getInt(DseDriverOption.CONTINUOUS_PAGING_MAX_ENQUEUED_PAGES); } @Override - protected int getMaxPages() { - return maxPages; + protected int getMaxPages(@NonNull Statement statement) { + DriverExecutionProfile executionProfile = + Conversions.resolveExecutionProfile(statement, context); + return executionProfile.getInt(DseDriverOption.CONTINUOUS_PAGING_MAX_PAGES); } @NonNull @Override - protected Message getMessage() { - return message; + protected Message getMessage(@NonNull Statement statement) { + DriverExecutionProfile executionProfile = + Conversions.resolveExecutionProfile(statement, context); + return DseConversions.toContinuousPagingMessage(statement, executionProfile, context); } @Override - protected boolean isTracingEnabled() { + protected boolean isTracingEnabled(@NonNull Statement statement) { return false; } @NonNull @Override - protected Map createPayload() { + protected Map createPayload(@NonNull Statement statement) { return statement.getCustomPayload(); } @@ -135,6 +139,7 @@ protected ContinuousAsyncResultSet createEmptyResultSet(@NonNull ExecutionInfo e @NonNull @Override protected DefaultContinuousAsyncResultSet createResultSet( + @NonNull Statement statement, @NonNull Rows rows, @NonNull ExecutionInfo executionInfo, @NonNull ColumnDefinitions columnDefinitions) { diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousCqlRequestSyncProcessor.java b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousCqlRequestSyncProcessor.java index 1333d50d720..f151eb7eae2 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousCqlRequestSyncProcessor.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousCqlRequestSyncProcessor.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousRequestHandlerBase.java b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousRequestHandlerBase.java index c7754702bcf..0453022cb6a 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousRequestHandlerBase.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousRequestHandlerBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -24,6 +26,7 @@ import com.datastax.oss.driver.api.core.AllNodesFailedException; import com.datastax.oss.driver.api.core.CqlIdentifier; import com.datastax.oss.driver.api.core.DriverTimeoutException; +import com.datastax.oss.driver.api.core.NodeUnavailableException; import com.datastax.oss.driver.api.core.ProtocolVersion; import com.datastax.oss.driver.api.core.RequestThrottlingException; import com.datastax.oss.driver.api.core.config.DefaultDriverOption; @@ -36,8 +39,8 @@ import com.datastax.oss.driver.api.core.metrics.DefaultSessionMetric; import com.datastax.oss.driver.api.core.metrics.NodeMetric; import com.datastax.oss.driver.api.core.metrics.SessionMetric; -import com.datastax.oss.driver.api.core.retry.RetryDecision; import com.datastax.oss.driver.api.core.retry.RetryPolicy; +import com.datastax.oss.driver.api.core.retry.RetryVerdict; import com.datastax.oss.driver.api.core.servererrors.BootstrappingException; import com.datastax.oss.driver.api.core.servererrors.CoordinatorException; import com.datastax.oss.driver.api.core.servererrors.FunctionFailureException; @@ -49,7 +52,6 @@ import com.datastax.oss.driver.api.core.session.Request; import com.datastax.oss.driver.api.core.session.throttling.RequestThrottler; import com.datastax.oss.driver.api.core.session.throttling.Throttled; -import com.datastax.oss.driver.api.core.specex.SpeculativeExecutionPolicy; import com.datastax.oss.driver.internal.core.adminrequest.ThrottledAdminRequestHandler; import com.datastax.oss.driver.internal.core.adminrequest.UnexpectedResponseException; import com.datastax.oss.driver.internal.core.channel.DriverChannel; @@ -63,7 +65,7 @@ import com.datastax.oss.driver.internal.core.session.DefaultSession; import com.datastax.oss.driver.internal.core.session.RepreparePayload; import com.datastax.oss.driver.internal.core.util.Loggers; -import com.datastax.oss.driver.internal.core.util.collection.QueryPlan; +import com.datastax.oss.driver.internal.core.util.collection.SimpleQueryPlan; import com.datastax.oss.driver.shaded.guava.common.annotations.VisibleForTesting; import com.datastax.oss.protocol.internal.Frame; import com.datastax.oss.protocol.internal.Message; @@ -114,23 +116,19 @@ public abstract class ContinuousRequestHandlerBase queryPlan; - private final RetryPolicy retryPolicy; protected final RequestThrottler throttler; private final boolean protocolBackpressureAvailable; - private final boolean isIdempotent; private final Timer timer; private final SessionMetricUpdater sessionMetricUpdater; private final boolean specExecEnabled; private final SessionMetric clientTimeoutsMetric; private final SessionMetric continuousRequestsMetric; private final NodeMetric messagesMetric; - private final SpeculativeExecutionPolicy speculativeExecutionPolicy; private final List scheduledExecutions; // The errors on the nodes that were already tried. @@ -162,10 +160,10 @@ public abstract class ContinuousRequestHandlerBase resultSetClass; + private final Class resultSetClass; public ContinuousRequestHandlerBase( @NonNull StatementT statement, @@ -191,23 +189,18 @@ public ContinuousRequestHandlerBase( this.messagesMetric = messagesMetric; this.logPrefix = sessionLogPrefix + "|" + this.hashCode(); LOG.trace("[{}] Creating new continuous handler for request {}", logPrefix, statement); - this.statement = statement; + this.initialStatement = statement; this.session = session; this.keyspace = session.getKeyspace().orElse(null); this.context = context; - this.executionProfile = Conversions.resolveExecutionProfile(this.statement, this.context); + DriverExecutionProfile executionProfile = + Conversions.resolveExecutionProfile(statement, context); this.queryPlan = statement.getNode() != null - ? new QueryPlan(statement.getNode()) + ? new SimpleQueryPlan(statement.getNode()) : context .getLoadBalancingPolicyWrapper() .newQueryPlan(statement, executionProfile.getName(), session); - this.retryPolicy = context.getRetryPolicy(executionProfile.getName()); - Boolean idempotent = statement.isIdempotent(); - this.isIdempotent = - idempotent == null - ? executionProfile.getBoolean(DefaultDriverOption.REQUEST_DEFAULT_IDEMPOTENCE) - : idempotent; this.timer = context.getNettyOptions().getTimer(); this.protocolBackpressureAvailable = @@ -215,11 +208,7 @@ public ContinuousRequestHandlerBase( this.throttler = context.getRequestThrottler(); this.sessionMetricUpdater = session.getMetricUpdater(); this.startTimeNanos = System.nanoTime(); - this.specExecEnabled = specExecEnabled && isIdempotent; - this.speculativeExecutionPolicy = - this.specExecEnabled - ? context.getSpeculativeExecutionPolicy(executionProfile.getName()) - : null; + this.specExecEnabled = specExecEnabled; this.scheduledExecutions = this.specExecEnabled ? new CopyOnWriteArrayList<>() : null; } @@ -227,22 +216,22 @@ public ContinuousRequestHandlerBase( protected abstract Duration getGlobalTimeout(); @NonNull - protected abstract Duration getPageTimeout(int pageNumber); + protected abstract Duration getPageTimeout(@NonNull StatementT statement, int pageNumber); @NonNull - protected abstract Duration getReviseRequestTimeout(); + protected abstract Duration getReviseRequestTimeout(@NonNull StatementT statement); - protected abstract int getMaxEnqueuedPages(); + protected abstract int getMaxEnqueuedPages(@NonNull StatementT statement); - protected abstract int getMaxPages(); + protected abstract int getMaxPages(@NonNull StatementT statement); @NonNull - protected abstract Message getMessage(); + protected abstract Message getMessage(@NonNull StatementT statement); - protected abstract boolean isTracingEnabled(); + protected abstract boolean isTracingEnabled(@NonNull StatementT statement); @NonNull - protected abstract Map createPayload(); + protected abstract Map createPayload(@NonNull StatementT statement); @NonNull protected abstract ResultSetT createEmptyResultSet(@NonNull ExecutionInfo executionInfo); @@ -251,6 +240,7 @@ public ContinuousRequestHandlerBase( @NonNull protected abstract ResultSetT createResultSet( + @NonNull StatementT statement, @NonNull Rows rows, @NonNull ExecutionInfo executionInfo, @NonNull ColumnDefinitions columnDefinitions) @@ -260,6 +250,8 @@ protected abstract ResultSetT createResultSet( @Override public void onThrottleReady(boolean wasDelayed) { + DriverExecutionProfile executionProfile = + Conversions.resolveExecutionProfile(initialStatement, context); if (wasDelayed // avoid call to nanoTime() if metric is disabled: && sessionMetricUpdater.isEnabled( @@ -273,11 +265,13 @@ public void onThrottleReady(boolean wasDelayed) { TimeUnit.NANOSECONDS); } activeExecutionsCount.incrementAndGet(); - sendRequest(null, 0, 0, specExecEnabled); + sendRequest(initialStatement, null, 0, 0, specExecEnabled); } @Override public void onThrottleFailure(@NonNull RequestThrottlingException error) { + DriverExecutionProfile executionProfile = + Conversions.resolveExecutionProfile(initialStatement, context); session .getMetricUpdater() .incrementCounter(DefaultSessionMetric.THROTTLING_ERRORS, executionProfile.getName()); @@ -346,6 +340,7 @@ public CompletionStage fetchNextPage() { * @param scheduleSpeculativeExecution whether to schedule the next speculative execution */ private void sendRequest( + StatementT statement, @Nullable Node node, int currentExecutionIndex, int retryCount, @@ -356,6 +351,8 @@ private void sendRequest( channel = session.getChannel(node, logPrefix); if (channel != null) { break; + } else { + recordError(node, new NodeUnavailableException(node)); } } } @@ -368,6 +365,7 @@ private void sendRequest( } else if (!chosenCallback.isDone()) { NodeResponseCallback nodeResponseCallback = new NodeResponseCallback( + statement, node, channel, currentExecutionIndex, @@ -376,7 +374,11 @@ private void sendRequest( logPrefix); inFlightCallbacks.add(nodeResponseCallback); channel - .write(getMessage(), isTracingEnabled(), createPayload(), nodeResponseCallback) + .write( + getMessage(statement), + isTracingEnabled(statement), + createPayload(statement), + nodeResponseCallback) .addListener(nodeResponseCallback); } } @@ -408,6 +410,7 @@ public void cancel() { cancelScheduledTasks(null); cancelGlobalTimeout(); + throttler.signalCancel(this); } private void cancelGlobalTimeout() { @@ -458,6 +461,10 @@ CompletableFuture getPendingResult() { } } + private void recordError(@NonNull Node node, @NonNull Throwable error) { + errors.add(new AbstractMap.SimpleEntry<>(node, error)); + } + /** * Handles the interaction with a single node in the query plan. * @@ -469,6 +476,7 @@ private class NodeResponseCallback implements ResponseCallback, GenericFutureListener> { private final long messageStartTimeNanos = System.nanoTime(); + private final StatementT statement; private final Node node; private final DriverChannel channel; // The identifier of the current execution (0 for the initial execution, 1 for the first @@ -479,6 +487,8 @@ private class NodeResponseCallback private final String logPrefix; private final boolean scheduleSpeculativeExecution; + private final DriverExecutionProfile executionProfile; + // Coordinates concurrent accesses between the client and I/O threads private final ReentrantLock lock = new ReentrantLock(); @@ -534,18 +544,21 @@ private class NodeResponseCallback private final AtomicBoolean nodeSuccessReported = new AtomicBoolean(false); public NodeResponseCallback( + StatementT statement, Node node, DriverChannel channel, int executionIndex, int retryCount, boolean scheduleSpeculativeExecution, String logPrefix) { + this.statement = statement; this.node = node; this.channel = channel; this.executionIndex = executionIndex; this.retryCount = retryCount; this.scheduleSpeculativeExecution = scheduleSpeculativeExecution; this.logPrefix = logPrefix + "|" + executionIndex; + this.executionProfile = Conversions.resolveExecutionProfile(statement, context); } @Override @@ -632,16 +645,18 @@ public void operationComplete(@NonNull Future future) { .incrementCounter(DefaultNodeMetric.UNSENT_REQUESTS, executionProfile.getName()); recordError(node, error); trackNodeError(node, error.getCause()); - sendRequest(null, executionIndex, retryCount, scheduleSpeculativeExecution); + sendRequest(statement, null, executionIndex, retryCount, scheduleSpeculativeExecution); } } else { LOG.trace("[{}] Request sent on {}", logPrefix, channel); - if (scheduleSpeculativeExecution) { + if (scheduleSpeculativeExecution + && Conversions.resolveIdempotence(statement, executionProfile)) { int nextExecution = executionIndex + 1; // Note that `node` is the first node of the execution, it might not be the "slow" one // if there were retries, but in practice retries are rare. long nextDelay = - speculativeExecutionPolicy.nextExecution(node, keyspace, statement, nextExecution); + Conversions.resolveSpeculativeExecutionPolicy(context, executionProfile) + .nextExecution(node, keyspace, statement, nextExecution); if (nextDelay >= 0) { scheduleSpeculativeExecution(nextExecution, nextDelay); } else { @@ -676,7 +691,7 @@ private void scheduleSpeculativeExecution(int nextExecutionIndex, long delay) { nodeMetricUpdater.incrementCounter( DefaultNodeMetric.SPECULATIVE_EXECUTIONS, executionProfile.getName()); } - sendRequest(null, nextExecutionIndex, 0, true); + sendRequest(statement, null, nextExecutionIndex, 0, true); } }, delay, @@ -690,34 +705,34 @@ private Timeout schedulePageTimeout(int expectedPage) { if (expectedPage < 0) { return null; } - Duration timeout = getPageTimeout(expectedPage); + Duration timeout = getPageTimeout(statement, expectedPage); if (timeout.toNanos() <= 0) { return null; } LOG.trace("[{}] Scheduling timeout for page {} in {}", logPrefix, expectedPage, timeout); return timer.newTimeout( - timeout1 -> { - lock.lock(); - try { - if (state == expectedPage) { - abort( - new DriverTimeoutException( - String.format("Timed out waiting for page %d", expectedPage)), - false); - } else { - // Ignore timeout if the request has moved on in the interim. - LOG.trace( - "[{}] Timeout fired for page {} but query already at state {}, skipping", - logPrefix, - expectedPage, - state); - } - } finally { - lock.unlock(); - } - }, - timeout.toNanos(), - TimeUnit.NANOSECONDS); + t -> onPageTimeout(expectedPage), timeout.toNanos(), TimeUnit.NANOSECONDS); + } + + private void onPageTimeout(int expectedPage) { + lock.lock(); + try { + if (state == expectedPage) { + abort( + new DriverTimeoutException( + String.format("Timed out waiting for page %d", expectedPage)), + false); + } else { + // Ignore timeout if the request has moved on in the interim. + LOG.trace( + "[{}] Timeout fired for page {} but query already at state {}, skipping", + logPrefix, + expectedPage, + state); + } + } finally { + lock.unlock(); + } } /** @@ -765,7 +780,7 @@ public void onResponse(@NonNull Frame response) { * Invoked when a continuous paging request hits an unexpected error. * *

Delegates further processing to to the retry policy ({@link - * #processRetryDecision(RetryDecision, Throwable)}. + * #processRetryVerdict(RetryVerdict, Throwable)}. * * @param error the error encountered, usually a network problem. */ @@ -773,12 +788,14 @@ public void onResponse(@NonNull Frame response) { public void onFailure(@NonNull Throwable error) { cancelTimeout(pageTimeout); LOG.trace(String.format("[%s] Request failure", logPrefix), error); - RetryDecision decision; - if (!isIdempotent || error instanceof FrameTooLongException) { - decision = RetryDecision.RETHROW; + RetryVerdict verdict; + if (!Conversions.resolveIdempotence(statement, executionProfile) + || error instanceof FrameTooLongException) { + verdict = RetryVerdict.RETHROW; } else { try { - decision = retryPolicy.onRequestAborted(statement, error, retryCount); + RetryPolicy retryPolicy = Conversions.resolveRetryPolicy(context, executionProfile); + verdict = retryPolicy.onRequestAbortedVerdict(statement, error, retryCount); } catch (Throwable cause) { abort( new IllegalStateException("Unexpected error while invoking the retry policy", cause), @@ -788,13 +805,13 @@ public void onFailure(@NonNull Throwable error) { } updateErrorMetrics( ((DefaultNode) node).getMetricUpdater(), - decision, + verdict, DefaultNodeMetric.ABORTED_REQUESTS, DefaultNodeMetric.RETRIES_ON_ABORTED, DefaultNodeMetric.IGNORES_ON_ABORTED); lock.lock(); try { - processRetryDecision(decision, error); + processRetryVerdict(verdict, error); } finally { lock.unlock(); } @@ -814,7 +831,7 @@ public void onFailure(@NonNull Throwable error) { private void processResultResponse(@NonNull Result result, @Nullable Frame frame) { assert lock.isHeldByCurrentThread(); try { - ExecutionInfo executionInfo = createExecutionInfo(node, result, frame, executionIndex); + ExecutionInfo executionInfo = createExecutionInfo(result, frame); if (result instanceof Rows) { DseRowsMetadata rowsMetadata = (DseRowsMetadata) ((Rows) result).getMetadata(); if (columnDefinitions == null) { @@ -833,7 +850,8 @@ private void processResultResponse(@NonNull Result result, @Nullable Frame frame false); } else { int pageSize = ((Rows) result).getData().size(); - ResultSetT resultSet = createResultSet((Rows) result, executionInfo, columnDefinitions); + ResultSetT resultSet = + createResultSet(statement, (Rows) result, executionInfo, columnDefinitions); if (rowsMetadata.isLastContinuousPage) { LOG.trace("[{}] Received last page ({} - {} rows)", logPrefix, pageNumber, pageSize); state = STATE_FINISHED; @@ -894,7 +912,7 @@ private void processErrorResponse(@NonNull Error errorMessage) { LOG.trace("[{}] {} is bootstrapping, trying next node", logPrefix, node); recordError(node, error); trackNodeError(node, error); - sendRequest(null, executionIndex, retryCount, false); + sendRequest(statement, null, executionIndex, retryCount, false); } else if (error instanceof QueryValidationException || error instanceof FunctionFailureException || error instanceof ProtocolError @@ -921,18 +939,19 @@ private void processErrorResponse(@NonNull Error errorMessage) { * Processes a recoverable error. * *

In most cases, delegates to the retry policy and its decision, see {@link - * #processRetryDecision(RetryDecision, Throwable)}. + * #processRetryVerdict(RetryVerdict, Throwable)}. * * @param error the recoverable error. */ private void processRecoverableError(@NonNull CoordinatorException error) { assert lock.isHeldByCurrentThread(); NodeMetricUpdater metricUpdater = ((DefaultNode) node).getMetricUpdater(); - RetryDecision decision; + RetryVerdict verdict; + RetryPolicy retryPolicy = Conversions.resolveRetryPolicy(context, executionProfile); if (error instanceof ReadTimeoutException) { ReadTimeoutException readTimeout = (ReadTimeoutException) error; - decision = - retryPolicy.onReadTimeout( + verdict = + retryPolicy.onReadTimeoutVerdict( statement, readTimeout.getConsistencyLevel(), readTimeout.getBlockFor(), @@ -941,15 +960,15 @@ private void processRecoverableError(@NonNull CoordinatorException error) { retryCount); updateErrorMetrics( metricUpdater, - decision, + verdict, DefaultNodeMetric.READ_TIMEOUTS, DefaultNodeMetric.RETRIES_ON_READ_TIMEOUT, DefaultNodeMetric.IGNORES_ON_READ_TIMEOUT); } else if (error instanceof WriteTimeoutException) { WriteTimeoutException writeTimeout = (WriteTimeoutException) error; - if (isIdempotent) { - decision = - retryPolicy.onWriteTimeout( + if (Conversions.resolveIdempotence(statement, executionProfile)) { + verdict = + retryPolicy.onWriteTimeoutVerdict( statement, writeTimeout.getConsistencyLevel(), writeTimeout.getWriteType(), @@ -957,18 +976,18 @@ private void processRecoverableError(@NonNull CoordinatorException error) { writeTimeout.getReceived(), retryCount); } else { - decision = RetryDecision.RETHROW; + verdict = RetryVerdict.RETHROW; } updateErrorMetrics( metricUpdater, - decision, + verdict, DefaultNodeMetric.WRITE_TIMEOUTS, DefaultNodeMetric.RETRIES_ON_WRITE_TIMEOUT, DefaultNodeMetric.IGNORES_ON_WRITE_TIMEOUT); } else if (error instanceof UnavailableException) { UnavailableException unavailable = (UnavailableException) error; - decision = - retryPolicy.onUnavailable( + verdict = + retryPolicy.onUnavailableVerdict( statement, unavailable.getConsistencyLevel(), unavailable.getRequired(), @@ -976,23 +995,23 @@ private void processRecoverableError(@NonNull CoordinatorException error) { retryCount); updateErrorMetrics( metricUpdater, - decision, + verdict, DefaultNodeMetric.UNAVAILABLES, DefaultNodeMetric.RETRIES_ON_UNAVAILABLE, DefaultNodeMetric.IGNORES_ON_UNAVAILABLE); } else { - decision = - isIdempotent - ? retryPolicy.onErrorResponse(statement, error, retryCount) - : RetryDecision.RETHROW; + verdict = + Conversions.resolveIdempotence(statement, executionProfile) + ? retryPolicy.onErrorResponseVerdict(statement, error, retryCount) + : RetryVerdict.RETHROW; updateErrorMetrics( metricUpdater, - decision, + verdict, DefaultNodeMetric.OTHER_ERRORS, DefaultNodeMetric.RETRIES_ON_OTHER_ERROR, DefaultNodeMetric.IGNORES_ON_OTHER_ERROR); } - processRetryDecision(decision, error); + processRetryVerdict(verdict, error); } /** @@ -1050,7 +1069,7 @@ private void processUnprepared(@NonNull Unprepared errorMessage) { "[{}] Re-prepare successful, retrying on the same node ({})", logPrefix, node); - sendRequest(node, executionIndex, retryCount, false); + sendRequest(statement, node, executionIndex, retryCount, false); } } else { if (exception instanceof UnexpectedResponseException) { @@ -1074,7 +1093,7 @@ private void processUnprepared(@NonNull Unprepared errorMessage) { LOG.trace("[{}] Re-prepare failed, trying next node", logPrefix); recordError(node, exception); trackNodeError(node, exception); - sendRequest(null, executionIndex, retryCount, false); + sendRequest(statement, null, executionIndex, retryCount, false); } } if (fatalError != null) { @@ -1092,22 +1111,24 @@ private void processUnprepared(@NonNull Unprepared errorMessage) { * Processes the retry decision by triggering a retry, aborting or ignoring; also records the * failures for further access. * - * @param decision the decision to process. + * @param verdict the verdict to process. * @param error the original error. */ - private void processRetryDecision(@NonNull RetryDecision decision, @NonNull Throwable error) { + private void processRetryVerdict(@NonNull RetryVerdict verdict, @NonNull Throwable error) { assert lock.isHeldByCurrentThread(); - LOG.trace("[{}] Processing retry decision {}", logPrefix, decision); - switch (decision) { + LOG.trace("[{}] Processing retry decision {}", logPrefix, verdict); + switch (verdict.getRetryDecision()) { case RETRY_SAME: recordError(node, error); trackNodeError(node, error); - sendRequest(node, executionIndex, retryCount + 1, false); + sendRequest( + verdict.getRetryRequest(statement), node, executionIndex, retryCount + 1, false); break; case RETRY_NEXT: recordError(node, error); trackNodeError(node, error); - sendRequest(null, executionIndex, retryCount + 1, false); + sendRequest( + verdict.getRetryRequest(statement), null, executionIndex, retryCount + 1, false); break; case RETHROW: trackNodeError(node, error); @@ -1148,8 +1169,8 @@ private void enqueueOrCompletePending(@NonNull Object pageOrError) { return; } - queue = new ArrayDeque<>(getMaxEnqueuedPages()); - numPagesRequested = protocolBackpressureAvailable ? getMaxEnqueuedPages() : 0; + queue = new ArrayDeque<>(getMaxEnqueuedPages(statement)); + numPagesRequested = protocolBackpressureAvailable ? getMaxEnqueuedPages(statement) : 0; cancelScheduledTasks(this); } @@ -1174,7 +1195,9 @@ private void enqueueOrCompletePending(@NonNull Object pageOrError) { // Backpressure without protocol support: if the queue grows too large, // disable auto-read so that the channel eventually becomes // non-writable on the server side (causing it to back off for a while) - if (!protocolBackpressureAvailable && queue.size() == getMaxEnqueuedPages() && state > 0) { + if (!protocolBackpressureAvailable + && queue.size() == getMaxEnqueuedPages(statement) + && state > 0) { LOG.trace( "[{}] Exceeded {} queued response pages, disabling auto-read", logPrefix, @@ -1207,7 +1230,7 @@ public CompletableFuture dequeueOrCreatePending() { head = queue.poll(); if (!protocolBackpressureAvailable && head != null - && queue.size() == getMaxEnqueuedPages() - 1) { + && queue.size() == getMaxEnqueuedPages(statement) - 1) { LOG.trace( "[{}] Back to {} queued response pages, re-enabling auto-read", logPrefix, @@ -1270,17 +1293,19 @@ private void maybeRequestMore() { return; } // if we have already requested more than the client needs, then no need to request some more - if (getMaxPages() > 0 && numPagesRequested >= getMaxPages()) { + int maxPages = getMaxPages(statement); + if (maxPages > 0 && numPagesRequested >= maxPages) { return; } // the pages received so far, which is the state minus one int received = state - 1; int requested = numPagesRequested; // the pages that fit in the queue, which is the queue free space minus the requests in flight - int freeSpace = getMaxEnqueuedPages() - queue.size(); + int freeSpace = getMaxEnqueuedPages(statement) - queue.size(); int inFlight = requested - received; int numPagesFittingInQueue = freeSpace - inFlight; - if (numPagesFittingInQueue > 0 && numPagesFittingInQueue >= getMaxEnqueuedPages() / 2) { + if (numPagesFittingInQueue > 0 + && numPagesFittingInQueue >= getMaxEnqueuedPages(statement) / 2) { LOG.trace("[{}] Requesting more {} pages", logPrefix, numPagesFittingInQueue); numPagesRequested = requested + numPagesFittingInQueue; sendMorePagesRequest(numPagesFittingInQueue); @@ -1305,7 +1330,7 @@ private void sendMorePagesRequest(int nextPages) { true, Revise.requestMoreContinuousPages(streamId, nextPages), statement.getCustomPayload(), - getReviseRequestTimeout(), + getReviseRequestTimeout(statement), throttler, session.getMetricUpdater(), logPrefix, @@ -1384,7 +1409,7 @@ private void sendCancelRequest() { true, Revise.cancelContinuousPaging(streamId), statement.getCustomPayload(), - getReviseRequestTimeout(), + getReviseRequestTimeout(statement), throttler, session.getMetricUpdater(), logPrefix, @@ -1419,16 +1444,12 @@ private void reenableAutoReadIfNeeded() { // ERROR HANDLING - private void recordError(@NonNull Node node, @NonNull Throwable error) { - errors.add(new AbstractMap.SimpleEntry<>(node, error)); - } - private void trackNodeError(@NonNull Node node, @NonNull Throwable error) { if (nodeErrorReported.compareAndSet(false, true)) { long latencyNanos = System.nanoTime() - this.messageStartTimeNanos; context .getRequestTracker() - .onNodeError(statement, error, latencyNanos, executionProfile, node, logPrefix); + .onNodeError(this.statement, error, latencyNanos, executionProfile, node, logPrefix); } } @@ -1490,19 +1511,19 @@ private void stopGlobalRequestTimer() { .getMetricUpdater() .updateTimer( continuousRequestsMetric, - executionProfile.getName(), + null, System.nanoTime() - startTimeNanos, TimeUnit.NANOSECONDS); } private void updateErrorMetrics( @NonNull NodeMetricUpdater metricUpdater, - @NonNull RetryDecision decision, + @NonNull RetryVerdict verdict, @NonNull DefaultNodeMetric error, @NonNull DefaultNodeMetric retriesOnError, @NonNull DefaultNodeMetric ignoresOnError) { metricUpdater.incrementCounter(error, executionProfile.getName()); - switch (decision) { + switch (verdict.getRetryDecision()) { case RETRY_SAME: case RETRY_NEXT: metricUpdater.incrementCounter(DefaultNodeMetric.RETRIES, executionProfile.getName()); @@ -1570,18 +1591,14 @@ private void completeResultSetFuture( } @NonNull - private ExecutionInfo createExecutionInfo( - @NonNull Node node, - @NonNull Result result, - @Nullable Frame response, - int successfulExecutionIndex) { + private ExecutionInfo createExecutionInfo(@NonNull Result result, @Nullable Frame response) { ByteBuffer pagingState = result instanceof Rows ? ((Rows) result).getMetadata().pagingState : null; return new DefaultExecutionInfo( statement, node, startedSpeculativeExecutionsCount.get(), - successfulExecutionIndex, + executionIndex, errors, pagingState, response, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/continuous/DefaultContinuousAsyncResultSet.java b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/continuous/DefaultContinuousAsyncResultSet.java index 98eefd2aac5..8562fde5905 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/continuous/DefaultContinuousAsyncResultSet.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/continuous/DefaultContinuousAsyncResultSet.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/continuous/DefaultContinuousResultSet.java b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/continuous/DefaultContinuousResultSet.java index 38fcd746f9e..929400bc7a6 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/continuous/DefaultContinuousResultSet.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/continuous/DefaultContinuousResultSet.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/continuous/reactive/ContinuousCqlRequestReactiveProcessor.java b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/continuous/reactive/ContinuousCqlRequestReactiveProcessor.java index 6feff64f04a..afe0e864181 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/continuous/reactive/ContinuousCqlRequestReactiveProcessor.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/continuous/reactive/ContinuousCqlRequestReactiveProcessor.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/continuous/reactive/DefaultContinuousReactiveResultSet.java b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/continuous/reactive/DefaultContinuousReactiveResultSet.java index d1131e9bbe8..b3f301edea6 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/continuous/reactive/DefaultContinuousReactiveResultSet.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/continuous/reactive/DefaultContinuousReactiveResultSet.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/CqlRequestReactiveProcessor.java b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/CqlRequestReactiveProcessor.java index c2b1872e252..3539c2e698c 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/CqlRequestReactiveProcessor.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/CqlRequestReactiveProcessor.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/DefaultReactiveResultSet.java b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/DefaultReactiveResultSet.java index f24d2638f37..33b6dc02f48 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/DefaultReactiveResultSet.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/DefaultReactiveResultSet.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/DefaultReactiveRow.java b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/DefaultReactiveRow.java index 64382440ca5..ca3b93e7f6b 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/DefaultReactiveRow.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/DefaultReactiveRow.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/EmptySubscription.java b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/EmptySubscription.java index 78bd30bed44..f760ecc395e 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/EmptySubscription.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/EmptySubscription.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/FailedPublisher.java b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/FailedPublisher.java index fc433a725b3..638434bb2d0 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/FailedPublisher.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/FailedPublisher.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/FailedReactiveResultSet.java b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/FailedReactiveResultSet.java index 07712f457fb..31c34d649aa 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/FailedReactiveResultSet.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/FailedReactiveResultSet.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/ReactiveOperators.java b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/ReactiveOperators.java index d296bb580df..f058149f570 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/ReactiveOperators.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/ReactiveOperators.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/ReactiveResultSetBase.java b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/ReactiveResultSetBase.java index 5136e25e593..5ba00e22298 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/ReactiveResultSetBase.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/ReactiveResultSetBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/ReactiveResultSetSubscription.java b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/ReactiveResultSetSubscription.java index 160e71296be..500a291e9d2 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/ReactiveResultSetSubscription.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/ReactiveResultSetSubscription.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -277,13 +279,10 @@ private Object tryNext() { if (pages.poll() == null) { throw new AssertionError("Queue is empty, this should not happen"); } - current = pages.peek(); // if the next page is readily available, // serve its first row now, no need to wait // for the next drain. - if (current != null && current.hasMoreRows()) { - return current.nextRow(); - } + return tryNext(); } } // No items available right now. diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/SimpleUnicastProcessor.java b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/SimpleUnicastProcessor.java index f93b4405ea0..845cbe2349b 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/SimpleUnicastProcessor.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/cql/reactive/SimpleUnicastProcessor.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/data/geometry/DefaultGeometry.java b/core/src/main/java/com/datastax/dse/driver/internal/core/data/geometry/DefaultGeometry.java index f4113f5fd62..885d9bd48b7 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/data/geometry/DefaultGeometry.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/data/geometry/DefaultGeometry.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/data/geometry/DefaultLineString.java b/core/src/main/java/com/datastax/dse/driver/internal/core/data/geometry/DefaultLineString.java index b7ceee3d36b..1cf64bb366d 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/data/geometry/DefaultLineString.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/data/geometry/DefaultLineString.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/data/geometry/DefaultPoint.java b/core/src/main/java/com/datastax/dse/driver/internal/core/data/geometry/DefaultPoint.java index 53fa8dde4ca..c9540b10d8a 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/data/geometry/DefaultPoint.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/data/geometry/DefaultPoint.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/data/geometry/DefaultPolygon.java b/core/src/main/java/com/datastax/dse/driver/internal/core/data/geometry/DefaultPolygon.java index f3d17e7c720..27d375d42b1 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/data/geometry/DefaultPolygon.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/data/geometry/DefaultPolygon.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/data/geometry/Distance.java b/core/src/main/java/com/datastax/dse/driver/internal/core/data/geometry/Distance.java index d6d235dd914..518f6aa1346 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/data/geometry/Distance.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/data/geometry/Distance.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/data/geometry/DistanceSerializationProxy.java b/core/src/main/java/com/datastax/dse/driver/internal/core/data/geometry/DistanceSerializationProxy.java index f264393aefd..515af121980 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/data/geometry/DistanceSerializationProxy.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/data/geometry/DistanceSerializationProxy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/data/geometry/WkbSerializationProxy.java b/core/src/main/java/com/datastax/dse/driver/internal/core/data/geometry/WkbSerializationProxy.java index 11ab10366e5..92c0f6de2d5 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/data/geometry/WkbSerializationProxy.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/data/geometry/WkbSerializationProxy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/data/geometry/WkbUtil.java b/core/src/main/java/com/datastax/dse/driver/internal/core/data/geometry/WkbUtil.java index 56f86ba1a47..3f18b32fda2 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/data/geometry/WkbUtil.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/data/geometry/WkbUtil.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/ByteBufUtil.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/ByteBufUtil.java index d009adaf3f7..333ba6099d3 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/ByteBufUtil.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/ByteBufUtil.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/BytecodeGraphStatement.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/BytecodeGraphStatement.java index 591b791c7a5..b6fe05a987c 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/BytecodeGraphStatement.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/BytecodeGraphStatement.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/ContinuousAsyncGraphResultSet.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/ContinuousAsyncGraphResultSet.java index 38514790e47..9c7f773c3a2 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/ContinuousAsyncGraphResultSet.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/ContinuousAsyncGraphResultSet.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/ContinuousGraphRequestHandler.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/ContinuousGraphRequestHandler.java index 0e4d79f90d3..07d9e4c84a3 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/ContinuousGraphRequestHandler.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/ContinuousGraphRequestHandler.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -24,9 +26,11 @@ import com.datastax.dse.driver.internal.core.cql.continuous.ContinuousRequestHandlerBase; import com.datastax.dse.driver.internal.core.graph.binary.GraphBinaryModule; import com.datastax.dse.protocol.internal.response.result.DseRowsMetadata; +import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; import com.datastax.oss.driver.api.core.cql.ColumnDefinitions; import com.datastax.oss.driver.api.core.cql.ExecutionInfo; import com.datastax.oss.driver.internal.core.context.InternalDriverContext; +import com.datastax.oss.driver.internal.core.cql.Conversions; import com.datastax.oss.driver.internal.core.session.DefaultSession; import com.datastax.oss.driver.shaded.guava.common.base.MoreObjects; import com.datastax.oss.protocol.internal.Message; @@ -49,12 +53,9 @@ public class ContinuousGraphRequestHandler extends ContinuousRequestHandlerBase, AsyncGraphResultSet> { - private final Message message; - private final GraphProtocol subProtocol; private final GraphBinaryModule graphBinaryModule; + private final GraphSupportChecker graphSupportChecker; private final Duration globalTimeout; - private final int maxEnqueuedPages; - private final int maxPages; ContinuousGraphRequestHandler( @NonNull GraphStatement statement, @@ -74,17 +75,13 @@ public class ContinuousGraphRequestHandler DseSessionMetric.GRAPH_REQUESTS, DseNodeMetric.GRAPH_MESSAGES); this.graphBinaryModule = graphBinaryModule; - subProtocol = graphSupportChecker.inferGraphProtocol(statement, executionProfile, context); - message = - GraphConversions.createContinuousMessageFromGraphStatement( - statement, subProtocol, executionProfile, context, graphBinaryModule); + this.graphSupportChecker = graphSupportChecker; + DriverExecutionProfile executionProfile = + Conversions.resolveExecutionProfile(statement, context); globalTimeout = MoreObjects.firstNonNull( statement.getTimeout(), executionProfile.getDuration(DseDriverOption.GRAPH_TIMEOUT, Duration.ZERO)); - maxEnqueuedPages = - executionProfile.getInt(DseDriverOption.GRAPH_CONTINUOUS_PAGING_MAX_ENQUEUED_PAGES); - maxPages = executionProfile.getInt(DseDriverOption.GRAPH_CONTINUOUS_PAGING_MAX_PAGES); // NOTE that ordering of the following statement matters. // We should register this request after all fields have been initialized. throttler.register(this); @@ -98,40 +95,53 @@ protected Duration getGlobalTimeout() { @NonNull @Override - protected Duration getPageTimeout(int pageNumber) { + protected Duration getPageTimeout(@NonNull GraphStatement statement, int pageNumber) { return Duration.ZERO; } @NonNull @Override - protected Duration getReviseRequestTimeout() { + protected Duration getReviseRequestTimeout(@NonNull GraphStatement statement) { return Duration.ZERO; } @Override - protected int getMaxEnqueuedPages() { - return maxEnqueuedPages; + protected int getMaxEnqueuedPages(@NonNull GraphStatement statement) { + DriverExecutionProfile executionProfile = + Conversions.resolveExecutionProfile(statement, context); + return executionProfile.getInt(DseDriverOption.GRAPH_CONTINUOUS_PAGING_MAX_ENQUEUED_PAGES); } @Override - protected int getMaxPages() { - return maxPages; + protected int getMaxPages(@NonNull GraphStatement statement) { + DriverExecutionProfile executionProfile = + Conversions.resolveExecutionProfile(statement, context); + return executionProfile.getInt(DseDriverOption.GRAPH_CONTINUOUS_PAGING_MAX_PAGES); } @NonNull @Override - protected Message getMessage() { - return message; + protected Message getMessage(@NonNull GraphStatement statement) { + DriverExecutionProfile executionProfile = + Conversions.resolveExecutionProfile(statement, context); + GraphProtocol subProtocol = + graphSupportChecker.inferGraphProtocol(statement, executionProfile, context); + return GraphConversions.createContinuousMessageFromGraphStatement( + statement, subProtocol, executionProfile, context, graphBinaryModule); } @Override - protected boolean isTracingEnabled() { + protected boolean isTracingEnabled(@NonNull GraphStatement statement) { return statement.isTracing(); } @NonNull @Override - protected Map createPayload() { + protected Map createPayload(@NonNull GraphStatement statement) { + DriverExecutionProfile executionProfile = + Conversions.resolveExecutionProfile(statement, context); + GraphProtocol subProtocol = + graphSupportChecker.inferGraphProtocol(statement, executionProfile, context); return GraphConversions.createCustomPayload( statement, subProtocol, executionProfile, context, graphBinaryModule); } @@ -145,10 +155,15 @@ protected AsyncGraphResultSet createEmptyResultSet(@NonNull ExecutionInfo execut @NonNull @Override protected ContinuousAsyncGraphResultSet createResultSet( + @NonNull GraphStatement statement, @NonNull Rows rows, @NonNull ExecutionInfo executionInfo, @NonNull ColumnDefinitions columnDefinitions) throws IOException { + DriverExecutionProfile executionProfile = + Conversions.resolveExecutionProfile(statement, context); + GraphProtocol subProtocol = + graphSupportChecker.inferGraphProtocol(statement, executionProfile, context); Queue graphNodes = new ArrayDeque<>(); for (List row : rows.getData()) { diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/CqlCollectionPredicate.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/CqlCollectionPredicate.java index 295df6a224d..349321da0cf 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/CqlCollectionPredicate.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/CqlCollectionPredicate.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/DefaultAsyncGraphResultSet.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/DefaultAsyncGraphResultSet.java index 8a7ce76075c..abc7cc9514e 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/DefaultAsyncGraphResultSet.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/DefaultAsyncGraphResultSet.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/DefaultBatchGraphStatement.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/DefaultBatchGraphStatement.java index 08acb2815f2..e16287c415d 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/DefaultBatchGraphStatement.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/DefaultBatchGraphStatement.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/DefaultDseRemoteConnectionBuilder.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/DefaultDseRemoteConnectionBuilder.java index 9aa984dbc56..146e8e17ea2 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/DefaultDseRemoteConnectionBuilder.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/DefaultDseRemoteConnectionBuilder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/DefaultFluentGraphStatement.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/DefaultFluentGraphStatement.java index e8e9dd9dd14..0f6f1faabbf 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/DefaultFluentGraphStatement.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/DefaultFluentGraphStatement.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/DefaultScriptGraphStatement.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/DefaultScriptGraphStatement.java index ac63e91d3a0..71f79134237 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/DefaultScriptGraphStatement.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/DefaultScriptGraphStatement.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/DseGraphRemoteConnection.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/DseGraphRemoteConnection.java index cc416c38abc..a5ec0a1d115 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/DseGraphRemoteConnection.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/DseGraphRemoteConnection.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/DseGraphTraversal.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/DseGraphTraversal.java index 374a0277ed2..e0a5cf2d675 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/DseGraphTraversal.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/DseGraphTraversal.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -33,16 +35,6 @@ public DseGraphTraversal(AsyncGraphResultSet firstPage) { this.graphNodeIterator = GraphResultSets.toSync(firstPage).iterator(); } - @Override - @SuppressWarnings("deprecation") - public org.apache.tinkerpop.gremlin.process.remote.traversal.RemoteTraversalSideEffects - getSideEffects() { - // This was deprecated as part of TINKERPOP-2265 - // and is no longer being promoted as a feature. - // return null but do not throw "NotSupportedException" - return null; - } - @Override public boolean hasNext() { return graphNodeIterator.hasNext(); diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/DsePredicate.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/DsePredicate.java index ddc68227388..b5f8c30fd8c 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/DsePredicate.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/DsePredicate.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/EditDistance.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/EditDistance.java index 6570a6f8e8a..5ab836babbf 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/EditDistance.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/EditDistance.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GeoPredicate.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GeoPredicate.java index ce192ac0330..39949e97198 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GeoPredicate.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GeoPredicate.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GeoUtils.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GeoUtils.java index b2ee84b63a7..80d55dac69d 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GeoUtils.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GeoUtils.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphConversions.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphConversions.java index 7af7160baa1..c95b26b2e26 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphConversions.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphConversions.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -179,9 +181,13 @@ static Message createMessageFromGraphStatement( } } + ConsistencyLevel consistency = statement.getConsistencyLevel(); int consistencyLevel = - DefaultConsistencyLevel.valueOf(config.getString(DefaultDriverOption.REQUEST_CONSISTENCY)) - .getProtocolCode(); + (consistency == null) + ? context + .getConsistencyLevelRegistry() + .nameToCode(config.getString(DefaultDriverOption.REQUEST_CONSISTENCY)) + : consistency.getProtocolCode(); long timestamp = statement.getTimestamp(); if (timestamp == Statement.NO_DEFAULT_TIMESTAMP) { @@ -384,4 +390,21 @@ public static GraphNode createGraphBinaryGraphNode( : "Graph protocol error. Received object should be a Traverser but it is not."; return new ObjectGraphNode(deserializedObject); } + + public static Duration resolveGraphRequestTimeout( + GraphStatement statement, InternalDriverContext context) { + DriverExecutionProfile executionProfile = resolveExecutionProfile(statement, context); + return statement.getTimeout() != null + ? statement.getTimeout() + : executionProfile.getDuration(DseDriverOption.GRAPH_TIMEOUT); + } + + public static GraphProtocol resolveGraphSubProtocol( + GraphStatement statement, + GraphSupportChecker graphSupportChecker, + InternalDriverContext context) { + DriverExecutionProfile executionProfile = + Conversions.resolveExecutionProfile(statement, context); + return graphSupportChecker.inferGraphProtocol(statement, executionProfile, context); + } } diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphExecutionInfoConverter.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphExecutionInfoConverter.java index 344b84ad050..b6472f690d3 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphExecutionInfoConverter.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphExecutionInfoConverter.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphProtocol.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphProtocol.java index 373dbe2ad44..6b7a9f4c430 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphProtocol.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphProtocol.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphRequestAsyncProcessor.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphRequestAsyncProcessor.java index bd86c98c953..050b03c66f4 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphRequestAsyncProcessor.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphRequestAsyncProcessor.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphRequestHandler.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphRequestHandler.java index 46dbaa88768..5c9ceb00df2 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphRequestHandler.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphRequestHandler.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -15,7 +17,6 @@ */ package com.datastax.dse.driver.internal.core.graph; -import com.datastax.dse.driver.api.core.config.DseDriverOption; import com.datastax.dse.driver.api.core.graph.AsyncGraphResultSet; import com.datastax.dse.driver.api.core.graph.GraphNode; import com.datastax.dse.driver.api.core.graph.GraphStatement; @@ -25,6 +26,7 @@ import com.datastax.oss.driver.api.core.AllNodesFailedException; import com.datastax.oss.driver.api.core.DriverException; import com.datastax.oss.driver.api.core.DriverTimeoutException; +import com.datastax.oss.driver.api.core.NodeUnavailableException; import com.datastax.oss.driver.api.core.RequestThrottlingException; import com.datastax.oss.driver.api.core.config.DefaultDriverOption; import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; @@ -33,8 +35,8 @@ import com.datastax.oss.driver.api.core.metadata.Node; import com.datastax.oss.driver.api.core.metrics.DefaultNodeMetric; import com.datastax.oss.driver.api.core.metrics.DefaultSessionMetric; -import com.datastax.oss.driver.api.core.retry.RetryDecision; import com.datastax.oss.driver.api.core.retry.RetryPolicy; +import com.datastax.oss.driver.api.core.retry.RetryVerdict; import com.datastax.oss.driver.api.core.servererrors.BootstrappingException; import com.datastax.oss.driver.api.core.servererrors.CoordinatorException; import com.datastax.oss.driver.api.core.servererrors.FunctionFailureException; @@ -45,7 +47,6 @@ import com.datastax.oss.driver.api.core.servererrors.WriteTimeoutException; import com.datastax.oss.driver.api.core.session.throttling.RequestThrottler; import com.datastax.oss.driver.api.core.session.throttling.Throttled; -import com.datastax.oss.driver.api.core.specex.SpeculativeExecutionPolicy; import com.datastax.oss.driver.api.core.tracker.RequestTracker; import com.datastax.oss.driver.internal.core.channel.DriverChannel; import com.datastax.oss.driver.internal.core.channel.ResponseCallback; @@ -59,7 +60,7 @@ import com.datastax.oss.driver.internal.core.tracker.NoopRequestTracker; import com.datastax.oss.driver.internal.core.tracker.RequestLogger; import com.datastax.oss.driver.internal.core.util.Loggers; -import com.datastax.oss.driver.internal.core.util.collection.QueryPlan; +import com.datastax.oss.driver.internal.core.util.collection.SimpleQueryPlan; import com.datastax.oss.protocol.internal.Frame; import com.datastax.oss.protocol.internal.Message; import com.datastax.oss.protocol.internal.response.Error; @@ -99,15 +100,11 @@ public class GraphRequestHandler implements Throttled { private final long startTimeNanos; private final String logPrefix; - private final GraphStatement statement; + private final GraphStatement initialStatement; private final DefaultSession session; private final InternalDriverContext context; - private final DriverExecutionProfile executionProfile; - private final boolean isIdempotent; protected final CompletableFuture result; - private final Message message; private final Timer timer; - private final GraphProtocol subProtocol; /** * How many speculative executions are currently running (including the initial execution). We @@ -126,13 +123,11 @@ public class GraphRequestHandler implements Throttled { private final Timeout scheduledTimeout; private final List scheduledExecutions; private final List inFlightCallbacks; - private final RetryPolicy retryPolicy; - private final SpeculativeExecutionPolicy speculativeExecutionPolicy; private final RequestThrottler throttler; private final RequestTracker requestTracker; private final SessionMetricUpdater sessionMetricUpdater; - private final Map queryCustomPayload; private final GraphBinaryModule graphBinaryModule; + private final GraphSupportChecker graphSupportChecker; // The errors on the nodes that were already tried (lazily initialized on the first error). // We don't use a map because nodes can appear multiple times. @@ -148,24 +143,17 @@ public class GraphRequestHandler implements Throttled { this.startTimeNanos = System.nanoTime(); this.logPrefix = sessionLogPrefix + "|" + this.hashCode(); LOG.trace("[{}] Creating new Graph request handler for request {}", logPrefix, statement); - this.statement = statement; + this.initialStatement = statement; this.session = dseSession; this.context = context; - this.executionProfile = GraphConversions.resolveExecutionProfile(this.statement, this.context); - this.retryPolicy = context.getRetryPolicy(executionProfile.getName()); - this.speculativeExecutionPolicy = - context.getSpeculativeExecutionPolicy(executionProfile.getName()); - Boolean statementIsIdempotent = statement.isIdempotent(); - this.isIdempotent = - (statementIsIdempotent == null) - ? executionProfile.getBoolean(DefaultDriverOption.REQUEST_DEFAULT_IDEMPOTENCE) - : statementIsIdempotent; + this.graphSupportChecker = graphSupportChecker; this.result = new CompletableFuture<>(); this.result.exceptionally( t -> { try { if (t instanceof CancellationException) { cancelScheduledTasks(); + context.getRequestThrottler().signalCancel(this); } } catch (Throwable t2) { Loggers.warnWithException(LOG, "[{}] Uncaught exception", logPrefix, t2); @@ -173,37 +161,27 @@ public class GraphRequestHandler implements Throttled { return null; }); this.graphBinaryModule = graphBinaryModule; - this.subProtocol = - graphSupportChecker.inferGraphProtocol(this.statement, executionProfile, this.context); - LOG.debug("[{}], Graph protocol used for query: {}", logPrefix, subProtocol); - this.message = - GraphConversions.createMessageFromGraphStatement( - this.statement, subProtocol, executionProfile, this.context, this.graphBinaryModule); this.timer = context.getNettyOptions().getTimer(); - Duration timeout = - statement.getTimeout() != null - ? statement.getTimeout() - : executionProfile.getDuration(DseDriverOption.GRAPH_TIMEOUT, null); - this.scheduledTimeout = scheduleTimeout(timeout); this.activeExecutionsCount = new AtomicInteger(1); this.startedSpeculativeExecutionsCount = new AtomicInteger(0); - this.scheduledExecutions = isIdempotent ? new CopyOnWriteArrayList<>() : null; + this.scheduledExecutions = new CopyOnWriteArrayList<>(); this.inFlightCallbacks = new CopyOnWriteArrayList<>(); - this.queryCustomPayload = - GraphConversions.createCustomPayload( - this.statement, subProtocol, executionProfile, this.context, this.graphBinaryModule); - this.requestTracker = context.getRequestTracker(); this.sessionMetricUpdater = session.getMetricUpdater(); + Duration timeout = GraphConversions.resolveGraphRequestTimeout(statement, context); + this.scheduledTimeout = scheduleTimeout(timeout); + this.throttler = context.getRequestThrottler(); this.throttler.register(this); } @Override public void onThrottleReady(boolean wasDelayed) { + DriverExecutionProfile executionProfile = + Conversions.resolveExecutionProfile(initialStatement, context); if (wasDelayed // avoid call to nanoTime() if metric is disabled: && sessionMetricUpdater.isEnabled( @@ -215,12 +193,12 @@ public void onThrottleReady(boolean wasDelayed) { TimeUnit.NANOSECONDS); } Queue queryPlan = - statement.getNode() != null - ? new QueryPlan(statement.getNode()) + initialStatement.getNode() != null + ? new SimpleQueryPlan(initialStatement.getNode()) : context .getLoadBalancingPolicyWrapper() - .newQueryPlan(statement, executionProfile.getName(), session); - sendRequest(null, queryPlan, 0, 0, true); + .newQueryPlan(initialStatement, executionProfile.getName(), session); + sendRequest(initialStatement, null, queryPlan, 0, 0, true); } public CompletionStage handle() { @@ -233,6 +211,7 @@ private Timeout scheduleTimeout(Duration timeoutDuration) { return this.timer.newTimeout( (Timeout timeout1) -> setFinalError( + initialStatement, new DriverTimeoutException("Query timed out after " + timeoutDuration), null, NO_SUCCESSFUL_EXECUTION), @@ -262,6 +241,7 @@ private Timeout scheduleTimeout(Duration timeoutDuration) { * @param scheduleNextExecution whether to schedule the next speculative execution */ private void sendRequest( + GraphStatement statement, Node retriedNode, Queue queryPlan, int currentExecutionIndex, @@ -277,6 +257,8 @@ private void sendRequest( channel = session.getChannel(node, logPrefix); if (channel != null) { break; + } else { + recordError(node, new NodeUnavailableException(node)); } } } @@ -285,11 +267,15 @@ private void sendRequest( if (!result.isDone() && activeExecutionsCount.decrementAndGet() == 0) { // We're the last execution so fail the result setFinalError( - AllNodesFailedException.fromErrors(this.errors), null, NO_SUCCESSFUL_EXECUTION); + statement, + AllNodesFailedException.fromErrors(this.errors), + null, + NO_SUCCESSFUL_EXECUTION); } } else { NodeResponseCallback nodeResponseCallback = new NodeResponseCallback( + statement, node, queryPlan, channel, @@ -297,8 +283,18 @@ private void sendRequest( retryCount, scheduleNextExecution, logPrefix); + DriverExecutionProfile executionProfile = + Conversions.resolveExecutionProfile(statement, context); + GraphProtocol graphSubProtocol = + GraphConversions.resolveGraphSubProtocol(statement, graphSupportChecker, context); + Message message = + GraphConversions.createMessageFromGraphStatement( + statement, graphSubProtocol, executionProfile, context, graphBinaryModule); + Map customPayload = + GraphConversions.createCustomPayload( + statement, graphSubProtocol, executionProfile, context, graphBinaryModule); channel - .write(message, statement.isTracing(), queryCustomPayload, nodeResponseCallback) + .write(message, statement.isTracing(), customPayload, nodeResponseCallback) .addListener(nodeResponseCallback); } } @@ -335,7 +331,11 @@ private void setFinalResult( Result resultMessage, Frame responseFrame, NodeResponseCallback callback) { try { ExecutionInfo executionInfo = buildExecutionInfo(callback, responseFrame); - + DriverExecutionProfile executionProfile = + Conversions.resolveExecutionProfile(callback.statement, context); + GraphProtocol subProtocol = + GraphConversions.resolveGraphSubProtocol( + callback.statement, graphSupportChecker, context); Queue graphNodes = new ArrayDeque<>(); for (List row : ((Rows) resultMessage).getData()) { if (subProtocol.isGraphBinary()) { @@ -361,9 +361,9 @@ private void setFinalResult( totalLatencyNanos = completionTimeNanos - startTimeNanos; long nodeLatencyNanos = completionTimeNanos - callback.nodeStartTimeNanos; requestTracker.onNodeSuccess( - statement, nodeLatencyNanos, executionProfile, callback.node, logPrefix); + callback.statement, nodeLatencyNanos, executionProfile, callback.node, logPrefix); requestTracker.onSuccess( - statement, totalLatencyNanos, executionProfile, callback.node, logPrefix); + callback.statement, totalLatencyNanos, executionProfile, callback.node, logPrefix); } if (sessionMetricUpdater.isEnabled( DseSessionMetric.GRAPH_REQUESTS, executionProfile.getName())) { @@ -382,14 +382,16 @@ private void setFinalResult( if (!executionInfo.getWarnings().isEmpty() && executionProfile.getBoolean(DefaultDriverOption.REQUEST_LOG_WARNINGS) && LOG.isWarnEnabled()) { - logServerWarnings(executionInfo.getWarnings()); + logServerWarnings(callback.statement, executionInfo.getWarnings()); } } catch (Throwable error) { - setFinalError(error, callback.node, NO_SUCCESSFUL_EXECUTION); + setFinalError(callback.statement, error, callback.node, NO_SUCCESSFUL_EXECUTION); } } - private void logServerWarnings(List warnings) { + private void logServerWarnings(GraphStatement statement, List warnings) { + DriverExecutionProfile executionProfile = + Conversions.resolveExecutionProfile(statement, context); // use the RequestLogFormatter to format the query StringBuilder statementString = new StringBuilder(); context @@ -416,8 +418,10 @@ private void logServerWarnings(List warnings) { } private ExecutionInfo buildExecutionInfo(NodeResponseCallback callback, Frame responseFrame) { + DriverExecutionProfile executionProfile = + Conversions.resolveExecutionProfile(callback.statement, context); return new DefaultExecutionInfo( - statement, + callback.statement, callback.node, startedSpeculativeExecutionsCount.get(), callback.execution, @@ -432,12 +436,17 @@ private ExecutionInfo buildExecutionInfo(NodeResponseCallback callback, Frame re @Override public void onThrottleFailure(@NonNull RequestThrottlingException error) { + DriverExecutionProfile executionProfile = + Conversions.resolveExecutionProfile(initialStatement, context); sessionMetricUpdater.incrementCounter( DefaultSessionMetric.THROTTLING_ERRORS, executionProfile.getName()); - setFinalError(error, null, NO_SUCCESSFUL_EXECUTION); + setFinalError(initialStatement, error, null, NO_SUCCESSFUL_EXECUTION); } - private void setFinalError(Throwable error, Node node, int execution) { + private void setFinalError( + GraphStatement statement, Throwable error, Node node, int execution) { + DriverExecutionProfile executionProfile = + Conversions.resolveExecutionProfile(statement, context); if (error instanceof DriverException) { ((DriverException) error) .setExecutionInfo( @@ -479,6 +488,7 @@ private class NodeResponseCallback implements ResponseCallback, GenericFutureListener> { private final long nodeStartTimeNanos = System.nanoTime(); + private final GraphStatement statement; private final Node node; private final Queue queryPlan; private final DriverChannel channel; @@ -490,8 +500,10 @@ private class NodeResponseCallback private final int retryCount; private final boolean scheduleNextExecution; private final String logPrefix; + private final DriverExecutionProfile executionProfile; private NodeResponseCallback( + GraphStatement statement, Node node, Queue queryPlan, DriverChannel channel, @@ -499,6 +511,7 @@ private NodeResponseCallback( int retryCount, boolean scheduleNextExecution, String logPrefix) { + this.statement = statement; this.node = node; this.queryPlan = queryPlan; this.channel = channel; @@ -506,6 +519,7 @@ private NodeResponseCallback( this.retryCount = retryCount; this.scheduleNextExecution = scheduleNextExecution; this.logPrefix = logPrefix + "|" + execution; + this.executionProfile = Conversions.resolveExecutionProfile(statement, context); } // this gets invoked once the write completes. @@ -516,7 +530,7 @@ public void operationComplete(Future future) { if (error instanceof EncoderException && error.getCause() instanceof FrameTooLongException) { trackNodeError(node, error.getCause(), NANOTIME_NOT_MEASURED_YET); - setFinalError(error.getCause(), node, execution); + setFinalError(statement, error.getCause(), node, execution); } else { LOG.trace( "[{}] Failed to send request on {}, trying next node (cause: {})", @@ -529,7 +543,12 @@ public void operationComplete(Future future) { .getMetricUpdater() .incrementCounter(DefaultNodeMetric.UNSENT_REQUESTS, executionProfile.getName()); sendRequest( - null, queryPlan, execution, retryCount, scheduleNextExecution); // try next node + statement, + null, + queryPlan, + execution, + retryCount, + scheduleNextExecution); // try next node } } else { LOG.trace("[{}] Request sent on {}", logPrefix, channel); @@ -539,12 +558,14 @@ public void operationComplete(Future future) { cancel(); } else { inFlightCallbacks.add(this); - if (scheduleNextExecution && isIdempotent) { + if (scheduleNextExecution + && Conversions.resolveIdempotence(statement, executionProfile)) { int nextExecution = execution + 1; long nextDelay; try { nextDelay = - speculativeExecutionPolicy.nextExecution(node, null, statement, nextExecution); + Conversions.resolveSpeculativeExecutionPolicy(context, executionProfile) + .nextExecution(node, null, statement, nextExecution); } catch (Throwable cause) { // This is a bug in the policy, but not fatal since we have at least one other // execution already running. Don't fail the whole request. @@ -586,7 +607,7 @@ private void scheduleSpeculativeExecution(int index, long delay) { .getMetricUpdater() .incrementCounter( DefaultNodeMetric.SPECULATIVE_EXECUTIONS, executionProfile.getName()); - sendRequest(null, queryPlan, index, 0, true); + sendRequest(statement, null, queryPlan, index, 0, true); } }, delay, @@ -632,11 +653,14 @@ public void onResponse(Frame responseFrame) { new IllegalStateException("Unexpected response " + responseMessage), nodeResponseTimeNanos); setFinalError( - new IllegalStateException("Unexpected response " + responseMessage), node, execution); + statement, + new IllegalStateException("Unexpected response " + responseMessage), + node, + execution); } } catch (Throwable t) { trackNodeError(node, t, nodeResponseTimeNanos); - setFinalError(t, node, execution); + setFinalError(statement, t, node, execution); } } @@ -647,20 +671,21 @@ private void processErrorResponse(Error errorMessage) { LOG.trace("[{}] {} is bootstrapping, trying next node", logPrefix, node); recordError(node, error); trackNodeError(node, error, NANOTIME_NOT_MEASURED_YET); - sendRequest(null, queryPlan, execution, retryCount, false); + sendRequest(statement, null, queryPlan, execution, retryCount, false); } else if (error instanceof QueryValidationException || error instanceof FunctionFailureException || error instanceof ProtocolError) { LOG.trace("[{}] Unrecoverable error, rethrowing", logPrefix); metricUpdater.incrementCounter(DefaultNodeMetric.OTHER_ERRORS, executionProfile.getName()); trackNodeError(node, error, NANOTIME_NOT_MEASURED_YET); - setFinalError(error, node, execution); + setFinalError(statement, error, node, execution); } else { - RetryDecision decision; + RetryPolicy retryPolicy = Conversions.resolveRetryPolicy(context, executionProfile); + RetryVerdict verdict; if (error instanceof ReadTimeoutException) { ReadTimeoutException readTimeout = (ReadTimeoutException) error; - decision = - retryPolicy.onReadTimeout( + verdict = + retryPolicy.onReadTimeoutVerdict( statement, readTimeout.getConsistencyLevel(), readTimeout.getBlockFor(), @@ -669,32 +694,32 @@ private void processErrorResponse(Error errorMessage) { retryCount); updateErrorMetrics( metricUpdater, - decision, + verdict, DefaultNodeMetric.READ_TIMEOUTS, DefaultNodeMetric.RETRIES_ON_READ_TIMEOUT, DefaultNodeMetric.IGNORES_ON_READ_TIMEOUT); } else if (error instanceof WriteTimeoutException) { WriteTimeoutException writeTimeout = (WriteTimeoutException) error; - decision = - isIdempotent - ? retryPolicy.onWriteTimeout( + verdict = + Conversions.resolveIdempotence(statement, executionProfile) + ? retryPolicy.onWriteTimeoutVerdict( statement, writeTimeout.getConsistencyLevel(), writeTimeout.getWriteType(), writeTimeout.getBlockFor(), writeTimeout.getReceived(), retryCount) - : RetryDecision.RETHROW; + : RetryVerdict.RETHROW; updateErrorMetrics( metricUpdater, - decision, + verdict, DefaultNodeMetric.WRITE_TIMEOUTS, DefaultNodeMetric.RETRIES_ON_WRITE_TIMEOUT, DefaultNodeMetric.IGNORES_ON_WRITE_TIMEOUT); } else if (error instanceof UnavailableException) { UnavailableException unavailable = (UnavailableException) error; - decision = - retryPolicy.onUnavailable( + verdict = + retryPolicy.onUnavailableVerdict( statement, unavailable.getConsistencyLevel(), unavailable.getRequired(), @@ -702,42 +727,54 @@ private void processErrorResponse(Error errorMessage) { retryCount); updateErrorMetrics( metricUpdater, - decision, + verdict, DefaultNodeMetric.UNAVAILABLES, DefaultNodeMetric.RETRIES_ON_UNAVAILABLE, DefaultNodeMetric.IGNORES_ON_UNAVAILABLE); } else { - decision = - isIdempotent - ? retryPolicy.onErrorResponse(statement, error, retryCount) - : RetryDecision.RETHROW; + verdict = + Conversions.resolveIdempotence(statement, executionProfile) + ? retryPolicy.onErrorResponseVerdict(statement, error, retryCount) + : RetryVerdict.RETHROW; updateErrorMetrics( metricUpdater, - decision, + verdict, DefaultNodeMetric.OTHER_ERRORS, DefaultNodeMetric.RETRIES_ON_OTHER_ERROR, DefaultNodeMetric.IGNORES_ON_OTHER_ERROR); } - processRetryDecision(decision, error); + processRetryVerdict(verdict, error); } } - private void processRetryDecision(RetryDecision decision, Throwable error) { - LOG.trace("[{}] Processing retry decision {}", logPrefix, decision); - switch (decision) { + private void processRetryVerdict(RetryVerdict verdict, Throwable error) { + LOG.trace("[{}] Processing retry decision {}", logPrefix, verdict); + switch (verdict.getRetryDecision()) { case RETRY_SAME: recordError(node, error); trackNodeError(node, error, NANOTIME_NOT_MEASURED_YET); - sendRequest(node, queryPlan, execution, retryCount + 1, false); + sendRequest( + verdict.getRetryRequest(statement), + node, + queryPlan, + execution, + retryCount + 1, + false); break; case RETRY_NEXT: recordError(node, error); trackNodeError(node, error, NANOTIME_NOT_MEASURED_YET); - sendRequest(null, queryPlan, execution, retryCount + 1, false); + sendRequest( + verdict.getRetryRequest(statement), + null, + queryPlan, + execution, + retryCount + 1, + false); break; case RETHROW: trackNodeError(node, error, NANOTIME_NOT_MEASURED_YET); - setFinalError(error, node, execution); + setFinalError(statement, error, node, execution); break; case IGNORE: setFinalResult(Void.INSTANCE, null, this); @@ -747,12 +784,12 @@ private void processRetryDecision(RetryDecision decision, Throwable error) { private void updateErrorMetrics( NodeMetricUpdater metricUpdater, - RetryDecision decision, + RetryVerdict verdict, DefaultNodeMetric error, DefaultNodeMetric retriesOnError, DefaultNodeMetric ignoresOnError) { metricUpdater.incrementCounter(error, executionProfile.getName()); - switch (decision) { + switch (verdict.getRetryDecision()) { case RETRY_SAME: case RETRY_NEXT: metricUpdater.incrementCounter(DefaultNodeMetric.RETRIES, executionProfile.getName()); @@ -774,24 +811,27 @@ public void onFailure(Throwable error) { return; } LOG.trace("[{}] Request failure, processing: {}", logPrefix, error); - RetryDecision decision; - if (!isIdempotent || error instanceof FrameTooLongException) { - decision = RetryDecision.RETHROW; + RetryVerdict verdict; + if (!Conversions.resolveIdempotence(statement, executionProfile) + || error instanceof FrameTooLongException) { + verdict = RetryVerdict.RETHROW; } else { try { - decision = retryPolicy.onRequestAborted(statement, error, retryCount); + RetryPolicy retryPolicy = Conversions.resolveRetryPolicy(context, executionProfile); + verdict = retryPolicy.onRequestAbortedVerdict(statement, error, retryCount); } catch (Throwable cause) { setFinalError( + statement, new IllegalStateException("Unexpected error while invoking the retry policy", cause), node, NO_SUCCESSFUL_EXECUTION); return; } } - processRetryDecision(decision, error); + processRetryVerdict(verdict, error); updateErrorMetrics( ((DefaultNode) node).getMetricUpdater(), - decision, + verdict, DefaultNodeMetric.ABORTED_REQUESTS, DefaultNodeMetric.RETRIES_ON_ABORTED, DefaultNodeMetric.IGNORES_ON_ABORTED); diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphRequestSyncProcessor.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphRequestSyncProcessor.java index 5447b6657c6..bc2381482a8 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphRequestSyncProcessor.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphRequestSyncProcessor.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphResultIterator.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphResultIterator.java index 8a000f03c48..7e9043affec 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphResultIterator.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphResultIterator.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphResultSets.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphResultSets.java index 2a2def58896..fb21f857cfa 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphResultSets.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphResultSets.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphSON1SerdeTP.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphSON1SerdeTP.java index 5377a4663e7..f880bca3764 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphSON1SerdeTP.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphSON1SerdeTP.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphSON2SerdeTP.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphSON2SerdeTP.java index c394ba219e9..d79afc71822 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphSON2SerdeTP.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphSON2SerdeTP.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphSONUtils.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphSONUtils.java index 42bc93e3550..02b35f7ee36 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphSONUtils.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphSONUtils.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphStatementBase.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphStatementBase.java index 624fec901ad..b8baa2f5e49 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphStatementBase.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphStatementBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphSupportChecker.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphSupportChecker.java index 58a2b518e40..6e586bbcf3f 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphSupportChecker.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/GraphSupportChecker.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/LegacyGraphNode.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/LegacyGraphNode.java index 3dc8360662b..1749bf00873 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/LegacyGraphNode.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/LegacyGraphNode.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/MultiPageGraphResultSet.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/MultiPageGraphResultSet.java index 8c7ac3668c3..fe81d73ba00 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/MultiPageGraphResultSet.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/MultiPageGraphResultSet.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/ObjectGraphNode.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/ObjectGraphNode.java index 320031feb8f..56123799fdd 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/ObjectGraphNode.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/ObjectGraphNode.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/SearchPredicate.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/SearchPredicate.java index a6991021a70..b69c3a59cf0 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/SearchPredicate.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/SearchPredicate.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/SearchUtils.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/SearchUtils.java index 1e64c5f2c7c..3440c40e87a 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/SearchUtils.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/SearchUtils.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/SinglePageGraphResultSet.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/SinglePageGraphResultSet.java index 09710c51bbf..ff1d984d745 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/SinglePageGraphResultSet.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/SinglePageGraphResultSet.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/TinkerpopBufferUtil.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/TinkerpopBufferUtil.java index f87cadee4fa..5650d904350 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/TinkerpopBufferUtil.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/TinkerpopBufferUtil.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/AbstractDynamicGraphBinaryCustomSerializer.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/AbstractDynamicGraphBinaryCustomSerializer.java index 77be1e885d4..649f5310c5d 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/AbstractDynamicGraphBinaryCustomSerializer.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/AbstractDynamicGraphBinaryCustomSerializer.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/AbstractSimpleGraphBinaryCustomSerializer.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/AbstractSimpleGraphBinaryCustomSerializer.java index 428ee5a72eb..6dd149707e8 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/AbstractSimpleGraphBinaryCustomSerializer.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/AbstractSimpleGraphBinaryCustomSerializer.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/ComplexTypeSerializerUtil.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/ComplexTypeSerializerUtil.java index f70ac661a75..bec3c78743a 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/ComplexTypeSerializerUtil.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/ComplexTypeSerializerUtil.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/CqlDurationSerializer.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/CqlDurationSerializer.java index 84a820c1f64..1ac97de0ef4 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/CqlDurationSerializer.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/CqlDurationSerializer.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/DistanceSerializer.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/DistanceSerializer.java index 1b77115c0be..9e281b2b84a 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/DistanceSerializer.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/DistanceSerializer.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/EditDistanceSerializer.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/EditDistanceSerializer.java index 6949f94a6ba..b2831040123 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/EditDistanceSerializer.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/EditDistanceSerializer.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/GeometrySerializer.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/GeometrySerializer.java index baa650bfeaa..996e79c7693 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/GeometrySerializer.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/GeometrySerializer.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/GraphBinaryModule.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/GraphBinaryModule.java index ba84aeab64c..59f966a34c2 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/GraphBinaryModule.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/GraphBinaryModule.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/GraphBinaryUtils.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/GraphBinaryUtils.java index 4bc1d3ab84f..42283cd5167 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/GraphBinaryUtils.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/GraphBinaryUtils.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/LineStringSerializer.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/LineStringSerializer.java index 4f9917de779..4dfa8f8f0f1 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/LineStringSerializer.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/LineStringSerializer.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/PairSerializer.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/PairSerializer.java index b80c25c6838..3f13dd5b3a0 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/PairSerializer.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/PairSerializer.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/PointSerializer.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/PointSerializer.java index 2c1a07f8e42..2204b0da073 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/PointSerializer.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/PointSerializer.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/PolygonSerializer.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/PolygonSerializer.java index d42c630e68c..8e3bc67838a 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/PolygonSerializer.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/PolygonSerializer.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/TupleValueSerializer.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/TupleValueSerializer.java index ac81e07b9cb..b7c6fc2098d 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/TupleValueSerializer.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/TupleValueSerializer.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/UdtValueSerializer.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/UdtValueSerializer.java index 2f0217a8fd4..3e617ebf926 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/UdtValueSerializer.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/UdtValueSerializer.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/buffer/DseNettyBuffer.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/buffer/DseNettyBuffer.java index bd07bf7b263..590ac2e9be2 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/buffer/DseNettyBuffer.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/buffer/DseNettyBuffer.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/buffer/DseNettyBufferFactory.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/buffer/DseNettyBufferFactory.java index 47cf713c05d..57ee3cb1a9d 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/buffer/DseNettyBufferFactory.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/binary/buffer/DseNettyBufferFactory.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/reactive/DefaultReactiveGraphNode.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/reactive/DefaultReactiveGraphNode.java index 95621bb92db..fda0eed5333 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/reactive/DefaultReactiveGraphNode.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/reactive/DefaultReactiveGraphNode.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/reactive/DefaultReactiveGraphResultSet.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/reactive/DefaultReactiveGraphResultSet.java index 486bbaf5db7..137e44e4d95 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/reactive/DefaultReactiveGraphResultSet.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/reactive/DefaultReactiveGraphResultSet.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/reactive/FailedReactiveGraphResultSet.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/reactive/FailedReactiveGraphResultSet.java index 183277439e2..45bbd8c62b0 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/reactive/FailedReactiveGraphResultSet.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/reactive/FailedReactiveGraphResultSet.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/reactive/ReactiveGraphRequestProcessor.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/reactive/ReactiveGraphRequestProcessor.java index ca044f6147d..ed2cd28926c 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/reactive/ReactiveGraphRequestProcessor.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/reactive/ReactiveGraphRequestProcessor.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/reactive/ReactiveGraphResultSetSubscription.java b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/reactive/ReactiveGraphResultSetSubscription.java index a7dd37f5b6a..c3234d74ebc 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/graph/reactive/ReactiveGraphResultSetSubscription.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/graph/reactive/ReactiveGraphResultSetSubscription.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/AddressFormatter.java b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/AddressFormatter.java index 9f1df8c7ddf..cecc951a3ab 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/AddressFormatter.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/AddressFormatter.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/ConfigAntiPatternsFinder.java b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/ConfigAntiPatternsFinder.java index 88f467270bb..7f5b9c20a0e 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/ConfigAntiPatternsFinder.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/ConfigAntiPatternsFinder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/DataCentersFinder.java b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/DataCentersFinder.java index c335a5639ff..7112b8dcdf7 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/DataCentersFinder.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/DataCentersFinder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/ExecutionProfilesInfoFinder.java b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/ExecutionProfilesInfoFinder.java index a255b5b0de0..a7c92d80d96 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/ExecutionProfilesInfoFinder.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/ExecutionProfilesInfoFinder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -158,9 +160,12 @@ private LoadBalancingInfo getLoadBalancingInfo(DriverExecutionProfile driverExec "localDataCenter", driverExecutionProfile.getString(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER)); } - options.put( - "filterFunction", - driverExecutionProfile.isDefined(DefaultDriverOption.LOAD_BALANCING_FILTER_CLASS)); + @SuppressWarnings("deprecation") + boolean hasNodeFiltering = + driverExecutionProfile.isDefined(DefaultDriverOption.LOAD_BALANCING_FILTER_CLASS) + || driverExecutionProfile.isDefined( + DefaultDriverOption.LOAD_BALANCING_DISTANCE_EVALUATOR_CLASS); + options.put("filterFunction", hasNodeFiltering); ClassSettingDetails loadBalancingDetails = PackageUtil.getLoadBalancingDetails( driverExecutionProfile.getString(DefaultDriverOption.LOAD_BALANCING_POLICY_CLASS)); diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/InsightsClient.java b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/InsightsClient.java index 3f02e2368a3..f19687adf45 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/InsightsClient.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/InsightsClient.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -41,6 +43,7 @@ import com.datastax.oss.driver.api.core.session.SessionBuilder; import com.datastax.oss.driver.api.core.type.DataTypes; import com.datastax.oss.driver.api.core.type.codec.TypeCodec; +import com.datastax.oss.driver.api.core.uuid.Uuids; import com.datastax.oss.driver.internal.core.adminrequest.AdminRequestHandler; import com.datastax.oss.driver.internal.core.context.DefaultDriverContext; import com.datastax.oss.driver.internal.core.context.InternalDriverContext; @@ -65,7 +68,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.ScheduledExecutorService; @@ -90,7 +92,7 @@ public class InsightsClient { static final String DEFAULT_JAVA_APPLICATION = "Default Java Application"; private final ControlConnection controlConnection; - private final String id = UUID.randomUUID().toString(); + private final String id = Uuids.random().toString(); private final InsightsConfiguration insightsConfiguration; private final AtomicInteger numberOfStatusEventErrors = new AtomicInteger(); diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/InsightsSupportVerifier.java b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/InsightsSupportVerifier.java index 8d6b83088e8..ec016ef52d8 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/InsightsSupportVerifier.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/InsightsSupportVerifier.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/PackageUtil.java b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/PackageUtil.java index 74a6cc82ea5..3c61dec4f20 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/PackageUtil.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/PackageUtil.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/PlatformInfoFinder.java b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/PlatformInfoFinder.java index f30a8e7a61c..30d41d40836 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/PlatformInfoFinder.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/PlatformInfoFinder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/ReconnectionPolicyInfoFinder.java b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/ReconnectionPolicyInfoFinder.java index a6dab75e70d..af8aff74035 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/ReconnectionPolicyInfoFinder.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/ReconnectionPolicyInfoFinder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/configuration/InsightsConfiguration.java b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/configuration/InsightsConfiguration.java index 900a64a0af3..ac27bb76389 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/configuration/InsightsConfiguration.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/configuration/InsightsConfiguration.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/exceptions/InsightEventFormatException.java b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/exceptions/InsightEventFormatException.java index 539734c0427..cfce68971ef 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/exceptions/InsightEventFormatException.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/exceptions/InsightEventFormatException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/AuthProviderType.java b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/AuthProviderType.java index df58f45c2fd..18aec53e899 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/AuthProviderType.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/AuthProviderType.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/Insight.java b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/Insight.java index 19759006178..ca4e6455345 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/Insight.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/Insight.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/InsightMetadata.java b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/InsightMetadata.java index 7b588270645..cfa2644b0c7 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/InsightMetadata.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/InsightMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/InsightType.java b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/InsightType.java index 7b8f3213c06..ae91e27d227 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/InsightType.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/InsightType.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/InsightsPlatformInfo.java b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/InsightsPlatformInfo.java index bc24f8dfb42..231f082d785 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/InsightsPlatformInfo.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/InsightsPlatformInfo.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/InsightsStartupData.java b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/InsightsStartupData.java index e57eb6f196a..bddd3ef94b3 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/InsightsStartupData.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/InsightsStartupData.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/InsightsStatusData.java b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/InsightsStatusData.java index 2ef967c4e85..6f5a135f7c4 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/InsightsStatusData.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/InsightsStatusData.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/LoadBalancingInfo.java b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/LoadBalancingInfo.java index 338bfed1dac..594583e3f28 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/LoadBalancingInfo.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/LoadBalancingInfo.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/PoolSizeByHostDistance.java b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/PoolSizeByHostDistance.java index 060e955d15b..07f76a18d40 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/PoolSizeByHostDistance.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/PoolSizeByHostDistance.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/ReconnectionPolicyInfo.java b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/ReconnectionPolicyInfo.java index 1a67c4b0633..463c23a4325 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/ReconnectionPolicyInfo.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/ReconnectionPolicyInfo.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/SSL.java b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/SSL.java index 96f0916a810..debcd85c025 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/SSL.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/SSL.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/SessionStateForNode.java b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/SessionStateForNode.java index 78e5b21dd87..8b50e5b2313 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/SessionStateForNode.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/SessionStateForNode.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/SpecificExecutionProfile.java b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/SpecificExecutionProfile.java index ed7b7a14096..58652fdf885 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/SpecificExecutionProfile.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/SpecificExecutionProfile.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/SpeculativeExecutionInfo.java b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/SpeculativeExecutionInfo.java index e2e30e6b982..779a4ed9e51 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/SpeculativeExecutionInfo.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/insights/schema/SpeculativeExecutionInfo.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/loadbalancing/DseDcInferringLoadBalancingPolicy.java b/core/src/main/java/com/datastax/dse/driver/internal/core/loadbalancing/DseDcInferringLoadBalancingPolicy.java index 9ff1851ac7d..501fa263258 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/loadbalancing/DseDcInferringLoadBalancingPolicy.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/loadbalancing/DseDcInferringLoadBalancingPolicy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/loadbalancing/DseLoadBalancingPolicy.java b/core/src/main/java/com/datastax/dse/driver/internal/core/loadbalancing/DseLoadBalancingPolicy.java index 65ab95bdfeb..059a37c4774 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/loadbalancing/DseLoadBalancingPolicy.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/loadbalancing/DseLoadBalancingPolicy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseAggregateMetadata.java b/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseAggregateMetadata.java index c71bf49e5e8..52a0b846076 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseAggregateMetadata.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseAggregateMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseColumnMetadata.java b/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseColumnMetadata.java index 01c76f2292b..2168f20fdc7 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseColumnMetadata.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseColumnMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseEdgeMetadata.java b/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseEdgeMetadata.java index f19a5e9aa72..e4de62f294c 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseEdgeMetadata.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseEdgeMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseFunctionMetadata.java b/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseFunctionMetadata.java index 8a8bc6a58ee..0a94491f1f7 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseFunctionMetadata.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseFunctionMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseIndexMetadata.java b/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseIndexMetadata.java index 3eeb1e14755..c66d7934151 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseIndexMetadata.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseIndexMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseKeyspaceMetadata.java b/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseKeyspaceMetadata.java index 2f47cb5aab4..8e54c9082e1 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseKeyspaceMetadata.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseKeyspaceMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseTableMetadata.java b/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseTableMetadata.java index b6bc1249e26..f8fb8cc10d1 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseTableMetadata.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseTableMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseVertexMetadata.java b/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseVertexMetadata.java index 16d18a11cab..05ba2823704 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseVertexMetadata.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseVertexMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseViewMetadata.java b/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseViewMetadata.java index 96c25f99812..f04b7640041 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseViewMetadata.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/DefaultDseViewMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/ScriptHelper.java b/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/ScriptHelper.java index 947e9a794b1..64f6cac19f0 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/ScriptHelper.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/ScriptHelper.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/parsing/DseAggregateParser.java b/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/parsing/DseAggregateParser.java index d894e1b1008..37a7a2768c2 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/parsing/DseAggregateParser.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/parsing/DseAggregateParser.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/parsing/DseFunctionParser.java b/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/parsing/DseFunctionParser.java index 696297a041e..0d88bce8740 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/parsing/DseFunctionParser.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/parsing/DseFunctionParser.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/parsing/DseSchemaParser.java b/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/parsing/DseSchemaParser.java index 4d7c6ef197e..ca7fb74a746 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/parsing/DseSchemaParser.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/parsing/DseSchemaParser.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/parsing/DseTableParser.java b/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/parsing/DseTableParser.java index 27bd363a6d3..7fd4a5f0167 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/parsing/DseTableParser.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/parsing/DseTableParser.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/parsing/DseViewParser.java b/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/parsing/DseViewParser.java index af3c0a246c7..07a1e2b5c39 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/parsing/DseViewParser.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/metadata/schema/parsing/DseViewParser.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/protocol/TinkerpopBufferPrimitiveCodec.java b/core/src/main/java/com/datastax/dse/driver/internal/core/protocol/TinkerpopBufferPrimitiveCodec.java index 43a9fd23f24..13238519e06 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/protocol/TinkerpopBufferPrimitiveCodec.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/protocol/TinkerpopBufferPrimitiveCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/search/DateRangeUtil.java b/core/src/main/java/com/datastax/dse/driver/internal/core/search/DateRangeUtil.java index 96d568d548b..15e278260c5 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/search/DateRangeUtil.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/search/DateRangeUtil.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/session/DefaultDseSession.java b/core/src/main/java/com/datastax/dse/driver/internal/core/session/DefaultDseSession.java index ef4f9851298..183f385aa4a 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/session/DefaultDseSession.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/session/DefaultDseSession.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/tracker/MultiplexingRequestTracker.java b/core/src/main/java/com/datastax/dse/driver/internal/core/tracker/MultiplexingRequestTracker.java deleted file mode 100644 index 694748f9965..00000000000 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/tracker/MultiplexingRequestTracker.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.datastax.dse.driver.internal.core.tracker; - -import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; -import com.datastax.oss.driver.api.core.metadata.Node; -import com.datastax.oss.driver.api.core.session.Request; -import com.datastax.oss.driver.api.core.session.Session; -import com.datastax.oss.driver.api.core.tracker.RequestTracker; -import edu.umd.cs.findbugs.annotations.NonNull; -import edu.umd.cs.findbugs.annotations.Nullable; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Combines multiple request trackers into a single one. - * - *

The default context always wraps any user-provided tracker into this, in case other internal - * components need to add their own trackers later (see InternalDriverContext.buildRequestTracker). - * - *

We also use it to catch and log any unexpected exception thrown by a tracker. - */ -public class MultiplexingRequestTracker implements RequestTracker { - - private static final Logger LOG = LoggerFactory.getLogger(MultiplexingRequestTracker.class); - - private final List trackers = new CopyOnWriteArrayList<>(); - - public void register(RequestTracker tracker) { - trackers.add(tracker); - } - - @Override - public void onSuccess( - @NonNull Request request, - long latencyNanos, - @NonNull DriverExecutionProfile executionProfile, - @NonNull Node node, - @NonNull String logPrefix) { - for (RequestTracker tracker : trackers) { - try { - tracker.onSuccess(request, latencyNanos, executionProfile, node, logPrefix); - } catch (Throwable t) { - LOG.error("[{}] Unexpected error while invoking request tracker", logPrefix, t); - } - } - } - - @Override - public void onError( - @NonNull Request request, - @NonNull Throwable error, - long latencyNanos, - @NonNull DriverExecutionProfile executionProfile, - @Nullable Node node, - @NonNull String logPrefix) { - for (RequestTracker tracker : trackers) { - try { - tracker.onError(request, error, latencyNanos, executionProfile, node, logPrefix); - } catch (Throwable t) { - LOG.error("[{}] Unexpected error while invoking request tracker", logPrefix, t); - } - } - } - - @Override - public void onNodeSuccess( - @NonNull Request request, - long latencyNanos, - @NonNull DriverExecutionProfile executionProfile, - @NonNull Node node, - @NonNull String logPrefix) { - for (RequestTracker tracker : trackers) { - try { - tracker.onNodeSuccess(request, latencyNanos, executionProfile, node, logPrefix); - } catch (Throwable t) { - LOG.error("[{}] Unexpected error while invoking request tracker", logPrefix, t); - } - } - } - - @Override - public void onNodeError( - @NonNull Request request, - @NonNull Throwable error, - long latencyNanos, - @NonNull DriverExecutionProfile executionProfile, - @NonNull Node node, - @NonNull String logPrefix) { - for (RequestTracker tracker : trackers) { - try { - tracker.onNodeError(request, error, latencyNanos, executionProfile, node, logPrefix); - } catch (Throwable t) { - LOG.error("[{}] Unexpected error while invoking request tracker", logPrefix, t); - } - } - } - - @Override - public void onSessionReady(@NonNull Session session) { - for (RequestTracker tracker : trackers) { - try { - tracker.onSessionReady(session); - } catch (Throwable t) { - LOG.error("[{}] Unexpected error while invoking request tracker", session.getName(), t); - } - } - } - - @Override - public void close() throws Exception { - Exception toThrow = null; - for (RequestTracker tracker : trackers) { - try { - tracker.close(); - } catch (Exception e) { - if (toThrow == null) { - toThrow = e; - } else { - toThrow.addSuppressed(e); - } - } - } - if (toThrow != null) { - throw toThrow; - } - } -} diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/type/codec/DseTypeCodecsRegistrar.java b/core/src/main/java/com/datastax/dse/driver/internal/core/type/codec/DseTypeCodecsRegistrar.java new file mode 100644 index 00000000000..55da2a9475f --- /dev/null +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/type/codec/DseTypeCodecsRegistrar.java @@ -0,0 +1,40 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.dse.driver.internal.core.type.codec; + +import static com.datastax.oss.driver.internal.core.util.Dependency.ESRI; + +import com.datastax.dse.driver.api.core.type.codec.DseTypeCodecs; +import com.datastax.oss.driver.api.core.type.codec.registry.MutableCodecRegistry; +import com.datastax.oss.driver.internal.core.util.DefaultDependencyChecker; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DseTypeCodecsRegistrar { + + private static final Logger LOG = LoggerFactory.getLogger(DseTypeCodecsRegistrar.class); + + public static void registerDseCodecs(MutableCodecRegistry registry) { + registry.register(DseTypeCodecs.DATE_RANGE); + if (DefaultDependencyChecker.isPresent(ESRI)) { + registry.register(DseTypeCodecs.LINE_STRING, DseTypeCodecs.POINT, DseTypeCodecs.POLYGON); + } else { + LOG.debug("ESRI was not found on the classpath: geo codecs will not be available"); + } + } +} diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/type/codec/DseTypeCodecsRegistrarSubstitutions.java b/core/src/main/java/com/datastax/dse/driver/internal/core/type/codec/DseTypeCodecsRegistrarSubstitutions.java new file mode 100644 index 00000000000..afd8d6cf9f6 --- /dev/null +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/type/codec/DseTypeCodecsRegistrarSubstitutions.java @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.dse.driver.internal.core.type.codec; + +import static com.datastax.oss.driver.internal.core.util.Dependency.ESRI; + +import com.datastax.dse.driver.api.core.type.codec.DseTypeCodecs; +import com.datastax.oss.driver.api.core.type.codec.registry.MutableCodecRegistry; +import com.datastax.oss.driver.internal.core.util.GraalDependencyChecker; +import com.oracle.svm.core.annotate.Substitute; +import com.oracle.svm.core.annotate.TargetClass; +import java.util.function.BooleanSupplier; + +@SuppressWarnings("unused") +public class DseTypeCodecsRegistrarSubstitutions { + + @TargetClass(value = DseTypeCodecsRegistrar.class, onlyWith = EsriMissing.class) + public static final class DseTypeCodecsRegistrarEsriMissing { + + @Substitute + public static void registerDseCodecs(MutableCodecRegistry registry) { + registry.register(DseTypeCodecs.DATE_RANGE); + } + } + + public static class EsriMissing implements BooleanSupplier { + @Override + public boolean getAsBoolean() { + return !GraalDependencyChecker.isPresent(ESRI); + } + } +} diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/type/codec/geometry/GeometryCodec.java b/core/src/main/java/com/datastax/dse/driver/internal/core/type/codec/geometry/GeometryCodec.java index 819fd9d108b..f6309bc1860 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/type/codec/geometry/GeometryCodec.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/type/codec/geometry/GeometryCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/type/codec/geometry/LineStringCodec.java b/core/src/main/java/com/datastax/dse/driver/internal/core/type/codec/geometry/LineStringCodec.java index d04d8459d12..bbec99a4103 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/type/codec/geometry/LineStringCodec.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/type/codec/geometry/LineStringCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/type/codec/geometry/PointCodec.java b/core/src/main/java/com/datastax/dse/driver/internal/core/type/codec/geometry/PointCodec.java index 1ccc7b0adc1..5ebae64cbab 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/type/codec/geometry/PointCodec.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/type/codec/geometry/PointCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/type/codec/geometry/PolygonCodec.java b/core/src/main/java/com/datastax/dse/driver/internal/core/type/codec/geometry/PolygonCodec.java index 823aaad7a4d..00a070a4b4a 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/type/codec/geometry/PolygonCodec.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/type/codec/geometry/PolygonCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/type/codec/time/DateRangeCodec.java b/core/src/main/java/com/datastax/dse/driver/internal/core/type/codec/time/DateRangeCodec.java index 094904edbc4..e8a23e88848 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/type/codec/time/DateRangeCodec.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/type/codec/time/DateRangeCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/dse/driver/internal/core/util/concurrent/BoundedConcurrentQueue.java b/core/src/main/java/com/datastax/dse/driver/internal/core/util/concurrent/BoundedConcurrentQueue.java index edb83d5f688..ea9ccd7d622 100644 --- a/core/src/main/java/com/datastax/dse/driver/internal/core/util/concurrent/BoundedConcurrentQueue.java +++ b/core/src/main/java/com/datastax/dse/driver/internal/core/util/concurrent/BoundedConcurrentQueue.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/AllNodesFailedException.java b/core/src/main/java/com/datastax/oss/driver/api/core/AllNodesFailedException.java index 3f00e0b474c..b6f1bf93838 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/AllNodesFailedException.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/AllNodesFailedException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/AsyncAutoCloseable.java b/core/src/main/java/com/datastax/oss/driver/api/core/AsyncAutoCloseable.java index f84cdf26c86..7f8cafbc895 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/AsyncAutoCloseable.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/AsyncAutoCloseable.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/AsyncPagingIterable.java b/core/src/main/java/com/datastax/oss/driver/api/core/AsyncPagingIterable.java index 9abe4136f66..fd7c5be6baa 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/AsyncPagingIterable.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/AsyncPagingIterable.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/ConsistencyLevel.java b/core/src/main/java/com/datastax/oss/driver/api/core/ConsistencyLevel.java index 87fdcb079d3..a1b6d8006df 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/ConsistencyLevel.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/ConsistencyLevel.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/CqlIdentifier.java b/core/src/main/java/com/datastax/oss/driver/api/core/CqlIdentifier.java index 89211d75382..82e4c2b30a6 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/CqlIdentifier.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/CqlIdentifier.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -21,6 +23,7 @@ import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; +import java.util.Locale; import net.jcip.annotations.Immutable; /** @@ -75,7 +78,7 @@ public static CqlIdentifier fromCql(@NonNull String cql) { if (Strings.isDoubleQuoted(cql)) { internal = Strings.unDoubleQuote(cql); } else { - internal = cql.toLowerCase(); + internal = cql.toLowerCase(Locale.ROOT); Preconditions.checkArgument( !Strings.needsDoubleQuotes(internal), "Invalid CQL form [%s]: needs double quotes", cql); } diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/CqlSession.java b/core/src/main/java/com/datastax/oss/driver/api/core/CqlSession.java index 2392182bf67..ff096719f3e 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/CqlSession.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/CqlSession.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -32,7 +34,7 @@ * *

    *
  • CQL requests: synchronous, asynchronous or reactive mode; - *
  • requests specific to Datastax Enterprise: graph and continuous paging. + *
  • requests specific to DataStax Enterprise: graph and continuous paging. *
* * Client applications can use this interface even if they don't need all the features. In diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/CqlSessionBuilder.java b/core/src/main/java/com/datastax/oss/driver/api/core/CqlSessionBuilder.java index 19ac5a6fc60..4598c078dca 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/CqlSessionBuilder.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/CqlSessionBuilder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/DefaultConsistencyLevel.java b/core/src/main/java/com/datastax/oss/driver/api/core/DefaultConsistencyLevel.java index 691428651ba..2e5a4a6f022 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/DefaultConsistencyLevel.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/DefaultConsistencyLevel.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/DefaultProtocolVersion.java b/core/src/main/java/com/datastax/oss/driver/api/core/DefaultProtocolVersion.java index 1a207a9ede9..91b45fc506a 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/DefaultProtocolVersion.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/DefaultProtocolVersion.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -30,14 +32,17 @@ public enum DefaultProtocolVersion implements ProtocolVersion { /** Version 4, supported by Cassandra 2.2 and above. */ V4(ProtocolConstants.Version.V4, false), + /** Version 5, supported by Cassandra 4.0 and above. */ + V5(ProtocolConstants.Version.V5, false), + /** - * Version 5, currently supported as a beta preview in Cassandra 3.10 and above. + * Version 6, currently supported as a beta preview in Cassandra 4.0 and above. * *

Do not use this in production. * * @see ProtocolVersion#isBeta() */ - V5(ProtocolConstants.Version.V5, true), + V6(ProtocolConstants.Version.V6, true), ; // Note that, for the sake of convenience, we also expose shortcuts to these constants on the // ProtocolVersion interface. If you add a new enum constant, remember to update the interface as diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/DriverException.java b/core/src/main/java/com/datastax/oss/driver/api/core/DriverException.java index 9497ef15cf5..f5cf76e29eb 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/DriverException.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/DriverException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -77,6 +79,10 @@ protected DriverException( * AllNodesFailedException#getAllErrors()} or {@link ExecutionInfo#getErrors()} do not contain * their own execution info, and therefore return null from this method. * + *

This method will also return null for low-level exceptions thrown directly from a driver + * channel, such as {@link com.datastax.oss.driver.api.core.connection.ConnectionInitException} or + * {@link com.datastax.oss.driver.api.core.connection.ClosedConnectionException}. + * *

It will also be null if you serialize and deserialize an exception. */ public ExecutionInfo getExecutionInfo() { diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/DriverExecutionException.java b/core/src/main/java/com/datastax/oss/driver/api/core/DriverExecutionException.java index e7d8e42f2b1..90ff875e375 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/DriverExecutionException.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/DriverExecutionException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/DriverTimeoutException.java b/core/src/main/java/com/datastax/oss/driver/api/core/DriverTimeoutException.java index 1966606256b..8b4cc5dc5bb 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/DriverTimeoutException.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/DriverTimeoutException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/InvalidKeyspaceException.java b/core/src/main/java/com/datastax/oss/driver/api/core/InvalidKeyspaceException.java index 0b1ec172812..aa3f774800c 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/InvalidKeyspaceException.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/InvalidKeyspaceException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/MappedAsyncPagingIterable.java b/core/src/main/java/com/datastax/oss/driver/api/core/MappedAsyncPagingIterable.java index c6cb7ae5831..b3902489a48 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/MappedAsyncPagingIterable.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/MappedAsyncPagingIterable.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/MavenCoordinates.java b/core/src/main/java/com/datastax/oss/driver/api/core/MavenCoordinates.java index ab26be868dd..3c3f18a5dc2 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/MavenCoordinates.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/MavenCoordinates.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/NoNodeAvailableException.java b/core/src/main/java/com/datastax/oss/driver/api/core/NoNodeAvailableException.java index 7b2e7c9ffae..9ef51fb99b6 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/NoNodeAvailableException.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/NoNodeAvailableException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/NodeUnavailableException.java b/core/src/main/java/com/datastax/oss/driver/api/core/NodeUnavailableException.java new file mode 100644 index 00000000000..5303119844e --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/api/core/NodeUnavailableException.java @@ -0,0 +1,62 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.api.core; + +import com.datastax.oss.driver.api.core.metadata.Node; +import edu.umd.cs.findbugs.annotations.NonNull; +import java.util.Objects; + +/** + * Indicates that a {@link Node} was selected in a query plan, but it had no connection available. + * + *

A common reason to encounter this error is when the configured number of connections per node + * and requests per connection is not high enough to absorb the overall request rate. This can be + * mitigated by tuning the following options: + * + *

    + *
  • {@code advanced.connection.pool.local.size}; + *
  • {@code advanced.connection.pool.remote.size}; + *
  • {@code advanced.connection.max-requests-per-connection}. + *
+ * + * See {@code reference.conf} for more details. + * + *

Another possibility is when you are trying to direct a request {@linkplain + * com.datastax.oss.driver.api.core.cql.Statement#setNode(Node) to a particular node}, but that node + * has no connections available. + */ +public class NodeUnavailableException extends DriverException { + + private final Node node; + + public NodeUnavailableException(Node node) { + super("No connection was available to " + node, null, null, true); + this.node = Objects.requireNonNull(node); + } + + @NonNull + public Node getNode() { + return node; + } + + @Override + @NonNull + public DriverException copy() { + return new NodeUnavailableException(node); + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/PagingIterable.java b/core/src/main/java/com/datastax/oss/driver/api/core/PagingIterable.java index d2fca141005..c2a81b554d0 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/PagingIterable.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/PagingIterable.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/ProtocolVersion.java b/core/src/main/java/com/datastax/oss/driver/api/core/ProtocolVersion.java index a633bcf892f..dd69f705453 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/ProtocolVersion.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/ProtocolVersion.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -31,13 +33,14 @@ public interface ProtocolVersion { ProtocolVersion V3 = DefaultProtocolVersion.V3; ProtocolVersion V4 = DefaultProtocolVersion.V4; ProtocolVersion V5 = DefaultProtocolVersion.V5; + ProtocolVersion V6 = DefaultProtocolVersion.V6; ProtocolVersion DSE_V1 = DseProtocolVersion.DSE_V1; ProtocolVersion DSE_V2 = DseProtocolVersion.DSE_V2; /** The default version used for {@link Detachable detached} objects. */ // Implementation note: we can't use the ProtocolVersionRegistry here, this has to be a // compile-time constant. - ProtocolVersion DEFAULT = DefaultProtocolVersion.V4; + ProtocolVersion DEFAULT = DefaultProtocolVersion.V5; /** * A numeric code that uniquely identifies the version (this is the code used in network frames). diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/RequestThrottlingException.java b/core/src/main/java/com/datastax/oss/driver/api/core/RequestThrottlingException.java index 5bd44fcb1d2..acf569d55f6 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/RequestThrottlingException.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/RequestThrottlingException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/UnsupportedProtocolVersionException.java b/core/src/main/java/com/datastax/oss/driver/api/core/UnsupportedProtocolVersionException.java index d80eba55514..030984dc274 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/UnsupportedProtocolVersionException.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/UnsupportedProtocolVersionException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/Version.java b/core/src/main/java/com/datastax/oss/driver/api/core/Version.java index 31bae49cb11..52751e02984 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/Version.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/Version.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -46,13 +48,16 @@ public class Version implements Comparable, Serializable { private static final Pattern pattern = Pattern.compile(VERSION_REGEXP); + @NonNull public static final Version V1_0_0 = Objects.requireNonNull(parse("1.0.0")); @NonNull public static final Version V2_1_0 = Objects.requireNonNull(parse("2.1.0")); @NonNull public static final Version V2_2_0 = Objects.requireNonNull(parse("2.2.0")); @NonNull public static final Version V3_0_0 = Objects.requireNonNull(parse("3.0.0")); @NonNull public static final Version V4_0_0 = Objects.requireNonNull(parse("4.0.0")); + @NonNull public static final Version V4_1_0 = Objects.requireNonNull(parse("4.1.0")); @NonNull public static final Version V5_0_0 = Objects.requireNonNull(parse("5.0.0")); @NonNull public static final Version V6_7_0 = Objects.requireNonNull(parse("6.7.0")); @NonNull public static final Version V6_8_0 = Objects.requireNonNull(parse("6.8.0")); + @NonNull public static final Version V6_9_0 = Objects.requireNonNull(parse("6.9.0")); private final int major; private final int minor; diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/addresstranslation/AddressTranslator.java b/core/src/main/java/com/datastax/oss/driver/api/core/addresstranslation/AddressTranslator.java index c80e16d3363..47ce62f1461 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/addresstranslation/AddressTranslator.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/addresstranslation/AddressTranslator.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/auth/AuthProvider.java b/core/src/main/java/com/datastax/oss/driver/api/core/auth/AuthProvider.java index e85b90e3b04..c73c3e4fb67 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/auth/AuthProvider.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/auth/AuthProvider.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/auth/AuthenticationException.java b/core/src/main/java/com/datastax/oss/driver/api/core/auth/AuthenticationException.java index abf77e293d5..28dde2123cb 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/auth/AuthenticationException.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/auth/AuthenticationException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/auth/Authenticator.java b/core/src/main/java/com/datastax/oss/driver/api/core/auth/Authenticator.java index 4f55545731a..150a1dfb63f 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/auth/Authenticator.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/auth/Authenticator.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/auth/PlainTextAuthProviderBase.java b/core/src/main/java/com/datastax/oss/driver/api/core/auth/PlainTextAuthProviderBase.java index e3869ba8319..fb85797af9e 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/auth/PlainTextAuthProviderBase.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/auth/PlainTextAuthProviderBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -36,7 +38,8 @@ * Common infrastructure for plain text auth providers. * *

This can be reused to write an implementation that retrieves the credentials from another - * source than the configuration. + * source than the configuration. The driver offers one built-in implementation: {@link + * ProgrammaticPlainTextAuthProvider}. */ @ThreadSafe public abstract class PlainTextAuthProviderBase implements AuthProvider { @@ -58,6 +61,9 @@ protected PlainTextAuthProviderBase(@NonNull String logPrefix) { * Retrieves the credentials from the underlying source. * *

This is invoked every time the driver opens a new connection. + * + * @param endPoint The endpoint being contacted. + * @param serverAuthenticator The authenticator class sent by the endpoint. */ @NonNull protected abstract Credentials getCredentials( @@ -96,7 +102,7 @@ public static class Credentials { * Builds an instance for username/password authentication, and proxy authentication with the * given authorizationId. * - *

This feature is only available with Datastax Enterprise. If the target server is Apache + *

This feature is only available with DataStax Enterprise. If the target server is Apache * Cassandra, the authorizationId will be ignored. */ public Credentials( diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/auth/ProgrammaticPlainTextAuthProvider.java b/core/src/main/java/com/datastax/oss/driver/api/core/auth/ProgrammaticPlainTextAuthProvider.java new file mode 100644 index 00000000000..d991f5c5cb5 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/api/core/auth/ProgrammaticPlainTextAuthProvider.java @@ -0,0 +1,136 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.api.core.auth; + +import com.datastax.oss.driver.api.core.metadata.EndPoint; +import com.datastax.oss.driver.api.core.session.SessionBuilder; +import com.datastax.oss.driver.internal.core.util.Strings; +import edu.umd.cs.findbugs.annotations.NonNull; +import java.util.Objects; +import net.jcip.annotations.ThreadSafe; + +/** + * A simple plaintext {@link AuthProvider} that receives the credentials programmatically instead of + * pulling them from the configuration. + * + *

To use this class, create an instance with the appropriate credentials to use and pass it to + * your session builder: + * + *

+ * AuthProvider authProvider = new ProgrammaticPlainTextAuthProvider("...", "...");
+ * CqlSession session =
+ *     CqlSession.builder()
+ *         .addContactEndPoints(...)
+ *         .withAuthProvider(authProvider)
+ *         .build();
+ * 
+ * + *

It also offers the possibility of changing the credentials at runtime. The new credentials + * will be used for all connections initiated after the change. + * + *

Implementation Note: this implementation is not particularly suited for highly-sensitive + * applications: it stores the credentials to use as private fields, and even if the fields are char + * arrays rather than strings to make it difficult to dump their contents, they are never cleared + * until the provider itself is garbage-collected, which typically only happens when the session is + * closed. + * + * @see SessionBuilder#withAuthProvider(AuthProvider) + * @see SessionBuilder#withAuthCredentials(String, String) + * @see SessionBuilder#withAuthCredentials(String, String, String) + */ +@ThreadSafe +public class ProgrammaticPlainTextAuthProvider extends PlainTextAuthProviderBase { + + private volatile char[] username; + private volatile char[] password; + private volatile char[] authorizationId; + + /** Builds an instance for simple username/password authentication. */ + public ProgrammaticPlainTextAuthProvider(@NonNull String username, @NonNull String password) { + this(username, password, ""); + } + + /** + * Builds an instance for username/password authentication, and proxy authentication with the + * given authorizationId. + * + *

This feature is only available with DataStax Enterprise. If the target server is Apache + * Cassandra, use {@link #ProgrammaticPlainTextAuthProvider(String, String)} instead, or set the + * authorizationId to an empty string. + */ + public ProgrammaticPlainTextAuthProvider( + @NonNull String username, @NonNull String password, @NonNull String authorizationId) { + // This will typically be built before the session so we don't know the log prefix yet. Pass an + // empty string, it's only used in one log message. + super(""); + this.username = Strings.requireNotEmpty(username, "username").toCharArray(); + this.password = Strings.requireNotEmpty(password, "password").toCharArray(); + this.authorizationId = + Objects.requireNonNull(authorizationId, "authorizationId cannot be null").toCharArray(); + } + + /** + * Changes the username. + * + *

The new credentials will be used for all connections initiated after this method was called. + * + * @param username the new name. + */ + public void setUsername(@NonNull String username) { + this.username = Strings.requireNotEmpty(username, "username").toCharArray(); + } + + /** + * Changes the password. + * + *

The new credentials will be used for all connections initiated after this method was called. + * + * @param password the new password. + */ + public void setPassword(@NonNull String password) { + this.password = Strings.requireNotEmpty(password, "password").toCharArray(); + } + + /** + * Changes the authorization id. + * + *

The new credentials will be used for all connections initiated after this method was called. + * + *

This feature is only available with DataStax Enterprise. If the target server is Apache + * Cassandra, this method should not be used. + * + * @param authorizationId the new authorization id. + */ + public void setAuthorizationId(@NonNull String authorizationId) { + this.authorizationId = + Objects.requireNonNull(authorizationId, "authorizationId cannot be null").toCharArray(); + } + + /** + * {@inheritDoc} + * + *

This implementation disregards the endpoint being connected to as well as the authenticator + * class sent by the server, and always returns the same credentials. + */ + @NonNull + @Override + protected Credentials getCredentials( + @NonNull EndPoint endPoint, @NonNull String serverAuthenticator) { + return new Credentials(username.clone(), password.clone(), authorizationId.clone()); + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/auth/SyncAuthenticator.java b/core/src/main/java/com/datastax/oss/driver/api/core/auth/SyncAuthenticator.java index f1a8acfb11a..016ac25680b 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/auth/SyncAuthenticator.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/auth/SyncAuthenticator.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/auth/package-info.java b/core/src/main/java/com/datastax/oss/driver/api/core/auth/package-info.java index d5d4efd9c9d..b265b9ba463 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/auth/package-info.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/auth/package-info.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/config/DefaultDriverOption.java b/core/src/main/java/com/datastax/oss/driver/api/core/config/DefaultDriverOption.java index 55e50ed9069..60c44193577 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/config/DefaultDriverOption.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/config/DefaultDriverOption.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -97,7 +99,10 @@ public enum DefaultDriverOption implements DriverOption { * A custom filter to include/exclude nodes. * *

Value-Type: {@link String} + * + * @deprecated use {@link #LOAD_BALANCING_DISTANCE_EVALUATOR_CLASS} instead. */ + @Deprecated LOAD_BALANCING_FILTER_CLASS("basic.load-balancing-policy.filter.class"), /** @@ -293,7 +298,10 @@ public enum DefaultDriverOption implements DriverOption { * The class of a session-wide component that tracks the outcome of requests. * *

Value-type: {@link String} + * + * @deprecated Use {@link #REQUEST_TRACKER_CLASSES} instead. */ + @Deprecated REQUEST_TRACKER_CLASS("advanced.request-tracker.class"), /** * Whether to log successful requests. @@ -385,14 +393,20 @@ public enum DefaultDriverOption implements DriverOption { * The class of a session-wide component that listens for node state changes. * *

Value-type: {@link String} + * + * @deprecated Use {@link #METADATA_NODE_STATE_LISTENER_CLASSES} instead. */ + @Deprecated METADATA_NODE_STATE_LISTENER_CLASS("advanced.node-state-listener.class"), /** * The class of a session-wide component that listens for schema changes. * *

Value-type: {@link String} + * + * @deprecated Use {@link #METADATA_SCHEMA_CHANGE_LISTENER_CLASSES} instead. */ + @Deprecated METADATA_SCHEMA_CHANGE_LISTENER_CLASS("advanced.schema-change-listener.class"), /** @@ -781,7 +795,7 @@ public enum DefaultDriverOption implements DriverOption { NETTY_DAEMON("advanced.netty.daemon"), /** - * The location of the cloud secure bundle used to connect to Datastax Apache Cassandra as a + * The location of the cloud secure bundle used to connect to DataStax Apache Cassandra as a * service. * *

Value-type: {@link String} @@ -823,7 +837,211 @@ public enum DefaultDriverOption implements DriverOption { *

Value-type: {@link String} */ METRICS_FACTORY_CLASS("advanced.metrics.factory.class"), - ; + + /** + * The maximum number of nodes from remote DCs to include in query plans. + * + *

Value-Type: int + */ + LOAD_BALANCING_DC_FAILOVER_MAX_NODES_PER_REMOTE_DC( + "advanced.load-balancing-policy.dc-failover.max-nodes-per-remote-dc"), + /** + * Whether to consider nodes from remote DCs if the request's consistency level is local. + * + *

Value-Type: boolean + */ + LOAD_BALANCING_DC_FAILOVER_ALLOW_FOR_LOCAL_CONSISTENCY_LEVELS( + "advanced.load-balancing-policy.dc-failover.allow-for-local-consistency-levels"), + + /** + * The classname of the desired {@code MetricIdGenerator} implementation. + * + *

Value-type: {@link String} + */ + METRICS_ID_GENERATOR_CLASS("advanced.metrics.id-generator.class"), + + /** + * The value of the prefix to prepend to all metric names. + * + *

Value-type: {@link String} + */ + METRICS_ID_GENERATOR_PREFIX("advanced.metrics.id-generator.prefix"), + + /** + * The class name of a custom {@link + * com.datastax.oss.driver.api.core.loadbalancing.NodeDistanceEvaluator}. + * + *

Value-Type: {@link String} + */ + LOAD_BALANCING_DISTANCE_EVALUATOR_CLASS("basic.load-balancing-policy.evaluator.class"), + + /** + * The shortest latency that we expect to record for requests. + * + *

Value-type: {@link java.time.Duration Duration} + */ + METRICS_SESSION_CQL_REQUESTS_LOWEST("advanced.metrics.session.cql-requests.lowest-latency"), + /** + * Optional service-level objectives to meet, as a list of latencies to track. + * + *

Value-type: List of {@link java.time.Duration Duration} + */ + METRICS_SESSION_CQL_REQUESTS_SLO("advanced.metrics.session.cql-requests.slo"), + + /** + * The shortest latency that we expect to record for throttling. + * + *

Value-type: {@link java.time.Duration Duration} + */ + METRICS_SESSION_THROTTLING_LOWEST("advanced.metrics.session.throttling.delay.lowest-latency"), + /** + * Optional service-level objectives to meet, as a list of latencies to track. + * + *

Value-type: List of {@link java.time.Duration Duration} + */ + METRICS_SESSION_THROTTLING_SLO("advanced.metrics.session.throttling.delay.slo"), + + /** + * The shortest latency that we expect to record for requests. + * + *

Value-type: {@link java.time.Duration Duration} + */ + METRICS_NODE_CQL_MESSAGES_LOWEST("advanced.metrics.node.cql-messages.lowest-latency"), + /** + * Optional service-level objectives to meet, as a list of latencies to track. + * + *

Value-type: List of {@link java.time.Duration Duration} + */ + METRICS_NODE_CQL_MESSAGES_SLO("advanced.metrics.node.cql-messages.slo"), + + /** + * Whether the prepared statements cache use weak values. + * + *

Value-type: boolean + */ + PREPARED_CACHE_WEAK_VALUES("advanced.prepared-statements.prepared-cache.weak-values"), + + /** + * The classes of session-wide components that track the outcome of requests. + * + *

Value-type: List of {@link String} + */ + REQUEST_TRACKER_CLASSES("advanced.request-tracker.classes"), + + /** + * The classes of session-wide components that listen for node state changes. + * + *

Value-type: List of {@link String} + */ + METADATA_NODE_STATE_LISTENER_CLASSES("advanced.node-state-listener.classes"), + + /** + * The classes of session-wide components that listen for schema changes. + * + *

Value-type: List of {@link String} + */ + METADATA_SCHEMA_CHANGE_LISTENER_CLASSES("advanced.schema-change-listener.classes"), + /** + * Optional list of percentiles to publish for cql-requests metric. Produces an additional time + * series for each requested percentile. This percentile is computed locally, and so can't be + * aggregated with percentiles computed across other dimensions (e.g. in a different instance). + * + *

Value type: {@link java.util.List List}<{@link Double}> + */ + METRICS_SESSION_CQL_REQUESTS_PUBLISH_PERCENTILES( + "advanced.metrics.session.cql-requests.publish-percentiles"), + /** + * Optional list of percentiles to publish for node cql-messages metric. Produces an additional + * time series for each requested percentile. This percentile is computed locally, and so can't be + * aggregated with percentiles computed across other dimensions (e.g. in a different instance). + * + *

Value type: {@link java.util.List List}<{@link Double}> + */ + METRICS_NODE_CQL_MESSAGES_PUBLISH_PERCENTILES( + "advanced.metrics.node.cql-messages.publish-percentiles"), + /** + * Optional list of percentiles to publish for throttling delay metric.Produces an additional time + * series for each requested percentile. This percentile is computed locally, and so can't be + * aggregated with percentiles computed across other dimensions (e.g. in a different instance). + * + *

Value type: {@link java.util.List List}<{@link Double}> + */ + METRICS_SESSION_THROTTLING_PUBLISH_PERCENTILES( + "advanced.metrics.session.throttling.delay.publish-percentiles"), + /** + * Adds histogram buckets used to generate aggregable percentile approximations in monitoring + * systems that have query facilities to do so (e.g. Prometheus histogram_quantile, Atlas + * percentiles). + * + *

Value-type: boolean + */ + METRICS_GENERATE_AGGREGABLE_HISTOGRAMS("advanced.metrics.histograms.generate-aggregable"), + /** + * The duration between attempts to reload the keystore. + * + *

Value-type: {@link java.time.Duration} + */ + SSL_KEYSTORE_RELOAD_INTERVAL("advanced.ssl-engine-factory.keystore-reload-interval"), + /** + * Ordered preference list of remote dcs optionally supplied for automatic failover. + * + *

Value type: {@link java.util.List List}<{@link String}> + */ + LOAD_BALANCING_DC_FAILOVER_PREFERRED_REMOTE_DCS( + "advanced.load-balancing-policy.dc-failover.preferred-remote-dcs"), + /** + * Whether or not to do a DNS reverse-lookup of provided server addresses for SAN addresses. + * + *

Value-type: boolean + */ + SSL_ALLOW_DNS_REVERSE_LOOKUP_SAN("advanced.ssl-engine-factory.allow-dns-reverse-lookup-san"), + /** + * The class of session-wide component that generates request IDs. + * + *

Value-type: {@link String} + */ + REQUEST_ID_GENERATOR_CLASS("advanced.request-id.generator.class"), + /** + * An address to always translate all node addresses to that same proxy hostname no matter what IP + * address a node has, but still using its native transport port. + * + *

Value-Type: {@link String} + */ + ADDRESS_TRANSLATOR_ADVERTISED_HOSTNAME("advanced.address-translator.advertised-hostname"), + /** + * A map of Cassandra node subnets (CIDR notations) to target addresses, for example (note quoted + * keys): + * + *

+   * advanced.address-translator.subnet-addresses {
+   *   "100.64.0.0/15" = "cassandra.datacenter1.com:9042"
+   *   "100.66.0.0/15" = "cassandra.datacenter2.com:9042"
+   *   # IPv6 example:
+   *   # "::ffff:6440:0/111" = "cassandra.datacenter1.com:9042"
+   *   # "::ffff:6442:0/111" = "cassandra.datacenter2.com:9042"
+   * }
+   * 
+ * + * Note: subnets must be represented as prefix blocks, see {@link + * inet.ipaddr.Address#isPrefixBlock()}. + * + *

Value type: {@link java.util.Map Map}<{@link String},{@link String}> + */ + ADDRESS_TRANSLATOR_SUBNET_ADDRESSES("advanced.address-translator.subnet-addresses"), + /** + * A default address to fallback to if Cassandra node IP isn't contained in any of the configured + * subnets. + * + *

Value-Type: {@link String} + */ + ADDRESS_TRANSLATOR_DEFAULT_ADDRESS("advanced.address-translator.default-address"), + /** + * Whether to resolve the addresses on initialization (if true) or on each node (re-)connection + * (if false). Defaults to false. + * + *

Value-Type: boolean + */ + ADDRESS_TRANSLATOR_RESOLVE_ADDRESSES("advanced.address-translator.resolve-addresses"); private final String path; diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/config/DriverConfig.java b/core/src/main/java/com/datastax/oss/driver/api/core/config/DriverConfig.java index fae096123c2..88519c82a22 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/config/DriverConfig.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/config/DriverConfig.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/config/DriverConfigLoader.java b/core/src/main/java/com/datastax/oss/driver/api/core/config/DriverConfigLoader.java index f4242592e06..15fae232d17 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/config/DriverConfigLoader.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/config/DriverConfigLoader.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -15,16 +17,12 @@ */ package com.datastax.oss.driver.api.core.config; -import com.datastax.oss.driver.api.core.CqlSession; import com.datastax.oss.driver.api.core.context.DriverContext; import com.datastax.oss.driver.api.core.session.SessionBuilder; import com.datastax.oss.driver.internal.core.config.composite.CompositeDriverConfigLoader; import com.datastax.oss.driver.internal.core.config.map.MapBasedDriverConfigLoader; import com.datastax.oss.driver.internal.core.config.typesafe.DefaultDriverConfigLoader; import com.datastax.oss.driver.internal.core.config.typesafe.DefaultProgrammaticDriverConfigLoaderBuilder; -import com.typesafe.config.Config; -import com.typesafe.config.ConfigFactory; -import com.typesafe.config.ConfigParseOptions; import edu.umd.cs.findbugs.annotations.NonNull; import java.io.File; import java.net.URL; @@ -92,19 +90,7 @@ static DriverConfigLoader fromClasspath(@NonNull String resourceBaseName) { @NonNull static DriverConfigLoader fromClasspath( @NonNull String resourceBaseName, @NonNull ClassLoader appClassLoader) { - return new DefaultDriverConfigLoader( - () -> { - ConfigFactory.invalidateCaches(); - Config config = - ConfigFactory.defaultOverrides() - .withFallback( - ConfigFactory.parseResourcesAnySyntax( - resourceBaseName, - ConfigParseOptions.defaults().setClassLoader(appClassLoader))) - .withFallback(ConfigFactory.defaultReference(CqlSession.class.getClassLoader())) - .resolve(); - return config.getConfig(DefaultDriverConfigLoader.DEFAULT_ROOT_PATH); - }); + return DefaultDriverConfigLoader.fromClasspath(resourceBaseName, appClassLoader); } /** @@ -154,16 +140,7 @@ static DriverConfigLoader fromPath(@NonNull Path file) { */ @NonNull static DriverConfigLoader fromFile(@NonNull File file) { - return new DefaultDriverConfigLoader( - () -> { - ConfigFactory.invalidateCaches(); - Config config = - ConfigFactory.defaultOverrides() - .withFallback(ConfigFactory.parseFileAnySyntax(file)) - .withFallback(ConfigFactory.defaultReference(CqlSession.class.getClassLoader())) - .resolve(); - return config.getConfig(DefaultDriverConfigLoader.DEFAULT_ROOT_PATH); - }); + return DefaultDriverConfigLoader.fromFile(file); } /** @@ -188,16 +165,7 @@ static DriverConfigLoader fromFile(@NonNull File file) { */ @NonNull static DriverConfigLoader fromUrl(@NonNull URL url) { - return new DefaultDriverConfigLoader( - () -> { - ConfigFactory.invalidateCaches(); - Config config = - ConfigFactory.defaultOverrides() - .withFallback(ConfigFactory.parseURL(url)) - .withFallback(ConfigFactory.defaultReference(CqlSession.class.getClassLoader())) - .resolve(); - return config.getConfig(DefaultDriverConfigLoader.DEFAULT_ROOT_PATH); - }); + return DefaultDriverConfigLoader.fromUrl(url); } /** @@ -227,17 +195,7 @@ static DriverConfigLoader fromUrl(@NonNull URL url) { */ @NonNull static DriverConfigLoader fromString(@NonNull String contents) { - return new DefaultDriverConfigLoader( - () -> { - ConfigFactory.invalidateCaches(); - Config config = - ConfigFactory.defaultOverrides() - .withFallback(ConfigFactory.parseString(contents)) - .withFallback(ConfigFactory.defaultReference(CqlSession.class.getClassLoader())) - .resolve(); - return config.getConfig(DefaultDriverConfigLoader.DEFAULT_ROOT_PATH); - }, - false); + return DefaultDriverConfigLoader.fromString(contents); } /** @@ -420,7 +378,7 @@ static DriverConfigLoader compose( boolean supportsReloading(); /** - * Called when the cluster closes. This is a good time to release any external resource, for + * Called when the session closes. This is a good time to release any external resource, for * example cancel a scheduled reloading task. */ @Override diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/config/DriverExecutionProfile.java b/core/src/main/java/com/datastax/oss/driver/api/core/config/DriverExecutionProfile.java index 8d656d0f886..89c28f0f521 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/config/DriverExecutionProfile.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/config/DriverExecutionProfile.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/config/DriverOption.java b/core/src/main/java/com/datastax/oss/driver/api/core/config/DriverOption.java index 3213dc4b2ad..2f15b701f36 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/config/DriverOption.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/config/DriverOption.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/config/OngoingConfigOptions.java b/core/src/main/java/com/datastax/oss/driver/api/core/config/OngoingConfigOptions.java index 0345150d770..2c931bbfa91 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/config/OngoingConfigOptions.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/config/OngoingConfigOptions.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -19,6 +21,7 @@ import java.time.Duration; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; /** An object where config options can be set programmatically. */ public interface OngoingConfigOptions> { @@ -59,6 +62,15 @@ default SelfT withClass(@NonNull DriverOption option, @NonNull Class value) { return withString(option, value.getName()); } + /** + * Note that this is just a shortcut to call {@link #withStringList(DriverOption, List)} with + * class names obtained from {@link Class#getName()}. + */ + @NonNull + default SelfT withClassList(@NonNull DriverOption option, @NonNull List> values) { + return withStringList(option, values.stream().map(Class::getName).collect(Collectors.toList())); + } + @NonNull SelfT withStringList(@NonNull DriverOption option, @NonNull List value); diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/config/OptionsMap.java b/core/src/main/java/com/datastax/oss/driver/api/core/config/OptionsMap.java index 6de7fc76355..98faf3e590c 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/config/OptionsMap.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/config/OptionsMap.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -15,6 +17,7 @@ */ package com.datastax.oss.driver.api.core.config; +import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableList; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; import java.io.InvalidObjectException; @@ -279,10 +282,7 @@ protected static void fillWithDriverDefaults(OptionsMap map) { map.put(TypedDriverOption.TIMESTAMP_GENERATOR_DRIFT_WARNING_THRESHOLD, Duration.ofSeconds(1)); map.put(TypedDriverOption.TIMESTAMP_GENERATOR_DRIFT_WARNING_INTERVAL, Duration.ofSeconds(10)); map.put(TypedDriverOption.TIMESTAMP_GENERATOR_FORCE_JAVA_CLOCK, false); - map.put(TypedDriverOption.REQUEST_TRACKER_CLASS, "NoopRequestTracker"); map.put(TypedDriverOption.REQUEST_THROTTLER_CLASS, "PassThroughRequestThrottler"); - map.put(TypedDriverOption.METADATA_NODE_STATE_LISTENER_CLASS, "NoopNodeStateListener"); - map.put(TypedDriverOption.METADATA_SCHEMA_CHANGE_LISTENER_CLASS, "NoopSchemaChangeListener"); map.put(TypedDriverOption.ADDRESS_TRANSLATOR_CLASS, "PassThroughAddressTranslator"); map.put(TypedDriverOption.RESOLVE_CONTACT_POINTS, true); map.put(TypedDriverOption.PROTOCOL_MAX_FRAME_LENGTH, 256L * 1024 * 1024); @@ -309,27 +309,36 @@ protected static void fillWithDriverDefaults(OptionsMap map) { map.put(TypedDriverOption.MONITOR_REPORTING_ENABLED, true); map.put(TypedDriverOption.METRICS_SESSION_ENABLED, Collections.emptyList()); map.put(TypedDriverOption.METRICS_SESSION_CQL_REQUESTS_HIGHEST, Duration.ofSeconds(3)); + map.put(TypedDriverOption.METRICS_SESSION_CQL_REQUESTS_LOWEST, Duration.ofMillis(1)); map.put(TypedDriverOption.METRICS_SESSION_CQL_REQUESTS_DIGITS, 3); map.put(TypedDriverOption.METRICS_SESSION_CQL_REQUESTS_INTERVAL, Duration.ofMinutes(5)); map.put(TypedDriverOption.METRICS_SESSION_THROTTLING_HIGHEST, Duration.ofSeconds(3)); + map.put(TypedDriverOption.METRICS_SESSION_THROTTLING_LOWEST, Duration.ofMillis(1)); map.put(TypedDriverOption.METRICS_SESSION_THROTTLING_DIGITS, 3); map.put(TypedDriverOption.METRICS_SESSION_THROTTLING_INTERVAL, Duration.ofMinutes(5)); map.put( TypedDriverOption.CONTINUOUS_PAGING_METRICS_SESSION_CQL_REQUESTS_HIGHEST, Duration.ofMinutes(2)); + map.put( + TypedDriverOption.CONTINUOUS_PAGING_METRICS_SESSION_CQL_REQUESTS_LOWEST, + Duration.ofMillis(10)); map.put(TypedDriverOption.CONTINUOUS_PAGING_METRICS_SESSION_CQL_REQUESTS_DIGITS, 3); map.put( TypedDriverOption.CONTINUOUS_PAGING_METRICS_SESSION_CQL_REQUESTS_INTERVAL, Duration.ofMinutes(5)); - map.put(TypedDriverOption.METRICS_FACTORY_CLASS, "DropwizardMetricsFactory"); + map.put(TypedDriverOption.METRICS_FACTORY_CLASS, "DefaultMetricsFactory"); + map.put(TypedDriverOption.METRICS_ID_GENERATOR_CLASS, "DefaultMetricIdGenerator"); map.put(TypedDriverOption.METRICS_SESSION_GRAPH_REQUESTS_HIGHEST, Duration.ofSeconds(12)); + map.put(TypedDriverOption.METRICS_SESSION_GRAPH_REQUESTS_LOWEST, Duration.ofMillis(1)); map.put(TypedDriverOption.METRICS_SESSION_GRAPH_REQUESTS_DIGITS, 3); map.put(TypedDriverOption.METRICS_SESSION_GRAPH_REQUESTS_INTERVAL, Duration.ofMinutes(5)); map.put(TypedDriverOption.METRICS_NODE_ENABLED, Collections.emptyList()); map.put(TypedDriverOption.METRICS_NODE_CQL_MESSAGES_HIGHEST, Duration.ofSeconds(3)); + map.put(TypedDriverOption.METRICS_NODE_CQL_MESSAGES_LOWEST, Duration.ofMillis(1)); map.put(TypedDriverOption.METRICS_NODE_CQL_MESSAGES_DIGITS, 3); map.put(TypedDriverOption.METRICS_NODE_CQL_MESSAGES_INTERVAL, Duration.ofMinutes(5)); map.put(TypedDriverOption.METRICS_NODE_GRAPH_MESSAGES_HIGHEST, Duration.ofSeconds(3)); + map.put(TypedDriverOption.METRICS_NODE_GRAPH_MESSAGES_LOWEST, Duration.ofMillis(1)); map.put(TypedDriverOption.METRICS_NODE_GRAPH_MESSAGES_DIGITS, 3); map.put(TypedDriverOption.METRICS_NODE_GRAPH_MESSAGES_INTERVAL, Duration.ofMinutes(5)); map.put(TypedDriverOption.METRICS_NODE_EXPIRE_AFTER, Duration.ofHours(1)); @@ -339,6 +348,9 @@ protected static void fillWithDriverDefaults(OptionsMap map) { map.put(TypedDriverOption.METADATA_TOPOLOGY_WINDOW, Duration.ofSeconds(1)); map.put(TypedDriverOption.METADATA_TOPOLOGY_MAX_EVENTS, 20); map.put(TypedDriverOption.METADATA_SCHEMA_ENABLED, true); + map.put( + TypedDriverOption.METADATA_SCHEMA_REFRESHED_KEYSPACES, + ImmutableList.of("!system", "!/^system_.*/", "!/^dse_.*/", "!solr_admin", "!OpsCenter")); map.put(TypedDriverOption.METADATA_SCHEMA_REQUEST_TIMEOUT, requestTimeout); map.put(TypedDriverOption.METADATA_SCHEMA_REQUEST_PAGE_SIZE, requestPageSize); map.put(TypedDriverOption.METADATA_SCHEMA_WINDOW, Duration.ofSeconds(1)); @@ -366,6 +378,11 @@ protected static void fillWithDriverDefaults(OptionsMap map) { map.put(TypedDriverOption.NETTY_TIMER_TICK_DURATION, Duration.ofMillis(100)); map.put(TypedDriverOption.NETTY_TIMER_TICKS_PER_WHEEL, 2048); map.put(TypedDriverOption.COALESCER_INTERVAL, Duration.of(10, ChronoUnit.MICROS)); + map.put(TypedDriverOption.LOAD_BALANCING_DC_FAILOVER_MAX_NODES_PER_REMOTE_DC, 0); + map.put(TypedDriverOption.LOAD_BALANCING_DC_FAILOVER_ALLOW_FOR_LOCAL_CONSISTENCY_LEVELS, false); + map.put(TypedDriverOption.METRICS_GENERATE_AGGREGABLE_HISTOGRAMS, true); + map.put( + TypedDriverOption.LOAD_BALANCING_DC_FAILOVER_PREFERRED_REMOTE_DCS, ImmutableList.of("")); } @Immutable diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/config/ProgrammaticDriverConfigLoaderBuilder.java b/core/src/main/java/com/datastax/oss/driver/api/core/config/ProgrammaticDriverConfigLoaderBuilder.java index 2f6aa64485e..c3ae1d1bf5b 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/config/ProgrammaticDriverConfigLoaderBuilder.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/config/ProgrammaticDriverConfigLoaderBuilder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/config/TypedDriverOption.java b/core/src/main/java/com/datastax/oss/driver/api/core/config/TypedDriverOption.java index c7c80fb9bf4..182753300e7 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/config/TypedDriverOption.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/config/TypedDriverOption.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -137,9 +139,21 @@ public String toString() { public static final TypedDriverOption LOAD_BALANCING_LOCAL_DATACENTER = new TypedDriverOption<>( DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER, GenericType.STRING); - /** A custom filter to include/exclude nodes. */ + /** + * A custom filter to include/exclude nodes. + * + * @deprecated Use {@link #LOAD_BALANCING_DISTANCE_EVALUATOR_CLASS} instead. + */ + @Deprecated public static final TypedDriverOption LOAD_BALANCING_FILTER_CLASS = new TypedDriverOption<>(DefaultDriverOption.LOAD_BALANCING_FILTER_CLASS, GenericType.STRING); + /** + * The class name of a custom {@link + * com.datastax.oss.driver.api.core.loadbalancing.NodeDistanceEvaluator}. + */ + public static final TypedDriverOption LOAD_BALANCING_DISTANCE_EVALUATOR_CLASS = + new TypedDriverOption<>( + DefaultDriverOption.LOAD_BALANCING_DISTANCE_EVALUATOR_CLASS, GenericType.STRING); /** The timeout to use for internal queries that run as part of the initialization process. */ public static final TypedDriverOption CONNECTION_INIT_QUERY_TIMEOUT = new TypedDriverOption<>( @@ -215,12 +229,22 @@ public String toString() { */ public static final TypedDriverOption SSL_HOSTNAME_VALIDATION = new TypedDriverOption<>(DefaultDriverOption.SSL_HOSTNAME_VALIDATION, GenericType.BOOLEAN); + + public static final TypedDriverOption SSL_ALLOW_DNS_REVERSE_LOOKUP_SAN = + new TypedDriverOption<>( + DefaultDriverOption.SSL_ALLOW_DNS_REVERSE_LOOKUP_SAN, GenericType.BOOLEAN); /** The location of the keystore file. */ public static final TypedDriverOption SSL_KEYSTORE_PATH = new TypedDriverOption<>(DefaultDriverOption.SSL_KEYSTORE_PATH, GenericType.STRING); /** The keystore password. */ public static final TypedDriverOption SSL_KEYSTORE_PASSWORD = new TypedDriverOption<>(DefaultDriverOption.SSL_KEYSTORE_PASSWORD, GenericType.STRING); + + /** The duration between attempts to reload the keystore. */ + public static final TypedDriverOption SSL_KEYSTORE_RELOAD_INTERVAL = + new TypedDriverOption<>( + DefaultDriverOption.SSL_KEYSTORE_RELOAD_INTERVAL, GenericType.DURATION); + /** The location of the truststore file. */ public static final TypedDriverOption SSL_TRUSTSTORE_PATH = new TypedDriverOption<>(DefaultDriverOption.SSL_TRUSTSTORE_PATH, GenericType.STRING); @@ -242,9 +266,25 @@ public String toString() { public static final TypedDriverOption TIMESTAMP_GENERATOR_DRIFT_WARNING_INTERVAL = new TypedDriverOption<>( DefaultDriverOption.TIMESTAMP_GENERATOR_DRIFT_WARNING_INTERVAL, GenericType.DURATION); - /** The class of a session-wide component that tracks the outcome of requests. */ + + /** + * The class of a session-wide component that tracks the outcome of requests. + * + * @deprecated Use {@link #REQUEST_TRACKER_CLASSES} instead. + */ + @Deprecated public static final TypedDriverOption REQUEST_TRACKER_CLASS = new TypedDriverOption<>(DefaultDriverOption.REQUEST_TRACKER_CLASS, GenericType.STRING); + + /** The classes of session-wide components that track the outcome of requests. */ + public static final TypedDriverOption> REQUEST_TRACKER_CLASSES = + new TypedDriverOption<>( + DefaultDriverOption.REQUEST_TRACKER_CLASSES, GenericType.listOf(String.class)); + + /** The class of a session-wide component that generates request IDs. */ + public static final TypedDriverOption REQUEST_ID_GENERATOR_CLASS = + new TypedDriverOption<>(DefaultDriverOption.REQUEST_ID_GENERATOR_CLASS, GenericType.STRING); + /** Whether to log successful requests. */ public static final TypedDriverOption REQUEST_LOGGER_SUCCESS_ENABLED = new TypedDriverOption<>( @@ -300,14 +340,39 @@ public String toString() { public static final TypedDriverOption REQUEST_THROTTLER_DRAIN_INTERVAL = new TypedDriverOption<>( DefaultDriverOption.REQUEST_THROTTLER_DRAIN_INTERVAL, GenericType.DURATION); - /** The class of a session-wide component that listens for node state changes. */ + + /** + * The class of a session-wide component that listens for node state changes. + * + * @deprecated Use {@link #METADATA_NODE_STATE_LISTENER_CLASSES} instead. + */ + @Deprecated public static final TypedDriverOption METADATA_NODE_STATE_LISTENER_CLASS = new TypedDriverOption<>( DefaultDriverOption.METADATA_NODE_STATE_LISTENER_CLASS, GenericType.STRING); - /** The class of a session-wide component that listens for schema changes. */ + + /** + * The class of a session-wide component that listens for schema changes. + * + * @deprecated Use {@link #METADATA_SCHEMA_CHANGE_LISTENER_CLASSES} instead. + */ + @Deprecated public static final TypedDriverOption METADATA_SCHEMA_CHANGE_LISTENER_CLASS = new TypedDriverOption<>( DefaultDriverOption.METADATA_SCHEMA_CHANGE_LISTENER_CLASS, GenericType.STRING); + + /** The classes of session-wide components that listen for node state changes. */ + public static final TypedDriverOption> METADATA_NODE_STATE_LISTENER_CLASSES = + new TypedDriverOption<>( + DefaultDriverOption.METADATA_NODE_STATE_LISTENER_CLASSES, + GenericType.listOf(String.class)); + + /** The classes of session-wide components that listen for schema changes. */ + public static final TypedDriverOption> METADATA_SCHEMA_CHANGE_LISTENER_CLASSES = + new TypedDriverOption<>( + DefaultDriverOption.METADATA_SCHEMA_CHANGE_LISTENER_CLASSES, + GenericType.listOf(String.class)); + /** * The class of the address translator to use to convert the addresses sent by Cassandra nodes * into ones that the driver uses to connect. @@ -339,6 +404,10 @@ public String toString() { /** The consistency level to use for trace queries. */ public static final TypedDriverOption REQUEST_TRACE_CONSISTENCY = new TypedDriverOption<>(DefaultDriverOption.REQUEST_TRACE_CONSISTENCY, GenericType.STRING); + /** Whether or not to publish aggregable histogram for metrics */ + public static final TypedDriverOption METRICS_GENERATE_AGGREGABLE_HISTOGRAMS = + new TypedDriverOption<>( + DefaultDriverOption.METRICS_GENERATE_AGGREGABLE_HISTOGRAMS, GenericType.BOOLEAN); /** List of enabled session-level metrics. */ public static final TypedDriverOption> METRICS_SESSION_ENABLED = new TypedDriverOption<>( @@ -351,6 +420,21 @@ public String toString() { public static final TypedDriverOption METRICS_SESSION_CQL_REQUESTS_HIGHEST = new TypedDriverOption<>( DefaultDriverOption.METRICS_SESSION_CQL_REQUESTS_HIGHEST, GenericType.DURATION); + /** The shortest latency that we expect to record for requests. */ + public static final TypedDriverOption METRICS_SESSION_CQL_REQUESTS_LOWEST = + new TypedDriverOption<>( + DefaultDriverOption.METRICS_SESSION_CQL_REQUESTS_LOWEST, GenericType.DURATION); + /** Optional service-level objectives to meet, as a list of latencies to track. */ + public static final TypedDriverOption> METRICS_SESSION_CQL_REQUESTS_SLO = + new TypedDriverOption<>( + DefaultDriverOption.METRICS_SESSION_CQL_REQUESTS_SLO, + GenericType.listOf(GenericType.DURATION)); + /** Optional pre-defined percentile of cql requests to publish, as a list of percentiles . */ + public static final TypedDriverOption> + METRICS_SESSION_CQL_REQUESTS_PUBLISH_PERCENTILES = + new TypedDriverOption<>( + DefaultDriverOption.METRICS_SESSION_CQL_REQUESTS_PUBLISH_PERCENTILES, + GenericType.listOf(GenericType.DOUBLE)); /** * The number of significant decimal digits to which internal structures will maintain for * requests. @@ -366,6 +450,21 @@ public String toString() { public static final TypedDriverOption METRICS_SESSION_THROTTLING_HIGHEST = new TypedDriverOption<>( DefaultDriverOption.METRICS_SESSION_THROTTLING_HIGHEST, GenericType.DURATION); + /** The shortest latency that we expect to record for throttling. */ + public static final TypedDriverOption METRICS_SESSION_THROTTLING_LOWEST = + new TypedDriverOption<>( + DefaultDriverOption.METRICS_SESSION_THROTTLING_LOWEST, GenericType.DURATION); + /** Optional service-level objectives to meet, as a list of latencies to track. */ + public static final TypedDriverOption> METRICS_SESSION_THROTTLING_SLO = + new TypedDriverOption<>( + DefaultDriverOption.METRICS_SESSION_THROTTLING_SLO, + GenericType.listOf(GenericType.DURATION)); + /** Optional pre-defined percentile of throttling delay to publish, as a list of percentiles . */ + public static final TypedDriverOption> + METRICS_SESSION_THROTTLING_PUBLISH_PERCENTILES = + new TypedDriverOption<>( + DefaultDriverOption.METRICS_SESSION_THROTTLING_PUBLISH_PERCENTILES, + GenericType.listOf(GenericType.DOUBLE)); /** * The number of significant decimal digits to which internal structures will maintain for * throttling. @@ -381,6 +480,21 @@ public String toString() { public static final TypedDriverOption METRICS_NODE_CQL_MESSAGES_HIGHEST = new TypedDriverOption<>( DefaultDriverOption.METRICS_NODE_CQL_MESSAGES_HIGHEST, GenericType.DURATION); + /** The shortest latency that we expect to record for requests. */ + public static final TypedDriverOption METRICS_NODE_CQL_MESSAGES_LOWEST = + new TypedDriverOption<>( + DefaultDriverOption.METRICS_NODE_CQL_MESSAGES_LOWEST, GenericType.DURATION); + /** Optional service-level objectives to meet, as a list of latencies to track. */ + public static final TypedDriverOption> METRICS_NODE_CQL_MESSAGES_SLO = + new TypedDriverOption<>( + DefaultDriverOption.METRICS_NODE_CQL_MESSAGES_SLO, + GenericType.listOf(GenericType.DURATION)); + /** Optional pre-defined percentile of node cql messages to publish, as a list of percentiles . */ + public static final TypedDriverOption> + METRICS_NODE_CQL_MESSAGES_PUBLISH_PERCENTILES = + new TypedDriverOption<>( + DefaultDriverOption.METRICS_NODE_CQL_MESSAGES_PUBLISH_PERCENTILES, + GenericType.listOf(GenericType.DOUBLE)); /** * The number of significant decimal digits to which internal structures will maintain for * requests. @@ -482,6 +596,9 @@ public String toString() { /** The request timeout when repreparing. */ public static final TypedDriverOption REPREPARE_TIMEOUT = new TypedDriverOption<>(DefaultDriverOption.REPREPARE_TIMEOUT, GenericType.DURATION); + /** Whether the prepared statements cache use weak values. */ + public static final TypedDriverOption PREPARED_CACHE_WEAK_VALUES = + new TypedDriverOption<>(DefaultDriverOption.PREPARED_CACHE_WEAK_VALUES, GenericType.BOOLEAN); /** The number of threads in the I/O group. */ public static final TypedDriverOption NETTY_IO_SIZE = new TypedDriverOption<>(DefaultDriverOption.NETTY_IO_SIZE, GenericType.INTEGER); @@ -538,7 +655,7 @@ public String toString() { public static final TypedDriverOption NETTY_DAEMON = new TypedDriverOption<>(DefaultDriverOption.NETTY_DAEMON, GenericType.BOOLEAN); /** - * The location of the cloud secure bundle used to connect to Datastax Apache Cassandra as a + * The location of the cloud secure bundle used to connect to DataStax Apache Cassandra as a * service. */ public static final TypedDriverOption CLOUD_SECURE_CONNECT_BUNDLE = @@ -609,6 +726,27 @@ public String toString() { new TypedDriverOption<>( DseDriverOption.CONTINUOUS_PAGING_METRICS_SESSION_CQL_REQUESTS_HIGHEST, GenericType.DURATION); + /** The shortest latency that we expect to record for continuous requests. */ + public static final TypedDriverOption + CONTINUOUS_PAGING_METRICS_SESSION_CQL_REQUESTS_LOWEST = + new TypedDriverOption<>( + DseDriverOption.CONTINUOUS_PAGING_METRICS_SESSION_CQL_REQUESTS_LOWEST, + GenericType.DURATION); + /** Optional service-level objectives to meet, as a list of latencies to track. */ + public static final TypedDriverOption> + CONTINUOUS_PAGING_METRICS_SESSION_CQL_REQUESTS_SLO = + new TypedDriverOption<>( + DseDriverOption.CONTINUOUS_PAGING_METRICS_SESSION_CQL_REQUESTS_SLO, + GenericType.listOf(GenericType.DURATION)); + /** + * Optional pre-defined percentile of continuous paging cql requests to publish, as a list of + * percentiles . + */ + public static final TypedDriverOption> + CONTINUOUS_PAGING_METRICS_SESSION_CQL_REQUESTS_PUBLISH_PERCENTILES = + new TypedDriverOption<>( + DseDriverOption.CONTINUOUS_PAGING_METRICS_SESSION_CQL_REQUESTS_PUBLISH_PERCENTILES, + GenericType.listOf(GenericType.DOUBLE)); /** * The number of significant decimal digits to which internal structures will maintain for * continuous requests. @@ -674,6 +812,21 @@ public String toString() { public static final TypedDriverOption METRICS_SESSION_GRAPH_REQUESTS_HIGHEST = new TypedDriverOption<>( DseDriverOption.METRICS_SESSION_GRAPH_REQUESTS_HIGHEST, GenericType.DURATION); + /** The shortest latency that we expect to record for graph requests. */ + public static final TypedDriverOption METRICS_SESSION_GRAPH_REQUESTS_LOWEST = + new TypedDriverOption<>( + DseDriverOption.METRICS_SESSION_GRAPH_REQUESTS_LOWEST, GenericType.DURATION); + /** Optional service-level objectives to meet, as a list of latencies to track. */ + public static final TypedDriverOption> METRICS_SESSION_GRAPH_REQUESTS_SLO = + new TypedDriverOption<>( + DseDriverOption.METRICS_SESSION_GRAPH_REQUESTS_SLO, + GenericType.listOf(GenericType.DURATION)); + /** Optional pre-defined percentile of graph requests to publish, as a list of percentiles . */ + public static final TypedDriverOption> + METRICS_SESSION_GRAPH_REQUESTS_PUBLISH_PERCENTILES = + new TypedDriverOption<>( + DseDriverOption.METRICS_SESSION_GRAPH_REQUESTS_PUBLISH_PERCENTILES, + GenericType.listOf(GenericType.DOUBLE)); /** * The number of significant decimal digits to which internal structures will maintain for graph * requests. @@ -689,6 +842,23 @@ public String toString() { public static final TypedDriverOption METRICS_NODE_GRAPH_MESSAGES_HIGHEST = new TypedDriverOption<>( DseDriverOption.METRICS_NODE_GRAPH_MESSAGES_HIGHEST, GenericType.DURATION); + /** The shortest latency that we expect to record for graph requests. */ + public static final TypedDriverOption METRICS_NODE_GRAPH_MESSAGES_LOWEST = + new TypedDriverOption<>( + DseDriverOption.METRICS_NODE_GRAPH_MESSAGES_LOWEST, GenericType.DURATION); + /** Optional service-level objectives to meet, as a list of latencies to track. */ + public static final TypedDriverOption> METRICS_NODE_GRAPH_MESSAGES_SLO = + new TypedDriverOption<>( + DseDriverOption.METRICS_NODE_GRAPH_MESSAGES_SLO, + GenericType.listOf(GenericType.DURATION)); + /** + * Optional pre-defined percentile of node graph requests to publish, as a list of percentiles . + */ + public static final TypedDriverOption> + METRICS_NODE_GRAPH_MESSAGES_PUBLISH_PERCENTILES = + new TypedDriverOption<>( + DseDriverOption.METRICS_NODE_GRAPH_MESSAGES_PUBLISH_PERCENTILES, + GenericType.listOf(GenericType.DOUBLE)); /** * The number of significant decimal digits to which internal structures will maintain for graph * requests. @@ -709,6 +879,51 @@ public String toString() { public static final TypedDriverOption METRICS_FACTORY_CLASS = new TypedDriverOption<>(DefaultDriverOption.METRICS_FACTORY_CLASS, GenericType.STRING); + /** The classname of the desired {@code MetricIdGenerator} implementation. */ + public static final TypedDriverOption METRICS_ID_GENERATOR_CLASS = + new TypedDriverOption<>(DefaultDriverOption.METRICS_ID_GENERATOR_CLASS, GenericType.STRING); + + /** The value of the prefix to prepend to all metric names. */ + public static final TypedDriverOption METRICS_ID_GENERATOR_PREFIX = + new TypedDriverOption<>(DefaultDriverOption.METRICS_ID_GENERATOR_PREFIX, GenericType.STRING); + + /** The maximum number of nodes from remote DCs to include in query plans. */ + public static final TypedDriverOption + LOAD_BALANCING_DC_FAILOVER_MAX_NODES_PER_REMOTE_DC = + new TypedDriverOption<>( + DefaultDriverOption.LOAD_BALANCING_DC_FAILOVER_MAX_NODES_PER_REMOTE_DC, + GenericType.INTEGER); + /** Whether to consider nodes from remote DCs if the request's consistency level is local. */ + public static final TypedDriverOption + LOAD_BALANCING_DC_FAILOVER_ALLOW_FOR_LOCAL_CONSISTENCY_LEVELS = + new TypedDriverOption<>( + DefaultDriverOption.LOAD_BALANCING_DC_FAILOVER_ALLOW_FOR_LOCAL_CONSISTENCY_LEVELS, + GenericType.BOOLEAN); + + public static final TypedDriverOption ADDRESS_TRANSLATOR_ADVERTISED_HOSTNAME = + new TypedDriverOption<>( + DefaultDriverOption.ADDRESS_TRANSLATOR_ADVERTISED_HOSTNAME, GenericType.STRING); + public static final TypedDriverOption> ADDRESS_TRANSLATOR_SUBNET_ADDRESSES = + new TypedDriverOption<>( + DefaultDriverOption.ADDRESS_TRANSLATOR_SUBNET_ADDRESSES, + GenericType.mapOf(GenericType.STRING, GenericType.STRING)); + public static final TypedDriverOption ADDRESS_TRANSLATOR_DEFAULT_ADDRESS = + new TypedDriverOption<>( + DefaultDriverOption.ADDRESS_TRANSLATOR_DEFAULT_ADDRESS, GenericType.STRING); + public static final TypedDriverOption ADDRESS_TRANSLATOR_RESOLVE_ADDRESSES = + new TypedDriverOption<>( + DefaultDriverOption.ADDRESS_TRANSLATOR_RESOLVE_ADDRESSES, GenericType.BOOLEAN); + + /** + * Ordered preference list of remote dcs optionally supplied for automatic failover and included + * in query plan. This feature is enabled only when max-nodes-per-remote-dc is greater than 0. + */ + public static final TypedDriverOption> + LOAD_BALANCING_DC_FAILOVER_PREFERRED_REMOTE_DCS = + new TypedDriverOption<>( + DefaultDriverOption.LOAD_BALANCING_DC_FAILOVER_PREFERRED_REMOTE_DCS, + GenericType.listOf(String.class)); + private static Iterable> introspectBuiltInValues() { try { ImmutableList.Builder> result = ImmutableList.builder(); diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/config/package-info.java b/core/src/main/java/com/datastax/oss/driver/api/core/config/package-info.java index 6ddc5abaf62..a751d983e70 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/config/package-info.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/config/package-info.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/connection/BusyConnectionException.java b/core/src/main/java/com/datastax/oss/driver/api/core/connection/BusyConnectionException.java index bbe513351ba..8069474612a 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/connection/BusyConnectionException.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/connection/BusyConnectionException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -25,7 +27,7 @@ * requests. * *

This might happen under heavy load. The driver will automatically try the next node in the - * query plan. Therefore the only way that the client can observe this exception is as part of a + * query plan. Therefore, the only way that the client can observe this exception is as part of a * {@link AllNodesFailedException}. */ public class BusyConnectionException extends DriverException { diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/connection/ClosedConnectionException.java b/core/src/main/java/com/datastax/oss/driver/api/core/connection/ClosedConnectionException.java index 9daee547a46..a192e2c5efc 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/connection/ClosedConnectionException.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/connection/ClosedConnectionException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -26,8 +28,9 @@ *

For example, this can happen if the node is unresponsive and a heartbeat query failed, or if * the node was forced down. * - *

The driver will always retry these requests on the next node transparently. Therefore, the - * only way to observe this exception is as part of an {@link AllNodesFailedException}. + *

The driver will retry these requests on the next node transparently, unless the request is not + * idempotent. Therefore, this exception is usually observed as part of an {@link + * AllNodesFailedException}. */ public class ClosedConnectionException extends DriverException { diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/connection/ConnectionInitException.java b/core/src/main/java/com/datastax/oss/driver/api/core/connection/ConnectionInitException.java index 4112bdcd6f8..519624e8d5d 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/connection/ConnectionInitException.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/connection/ConnectionInitException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -26,7 +28,7 @@ * *

The only time when this is returned directly to the client (wrapped in a {@link * AllNodesFailedException}) is at initialization. If it happens later when the driver is already - * connected, it is just logged an the connection is reattempted. + * connected, it is just logged and the connection is reattempted. */ public class ConnectionInitException extends DriverException { public ConnectionInitException(@NonNull String message, @Nullable Throwable cause) { diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/connection/CrcMismatchException.java b/core/src/main/java/com/datastax/oss/driver/api/core/connection/CrcMismatchException.java index e1115b6e38f..d0fc8fc3b73 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/connection/CrcMismatchException.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/connection/CrcMismatchException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/connection/FrameTooLongException.java b/core/src/main/java/com/datastax/oss/driver/api/core/connection/FrameTooLongException.java index e84504d089f..9954aefb3d4 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/connection/FrameTooLongException.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/connection/FrameTooLongException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/connection/HeartbeatException.java b/core/src/main/java/com/datastax/oss/driver/api/core/connection/HeartbeatException.java index 183f7c5366e..60c3d60a69d 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/connection/HeartbeatException.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/connection/HeartbeatException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -28,8 +30,8 @@ * *

Heartbeat queries are sent automatically on idle connections, to ensure that they are still * alive. If a heartbeat query fails, the connection is closed, and all pending queries are aborted. - * The exception will be passed to {@link RetryPolicy#onRequestAborted(Request, Throwable, int)}, - * which decides what to do next (the default policy retries the query on the next node). + * The exception will be passed to {@link RetryPolicy#onRequestAbortedVerdict(Request, Throwable, + * int)}, which decides what to do next (the default policy retries the query on the next node). */ public class HeartbeatException extends DriverException { diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/connection/ReconnectionPolicy.java b/core/src/main/java/com/datastax/oss/driver/api/core/connection/ReconnectionPolicy.java index 083e83950c6..9f81843c9c0 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/connection/ReconnectionPolicy.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/connection/ReconnectionPolicy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/connection/package-info.java b/core/src/main/java/com/datastax/oss/driver/api/core/connection/package-info.java index ade4f228669..737f985ad1d 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/connection/package-info.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/connection/package-info.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/context/DriverContext.java b/core/src/main/java/com/datastax/oss/driver/api/core/context/DriverContext.java index b4efb691494..6f0afd3df8a 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/context/DriverContext.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/context/DriverContext.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -31,6 +33,7 @@ import com.datastax.oss.driver.api.core.specex.SpeculativeExecutionPolicy; import com.datastax.oss.driver.api.core.ssl.SslEngineFactory; import com.datastax.oss.driver.api.core.time.TimestampGenerator; +import com.datastax.oss.driver.api.core.tracker.RequestIdGenerator; import com.datastax.oss.driver.api.core.tracker.RequestTracker; import edu.umd.cs.findbugs.annotations.NonNull; import java.util.Map; @@ -137,6 +140,10 @@ default SpeculativeExecutionPolicy getSpeculativeExecutionPolicy(@NonNull String @NonNull RequestTracker getRequestTracker(); + /** @return The driver's request ID generator; never {@code null}. */ + @NonNull + Optional getRequestIdGenerator(); + /** @return The driver's request throttler; never {@code null}. */ @NonNull RequestThrottler getRequestThrottler(); diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/cql/AsyncCqlSession.java b/core/src/main/java/com/datastax/oss/driver/api/core/cql/AsyncCqlSession.java index 2f554361ea8..7b56bd61a09 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/cql/AsyncCqlSession.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/cql/AsyncCqlSession.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/cql/AsyncResultSet.java b/core/src/main/java/com/datastax/oss/driver/api/core/cql/AsyncResultSet.java index a21c0ee8cd6..05a292ccbd0 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/cql/AsyncResultSet.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/cql/AsyncResultSet.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/cql/BatchStatement.java b/core/src/main/java/com/datastax/oss/driver/api/core/cql/BatchStatement.java index 733b959d9a0..9deb33c6007 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/cql/BatchStatement.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/cql/BatchStatement.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -24,6 +26,7 @@ import com.datastax.oss.driver.internal.core.util.Sizes; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableList; import com.datastax.oss.protocol.internal.PrimitiveSizes; +import edu.umd.cs.findbugs.annotations.CheckReturnValue; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; import java.util.ArrayList; @@ -162,6 +165,7 @@ static BatchStatementBuilder builder(@NonNull BatchStatement template) { * method. However custom implementations may choose to be mutable and return the same instance. */ @NonNull + @CheckReturnValue BatchStatement setBatchType(@NonNull BatchType newBatchType); /** @@ -178,6 +182,7 @@ static BatchStatementBuilder builder(@NonNull BatchStatement template) { * @see Request#getKeyspace() */ @NonNull + @CheckReturnValue BatchStatement setKeyspace(@Nullable CqlIdentifier newKeyspace); /** @@ -185,6 +190,7 @@ static BatchStatementBuilder builder(@NonNull BatchStatement template) { * setKeyspace(CqlIdentifier.fromCql(newKeyspaceName))}. */ @NonNull + @CheckReturnValue default BatchStatement setKeyspace(@NonNull String newKeyspaceName) { return setKeyspace(CqlIdentifier.fromCql(newKeyspaceName)); } @@ -199,6 +205,7 @@ default BatchStatement setKeyspace(@NonNull String newKeyspaceName) { * method. However custom implementations may choose to be mutable and return the same instance. */ @NonNull + @CheckReturnValue BatchStatement add(@NonNull BatchableStatement statement); /** @@ -211,10 +218,12 @@ default BatchStatement setKeyspace(@NonNull String newKeyspaceName) { * method. However custom implementations may choose to be mutable and return the same instance. */ @NonNull + @CheckReturnValue BatchStatement addAll(@NonNull Iterable> statements); /** @see #addAll(Iterable) */ @NonNull + @CheckReturnValue default BatchStatement addAll(@NonNull BatchableStatement... statements) { return addAll(Arrays.asList(statements)); } @@ -229,6 +238,7 @@ default BatchStatement addAll(@NonNull BatchableStatement... statements) { * method. However custom implementations may choose to be mutable and return the same instance. */ @NonNull + @CheckReturnValue BatchStatement clear(); @Override diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/cql/BatchStatementBuilder.java b/core/src/main/java/com/datastax/oss/driver/api/core/cql/BatchStatementBuilder.java index c05c5d2f0cf..a8e2b8ab659 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/cql/BatchStatementBuilder.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/cql/BatchStatementBuilder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/cql/BatchType.java b/core/src/main/java/com/datastax/oss/driver/api/core/cql/BatchType.java index f019e295370..6b0a7f09688 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/cql/BatchType.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/cql/BatchType.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/cql/BatchableStatement.java b/core/src/main/java/com/datastax/oss/driver/api/core/cql/BatchableStatement.java index 5fb50fc5348..a25f625bae9 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/cql/BatchableStatement.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/cql/BatchableStatement.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/cql/Bindable.java b/core/src/main/java/com/datastax/oss/driver/api/core/cql/Bindable.java index dc9577ae23e..64f0f22a051 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/cql/Bindable.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/cql/Bindable.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/cql/BoundStatement.java b/core/src/main/java/com/datastax/oss/driver/api/core/cql/BoundStatement.java index 480911fde12..bd7c142907f 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/cql/BoundStatement.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/cql/BoundStatement.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/cql/BoundStatementBuilder.java b/core/src/main/java/com/datastax/oss/driver/api/core/cql/BoundStatementBuilder.java index 5cdd07f2a61..7e8f8723e1b 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/cql/BoundStatementBuilder.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/cql/BoundStatementBuilder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -99,6 +101,12 @@ public BoundStatementBuilder(@NonNull BoundStatement template) { this.node = template.getNode(); } + /** The prepared statement that was used to create this statement. */ + @NonNull + public PreparedStatement getPreparedStatement() { + return preparedStatement; + } + @NonNull @Override public List allIndicesOf(@NonNull CqlIdentifier id) { diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/cql/ColumnDefinition.java b/core/src/main/java/com/datastax/oss/driver/api/core/cql/ColumnDefinition.java index 5bdee0410ad..cb48f058be4 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/cql/ColumnDefinition.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/cql/ColumnDefinition.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/cql/ColumnDefinitions.java b/core/src/main/java/com/datastax/oss/driver/api/core/cql/ColumnDefinitions.java index 176884db998..7a775064317 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/cql/ColumnDefinitions.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/cql/ColumnDefinitions.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/cql/DefaultBatchType.java b/core/src/main/java/com/datastax/oss/driver/api/core/cql/DefaultBatchType.java index a8f978d807e..f699438df59 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/cql/DefaultBatchType.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/cql/DefaultBatchType.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/cql/ExecutionInfo.java b/core/src/main/java/com/datastax/oss/driver/api/core/cql/ExecutionInfo.java index 239851f2731..40cfca827d1 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/cql/ExecutionInfo.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/cql/ExecutionInfo.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/cql/PagingState.java b/core/src/main/java/com/datastax/oss/driver/api/core/cql/PagingState.java index dd5a16db167..b9042f99841 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/cql/PagingState.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/cql/PagingState.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/cql/PrepareRequest.java b/core/src/main/java/com/datastax/oss/driver/api/core/cql/PrepareRequest.java index 3e7308ccd4f..eb04f26c046 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/cql/PrepareRequest.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/cql/PrepareRequest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/cql/PreparedStatement.java b/core/src/main/java/com/datastax/oss/driver/api/core/cql/PreparedStatement.java index f412b9a3bc4..7828f9f809c 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/cql/PreparedStatement.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/cql/PreparedStatement.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/cql/QueryTrace.java b/core/src/main/java/com/datastax/oss/driver/api/core/cql/QueryTrace.java index 09d93f47fff..37ebb85c0db 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/cql/QueryTrace.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/cql/QueryTrace.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/cql/ResultSet.java b/core/src/main/java/com/datastax/oss/driver/api/core/cql/ResultSet.java index d4383476ca3..54f786b2068 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/cql/ResultSet.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/cql/ResultSet.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/cql/Row.java b/core/src/main/java/com/datastax/oss/driver/api/core/cql/Row.java index 49b85c54719..5eab449b057 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/cql/Row.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/cql/Row.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/cql/SimpleStatement.java b/core/src/main/java/com/datastax/oss/driver/api/core/cql/SimpleStatement.java index 95841cbdcb4..ef04cd14a5b 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/cql/SimpleStatement.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/cql/SimpleStatement.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -26,6 +28,7 @@ import com.datastax.oss.protocol.internal.PrimitiveSizes; import com.datastax.oss.protocol.internal.util.collection.NullAllowingImmutableList; import com.datastax.oss.protocol.internal.util.collection.NullAllowingImmutableMap; +import edu.umd.cs.findbugs.annotations.CheckReturnValue; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; import java.util.List; @@ -195,6 +198,7 @@ static SimpleStatementBuilder builder(@NonNull SimpleStatement template) { * @see #setNamedValuesWithIds(Map) */ @NonNull + @CheckReturnValue SimpleStatement setQuery(@NonNull String newQuery); /** @@ -207,6 +211,7 @@ static SimpleStatementBuilder builder(@NonNull SimpleStatement template) { * @see Request#getKeyspace() */ @NonNull + @CheckReturnValue SimpleStatement setKeyspace(@Nullable CqlIdentifier newKeyspace); /** @@ -214,6 +219,7 @@ static SimpleStatementBuilder builder(@NonNull SimpleStatement template) { * setKeyspace(CqlIdentifier.fromCql(newKeyspaceName))}. */ @NonNull + @CheckReturnValue default SimpleStatement setKeyspace(@NonNull String newKeyspaceName) { return setKeyspace(CqlIdentifier.fromCql(newKeyspaceName)); } @@ -234,6 +240,7 @@ default SimpleStatement setKeyspace(@NonNull String newKeyspaceName) { * @see #setQuery(String) */ @NonNull + @CheckReturnValue SimpleStatement setPositionalValues(@NonNull List newPositionalValues); @NonNull @@ -254,6 +261,7 @@ default SimpleStatement setKeyspace(@NonNull String newKeyspaceName) { * @see #setQuery(String) */ @NonNull + @CheckReturnValue SimpleStatement setNamedValuesWithIds(@NonNull Map newNamedValues); /** @@ -261,6 +269,7 @@ default SimpleStatement setKeyspace(@NonNull String newKeyspaceName) { * converted on the fly with {@link CqlIdentifier#fromCql(String)}. */ @NonNull + @CheckReturnValue default SimpleStatement setNamedValues(@NonNull Map newNamedValues) { return setNamedValuesWithIds(DefaultSimpleStatement.wrapKeys(newNamedValues)); } diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/cql/SimpleStatementBuilder.java b/core/src/main/java/com/datastax/oss/driver/api/core/cql/SimpleStatementBuilder.java index 78ec90d6722..1ac910ff6a7 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/cql/SimpleStatementBuilder.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/cql/SimpleStatementBuilder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/cql/Statement.java b/core/src/main/java/com/datastax/oss/driver/api/core/cql/Statement.java index 52023d3a6b7..d70c56686c5 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/cql/Statement.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/cql/Statement.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -255,7 +257,8 @@ default SelfT disableTracing() { } /** - * Returns the query timestamp, in microseconds, to send with the statement. + * Returns the query timestamp, in microseconds, to send with the statement. See {@link + * #setQueryTimestamp(long)} for details. * *

If this is equal to {@link #NO_DEFAULT_TIMESTAMP}, the {@link TimestampGenerator} configured * for this driver instance will be used to generate a timestamp. @@ -277,6 +280,19 @@ default long getDefaultTimestamp() { /** * Sets the query timestamp, in microseconds, to send with the statement. * + *

This is an alternative to appending a {@code USING TIMESTAMP} clause in the statement's + * query string, and has the advantage of sending the timestamp separately from the query string + * itself, which doesn't have to be modified when executing the same statement with different + * timestamps. Note that, if both a {@code USING TIMESTAMP} clause and a query timestamp are set + * for a given statement, the timestamp from the {@code USING TIMESTAMP} clause wins. + * + *

This method can be used on any instance of {@link SimpleStatement}, {@link BoundStatement} + * or {@link BatchStatement}. For a {@link BatchStatement}, the timestamp will apply to all its + * child statements; it is not possible to define per-child timestamps using this method, and + * consequently, if this method is called on a batch child statement, the provided timestamp will + * be silently ignored. If different timestamps are required for individual child statements, this + * can only be achieved with a custom {@code USING TIMESTAMP} clause in each child query. + * *

If this is equal to {@link #NO_DEFAULT_TIMESTAMP}, the {@link TimestampGenerator} configured * for this driver instance will be used to generate a timestamp. * @@ -497,6 +513,7 @@ default int getNowInSeconds() { * @see #NO_NOW_IN_SECONDS */ @NonNull + @CheckReturnValue @SuppressWarnings("unchecked") default SelfT setNowInSeconds(int nowInSeconds) { return (SelfT) this; diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/cql/StatementBuilder.java b/core/src/main/java/com/datastax/oss/driver/api/core/cql/StatementBuilder.java index e93bb8e5c96..531070b854c 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/cql/StatementBuilder.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/cql/StatementBuilder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/cql/SyncCqlSession.java b/core/src/main/java/com/datastax/oss/driver/api/core/cql/SyncCqlSession.java index d691bf41b37..a0f752db407 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/cql/SyncCqlSession.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/cql/SyncCqlSession.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/cql/TraceEvent.java b/core/src/main/java/com/datastax/oss/driver/api/core/cql/TraceEvent.java index 36c53e444e0..3043d94057f 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/cql/TraceEvent.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/cql/TraceEvent.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/data/AccessibleById.java b/core/src/main/java/com/datastax/oss/driver/api/core/data/AccessibleById.java index 7d39b66c861..2ca2222424c 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/data/AccessibleById.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/data/AccessibleById.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/data/AccessibleByIndex.java b/core/src/main/java/com/datastax/oss/driver/api/core/data/AccessibleByIndex.java index 509dd4866f9..3007ed1fb68 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/data/AccessibleByIndex.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/data/AccessibleByIndex.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/data/AccessibleByName.java b/core/src/main/java/com/datastax/oss/driver/api/core/data/AccessibleByName.java index edd82a40c8e..74574a82f38 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/data/AccessibleByName.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/data/AccessibleByName.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/data/ByteUtils.java b/core/src/main/java/com/datastax/oss/driver/api/core/data/ByteUtils.java index 232a75543cb..d3dc68733e4 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/data/ByteUtils.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/data/ByteUtils.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/data/CqlDuration.java b/core/src/main/java/com/datastax/oss/driver/api/core/data/CqlDuration.java index 40b6b41ee60..bfa9df20bbb 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/data/CqlDuration.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/data/CqlDuration.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -20,6 +22,7 @@ import com.datastax.oss.driver.shaded.guava.common.base.Preconditions; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableList; import edu.umd.cs.findbugs.annotations.NonNull; +import java.io.Serializable; import java.time.Duration; import java.time.Period; import java.time.temporal.ChronoUnit; @@ -28,6 +31,7 @@ import java.time.temporal.TemporalUnit; import java.time.temporal.UnsupportedTemporalTypeException; import java.util.List; +import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.jcip.annotations.Immutable; @@ -41,7 +45,9 @@ * in time, regardless of the calendar). */ @Immutable -public final class CqlDuration implements TemporalAmount { +public final class CqlDuration implements TemporalAmount, Serializable { + + private static final long serialVersionUID = 1L; @VisibleForTesting static final long NANOS_PER_MICRO = 1000L; @VisibleForTesting static final long NANOS_PER_MILLI = 1000 * NANOS_PER_MICRO; @@ -74,8 +80,11 @@ public final class CqlDuration implements TemporalAmount { private static final ImmutableList TEMPORAL_UNITS = ImmutableList.of(ChronoUnit.MONTHS, ChronoUnit.DAYS, ChronoUnit.NANOS); + /** @serial */ private final int months; + /** @serial */ private final int days; + /** @serial */ private final long nanoseconds; private CqlDuration(int months, int days, long nanoseconds) { @@ -232,7 +241,7 @@ private static long groupAsLong(@NonNull Matcher matcher, int group) { } private static Builder add(@NonNull Builder builder, long number, @NonNull String symbol) { - String s = symbol.toLowerCase(); + String s = symbol.toLowerCase(Locale.ROOT); if (s.equals("y")) { return builder.addYears(number); } else if (s.equals("mo")) { diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/data/CqlVector.java b/core/src/main/java/com/datastax/oss/driver/api/core/data/CqlVector.java new file mode 100644 index 00000000000..8089d551750 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/api/core/data/CqlVector.java @@ -0,0 +1,293 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.api.core.data; + +import com.datastax.oss.driver.api.core.type.codec.TypeCodec; +import com.datastax.oss.driver.internal.core.type.codec.ParseUtils; +import com.datastax.oss.driver.shaded.guava.common.base.Preconditions; +import com.datastax.oss.driver.shaded.guava.common.base.Predicates; +import com.datastax.oss.driver.shaded.guava.common.collect.Iterables; +import edu.umd.cs.findbugs.annotations.NonNull; +import java.io.IOException; +import java.io.InvalidObjectException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.ObjectStreamException; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Objects; +import java.util.stream.Stream; + +/** + * Representation of a vector as defined in CQL. + * + *

A CQL vector is a fixed-length array of non-null numeric values. These properties don't map + * cleanly to an existing class in the standard JDK Collections hierarchy so we provide this value + * object instead. Like other value object collections returned by the driver instances of this + * class are not immutable; think of these value objects as a representation of a vector stored in + * the database as an initial step in some additional computation. + * + *

While we don't implement any Collection APIs we do implement Iterable. We also attempt to play + * nice with the Streams API in order to better facilitate integration with data pipelines. Finally, + * where possible we've tried to make the API of this class similar to the equivalent methods on + * {@link List}. + */ +public class CqlVector implements Iterable, Serializable { + + /** + * Create a new CqlVector containing the specified values. + * + * @param vals the collection of values to wrap. + * @return a CqlVector wrapping those values + */ + public static CqlVector newInstance(V... vals) { + + // Note that Array.asList() guarantees the return of an array which implements RandomAccess + return new CqlVector(Arrays.asList(vals)); + } + + /** + * Create a new CqlVector that "wraps" an existing ArrayList. Modifications to the passed + * ArrayList will also be reflected in the returned CqlVector. + * + * @param list the collection of values to wrap. + * @return a CqlVector wrapping those values + */ + public static CqlVector newInstance(List list) { + Preconditions.checkArgument(list != null, "Input list should not be null"); + return new CqlVector(list); + } + + /** + * Create a new CqlVector instance from the specified string representation. + * + * @param str a String representation of a CqlVector + * @param subtypeCodec + * @return a new CqlVector built from the String representation + */ + public static CqlVector from(@NonNull String str, @NonNull TypeCodec subtypeCodec) { + Preconditions.checkArgument(str != null, "Cannot create CqlVector from null string"); + Preconditions.checkArgument(!str.isEmpty(), "Cannot create CqlVector from empty string"); + if (str.equalsIgnoreCase("NULL")) return null; + + int idx = ParseUtils.skipSpaces(str, 0); + if (str.charAt(idx++) != '[') + throw new IllegalArgumentException( + String.format( + "Cannot parse vector value from \"%s\", at character %d expecting '[' but got '%c'", + str, idx, str.charAt(idx))); + + idx = ParseUtils.skipSpaces(str, idx); + + if (str.charAt(idx) == ']') { + return new CqlVector<>(new ArrayList<>()); + } + + List list = new ArrayList<>(); + while (idx < str.length()) { + int n; + try { + n = ParseUtils.skipCQLValue(str, idx); + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException( + String.format( + "Cannot parse vector value from \"%s\", invalid CQL value at character %d", + str, idx), + e); + } + + list.add(subtypeCodec.parse(str.substring(idx, n))); + idx = n; + + idx = ParseUtils.skipSpaces(str, idx); + if (str.charAt(idx) == ']') return new CqlVector<>(list); + if (str.charAt(idx++) != ',') + throw new IllegalArgumentException( + String.format( + "Cannot parse vector value from \"%s\", at character %d expecting ',' but got '%c'", + str, idx, str.charAt(idx))); + + idx = ParseUtils.skipSpaces(str, idx); + } + throw new IllegalArgumentException( + String.format("Malformed vector value \"%s\", missing closing ']'", str)); + } + + private final List list; + + private CqlVector(@NonNull List list) { + + Preconditions.checkArgument( + Iterables.all(list, Predicates.notNull()), "CqlVectors cannot contain null values"); + this.list = list; + } + + /** + * Retrieve the value at the specified index. Modelled after {@link List#get(int)} + * + * @param idx the index to retrieve + * @return the value at the specified index + */ + public T get(int idx) { + return list.get(idx); + } + + /** + * Update the value at the specified index. Modelled after {@link List#set(int, Object)} + * + * @param idx the index to set + * @param val the new value for the specified index + * @return the old value for the specified index + */ + public T set(int idx, T val) { + return list.set(idx, val); + } + + /** + * Return the size of this vector. Modelled after {@link List#size()} + * + * @return the vector size + */ + public int size() { + return this.list.size(); + } + + /** + * Return a CqlVector consisting of the contents of a portion of this vector. Modelled after + * {@link List#subList(int, int)} + * + * @param from the index to start from (inclusive) + * @param to the index to end on (exclusive) + * @return a new CqlVector wrapping the sublist + */ + public CqlVector subVector(int from, int to) { + return new CqlVector(this.list.subList(from, to)); + } + + /** + * Return a boolean indicating whether the vector is empty. Modelled after {@link List#isEmpty()} + * + * @return true if the list is empty, false otherwise + */ + public boolean isEmpty() { + return this.list.isEmpty(); + } + + /** + * Create an {@link Iterator} for this vector + * + * @return the generated iterator + */ + @Override + public Iterator iterator() { + return this.list.iterator(); + } + + /** + * Create a {@link Stream} of the values in this vector + * + * @return the Stream instance + */ + public Stream stream() { + return this.list.stream(); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } else if (o instanceof CqlVector) { + CqlVector that = (CqlVector) o; + return this.list.equals(that.list); + } else { + return false; + } + } + + @Override + public int hashCode() { + return Objects.hash(list); + } + + /** + * The string representation of the vector. Elements, like strings, may not be properly quoted. + * + * @return the string representation + */ + @Override + public String toString() { + return Iterables.toString(this.list); + } + + /** + * Serialization proxy for CqlVector. Allows serialization regardless of implementation of list + * field. + * + * @param inner type of CqlVector, assume Number is always Serializable. + */ + private static class SerializationProxy implements Serializable { + + private static final long serialVersionUID = 1; + + private transient List list; + + SerializationProxy(CqlVector vector) { + this.list = vector.list; + } + + // Reconstruct CqlVector's list of elements. + private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { + stream.defaultReadObject(); + + int size = stream.readInt(); + list = new ArrayList<>(); + for (int i = 0; i < size; i++) { + list.add((T) stream.readObject()); + } + } + + // Return deserialized proxy object as CqlVector. + private Object readResolve() throws ObjectStreamException { + return new CqlVector(list); + } + + // Write size of CqlVector followed by items in order. + private void writeObject(ObjectOutputStream stream) throws IOException { + stream.defaultWriteObject(); + + stream.writeInt(list.size()); + for (T item : list) { + stream.writeObject(item); + } + } + } + + /** @serialData The number of elements in the vector, followed by each element in-order. */ + private Object writeReplace() { + return new SerializationProxy(this); + } + + private void readObject(@SuppressWarnings("unused") ObjectInputStream stream) + throws InvalidObjectException { + // Should never be called since we serialized a proxy + throw new InvalidObjectException("Proxy required"); + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/data/Data.java b/core/src/main/java/com/datastax/oss/driver/api/core/data/Data.java index 0db0a6b44e8..495b96e97c7 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/data/Data.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/data/Data.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/data/GettableById.java b/core/src/main/java/com/datastax/oss/driver/api/core/data/GettableById.java index a6c46e4abe8..8393bc9f758 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/data/GettableById.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/data/GettableById.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -515,6 +517,25 @@ default CqlDuration getCqlDuration(@NonNull CqlIdentifier id) { return getCqlDuration(firstIndexOf(id)); } + /** + * Returns the value for the first occurrence of {@code id} as a vector. + * + *

By default, this works with CQL type {@code vector}. + * + *

If an identifier appears multiple times, this can only be used to access the first value. + * For the other ones, use positional getters. + * + *

If you want to avoid the overhead of building a {@code CqlIdentifier}, use the variant of + * this method that takes a string argument. + * + * @throws IllegalArgumentException if the id is invalid. + */ + @Nullable + default CqlVector getVector( + @NonNull CqlIdentifier id, @NonNull Class elementsClass) { + return getVector(firstIndexOf(id), elementsClass); + } + /** * Returns the value for the first occurrence of {@code id} as a token. * diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/data/GettableByIndex.java b/core/src/main/java/com/datastax/oss/driver/api/core/data/GettableByIndex.java index 9e3502732c9..bb75bd9a2b4 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/data/GettableByIndex.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/data/GettableByIndex.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -436,6 +438,18 @@ default CqlDuration getCqlDuration(int i) { return get(i, CqlDuration.class); } + /** + * Returns the {@code i}th value as a vector. + * + *

By default, this works with CQL type {@code vector}. + * + * @throws IndexOutOfBoundsException if the index is invalid. + */ + @Nullable + default CqlVector getVector(int i, @NonNull Class elementsClass) { + return get(i, GenericType.vectorOf(elementsClass)); + } + /** * Returns the {@code i}th value as a token. * diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/data/GettableByName.java b/core/src/main/java/com/datastax/oss/driver/api/core/data/GettableByName.java index abbb16aeb75..b0a4660033b 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/data/GettableByName.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/data/GettableByName.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -511,6 +513,25 @@ default CqlDuration getCqlDuration(@NonNull String name) { return getCqlDuration(firstIndexOf(name)); } + /** + * Returns the value for the first occurrence of {@code name} as a vector. + * + *

By default, this works with CQL type {@code vector}. + * + *

If an identifier appears multiple times, this can only be used to access the first value. + * For the other ones, use positional getters. + * + *

This method deals with case sensitivity in the way explained in the documentation of {@link + * AccessibleByName}. + * + * @throws IllegalArgumentException if the name is invalid. + */ + @Nullable + default CqlVector getVector( + @NonNull String name, @NonNull Class elementsClass) { + return getVector(firstIndexOf(name), elementsClass); + } + /** * Returns the value for the first occurrence of {@code name} as a token. * diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/data/SettableById.java b/core/src/main/java/com/datastax/oss/driver/api/core/data/SettableById.java index 0d3cba5601d..0f5e3cd9daa 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/data/SettableById.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/data/SettableById.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -559,6 +561,30 @@ default SelfT setCqlDuration(@NonNull CqlIdentifier id, @Nullable CqlDuration v) return result; } + /** + * Sets the value for all occurrences of {@code id} to the provided {@code vector}. + * + *

By default, this works with CQL type {@code vector}. + * + *

If you want to avoid the overhead of building a {@code CqlIdentifier}, use the variant of + * this method that takes a string argument. + * + * @throws IllegalArgumentException if the id is invalid. + */ + @NonNull + @CheckReturnValue + default SelfT setVector( + @NonNull CqlIdentifier id, + @Nullable CqlVector v, + @NonNull Class elementsClass) { + SelfT result = null; + for (Integer i : allIndicesOf(id)) { + result = (result == null ? this : result).setVector(i, v, elementsClass); + } + assert result != null; // allIndices throws if there are no results + return result; + } + /** * Sets the value for all occurrences of {@code id} to the provided token. * diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/data/SettableByIndex.java b/core/src/main/java/com/datastax/oss/driver/api/core/data/SettableByIndex.java index 7cd0b5671ff..4ecdf647590 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/data/SettableByIndex.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/data/SettableByIndex.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -414,6 +416,20 @@ default SelfT setCqlDuration(int i, @Nullable CqlDuration v) { return set(i, v, CqlDuration.class); } + /** + * Sets the {@code i}th value to the provided vector. + * + *

By default, this works with CQL type {@code vector}. + * + * @throws IndexOutOfBoundsException if the index is invalid. + */ + @NonNull + @CheckReturnValue + default SelfT setVector( + int i, @Nullable CqlVector v, @NonNull Class elementsClass) { + return set(i, v, GenericType.vectorOf(elementsClass)); + } + /** * Sets the {@code i}th value to the provided token. * diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/data/SettableByName.java b/core/src/main/java/com/datastax/oss/driver/api/core/data/SettableByName.java index d93f4ebf5b2..afe9ba59f64 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/data/SettableByName.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/data/SettableByName.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -558,6 +560,30 @@ default SelfT setCqlDuration(@NonNull String name, @Nullable CqlDuration v) { return result; } + /** + * Sets the value for all occurrences of {@code name} to the provided vector. + * + *

By default, this works with CQL type {@code vector}. + * + *

This method deals with case sensitivity in the way explained in the documentation of {@link + * AccessibleByName}. + * + * @throws IllegalArgumentException if the name is invalid. + */ + @NonNull + @CheckReturnValue + default SelfT setVector( + @NonNull String name, + @Nullable CqlVector v, + @NonNull Class elementsClass) { + SelfT result = null; + for (Integer i : allIndicesOf(name)) { + result = (result == null ? this : result).setVector(i, v, elementsClass); + } + assert result != null; // allIndices throws if there are no results + return result; + } + /** * Sets the value for all occurrences of {@code name} to the provided token. * diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/data/TupleValue.java b/core/src/main/java/com/datastax/oss/driver/api/core/data/TupleValue.java index 01689a92f78..0fde2d87e71 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/data/TupleValue.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/data/TupleValue.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/data/UdtValue.java b/core/src/main/java/com/datastax/oss/driver/api/core/data/UdtValue.java index 1e67d796bba..7e8bc80793b 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/data/UdtValue.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/data/UdtValue.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/detach/AttachmentPoint.java b/core/src/main/java/com/datastax/oss/driver/api/core/detach/AttachmentPoint.java index a8151da3079..d1897f66e16 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/detach/AttachmentPoint.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/detach/AttachmentPoint.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/detach/Detachable.java b/core/src/main/java/com/datastax/oss/driver/api/core/detach/Detachable.java index 73d1f804fac..0c92bb727ea 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/detach/Detachable.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/detach/Detachable.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/loadbalancing/LoadBalancingPolicy.java b/core/src/main/java/com/datastax/oss/driver/api/core/loadbalancing/LoadBalancingPolicy.java index 425e11c0c5a..de0d9db4ebd 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/loadbalancing/LoadBalancingPolicy.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/loadbalancing/LoadBalancingPolicy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -19,22 +21,41 @@ import com.datastax.oss.driver.api.core.metadata.NodeState; import com.datastax.oss.driver.api.core.session.Request; import com.datastax.oss.driver.api.core.session.Session; +import com.datastax.oss.driver.api.core.tracker.RequestTracker; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; +import java.util.Collections; import java.util.Map; +import java.util.Optional; import java.util.Queue; import java.util.UUID; /** Decides which Cassandra nodes to contact for each query. */ public interface LoadBalancingPolicy extends AutoCloseable { + /** + * Returns an optional {@link RequestTracker} to be registered with the session. Registering a + * request tracker allows load-balancing policies to track node latencies in order to pick the + * fastest ones. + * + *

This method is invoked only once during session configuration, and before any other methods + * in this interface. Note that at this point, the driver hasn't connected to any node yet. + * + * @since 4.13.0 + */ + @NonNull + default Optional getRequestTracker() { + return Optional.empty(); + } + /** * Initializes this policy with the nodes discovered during driver initialization. * *

This method is guaranteed to be called exactly once per instance, and before any other - * method in this class. At this point, the driver has successfully connected to one of the - * contact points, and performed a first refresh of topology information (by default, the contents - * of {@code system.peers}), to discover other nodes in the cluster. + * method in this interface except {@link #getRequestTracker()}. At this point, the driver has + * successfully connected to one of the contact points, and performed a first refresh of topology + * information (by default, the contents of {@code system.peers}), to discover other nodes in the + * cluster. * *

This method must call {@link DistanceReporter#setDistance(Node, NodeDistance) * distanceReporter.setDistance} for each provided node (otherwise that node will stay at distance @@ -50,12 +71,18 @@ public interface LoadBalancingPolicy extends AutoCloseable { * @param nodes all the nodes that are known to exist in the cluster (regardless of their state) * at the time of invocation. * @param distanceReporter an object that will be used by the policy to signal distance changes. - * Implementations will typically store a this in a field, since new nodes may get {@link + * Implementations will typically store this in a field, since new nodes may get {@link * #onAdd(Node) added} later and will need to have their distance set (or the policy might * change distances dynamically over time). */ void init(@NonNull Map nodes, @NonNull DistanceReporter distanceReporter); + /** Returns map containing details that impact C* node connectivity. */ + @NonNull + default Map getStartupConfiguration() { + return Collections.emptyMap(); + } + /** * Returns the coordinators to use for a new query. * diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/loadbalancing/NodeDistance.java b/core/src/main/java/com/datastax/oss/driver/api/core/loadbalancing/NodeDistance.java index 0bff43d6a46..aaae7957d00 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/loadbalancing/NodeDistance.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/loadbalancing/NodeDistance.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/loadbalancing/NodeDistanceEvaluator.java b/core/src/main/java/com/datastax/oss/driver/api/core/loadbalancing/NodeDistanceEvaluator.java new file mode 100644 index 00000000000..9a5a7f5a894 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/api/core/loadbalancing/NodeDistanceEvaluator.java @@ -0,0 +1,54 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.api.core.loadbalancing; + +import com.datastax.oss.driver.api.core.metadata.Node; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.Nullable; + +/** + * A pluggable {@link NodeDistance} evaluator. + * + *

Node distance evaluators are recognized by all the driver built-in load balancing policies. + * They can be specified {@linkplain + * com.datastax.oss.driver.api.core.session.SessionBuilder#withNodeDistanceEvaluator(String, + * NodeDistanceEvaluator) programmatically} or through the configuration (with the {@code + * load-balancing-policy.evaluator.class} option). + * + * @see com.datastax.oss.driver.api.core.session.SessionBuilder#withNodeDistanceEvaluator(String, + * NodeDistanceEvaluator) + */ +@FunctionalInterface +public interface NodeDistanceEvaluator { + + /** + * Evaluates the distance to apply to the given node. + * + *

This method will be invoked each time the {@link LoadBalancingPolicy} processes a topology + * or state change, and will be passed the node being inspected, and the local datacenter name (or + * null if none is defined). If it returns a non-null {@link NodeDistance}, the policy will + * suggest that distance for the node; if it returns null, the policy will assign a default + * distance instead, based on its internal algorithm for computing node distances. + * + * @param node The node to assign a new distance to. + * @param localDc The local datacenter name, if defined, or null otherwise. + * @return The {@link NodeDistance} to assign to the node, or null to let the policy decide. + */ + @Nullable + NodeDistance evaluateDistance(@NonNull Node node, @Nullable String localDc); +} diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/EndPoint.java b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/EndPoint.java index 18908d90c5e..530f2ad38ac 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/EndPoint.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/EndPoint.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/Metadata.java b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/Metadata.java index 287298c44fd..21ad200abed 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/Metadata.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/Metadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/Node.java b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/Node.java index 9b67e616a5a..fbfc748dd52 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/Node.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/Node.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/NodeState.java b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/NodeState.java index 0f4667e909b..2f2460886ef 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/NodeState.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/NodeState.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/NodeStateListener.java b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/NodeStateListener.java index 3d665a3dc3d..bb52e9d1496 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/NodeStateListener.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/NodeStateListener.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -23,8 +25,9 @@ /** * A listener that gets notified when nodes states change. * - *

An implementation of this interface can be registered in the configuration, or with {@link - * SessionBuilder#withNodeStateListener(NodeStateListener)}. + *

Implementations of this interface can be registered either via the configuration (see {@code + * reference.conf} in the manual or core driver JAR), or programmatically via {@link + * SessionBuilder#addNodeStateListener(NodeStateListener)}. * *

Note that the methods defined by this interface will be executed by internal driver threads, * and are therefore expected to have short execution times. If you need to perform long @@ -33,6 +36,9 @@ * *

If you implement this interface but don't need to implement all the methods, extend {@link * NodeStateListenerBase}. + * + *

If your implementation of this interface requires access to a fully-initialized session, + * consider wrapping it in a {@link SafeInitNodeStateListener}. */ public interface NodeStateListener extends AutoCloseable { diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/NodeStateListenerBase.java b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/NodeStateListenerBase.java index 6420ee0b53f..0b747a00084 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/NodeStateListenerBase.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/NodeStateListenerBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/SafeInitNodeStateListener.java b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/SafeInitNodeStateListener.java index f75f2179a8a..c33f7616b5a 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/SafeInitNodeStateListener.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/SafeInitNodeStateListener.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -58,6 +60,9 @@ *

  • if {@code false}, they are discarded. * * + *

    Usage in non-blocking applications: beware that this class is not lock-free. It is implemented + * with locks for internal coordination. + * * @since 4.6.0 */ public class SafeInitNodeStateListener implements NodeStateListener { diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/TokenMap.java b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/TokenMap.java index 319e3e82d8f..7746bf3382e 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/TokenMap.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/TokenMap.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/AggregateMetadata.java b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/AggregateMetadata.java index acc06540225..35eec88eb45 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/AggregateMetadata.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/AggregateMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/ClusteringOrder.java b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/ClusteringOrder.java index ce50cc6ef40..97613e2d2f1 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/ClusteringOrder.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/ClusteringOrder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/ColumnMetadata.java b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/ColumnMetadata.java index 236cfd9b385..fb91211e2fa 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/ColumnMetadata.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/ColumnMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/Describable.java b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/Describable.java index 3512c9a5560..bf1bf97b19e 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/Describable.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/Describable.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/FunctionMetadata.java b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/FunctionMetadata.java index ff273c34f81..ed2d4d780de 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/FunctionMetadata.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/FunctionMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/FunctionSignature.java b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/FunctionSignature.java index 0b0638f074a..8108b4b7afd 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/FunctionSignature.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/FunctionSignature.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/IndexKind.java b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/IndexKind.java index 941b67587ba..67ac4c06a2c 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/IndexKind.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/IndexKind.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/IndexMetadata.java b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/IndexMetadata.java index 9b0e2fede9e..631a6584a27 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/IndexMetadata.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/IndexMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/KeyspaceMetadata.java b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/KeyspaceMetadata.java index 9b3461f62a8..e5080932b3c 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/KeyspaceMetadata.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/KeyspaceMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/RelationMetadata.java b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/RelationMetadata.java index 2cf5a803aa0..8b70ba04955 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/RelationMetadata.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/RelationMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/SchemaChangeListener.java b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/SchemaChangeListener.java index bfcd53b8a16..ac7317574ed 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/SchemaChangeListener.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/SchemaChangeListener.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -23,8 +25,9 @@ /** * Tracks schema changes. * - *

    An implementation of this interface can be registered in the configuration, or with {@link - * SessionBuilder#withSchemaChangeListener(SchemaChangeListener)}. + *

    Implementations of this interface can be registered either via the configuration (see {@code + * reference.conf} in the manual or core driver JAR), or programmatically via {@link + * SessionBuilder#addSchemaChangeListener(SchemaChangeListener)}. * *

    Note that the methods defined by this interface will be executed by internal driver threads, * and are therefore expected to have short execution times. If you need to perform long diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/SchemaChangeListenerBase.java b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/SchemaChangeListenerBase.java index 0d4adef2878..1cd449b39d8 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/SchemaChangeListenerBase.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/SchemaChangeListenerBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/TableMetadata.java b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/TableMetadata.java index 5f286c23787..bcda226b45d 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/TableMetadata.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/TableMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/ViewMetadata.java b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/ViewMetadata.java index 6d6b599e355..e6b06cffb97 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/ViewMetadata.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/schema/ViewMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/token/Token.java b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/token/Token.java index af41553b7b4..f39de8ec5b6 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/token/Token.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/token/Token.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/token/TokenRange.java b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/token/TokenRange.java index 740c54caebc..e384300c571 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/metadata/token/TokenRange.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/metadata/token/TokenRange.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/metrics/DefaultNodeMetric.java b/core/src/main/java/com/datastax/oss/driver/api/core/metrics/DefaultNodeMetric.java index c42fa6ca0ba..0e9934c7034 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/metrics/DefaultNodeMetric.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/metrics/DefaultNodeMetric.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/metrics/DefaultSessionMetric.java b/core/src/main/java/com/datastax/oss/driver/api/core/metrics/DefaultSessionMetric.java index b9b01cf3364..63027a23fe7 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/metrics/DefaultSessionMetric.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/metrics/DefaultSessionMetric.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/metrics/Metrics.java b/core/src/main/java/com/datastax/oss/driver/api/core/metrics/Metrics.java index 34bcc1d9c22..58d531b3464 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/metrics/Metrics.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/metrics/Metrics.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/metrics/NodeMetric.java b/core/src/main/java/com/datastax/oss/driver/api/core/metrics/NodeMetric.java index 6f7c3c8e7f6..b31c0ed8bcf 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/metrics/NodeMetric.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/metrics/NodeMetric.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -21,8 +23,9 @@ /** * A node-level metric exposed through {@link Session#getMetrics()}. * - *

    All metrics exposed out of the box by the driver are instances of {@link DefaultNodeMetric} - * (this interface only exists to allow custom metrics in driver extensions). + *

    All metrics exposed out of the box by the driver are instances of {@link DefaultNodeMetric} or + * {@link com.datastax.dse.driver.api.core.metrics.DseNodeMetric DseNodeMetric} (this interface only + * exists to allow custom metrics in driver extensions). * * @see SessionMetric */ diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/metrics/SessionMetric.java b/core/src/main/java/com/datastax/oss/driver/api/core/metrics/SessionMetric.java index 4b591e14085..2a1ee599754 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/metrics/SessionMetric.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/metrics/SessionMetric.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -22,7 +24,8 @@ * A session-level metric exposed through {@link Session#getMetrics()}. * *

    All metrics exposed out of the box by the driver are instances of {@link DefaultSessionMetric} - * (this interface only exists to allow custom metrics in driver extensions). + * or {@link com.datastax.dse.driver.api.core.metrics.DseSessionMetric DseSessionMetric} (this + * interface only exists to allow custom metrics in driver extensions). * * @see NodeMetric */ diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/package-info.java b/core/src/main/java/com/datastax/oss/driver/api/core/package-info.java index 919bdab6bd5..597b333267b 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/package-info.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/package-info.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/paging/OffsetPager.java b/core/src/main/java/com/datastax/oss/driver/api/core/paging/OffsetPager.java index 8f87a84f9d3..3cb838f3171 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/paging/OffsetPager.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/paging/OffsetPager.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/retry/RetryDecision.java b/core/src/main/java/com/datastax/oss/driver/api/core/retry/RetryDecision.java index 8859cdd6e4f..4b57b781822 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/retry/RetryDecision.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/retry/RetryDecision.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -15,7 +17,11 @@ */ package com.datastax.oss.driver.api.core.retry; -/** A decision from the {@link RetryPolicy} on how to handle a retry. */ +/** + * A decision from the {@link RetryPolicy} on how to handle a retry. + * + * @see RetryVerdict#getRetryDecision() + */ public enum RetryDecision { /** Retry the operation on the same node. */ RETRY_SAME, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/retry/RetryPolicy.java b/core/src/main/java/com/datastax/oss/driver/api/core/retry/RetryPolicy.java index e36658c9d8e..e8546816e23 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/retry/RetryPolicy.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/retry/RetryPolicy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -64,7 +66,10 @@ public interface RetryPolicy extends AutoCloseable { * {@link ReadTimeoutException#wasDataPresent()}. * @param retryCount how many times the retry policy has been invoked already for this request * (not counting the current invocation). + * @deprecated As of version 4.10, use {@link #onReadTimeoutVerdict(Request, ConsistencyLevel, + * int, int, boolean, int)} instead. */ + @Deprecated RetryDecision onReadTimeout( @NonNull Request request, @NonNull ConsistencyLevel cl, @@ -73,6 +78,34 @@ RetryDecision onReadTimeout( boolean dataPresent, int retryCount); + /** + * Whether to retry when the server replied with a {@code READ_TIMEOUT} error; this indicates a + * server-side timeout during a read query, i.e. some replicas did not reply to the + * coordinator in time. + * + * @param request the request that timed out. + * @param cl the requested consistency level. + * @param blockFor the minimum number of replica acknowledgements/responses that were required to + * fulfill the operation. + * @param received the number of replica that had acknowledged/responded to the operation before + * it failed. + * @param dataPresent whether the actual data was amongst the received replica responses. See + * {@link ReadTimeoutException#wasDataPresent()}. + * @param retryCount how many times the retry policy has been invoked already for this request + * (not counting the current invocation). + */ + default RetryVerdict onReadTimeoutVerdict( + @NonNull Request request, + @NonNull ConsistencyLevel cl, + int blockFor, + int received, + boolean dataPresent, + int retryCount) { + RetryDecision decision = + onReadTimeout(request, cl, blockFor, received, dataPresent, retryCount); + return () -> decision; + } + /** * Whether to retry when the server replied with a {@code WRITE_TIMEOUT} error; this indicates a * server-side timeout during a write query, i.e. some replicas did not reply to the @@ -92,7 +125,10 @@ RetryDecision onReadTimeout( * it failed. * @param retryCount how many times the retry policy has been invoked already for this request * (not counting the current invocation). + * @deprecated As of version 4.10, use {@link #onWriteTimeoutVerdict(Request, ConsistencyLevel, + * WriteType, int, int, int)} instead. */ + @Deprecated RetryDecision onWriteTimeout( @NonNull Request request, @NonNull ConsistencyLevel cl, @@ -101,6 +137,37 @@ RetryDecision onWriteTimeout( int received, int retryCount); + /** + * Whether to retry when the server replied with a {@code WRITE_TIMEOUT} error; this indicates a + * server-side timeout during a write query, i.e. some replicas did not reply to the + * coordinator in time. + * + *

    Note that this method will only be invoked for {@link Request#isIdempotent()} idempotent} + * requests: when a write times out, it is impossible to determine with 100% certainty whether the + * mutation was applied or not, so the write is never safe to retry; the driver will rethrow the + * error directly, without invoking the retry policy. + * + * @param request the request that timed out. + * @param cl the requested consistency level. + * @param writeType the type of the write for which the timeout was raised. + * @param blockFor the minimum number of replica acknowledgements/responses that were required to + * fulfill the operation. + * @param received the number of replica that had acknowledged/responded to the operation before + * it failed. + * @param retryCount how many times the retry policy has been invoked already for this request + * (not counting the current invocation). + */ + default RetryVerdict onWriteTimeoutVerdict( + @NonNull Request request, + @NonNull ConsistencyLevel cl, + @NonNull WriteType writeType, + int blockFor, + int received, + int retryCount) { + RetryDecision decision = onWriteTimeout(request, cl, writeType, blockFor, received, retryCount); + return () -> decision; + } + /** * Whether to retry when the server replied with an {@code UNAVAILABLE} error; this indicates that * the coordinator determined that there were not enough replicas alive to perform a query with @@ -114,7 +181,10 @@ RetryDecision onWriteTimeout( * tried to execute the operation. * @param retryCount how many times the retry policy has been invoked already for this request * (not counting the current invocation). + * @deprecated As of version 4.10, use {@link #onUnavailableVerdict(Request, ConsistencyLevel, + * int, int, int)} instead. */ + @Deprecated RetryDecision onUnavailable( @NonNull Request request, @NonNull ConsistencyLevel cl, @@ -122,6 +192,30 @@ RetryDecision onUnavailable( int alive, int retryCount); + /** + * Whether to retry when the server replied with an {@code UNAVAILABLE} error; this indicates that + * the coordinator determined that there were not enough replicas alive to perform a query with + * the requested consistency level. + * + * @param request the request that timed out. + * @param cl the requested consistency level. + * @param required the number of replica acknowledgements/responses required to perform the + * operation (with its required consistency level). + * @param alive the number of replicas that were known to be alive by the coordinator node when it + * tried to execute the operation. + * @param retryCount how many times the retry policy has been invoked already for this request + * (not counting the current invocation). + */ + default RetryVerdict onUnavailableVerdict( + @NonNull Request request, + @NonNull ConsistencyLevel cl, + int required, + int alive, + int retryCount) { + RetryDecision decision = onUnavailable(request, cl, required, alive, retryCount); + return () -> decision; + } + /** * Whether to retry when a request was aborted before we could get a response from the server. * @@ -139,10 +233,37 @@ RetryDecision onUnavailable( * @param error the error. * @param retryCount how many times the retry policy has been invoked already for this request * (not counting the current invocation). + * @deprecated As of version 4.10, use {@link #onRequestAbortedVerdict(Request, Throwable, int)} + * instead. */ + @Deprecated RetryDecision onRequestAborted( @NonNull Request request, @NonNull Throwable error, int retryCount); + /** + * Whether to retry when a request was aborted before we could get a response from the server. + * + *

    This can happen in two cases: if the connection was closed due to an external event (this + * will manifest as a {@link ClosedConnectionException}, or {@link HeartbeatException} for a + * heartbeat failure); or if there was an unexpected error while decoding the response (this can + * only be a driver bug). + * + *

    Note that this method will only be invoked for {@linkplain Request#isIdempotent() + * idempotent} requests: when execution was aborted before getting a response, it is impossible to + * determine with 100% certainty whether a mutation was applied or not, so a write is never safe + * to retry; the driver will rethrow the error directly, without invoking the retry policy. + * + * @param request the request that was aborted. + * @param error the error. + * @param retryCount how many times the retry policy has been invoked already for this request + * (not counting the current invocation). + */ + default RetryVerdict onRequestAbortedVerdict( + @NonNull Request request, @NonNull Throwable error, int retryCount) { + RetryDecision decision = onRequestAborted(request, error, retryCount); + return () -> decision; + } + /** * Whether to retry when the server replied with a recoverable error (other than {@code * READ_TIMEOUT}, {@code WRITE_TIMEOUT} or {@code UNAVAILABLE}). @@ -168,10 +289,45 @@ RetryDecision onRequestAborted( * @param error the error. * @param retryCount how many times the retry policy has been invoked already for this request * (not counting the current invocation). + * @deprecated As of version 4.10, use {@link #onErrorResponseVerdict(Request, + * CoordinatorException, int)} instead. */ + @Deprecated RetryDecision onErrorResponse( @NonNull Request request, @NonNull CoordinatorException error, int retryCount); + /** + * Whether to retry when the server replied with a recoverable error (other than {@code + * READ_TIMEOUT}, {@code WRITE_TIMEOUT} or {@code UNAVAILABLE}). + * + *

    This can happen for the following errors: {@link OverloadedException}, {@link ServerError}, + * {@link TruncateException}, {@link ReadFailureException}, {@link WriteFailureException}. + * + *

    The following errors are handled internally by the driver, and therefore will never + * be encountered in this method: + * + *

      + *
    • {@link BootstrappingException}: always retried on the next node; + *
    • {@link QueryValidationException} (and its subclasses), {@link FunctionFailureException} + * and {@link ProtocolError}: always rethrown. + *
    + * + *

    Note that this method will only be invoked for {@link Request#isIdempotent()} idempotent} + * requests: when execution was aborted before getting a response, it is impossible to determine + * with 100% certainty whether a mutation was applied or not, so a write is never safe to retry; + * the driver will rethrow the error directly, without invoking the retry policy. + * + * @param request the request that failed. + * @param error the error. + * @param retryCount how many times the retry policy has been invoked already for this request + * (not counting the current invocation). + */ + default RetryVerdict onErrorResponseVerdict( + @NonNull Request request, @NonNull CoordinatorException error, int retryCount) { + RetryDecision decision = onErrorResponse(request, error, retryCount); + return () -> decision; + } + /** Called when the cluster that this policy is associated with closes. */ @Override void close(); diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/retry/RetryVerdict.java b/core/src/main/java/com/datastax/oss/driver/api/core/retry/RetryVerdict.java new file mode 100644 index 00000000000..9abb54156db --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/api/core/retry/RetryVerdict.java @@ -0,0 +1,63 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.api.core.retry; + +import com.datastax.oss.driver.api.core.session.Request; +import com.datastax.oss.driver.internal.core.retry.DefaultRetryVerdict; +import edu.umd.cs.findbugs.annotations.NonNull; + +/** + * The verdict returned by a {@link RetryPolicy} determining what to do when a request failed. A + * verdict contains a {@link RetryDecision} indicating if a retry should be attempted at all and + * where, and a method that allows the original request to be modified before the retry. + */ +@FunctionalInterface +public interface RetryVerdict { + + /** A retry verdict that retries the same request on the same node. */ + RetryVerdict RETRY_SAME = new DefaultRetryVerdict(RetryDecision.RETRY_SAME); + + /** A retry verdict that retries the same request on the next node in the query plan. */ + RetryVerdict RETRY_NEXT = new DefaultRetryVerdict(RetryDecision.RETRY_NEXT); + + /** A retry verdict that ignores the error, returning and empty result set to the caller. */ + RetryVerdict IGNORE = new DefaultRetryVerdict(RetryDecision.IGNORE); + + /** A retry verdict that rethrows the execution error to the calling code. */ + RetryVerdict RETHROW = new DefaultRetryVerdict(RetryDecision.RETHROW); + + /** @return The retry decision to apply. */ + @NonNull + RetryDecision getRetryDecision(); + + /** + * Returns the request to retry, based on the request that was just executed (and failed). + * + *

    The default retry policy always returns the request as is. Custom retry policies can use + * this method to customize the request to retry, for example, by changing its consistency level, + * query timestamp, custom payload, or even its execution profile. + * + * @param The actual type of the request. + * @param previous The request that was just executed (and failed). + * @return The request to retry. + */ + @NonNull + default RequestT getRetryRequest(@NonNull RequestT previous) { + return previous; + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/AlreadyExistsException.java b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/AlreadyExistsException.java index 7128c8c2d4f..2bf541c91de 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/AlreadyExistsException.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/AlreadyExistsException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/BootstrappingException.java b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/BootstrappingException.java index bd96aff1518..a408e0384f5 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/BootstrappingException.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/BootstrappingException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/CASWriteUnknownException.java b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/CASWriteUnknownException.java new file mode 100644 index 00000000000..477bf7813c9 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/CASWriteUnknownException.java @@ -0,0 +1,86 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.api.core.servererrors; + +import com.datastax.oss.driver.api.core.AllNodesFailedException; +import com.datastax.oss.driver.api.core.ConsistencyLevel; +import com.datastax.oss.driver.api.core.DriverException; +import com.datastax.oss.driver.api.core.cql.ExecutionInfo; +import com.datastax.oss.driver.api.core.metadata.Node; +import com.datastax.oss.driver.api.core.retry.RetryPolicy; +import com.datastax.oss.driver.api.core.session.Request; +import edu.umd.cs.findbugs.annotations.NonNull; + +/** + * The result of a CAS operation is in an unknown state. + * + *

    This exception is processed by {@link RetryPolicy#onErrorResponseVerdict(Request, + * CoordinatorException, int)} , which will decide if it is rethrown directly to the client or if + * the request should be retried. If all other tried nodes also fail, this exception will appear in + * the {@link AllNodesFailedException} thrown to the client. + */ +public class CASWriteUnknownException extends QueryConsistencyException { + + public CASWriteUnknownException( + @NonNull Node coordinator, + @NonNull ConsistencyLevel consistencyLevel, + int received, + int blockFor) { + this( + coordinator, + String.format( + "CAS operation result is unknown - proposal was not accepted by a quorum. (%d / %d)", + received, blockFor), + consistencyLevel, + received, + blockFor, + null, + false); + } + + private CASWriteUnknownException( + @NonNull Node coordinator, + @NonNull String message, + @NonNull ConsistencyLevel consistencyLevel, + int received, + int blockFor, + ExecutionInfo executionInfo, + boolean writableStackTrace) { + super( + coordinator, + message, + consistencyLevel, + received, + blockFor, + executionInfo, + writableStackTrace); + } + + @NonNull + @Override + public DriverException copy() { + return new CASWriteUnknownException( + getCoordinator(), + getMessage(), + getConsistencyLevel(), + getReceived(), + getBlockFor(), + getExecutionInfo(), + true); + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/CDCWriteFailureException.java b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/CDCWriteFailureException.java new file mode 100644 index 00000000000..3ce782653ab --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/CDCWriteFailureException.java @@ -0,0 +1,60 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.api.core.servererrors; + +import com.datastax.oss.driver.api.core.AllNodesFailedException; +import com.datastax.oss.driver.api.core.DriverException; +import com.datastax.oss.driver.api.core.cql.ExecutionInfo; +import com.datastax.oss.driver.api.core.metadata.Node; +import com.datastax.oss.driver.api.core.retry.RetryPolicy; +import com.datastax.oss.driver.api.core.session.Request; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.Nullable; + +/** + * An attempt was made to write to a commitlog segment which doesn't support CDC mutations. + * + *

    This exception is processed by {@link RetryPolicy#onErrorResponseVerdict(Request, + * CoordinatorException, int)}, which will decide if it is rethrown directly to the client or if the + * request should be retried. If all other tried nodes also fail, this exception will appear in the + * {@link AllNodesFailedException} thrown to the client. + */ +public class CDCWriteFailureException extends QueryExecutionException { + + public CDCWriteFailureException(@NonNull Node coordinator) { + super(coordinator, "Commitlog does not support CDC mutations", null, false); + } + + public CDCWriteFailureException(@NonNull Node coordinator, @NonNull String message) { + super(coordinator, "Commitlog does not support CDC mutations", null, false); + } + + private CDCWriteFailureException( + @NonNull Node coordinator, + @NonNull String message, + @Nullable ExecutionInfo executionInfo, + boolean writableStackTrace) { + super(coordinator, message, executionInfo, writableStackTrace); + } + + @NonNull + @Override + public DriverException copy() { + return new CDCWriteFailureException(getCoordinator(), getMessage(), getExecutionInfo(), true); + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/CoordinatorException.java b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/CoordinatorException.java index 975d7252747..8f6052850df 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/CoordinatorException.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/CoordinatorException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/DefaultWriteType.java b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/DefaultWriteType.java index dc12e937aa8..a24097e6e5b 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/DefaultWriteType.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/DefaultWriteType.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/FunctionFailureException.java b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/FunctionFailureException.java index 1a9b178d0fe..31993762319 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/FunctionFailureException.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/FunctionFailureException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/InvalidConfigurationInQueryException.java b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/InvalidConfigurationInQueryException.java index 900d9c281ed..405efa47299 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/InvalidConfigurationInQueryException.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/InvalidConfigurationInQueryException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/InvalidQueryException.java b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/InvalidQueryException.java index bbf50a5b5fb..468de8a1bd0 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/InvalidQueryException.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/InvalidQueryException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/OverloadedException.java b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/OverloadedException.java index 4b7b4bb6d9a..f56a7f30a7e 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/OverloadedException.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/OverloadedException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -27,7 +29,7 @@ /** * Thrown when the coordinator reported itself as being overloaded. * - *

    This exception is processed by {@link RetryPolicy#onErrorResponse(Request, + *

    This exception is processed by {@link RetryPolicy#onErrorResponseVerdict(Request, * CoordinatorException, int)}, which will decide if it is rethrown directly to the client or if the * request should be retried. If all other tried nodes also fail, this exception will appear in the * {@link AllNodesFailedException} thrown to the client. @@ -35,7 +37,11 @@ public class OverloadedException extends QueryExecutionException { public OverloadedException(@NonNull Node coordinator) { - super(coordinator, String.format("%s is bootstrapping", coordinator), null, false); + super(coordinator, String.format("%s is overloaded", coordinator), null, false); + } + + public OverloadedException(@NonNull Node coordinator, @NonNull String message) { + super(coordinator, String.format("%s is overloaded: %s", coordinator, message), null, false); } private OverloadedException( diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/ProtocolError.java b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/ProtocolError.java index 813bfa6cae9..898a857954f 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/ProtocolError.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/ProtocolError.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/QueryConsistencyException.java b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/QueryConsistencyException.java index 67c4fcd9ca0..4a6f97f3342 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/QueryConsistencyException.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/QueryConsistencyException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/QueryExecutionException.java b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/QueryExecutionException.java index a23d9d9dca7..541a32d9fba 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/QueryExecutionException.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/QueryExecutionException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/QueryValidationException.java b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/QueryValidationException.java index 448a6026892..9c8dfe537b6 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/QueryValidationException.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/QueryValidationException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/ReadFailureException.java b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/ReadFailureException.java index adecf20ccbe..94c4404f8d9 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/ReadFailureException.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/ReadFailureException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -33,7 +35,7 @@ *

    This happens when some of the replicas that were contacted by the coordinator replied with an * error. * - *

    This exception is processed by {@link RetryPolicy#onErrorResponse(Request, + *

    This exception is processed by {@link RetryPolicy#onErrorResponseVerdict(Request, * CoordinatorException, int)}, which will decide if it is rethrown directly to the client or if the * request should be retried. If all other tried nodes also fail, this exception will appear in the * {@link AllNodesFailedException} thrown to the client. diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/ReadTimeoutException.java b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/ReadTimeoutException.java index 1d199a695eb..4dddfedf49a 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/ReadTimeoutException.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/ReadTimeoutException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -27,10 +29,10 @@ /** * A server-side timeout during a read query. * - *

    This exception is processed by {@link RetryPolicy#onReadTimeout(Request, ConsistencyLevel, - * int, int, boolean, int)}, which will decide if it is rethrown directly to the client or if the - * request should be retried. If all other tried nodes also fail, this exception will appear in the - * {@link AllNodesFailedException} thrown to the client. + *

    This exception is processed by {@link RetryPolicy#onReadTimeoutVerdict(Request, + * ConsistencyLevel, int, int, boolean, int)}, which will decide if it is rethrown directly to the + * client or if the request should be retried. If all other tried nodes also fail, this exception + * will appear in the {@link AllNodesFailedException} thrown to the client. */ public class ReadTimeoutException extends QueryConsistencyException { @@ -45,7 +47,8 @@ public ReadTimeoutException( this( coordinator, String.format( - "Cassandra timeout during read query at consistency %s (%s)", + "Cassandra timeout during read query at consistency %s (%s). " + + "In case this was generated during read repair, the consistency level is not representative of the actual consistency.", consistencyLevel, formatDetails(received, blockFor, dataPresent)), consistencyLevel, received, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/ServerError.java b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/ServerError.java index 9afe5ea45b3..de300803421 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/ServerError.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/ServerError.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -29,7 +31,7 @@ * *

    This should be considered as a server bug and reported as such. * - *

    This exception is processed by {@link RetryPolicy#onErrorResponse(Request, + *

    This exception is processed by {@link RetryPolicy#onErrorResponseVerdict(Request, * CoordinatorException, int)}, which will decide if it is rethrown directly to the client or if the * request should be retried. If all other tried nodes also fail, this exception will appear in the * {@link AllNodesFailedException} thrown to the client. diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/SyntaxError.java b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/SyntaxError.java index 32c5e930741..708068c0299 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/SyntaxError.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/SyntaxError.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/TruncateException.java b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/TruncateException.java index 12f265e135d..2091d166e98 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/TruncateException.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/TruncateException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -27,7 +29,7 @@ /** * An error during a truncation operation. * - *

    This exception is processed by {@link RetryPolicy#onErrorResponse(Request, + *

    This exception is processed by {@link RetryPolicy#onErrorResponseVerdict(Request, * CoordinatorException, int)}, which will decide if it is rethrown directly to the client or if the * request should be retried. If all other tried nodes also fail, this exception will appear in the * {@link AllNodesFailedException} thrown to the client. diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/UnauthorizedException.java b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/UnauthorizedException.java index e15ab02dc4b..7a6235422de 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/UnauthorizedException.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/UnauthorizedException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/UnavailableException.java b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/UnavailableException.java index 98e119791d8..b9e9848ce36 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/UnavailableException.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/UnavailableException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -28,10 +30,10 @@ * Thrown when the coordinator knows there is not enough replicas alive to perform a query with the * requested consistency level. * - *

    This exception is processed by {@link RetryPolicy#onUnavailable(Request, ConsistencyLevel, - * int, int, int)}, which will decide if it is rethrown directly to the client or if the request - * should be retried. If all other tried nodes also fail, this exception will appear in the {@link - * AllNodesFailedException} thrown to the client. + *

    This exception is processed by {@link RetryPolicy#onUnavailableVerdict(Request, + * ConsistencyLevel, int, int, int)}, which will decide if it is rethrown directly to the client or + * if the request should be retried. If all other tried nodes also fail, this exception will appear + * in the {@link AllNodesFailedException} thrown to the client. */ public class UnavailableException extends QueryExecutionException { private final ConsistencyLevel consistencyLevel; diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/WriteFailureException.java b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/WriteFailureException.java index f2589ff1b65..ffbbd2aef6f 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/WriteFailureException.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/WriteFailureException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -33,7 +35,7 @@ *

    This happens when some of the replicas that were contacted by the coordinator replied with an * error. * - *

    This exception is processed by {@link RetryPolicy#onErrorResponse(Request, + *

    This exception is processed by {@link RetryPolicy#onErrorResponseVerdict(Request, * CoordinatorException, int)}, which will decide if it is rethrown directly to the client or if the * request should be retried. If all other tried nodes also fail, this exception will appear in the * {@link AllNodesFailedException} thrown to the client. diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/WriteTimeoutException.java b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/WriteTimeoutException.java index 600b5e36895..9913dbd0a91 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/WriteTimeoutException.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/WriteTimeoutException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -28,10 +30,10 @@ /** * A server-side timeout during a write query. * - *

    This exception is processed by {@link RetryPolicy#onWriteTimeout(Request, ConsistencyLevel, - * WriteType, int, int, int)}, which will decide if it is rethrown directly to the client or if the - * request should be retried. If all other tried nodes also fail, this exception will appear in the - * {@link AllNodesFailedException} thrown to the client. + *

    This exception is processed by {@link RetryPolicy#onWriteTimeoutVerdict(Request, + * ConsistencyLevel, WriteType, int, int, int)}, which will decide if it is rethrown directly to the + * client or if the request should be retried. If all other tried nodes also fail, this exception + * will appear in the {@link AllNodesFailedException} thrown to the client. */ public class WriteTimeoutException extends QueryConsistencyException { diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/WriteType.java b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/WriteType.java index c64a301d5af..05ad99e5ce4 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/WriteType.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/servererrors/WriteType.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/session/ProgrammaticArguments.java b/core/src/main/java/com/datastax/oss/driver/api/core/session/ProgrammaticArguments.java index 6d693f69b72..5e10fb4d915 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/session/ProgrammaticArguments.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/session/ProgrammaticArguments.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,13 +18,19 @@ package com.datastax.oss.driver.api.core.session; import com.datastax.oss.driver.api.core.auth.AuthProvider; +import com.datastax.oss.driver.api.core.loadbalancing.NodeDistanceEvaluator; import com.datastax.oss.driver.api.core.metadata.Node; import com.datastax.oss.driver.api.core.metadata.NodeStateListener; import com.datastax.oss.driver.api.core.metadata.schema.SchemaChangeListener; import com.datastax.oss.driver.api.core.ssl.SslEngineFactory; +import com.datastax.oss.driver.api.core.tracker.RequestIdGenerator; import com.datastax.oss.driver.api.core.tracker.RequestTracker; import com.datastax.oss.driver.api.core.type.codec.TypeCodec; import com.datastax.oss.driver.api.core.type.codec.registry.MutableCodecRegistry; +import com.datastax.oss.driver.internal.core.loadbalancing.helper.NodeFilterToDistanceEvaluatorAdapter; +import com.datastax.oss.driver.internal.core.metadata.MultiplexingNodeStateListener; +import com.datastax.oss.driver.internal.core.metadata.schema.MultiplexingSchemaChangeListener; +import com.datastax.oss.driver.internal.core.tracker.MultiplexingRequestTracker; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableList; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap; import edu.umd.cs.findbugs.annotations.NonNull; @@ -30,6 +38,8 @@ import java.net.InetSocketAddress; import java.util.List; import java.util.Map; +import java.util.Map.Entry; +import java.util.Objects; import java.util.UUID; import java.util.function.Predicate; @@ -50,8 +60,10 @@ public static Builder builder() { private final NodeStateListener nodeStateListener; private final SchemaChangeListener schemaChangeListener; private final RequestTracker requestTracker; + private final RequestIdGenerator requestIdGenerator; private final Map localDatacenters; private final Map> nodeFilters; + private final Map nodeDistanceEvaluators; private final ClassLoader classLoader; private final AuthProvider authProvider; private final SslEngineFactory sslEngineFactory; @@ -67,8 +79,10 @@ private ProgrammaticArguments( @Nullable NodeStateListener nodeStateListener, @Nullable SchemaChangeListener schemaChangeListener, @Nullable RequestTracker requestTracker, + @Nullable RequestIdGenerator requestIdGenerator, @NonNull Map localDatacenters, @NonNull Map> nodeFilters, + @NonNull Map nodeDistanceEvaluators, @Nullable ClassLoader classLoader, @Nullable AuthProvider authProvider, @Nullable SslEngineFactory sslEngineFactory, @@ -83,8 +97,10 @@ private ProgrammaticArguments( this.nodeStateListener = nodeStateListener; this.schemaChangeListener = schemaChangeListener; this.requestTracker = requestTracker; + this.requestIdGenerator = requestIdGenerator; this.localDatacenters = localDatacenters; this.nodeFilters = nodeFilters; + this.nodeDistanceEvaluators = nodeDistanceEvaluators; this.classLoader = classLoader; this.authProvider = authProvider; this.sslEngineFactory = sslEngineFactory; @@ -116,16 +132,28 @@ public RequestTracker getRequestTracker() { return requestTracker; } + @Nullable + public RequestIdGenerator getRequestIdGenerator() { + return requestIdGenerator; + } + @NonNull public Map getLocalDatacenters() { return localDatacenters; } @NonNull + @Deprecated + @SuppressWarnings("DeprecatedIsStillUsed") public Map> getNodeFilters() { return nodeFilters; } + @NonNull + public Map getNodeDistanceEvaluators() { + return nodeDistanceEvaluators; + } + @Nullable public ClassLoader getClassLoader() { return classLoader; @@ -173,13 +201,16 @@ public Object getMetricRegistry() { public static class Builder { - private ImmutableList.Builder> typeCodecsBuilder = ImmutableList.builder(); + private final ImmutableList.Builder> typeCodecsBuilder = ImmutableList.builder(); private NodeStateListener nodeStateListener; private SchemaChangeListener schemaChangeListener; private RequestTracker requestTracker; + private RequestIdGenerator requestIdGenerator; private ImmutableMap.Builder localDatacentersBuilder = ImmutableMap.builder(); - private ImmutableMap.Builder> nodeFiltersBuilder = + private final ImmutableMap.Builder> nodeFiltersBuilder = ImmutableMap.builder(); + private final ImmutableMap.Builder + nodeDistanceEvaluatorsBuilder = ImmutableMap.builder(); private ClassLoader classLoader; private AuthProvider authProvider; private SslEngineFactory sslEngineFactory; @@ -202,18 +233,83 @@ public Builder withNodeStateListener(@Nullable NodeStateListener nodeStateListen return this; } + @NonNull + public Builder addNodeStateListener(@NonNull NodeStateListener nodeStateListener) { + Objects.requireNonNull(nodeStateListener, "nodeStateListener cannot be null"); + if (this.nodeStateListener == null) { + this.nodeStateListener = nodeStateListener; + } else { + NodeStateListener previousListener = this.nodeStateListener; + if (previousListener instanceof MultiplexingNodeStateListener) { + ((MultiplexingNodeStateListener) previousListener).register(nodeStateListener); + } else { + MultiplexingNodeStateListener multiplexingNodeStateListener = + new MultiplexingNodeStateListener(); + multiplexingNodeStateListener.register(previousListener); + multiplexingNodeStateListener.register(nodeStateListener); + this.nodeStateListener = multiplexingNodeStateListener; + } + } + return this; + } + @NonNull public Builder withSchemaChangeListener(@Nullable SchemaChangeListener schemaChangeListener) { this.schemaChangeListener = schemaChangeListener; return this; } + @NonNull + public Builder addSchemaChangeListener(@NonNull SchemaChangeListener schemaChangeListener) { + Objects.requireNonNull(schemaChangeListener, "schemaChangeListener cannot be null"); + if (this.schemaChangeListener == null) { + this.schemaChangeListener = schemaChangeListener; + } else { + SchemaChangeListener previousListener = this.schemaChangeListener; + if (previousListener instanceof MultiplexingSchemaChangeListener) { + ((MultiplexingSchemaChangeListener) previousListener).register(schemaChangeListener); + } else { + MultiplexingSchemaChangeListener multiplexingSchemaChangeListener = + new MultiplexingSchemaChangeListener(); + multiplexingSchemaChangeListener.register(previousListener); + multiplexingSchemaChangeListener.register(schemaChangeListener); + this.schemaChangeListener = multiplexingSchemaChangeListener; + } + } + return this; + } + @NonNull public Builder withRequestTracker(@Nullable RequestTracker requestTracker) { this.requestTracker = requestTracker; return this; } + @NonNull + public Builder addRequestTracker(@NonNull RequestTracker requestTracker) { + Objects.requireNonNull(requestTracker, "requestTracker cannot be null"); + if (this.requestTracker == null) { + this.requestTracker = requestTracker; + } else { + RequestTracker previousTracker = this.requestTracker; + if (previousTracker instanceof MultiplexingRequestTracker) { + ((MultiplexingRequestTracker) previousTracker).register(requestTracker); + } else { + MultiplexingRequestTracker multiplexingRequestTracker = new MultiplexingRequestTracker(); + multiplexingRequestTracker.register(previousTracker); + multiplexingRequestTracker.register(requestTracker); + this.requestTracker = multiplexingRequestTracker; + } + } + return this; + } + + @NonNull + public Builder withRequestIdGenerator(@Nullable RequestIdGenerator requestIdGenerator) { + this.requestIdGenerator = requestIdGenerator; + return this; + } + @NonNull public Builder withLocalDatacenter( @NonNull String profileName, @NonNull String localDatacenter) { @@ -236,16 +332,42 @@ public Builder withLocalDatacenters(Map localDatacenters) { } @NonNull + public Builder withNodeDistanceEvaluator( + @NonNull String profileName, @NonNull NodeDistanceEvaluator nodeDistanceEvaluator) { + this.nodeDistanceEvaluatorsBuilder.put(profileName, nodeDistanceEvaluator); + return this; + } + + @NonNull + public Builder withNodeDistanceEvaluators( + Map nodeDistanceReporters) { + for (Entry entry : nodeDistanceReporters.entrySet()) { + this.nodeDistanceEvaluatorsBuilder.put(entry.getKey(), entry.getValue()); + } + return this; + } + + /** + * @deprecated Use {@link #withNodeDistanceEvaluator(String, NodeDistanceEvaluator)} instead. + */ + @NonNull + @Deprecated public Builder withNodeFilter( @NonNull String profileName, @NonNull Predicate nodeFilter) { this.nodeFiltersBuilder.put(profileName, nodeFilter); + this.nodeDistanceEvaluatorsBuilder.put( + profileName, new NodeFilterToDistanceEvaluatorAdapter(nodeFilter)); return this; } + /** @deprecated Use {@link #withNodeDistanceEvaluators(Map)} instead. */ @NonNull + @Deprecated public Builder withNodeFilters(Map> nodeFilters) { for (Map.Entry> entry : nodeFilters.entrySet()) { this.nodeFiltersBuilder.put(entry.getKey(), entry.getValue()); + this.nodeDistanceEvaluatorsBuilder.put( + entry.getKey(), new NodeFilterToDistanceEvaluatorAdapter(entry.getValue())); } return this; } @@ -311,8 +433,10 @@ public ProgrammaticArguments build() { nodeStateListener, schemaChangeListener, requestTracker, + requestIdGenerator, localDatacentersBuilder.build(), nodeFiltersBuilder.build(), + nodeDistanceEvaluatorsBuilder.build(), classLoader, authProvider, sslEngineFactory, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/session/Request.java b/core/src/main/java/com/datastax/oss/driver/api/core/session/Request.java index b10bd74b4c6..7d122276cbf 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/session/Request.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/session/Request.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/session/Session.java b/core/src/main/java/com/datastax/oss/driver/api/core/session/Session.java index a4157c48b4a..e047bf2fe09 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/session/Session.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/session/Session.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/session/SessionBuilder.java b/core/src/main/java/com/datastax/oss/driver/api/core/session/SessionBuilder.java index f4bab46022e..25500119047 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/session/SessionBuilder.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/session/SessionBuilder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -19,24 +21,26 @@ import com.datastax.oss.driver.api.core.CqlSession; import com.datastax.oss.driver.api.core.auth.AuthProvider; import com.datastax.oss.driver.api.core.auth.PlainTextAuthProviderBase; +import com.datastax.oss.driver.api.core.auth.ProgrammaticPlainTextAuthProvider; import com.datastax.oss.driver.api.core.config.DefaultDriverOption; import com.datastax.oss.driver.api.core.config.DriverConfig; import com.datastax.oss.driver.api.core.config.DriverConfigLoader; import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; import com.datastax.oss.driver.api.core.context.DriverContext; import com.datastax.oss.driver.api.core.loadbalancing.LoadBalancingPolicy; +import com.datastax.oss.driver.api.core.loadbalancing.NodeDistanceEvaluator; import com.datastax.oss.driver.api.core.metadata.EndPoint; import com.datastax.oss.driver.api.core.metadata.Node; import com.datastax.oss.driver.api.core.metadata.NodeStateListener; import com.datastax.oss.driver.api.core.metadata.schema.SchemaChangeListener; import com.datastax.oss.driver.api.core.ssl.ProgrammaticSslEngineFactory; import com.datastax.oss.driver.api.core.ssl.SslEngineFactory; +import com.datastax.oss.driver.api.core.tracker.RequestIdGenerator; import com.datastax.oss.driver.api.core.tracker.RequestTracker; import com.datastax.oss.driver.api.core.type.codec.TypeCodec; import com.datastax.oss.driver.api.core.type.codec.registry.MutableCodecRegistry; import com.datastax.oss.driver.api.core.uuid.Uuids; import com.datastax.oss.driver.internal.core.ContactPoints; -import com.datastax.oss.driver.internal.core.auth.ProgrammaticPlainTextAuthProvider; import com.datastax.oss.driver.internal.core.config.cloud.CloudConfig; import com.datastax.oss.driver.internal.core.config.cloud.CloudConfigFactory; import com.datastax.oss.driver.internal.core.config.typesafe.DefaultDriverConfigLoader; @@ -44,6 +48,7 @@ import com.datastax.oss.driver.internal.core.context.InternalDriverContext; import com.datastax.oss.driver.internal.core.metadata.DefaultEndPoint; import com.datastax.oss.driver.internal.core.session.DefaultSession; +import com.datastax.oss.driver.internal.core.tracker.W3CContextRequestIdGenerator; import com.datastax.oss.driver.internal.core.util.concurrent.BlockingOperation; import com.datastax.oss.driver.internal.core.util.concurrent.CompletableFutures; import edu.umd.cs.findbugs.annotations.NonNull; @@ -80,6 +85,8 @@ @NotThreadSafe public abstract class SessionBuilder { + public static final String ASTRA_PAYLOAD_KEY = "traceparent"; + private static final Logger LOG = LoggerFactory.getLogger(SessionBuilder.class); @SuppressWarnings("unchecked") @@ -219,8 +226,11 @@ public SelfT addTypeCodecs(@NonNull TypeCodec... typeCodecs) { /** * Registers a node state listener to use with the session. * - *

    If the listener is specified programmatically with this method, it overrides the - * configuration (that is, the {@code metadata.node-state-listener.class} option will be ignored). + *

    Listeners can be registered in two ways: either programmatically with this method, or via + * the configuration using the {@code advanced.metadata.node-state-listener.classes} option. + * + *

    This method unregisters any previously-registered listener. If you intend to register more + * than one listener, use {@link #addNodeStateListener(NodeStateListener)} instead. */ @NonNull public SelfT withNodeStateListener(@Nullable NodeStateListener nodeStateListener) { @@ -228,12 +238,32 @@ public SelfT withNodeStateListener(@Nullable NodeStateListener nodeStateListener return self; } + /** + * Registers a node state listener to use with the session, without removing previously-registered + * listeners. + * + *

    Listeners can be registered in two ways: either programmatically with this method, or via + * the configuration using the {@code advanced.metadata.node-state-listener.classes} option. + * + *

    Unlike {@link #withNodeStateListener(NodeStateListener)}, this method adds the new listener + * to the list of already-registered listeners, thus allowing applications to register multiple + * listeners. When multiple listeners are registered, they are notified in sequence every time a + * new listener event is triggered. + */ + @NonNull + public SelfT addNodeStateListener(@NonNull NodeStateListener nodeStateListener) { + programmaticArgumentsBuilder.addNodeStateListener(nodeStateListener); + return self; + } + /** * Registers a schema change listener to use with the session. * - *

    If the listener is specified programmatically with this method, it overrides the - * configuration (that is, the {@code metadata.schema-change-listener.class} option will be - * ignored). + *

    Listeners can be registered in two ways: either programmatically with this method, or via + * the configuration using the {@code advanced.metadata.schema-change-listener.classes} option. + * + *

    This method unregisters any previously-registered listener. If you intend to register more + * than one listener, use {@link #addSchemaChangeListener(SchemaChangeListener)} instead. */ @NonNull public SelfT withSchemaChangeListener(@Nullable SchemaChangeListener schemaChangeListener) { @@ -241,11 +271,32 @@ public SelfT withSchemaChangeListener(@Nullable SchemaChangeListener schemaChang return self; } + /** + * Registers a schema change listener to use with the session, without removing + * previously-registered listeners. + * + *

    Listeners can be registered in two ways: either programmatically with this method, or via + * the configuration using the {@code advanced.metadata.schema-change-listener.classes} option. + * + *

    Unlike {@link #withSchemaChangeListener(SchemaChangeListener)}, this method adds the new + * listener to the list of already-registered listeners, thus allowing applications to register + * multiple listeners. When multiple listeners are registered, they are notified in sequence every + * time a new listener event is triggered. + */ + @NonNull + public SelfT addSchemaChangeListener(@NonNull SchemaChangeListener schemaChangeListener) { + programmaticArgumentsBuilder.addSchemaChangeListener(schemaChangeListener); + return self; + } + /** * Registers a request tracker to use with the session. * - *

    If the tracker is specified programmatically with this method, it overrides the - * configuration (that is, the {@code request.tracker.class} option will be ignored). + *

    Trackers can be registered in two ways: either programmatically with this method, or via the + * configuration using the {@code advanced.request-tracker.classes} option. + * + *

    This method unregisters any previously-registered tracker. If you intend to register more + * than one tracker, use {@link #addRequestTracker(RequestTracker)} instead. */ @NonNull public SelfT withRequestTracker(@Nullable RequestTracker requestTracker) { @@ -253,6 +304,35 @@ public SelfT withRequestTracker(@Nullable RequestTracker requestTracker) { return self; } + /** + * Registers a request tracker to use with the session, without removing previously-registered + * trackers. + * + *

    Trackers can be registered in two ways: either programmatically with this method, or via the + * configuration using the {@code advanced.request-tracker.classes} option. + * + *

    Unlike {@link #withRequestTracker(RequestTracker)}, this method adds the new tracker to the + * list of already-registered trackers, thus allowing applications to register multiple trackers. + * When multiple trackers are registered, they are notified in sequence every time a new tracker + * event is triggered. + */ + @NonNull + public SelfT addRequestTracker(@NonNull RequestTracker requestTracker) { + programmaticArgumentsBuilder.addRequestTracker(requestTracker); + return self; + } + + /** + * Registers a request ID generator. The driver will use the generated ID in the logs and + * optionally add to the custom payload so that users can correlate logs about the same request + * from the Cassandra side. + */ + @NonNull + public SelfT withRequestIdGenerator(@NonNull RequestIdGenerator requestIdGenerator) { + this.programmaticArgumentsBuilder.withRequestIdGenerator(requestIdGenerator); + return self; + } + /** * Registers an authentication provider to use with the session. * @@ -288,7 +368,7 @@ public SelfT withAuthCredentials(@NonNull String username, @NonNull String passw * Configures the session to use DSE plaintext authentication with the given username and * password, and perform proxy authentication with the given authorization id. * - *

    This feature is only available in Datastax Enterprise. If connecting to Apache Cassandra, + *

    This feature is only available in DataStax Enterprise. If connecting to Apache Cassandra, * the authorization id will be ignored; it is recommended to use {@link * #withAuthCredentials(String, String)} instead. * @@ -389,6 +469,36 @@ public SelfT withLocalDatacenter(@NonNull String localDatacenter) { return withLocalDatacenter(DriverExecutionProfile.DEFAULT_NAME, localDatacenter); } + /** + * Adds a custom {@link NodeDistanceEvaluator} for a particular execution profile. This assumes + * that you're also using a dedicated load balancing policy for that profile. + * + *

    Node distance evaluators are honored by all the driver built-in load balancing policies. If + * you use a custom policy implementation however, you'll need to explicitly invoke the evaluator + * whenever appropriate. + * + *

    If an evaluator is specified programmatically with this method, it overrides the + * configuration (that is, the {@code load-balancing-policy.evaluator.class} option will be + * ignored). + * + * @see #withNodeDistanceEvaluator(NodeDistanceEvaluator) + */ + @NonNull + public SelfT withNodeDistanceEvaluator( + @NonNull String profileName, @NonNull NodeDistanceEvaluator nodeDistanceEvaluator) { + this.programmaticArgumentsBuilder.withNodeDistanceEvaluator(profileName, nodeDistanceEvaluator); + return self; + } + + /** + * Alias to {@link #withNodeDistanceEvaluator(String, NodeDistanceEvaluator)} for the default + * profile. + */ + @NonNull + public SelfT withNodeDistanceEvaluator(@NonNull NodeDistanceEvaluator nodeDistanceEvaluator) { + return withNodeDistanceEvaluator(DriverExecutionProfile.DEFAULT_NAME, nodeDistanceEvaluator); + } + /** * Adds a custom filter to include/exclude nodes for a particular execution profile. This assumes * that you're also using a dedicated load balancing policy for that profile. @@ -398,21 +508,60 @@ public SelfT withLocalDatacenter(@NonNull String localDatacenter) { * policy will suggest distance IGNORED (meaning the driver won't ever connect to it if all * policies agree), and never included in any query plan. * - *

    Note that this behavior is implemented in the default load balancing policy. If you use a - * custom policy implementation, you'll need to explicitly invoke the filter. + *

    Note that this behavior is implemented in the driver built-in load balancing policies. If + * you use a custom policy implementation, you'll need to explicitly invoke the filter. * *

    If the filter is specified programmatically with this method, it overrides the configuration * (that is, the {@code load-balancing-policy.filter.class} option will be ignored). * + *

    This method has been deprecated in favor of {@link + * #withNodeDistanceEvaluator(String, NodeDistanceEvaluator)}. If you were using node + * filters, you can easily replace your filters with the following implementation of {@link + * NodeDistanceEvaluator}: + * + *

    {@code
    +   * public class NodeFilterToDistanceEvaluatorAdapter implements NodeDistanceEvaluator {
    +   *
    +   *   private final Predicate nodeFilter;
    +   *
    +   *   public NodeFilterToDistanceEvaluatorAdapter(Predicate nodeFilter) {
    +   *     this.nodeFilter = nodeFilter;
    +   *   }
    +   *
    +   *   public NodeDistance evaluateDistance(Node node, String localDc) {
    +   *     return nodeFilter.test(node) ? null : NodeDistance.IGNORED;
    +   *   }
    +   * }
    +   * }
    + * + * The same can be achieved using a lambda + closure: + * + *
    {@code
    +   * Predicate nodeFilter = ...
    +   * NodeDistanceEvaluator evaluator =
    +   *   (node, localDc) -> nodeFilter.test(node) ? null : NodeDistance.IGNORED;
    +   * }
    + * * @see #withNodeFilter(Predicate) + * @deprecated Use {@link #withNodeDistanceEvaluator(String, NodeDistanceEvaluator)} instead. */ + @Deprecated @NonNull public SelfT withNodeFilter(@NonNull String profileName, @NonNull Predicate nodeFilter) { this.programmaticArgumentsBuilder.withNodeFilter(profileName, nodeFilter); return self; } - /** Alias to {@link #withNodeFilter(String, Predicate)} for the default profile. */ + /** + * Alias to {@link #withNodeFilter(String, Predicate)} for the default profile. + * + *

    This method has been deprecated in favor of {@link + * #withNodeDistanceEvaluator(NodeDistanceEvaluator)}. See the javadocs of {@link + * #withNodeFilter(String, Predicate)} to understand how to migrate your legacy node filters. + * + * @deprecated Use {@link #withNodeDistanceEvaluator(NodeDistanceEvaluator)} instead. + */ + @Deprecated @NonNull public SelfT withNodeFilter(@NonNull Predicate nodeFilter) { return withNodeFilter(DriverExecutionProfile.DEFAULT_NAME, nodeFilter); @@ -497,10 +646,10 @@ public SelfT withClassLoader(@Nullable ClassLoader classLoader) { * the provided {@link Path}. * *

    To connect to a Cloud database, you must first download the secure database bundle from the - * DataStax Constellation console that contains the connection information, then instruct the - * driver to read its contents using either this method or one if its variants. + * DataStax Astra console that contains the connection information, then instruct the driver to + * read its contents using either this method or one if its variants. * - *

    For more information, please refer to the DataStax Constellation documentation. + *

    For more information, please refer to the DataStax Astra documentation. * * @param cloudConfigPath Path to the secure connect bundle zip file. * @see #withCloudSecureConnectBundle(URL) @@ -534,10 +683,10 @@ public SelfT withCodecRegistry(@Nullable MutableCodecRegistry codecRegistry) { * the provided {@link URL}. * *

    To connect to a Cloud database, you must first download the secure database bundle from the - * DataStax Constellation console that contains the connection information, then instruct the - * driver to read its contents using either this method or one if its variants. + * DataStax Astra console that contains the connection information, then instruct the driver to + * read its contents using either this method or one if its variants. * - *

    For more information, please refer to the DataStax Constellation documentation. + *

    For more information, please refer to the DataStax Astra documentation. * * @param cloudConfigUrl URL to the secure connect bundle zip file. * @see #withCloudSecureConnectBundle(Path) @@ -554,10 +703,10 @@ public SelfT withCloudSecureConnectBundle(@NonNull URL cloudConfigUrl) { * the provided {@link InputStream}. * *

    To connect to a Cloud database, you must first download the secure database bundle from the - * DataStax Constellation console that contains the connection information, then instruct the - * driver to read its contents using either this method or one if its variants. + * DataStax Astra console that contains the connection information, then instruct the driver to + * read its contents using either this method or one if its variants. * - *

    For more information, please refer to the DataStax Constellation documentation. + *

    For more information, please refer to the DataStax Astra documentation. * *

    Note that the provided stream will be consumed and closed when either {@link * #build()} or {@link #buildAsync()} are called; attempting to reuse it afterwards will result in @@ -584,7 +733,7 @@ public SelfT withCloudSecureConnectBundle(@NonNull InputStream cloudConfigInputS * monitor tailored for Cloud deployments. This topology monitor assumes that the target cluster * should be contacted through the proxy specified here, using SNI routing. * - *

    For more information, please refer to the DataStax Constellation documentation. + *

    For more information, please refer to the DataStax Astra documentation. * * @param cloudProxyAddress The address of the Cloud proxy to use. * @see Server Name Indication @@ -676,6 +825,8 @@ public SelfT withMetricRegistry(@Nullable Object metricRegistry) { /** * Creates the session with the options set by this builder. * + *

    The session initialization will happen asynchronously in a driver internal thread pool. + * * @return a completion stage that completes with the session when it is fully initialized. */ @NonNull @@ -689,6 +840,10 @@ public CompletionStage buildAsync() { /** * Convenience method to call {@link #buildAsync()} and block on the result. * + *

    Usage in non-blocking applications: beware that session initialization is a costly + * operation. It should only be triggered from a thread that is allowed to block. If that is not + * the case, consider using {@link #buildAsync()} instead. + * *

    This must not be called on a driver thread. */ @NonNull @@ -721,6 +876,13 @@ protected final CompletionStage buildDefaultSessionAsync() { List configContactPoints = defaultConfig.getStringList(DefaultDriverOption.CONTACT_POINTS, Collections.emptyList()); if (cloudConfigInputStream != null) { + // override request id generator, unless user has already set it + if (programmaticArguments.getRequestIdGenerator() == null) { + programmaticArgumentsBuilder.withRequestIdGenerator( + new W3CContextRequestIdGenerator(ASTRA_PAYLOAD_KEY)); + LOG.debug( + "A secure connect bundle is provided, using W3CContextRequestIdGenerator as request ID generator."); + } if (!programmaticContactPoints.isEmpty() || !configContactPoints.isEmpty()) { LOG.info( "Both a secure connect bundle and contact points were provided. These are mutually exclusive. The contact points from the secure bundle will have priority."); diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/session/throttling/RequestThrottler.java b/core/src/main/java/com/datastax/oss/driver/api/core/session/throttling/RequestThrottler.java index 21ae3b5e396..73d347d533e 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/session/throttling/RequestThrottler.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/session/throttling/RequestThrottler.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -18,7 +20,14 @@ import edu.umd.cs.findbugs.annotations.NonNull; import java.io.Closeable; -/** Limits the number of concurrent requests executed by the driver. */ +/** + * Limits the number of concurrent requests executed by the driver. + * + *

    Usage in non-blocking applications: beware that some implementations of this interface use + * locks for internal coordination, and do not qualify as lock-free. If your application enforces + * strict lock-freedom, then you should use the {@code PassThroughRequestThrottler} or the {@code + * ConcurrencyLimitingRequestThrottler}. + */ public interface RequestThrottler extends Closeable { /** @@ -47,4 +56,12 @@ public interface RequestThrottler extends Closeable { * perform time-based eviction on pending requests. */ void signalTimeout(@NonNull Throttled request); + + /** + * Signals that a request has been cancelled. This indicates to the throttler that another request + * might be started. + */ + default void signalCancel(@NonNull Throttled request) { + // no-op for backward compatibility purposes + } } diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/session/throttling/Throttled.java b/core/src/main/java/com/datastax/oss/driver/api/core/session/throttling/Throttled.java index f64ec481743..6fd562804da 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/session/throttling/Throttled.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/session/throttling/Throttled.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/specex/SpeculativeExecutionPolicy.java b/core/src/main/java/com/datastax/oss/driver/api/core/specex/SpeculativeExecutionPolicy.java index 149a2f3c285..163204ba62d 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/specex/SpeculativeExecutionPolicy.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/specex/SpeculativeExecutionPolicy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/ssl/ProgrammaticSslEngineFactory.java b/core/src/main/java/com/datastax/oss/driver/api/core/ssl/ProgrammaticSslEngineFactory.java index ba99f3bf7fa..d65eaa864aa 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/ssl/ProgrammaticSslEngineFactory.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/ssl/ProgrammaticSslEngineFactory.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -43,6 +45,7 @@ public class ProgrammaticSslEngineFactory implements SslEngineFactory { protected final SSLContext sslContext; protected final String[] cipherSuites; protected final boolean requireHostnameValidation; + protected final boolean allowDnsReverseLookupSan; /** * Creates an instance with the given {@link SSLContext}, default cipher suites and no host name @@ -78,9 +81,28 @@ public ProgrammaticSslEngineFactory( @NonNull SSLContext sslContext, @Nullable String[] cipherSuites, boolean requireHostnameValidation) { + this(sslContext, cipherSuites, requireHostnameValidation, true); + } + + /** + * Creates an instance with the given {@link SSLContext}, cipher suites and host name validation. + * + * @param sslContext the {@link SSLContext} to use. + * @param cipherSuites the cipher suites to use, or null to use the default ones. + * @param requireHostnameValidation whether to enable host name validation. If enabled, host name + * validation will be done using HTTPS algorithm. + * @param allowDnsReverseLookupSan whether to allow raw server IPs to be DNS reverse-resolved to + * choose the appropriate Subject Alternative Name. + */ + public ProgrammaticSslEngineFactory( + @NonNull SSLContext sslContext, + @Nullable String[] cipherSuites, + boolean requireHostnameValidation, + boolean allowDnsReverseLookupSan) { this.sslContext = sslContext; this.cipherSuites = cipherSuites; this.requireHostnameValidation = requireHostnameValidation; + this.allowDnsReverseLookupSan = allowDnsReverseLookupSan; } @NonNull @@ -90,7 +112,12 @@ public SSLEngine newSslEngine(@NonNull EndPoint remoteEndpoint) { SocketAddress remoteAddress = remoteEndpoint.resolve(); if (remoteAddress instanceof InetSocketAddress) { InetSocketAddress socketAddress = (InetSocketAddress) remoteAddress; - engine = sslContext.createSSLEngine(socketAddress.getHostName(), socketAddress.getPort()); + engine = + sslContext.createSSLEngine( + allowDnsReverseLookupSan + ? socketAddress.getHostName() + : socketAddress.getHostString(), + socketAddress.getPort()); } else { engine = sslContext.createSSLEngine(); } diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/ssl/SslEngineFactory.java b/core/src/main/java/com/datastax/oss/driver/api/core/ssl/SslEngineFactory.java index a001c696fe0..db4f18a97b9 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/ssl/SslEngineFactory.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/ssl/SslEngineFactory.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/ssl/package-info.java b/core/src/main/java/com/datastax/oss/driver/api/core/ssl/package-info.java index 343a8ab0360..a0cb3e73397 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/ssl/package-info.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/ssl/package-info.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/time/TimestampGenerator.java b/core/src/main/java/com/datastax/oss/driver/api/core/time/TimestampGenerator.java index b25b0c839d8..b1139dd9f4d 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/time/TimestampGenerator.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/time/TimestampGenerator.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/tracker/RequestIdGenerator.java b/core/src/main/java/com/datastax/oss/driver/api/core/tracker/RequestIdGenerator.java new file mode 100644 index 00000000000..21db3793b01 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/api/core/tracker/RequestIdGenerator.java @@ -0,0 +1,84 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.api.core.tracker; + +import com.datastax.oss.driver.api.core.cql.Statement; +import com.datastax.oss.driver.api.core.session.Request; +import edu.umd.cs.findbugs.annotations.NonNull; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +/** + * Interface responsible for generating request IDs. + * + *

    Note that all request IDs have a parent/child relationship. A "session request ID" can loosely + * be thought of as encompassing a sequence of a request + any attendant retries, speculative + * executions etc. It's scope is identical to that of a {@link + * com.datastax.oss.driver.internal.core.cql.CqlRequestHandler}. A "node request ID" represents a + * single request within this larger scope. Note that a request corresponding to a request ID may be + * retried; in that case the retry count will be appended to the corresponding identifier in the + * logs. + */ +public interface RequestIdGenerator { + + String DEFAULT_PAYLOAD_KEY = "request-id"; + + /** + * Generates a unique identifier for the session request. This will be the identifier for the + * entire `session.execute()` call. This identifier will be added to logs, and propagated to + * request trackers. + * + * @return a unique identifier for the session request + */ + String getSessionRequestId(); + + /** + * Generates a unique identifier for the node request. This will be the identifier for the CQL + * request against a particular node. There can be one or more node requests for a single session + * request, due to retries or speculative executions. This identifier will be added to logs, and + * propagated to request trackers. + * + * @param statement the statement to be executed + * @param parentId the session request identifier + * @return a unique identifier for the node request + */ + String getNodeRequestId(@NonNull Request statement, @NonNull String parentId); + + default String getCustomPayloadKey() { + return DEFAULT_PAYLOAD_KEY; + } + + default Statement getDecoratedStatement( + @NonNull Statement statement, @NonNull String requestId) { + + Map existing = new HashMap<>(statement.getCustomPayload()); + String key = getCustomPayloadKey(); + + // Add or overwrite + existing.put(key, ByteBuffer.wrap(requestId.getBytes(StandardCharsets.UTF_8))); + + // Allowing null key/values + // Wrap a map inside to be immutable without instanciating a new map + Map unmodifiableMap = Collections.unmodifiableMap(existing); + + return statement.setCustomPayload(unmodifiableMap); + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/tracker/RequestTracker.java b/core/src/main/java/com/datastax/oss/driver/api/core/tracker/RequestTracker.java index 4d8f08e25a3..065b41e496a 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/tracker/RequestTracker.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/tracker/RequestTracker.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -27,9 +29,9 @@ /** * Tracks request execution for a session. * - *

    There is exactly one tracker per {@link Session}. It can be provided either via the - * configuration (see {@code reference.conf} in the manual or core driver JAR), or programmatically - * via {@link SessionBuilder#withRequestTracker(RequestTracker)}. + *

    Implementations of this interface can be registered either via the configuration (see {@code + * reference.conf} in the manual or core driver JAR), or programmatically via {@link + * SessionBuilder#addRequestTracker(RequestTracker)}. */ public interface RequestTracker extends AutoCloseable { @@ -45,21 +47,22 @@ default void onSuccess( @NonNull Node node) {} /** - * Invoked each time a request succeeds. + * Invoked each time a session request succeeds. A session request is a `session.execute()` call * * @param latencyNanos the overall execution time (from the {@link Session#execute(Request, * GenericType) session.execute} call until the result is made available to the client). * @param executionProfile the execution profile of this request. * @param node the node that returned the successful response. - * @param requestLogPrefix the dedicated log prefix for this request + * @param sessionRequestLogPrefix the dedicated log prefix for this request */ default void onSuccess( @NonNull Request request, long latencyNanos, @NonNull DriverExecutionProfile executionProfile, @NonNull Node node, - @NonNull String requestLogPrefix) { - // If client doesn't override onSuccess with requestLogPrefix delegate call to the old method + @NonNull String sessionRequestLogPrefix) { + // If client doesn't override onSuccess with sessionRequestLogPrefix delegate call to the old + // method onSuccess(request, latencyNanos, executionProfile, node); } @@ -76,13 +79,13 @@ default void onError( @Nullable Node node) {} /** - * Invoked each time a request fails. + * Invoked each time a session request fails. A session request is a `session.execute()` call * * @param latencyNanos the overall execution time (from the {@link Session#execute(Request, * GenericType) session.execute} call until the error is propagated to the client). * @param executionProfile the execution profile of this request. * @param node the node that returned the error response, or {@code null} if the error occurred - * @param requestLogPrefix the dedicated log prefix for this request + * @param sessionRequestLogPrefix the dedicated log prefix for this request */ default void onError( @NonNull Request request, @@ -90,8 +93,9 @@ default void onError( long latencyNanos, @NonNull DriverExecutionProfile executionProfile, @Nullable Node node, - @NonNull String requestLogPrefix) { - // If client doesn't override onError with requestLogPrefix delegate call to the old method + @NonNull String sessionRequestLogPrefix) { + // If client doesn't override onError with sessionRequestLogPrefix delegate call to the old + // method onError(request, error, latencyNanos, executionProfile, node); } @@ -108,14 +112,15 @@ default void onNodeError( @NonNull Node node) {} /** - * Invoked each time a request fails at the node level. Similar to {@link #onError(Request, - * Throwable, long, DriverExecutionProfile, Node, String)} but at a per node level. + * Invoked each time a node request fails. A node request is a CQL request sent to a particular + * node. There can be one or more node requests for a single session request, due to retries or + * speculative executions. * * @param latencyNanos the overall execution time (from the {@link Session#execute(Request, * GenericType) session.execute} call until the error is propagated to the client). * @param executionProfile the execution profile of this request. * @param node the node that returned the error response. - * @param requestLogPrefix the dedicated log prefix for this request + * @param nodeRequestLogPrefix the dedicated log prefix for this request */ default void onNodeError( @NonNull Request request, @@ -123,8 +128,9 @@ default void onNodeError( long latencyNanos, @NonNull DriverExecutionProfile executionProfile, @NonNull Node node, - @NonNull String requestLogPrefix) { - // If client doesn't override onNodeError with requestLogPrefix delegate call to the old method + @NonNull String nodeRequestLogPrefix) { + // If client doesn't override onNodeError with nodeRequestLogPrefix delegate call to the old + // method onNodeError(request, error, latencyNanos, executionProfile, node); } @@ -140,22 +146,23 @@ default void onNodeSuccess( @NonNull Node node) {} /** - * Invoked each time a request succeeds at the node level. Similar to {@link #onSuccess(Request, - * long, DriverExecutionProfile, Node, String)} but at per node level. + * Invoked each time a node request succeeds. A node request is a CQL request sent to a particular + * node. There can be one or more node requests for a single session request, due to retries or + * speculative executions. * * @param latencyNanos the overall execution time (from the {@link Session#execute(Request, * GenericType) session.execute} call until the result is made available to the client). * @param executionProfile the execution profile of this request. * @param node the node that returned the successful response. - * @param requestLogPrefix the dedicated log prefix for this request + * @param nodeRequestLogPrefix the dedicated log prefix for this request */ default void onNodeSuccess( @NonNull Request request, long latencyNanos, @NonNull DriverExecutionProfile executionProfile, @NonNull Node node, - @NonNull String requestLogPrefix) { - // If client doesn't override onNodeSuccess with requestLogPrefix delegate call to the old + @NonNull String nodeRequestLogPrefix) { + // If client doesn't override onNodeSuccess with nodeRequestLogPrefix delegate call to the old // method onNodeSuccess(request, latencyNanos, executionProfile, node); } diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/type/ContainerType.java b/core/src/main/java/com/datastax/oss/driver/api/core/type/ContainerType.java new file mode 100644 index 00000000000..93e92ec2c2b --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/api/core/type/ContainerType.java @@ -0,0 +1,30 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.api.core.type; + +import edu.umd.cs.findbugs.annotations.NonNull; + +/** + * Representation of a type which "contains" some other type. This might be a collection type or it + * could be some other kind of container; the term is deliberately left somewhat vague. + */ +public interface ContainerType { + + @NonNull + DataType getElementType(); +} diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/type/CustomType.java b/core/src/main/java/com/datastax/oss/driver/api/core/type/CustomType.java index bc4f5ce7c5a..93f913a584d 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/type/CustomType.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/type/CustomType.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/type/DataType.java b/core/src/main/java/com/datastax/oss/driver/api/core/type/DataType.java index 87dc34144f7..92e5cc5edf0 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/type/DataType.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/type/DataType.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/type/DataTypes.java b/core/src/main/java/com/datastax/oss/driver/api/core/type/DataTypes.java index 0a61314ca71..492fc121c71 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/type/DataTypes.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/type/DataTypes.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -15,12 +17,15 @@ */ package com.datastax.oss.driver.api.core.type; +import com.datastax.oss.driver.api.core.detach.AttachmentPoint; import com.datastax.oss.driver.api.core.detach.Detachable; +import com.datastax.oss.driver.internal.core.metadata.schema.parsing.DataTypeClassNameParser; import com.datastax.oss.driver.internal.core.type.DefaultCustomType; import com.datastax.oss.driver.internal.core.type.DefaultListType; import com.datastax.oss.driver.internal.core.type.DefaultMapType; import com.datastax.oss.driver.internal.core.type.DefaultSetType; import com.datastax.oss.driver.internal.core.type.DefaultTupleType; +import com.datastax.oss.driver.internal.core.type.DefaultVectorType; import com.datastax.oss.driver.internal.core.type.PrimitiveType; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableList; import com.datastax.oss.protocol.internal.ProtocolConstants; @@ -51,14 +56,18 @@ public class DataTypes { public static final DataType TINYINT = new PrimitiveType(ProtocolConstants.DataType.TINYINT); public static final DataType DURATION = new PrimitiveType(ProtocolConstants.DataType.DURATION); + private static final DataTypeClassNameParser classNameParser = new DataTypeClassNameParser(); + @NonNull public static DataType custom(@NonNull String className) { + // In protocol v4, duration is implemented as a custom type - if ("org.apache.cassandra.db.marshal.DurationType".equals(className)) { - return DURATION; - } else { - return new DefaultCustomType(className); - } + if (className.equals("org.apache.cassandra.db.marshal.DurationType")) return DURATION; + + /* Vector support is currently implemented as a custom type but is also parameterized */ + if (className.startsWith(DefaultVectorType.VECTOR_CLASS_NAME)) + return classNameParser.parse(className, AttachmentPoint.NONE); + return new DefaultCustomType(className); } @NonNull @@ -118,4 +127,8 @@ public static MapType frozenMapOf(@NonNull DataType keyType, @NonNull DataType v public static TupleType tupleOf(@NonNull DataType... componentTypes) { return new DefaultTupleType(ImmutableList.copyOf(Arrays.asList(componentTypes))); } + + public static VectorType vectorOf(DataType subtype, int dimensions) { + return new DefaultVectorType(subtype, dimensions); + } } diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/type/ListType.java b/core/src/main/java/com/datastax/oss/driver/api/core/type/ListType.java index 1bafb1693d7..ca377d10bbf 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/type/ListType.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/type/ListType.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -18,10 +20,7 @@ import com.datastax.oss.protocol.internal.ProtocolConstants; import edu.umd.cs.findbugs.annotations.NonNull; -public interface ListType extends DataType { - - @NonNull - DataType getElementType(); +public interface ListType extends DataType, ContainerType { boolean isFrozen(); diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/type/MapType.java b/core/src/main/java/com/datastax/oss/driver/api/core/type/MapType.java index e79990f0782..f3bca2ac6a4 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/type/MapType.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/type/MapType.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/type/SetType.java b/core/src/main/java/com/datastax/oss/driver/api/core/type/SetType.java index eadd0a702e3..fa902c72bb8 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/type/SetType.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/type/SetType.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -18,10 +20,7 @@ import com.datastax.oss.protocol.internal.ProtocolConstants; import edu.umd.cs.findbugs.annotations.NonNull; -public interface SetType extends DataType { - - @NonNull - DataType getElementType(); +public interface SetType extends DataType, ContainerType { boolean isFrozen(); diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/type/TupleType.java b/core/src/main/java/com/datastax/oss/driver/api/core/type/TupleType.java index a22bca8856d..9e2736ddce8 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/type/TupleType.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/type/TupleType.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/type/UserDefinedType.java b/core/src/main/java/com/datastax/oss/driver/api/core/type/UserDefinedType.java index 50171470611..4d4768a8ae4 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/type/UserDefinedType.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/type/UserDefinedType.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/type/VectorType.java b/core/src/main/java/com/datastax/oss/driver/api/core/type/VectorType.java new file mode 100644 index 00000000000..1d7c13807ec --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/api/core/type/VectorType.java @@ -0,0 +1,27 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.api.core.type; + +/** + * Type representing a Cassandra vector type as described in CEP-30. At the moment this is + * implemented as a custom type so we include the CustomType interface as well. + */ +public interface VectorType extends CustomType, ContainerType { + + int getDimensions(); +} diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/CodecNotFoundException.java b/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/CodecNotFoundException.java index 4d46f253915..4f45af0924f 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/CodecNotFoundException.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/CodecNotFoundException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -15,6 +17,7 @@ */ package com.datastax.oss.driver.api.core.type.codec; +import com.datastax.oss.driver.api.core.DriverException; import com.datastax.oss.driver.api.core.type.DataType; import com.datastax.oss.driver.api.core.type.codec.registry.CodecRegistry; import com.datastax.oss.driver.api.core.type.reflect.GenericType; @@ -22,7 +25,7 @@ import edu.umd.cs.findbugs.annotations.Nullable; /** Thrown when a suitable {@link TypeCodec} cannot be found by the {@link CodecRegistry}. */ -public class CodecNotFoundException extends RuntimeException { +public class CodecNotFoundException extends DriverException { private final DataType cqlType; @@ -48,7 +51,7 @@ public CodecNotFoundException( private CodecNotFoundException( String msg, Throwable cause, DataType cqlType, GenericType javaType) { - super(msg, cause); + super(msg, null, cause, true); this.cqlType = cqlType; this.javaType = javaType; } @@ -62,4 +65,10 @@ public DataType getCqlType() { public GenericType getJavaType() { return javaType; } + + @NonNull + @Override + public DriverException copy() { + return new CodecNotFoundException(getMessage(), getCause(), getCqlType(), getJavaType()); + } } diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.java b/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.java index 6bf044ebf03..51a96a16376 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,8 +18,10 @@ package com.datastax.oss.driver.api.core.type.codec; import com.datastax.oss.driver.api.core.session.SessionBuilder; +import com.datastax.oss.driver.api.core.type.DataTypes; import com.datastax.oss.driver.api.core.type.codec.registry.MutableCodecRegistry; import com.datastax.oss.driver.api.core.type.reflect.GenericType; +import com.datastax.oss.driver.internal.core.type.DefaultVectorType; import com.datastax.oss.driver.internal.core.type.codec.SimpleBlobCodec; import com.datastax.oss.driver.internal.core.type.codec.TimestampCodec; import com.datastax.oss.driver.internal.core.type.codec.extras.OptionalCodec; @@ -36,6 +40,7 @@ import com.datastax.oss.driver.internal.core.type.codec.extras.time.PersistentZonedTimestampCodec; import com.datastax.oss.driver.internal.core.type.codec.extras.time.TimestampMillisCodec; import com.datastax.oss.driver.internal.core.type.codec.extras.time.ZonedTimestampCodec; +import com.datastax.oss.driver.internal.core.type.codec.extras.vector.FloatVectorToArrayCodec; import com.fasterxml.jackson.databind.ObjectMapper; import edu.umd.cs.findbugs.annotations.NonNull; import java.nio.ByteBuffer; @@ -479,4 +484,9 @@ public static TypeCodec json( @NonNull Class javaType, @NonNull ObjectMapper objectMapper) { return new JsonCodec<>(javaType, objectMapper); } + + /** Builds a new codec that maps CQL float vectors of the specified size to an array of floats. */ + public static TypeCodec floatVectorToArray(int dimensions) { + return new FloatVectorToArrayCodec(new DefaultVectorType(DataTypes.FLOAT, dimensions)); + } } diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/MappingCodec.java b/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/MappingCodec.java index 6694132cfc6..df1a34a566a 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/MappingCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/MappingCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/PrimitiveBooleanCodec.java b/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/PrimitiveBooleanCodec.java index 45f3577284a..2ad4f2fa15a 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/PrimitiveBooleanCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/PrimitiveBooleanCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/PrimitiveByteCodec.java b/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/PrimitiveByteCodec.java index 119b950cfb9..5909bcd4ff9 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/PrimitiveByteCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/PrimitiveByteCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/PrimitiveDoubleCodec.java b/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/PrimitiveDoubleCodec.java index 87d504a1ee3..c46160f0942 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/PrimitiveDoubleCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/PrimitiveDoubleCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/PrimitiveFloatCodec.java b/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/PrimitiveFloatCodec.java index fcb048da7ae..585d5fdb1fa 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/PrimitiveFloatCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/PrimitiveFloatCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/PrimitiveIntCodec.java b/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/PrimitiveIntCodec.java index e029302f060..b3f374eb8d7 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/PrimitiveIntCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/PrimitiveIntCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/PrimitiveLongCodec.java b/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/PrimitiveLongCodec.java index 56eaeb3e52c..ec65820c60f 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/PrimitiveLongCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/PrimitiveLongCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/PrimitiveShortCodec.java b/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/PrimitiveShortCodec.java index dfeb7f0c72a..48c063b3dc6 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/PrimitiveShortCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/PrimitiveShortCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/TypeCodec.java b/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/TypeCodec.java index 777d35b25fb..d6afbe0380a 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/TypeCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/TypeCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -26,6 +28,7 @@ import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; import java.nio.ByteBuffer; +import java.util.Optional; /** * Manages the two-way conversion between a CQL type and a Java type. @@ -232,4 +235,9 @@ default boolean accepts(@NonNull DataType cqlType) { */ @Nullable JavaTypeT parse(@Nullable String value); + + @NonNull + default Optional serializedSize() { + return Optional.empty(); + } } diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/TypeCodecs.java b/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/TypeCodecs.java index 6cd4b68a042..68f1b07b106 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/TypeCodecs.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/TypeCodecs.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,6 +18,7 @@ package com.datastax.oss.driver.api.core.type.codec; import com.datastax.oss.driver.api.core.data.CqlDuration; +import com.datastax.oss.driver.api.core.data.CqlVector; import com.datastax.oss.driver.api.core.data.TupleValue; import com.datastax.oss.driver.api.core.data.UdtValue; import com.datastax.oss.driver.api.core.type.CustomType; @@ -23,6 +26,7 @@ import com.datastax.oss.driver.api.core.type.DataTypes; import com.datastax.oss.driver.api.core.type.TupleType; import com.datastax.oss.driver.api.core.type.UserDefinedType; +import com.datastax.oss.driver.api.core.type.VectorType; import com.datastax.oss.driver.internal.core.type.codec.BigIntCodec; import com.datastax.oss.driver.internal.core.type.codec.BlobCodec; import com.datastax.oss.driver.internal.core.type.codec.BooleanCodec; @@ -48,6 +52,7 @@ import com.datastax.oss.driver.internal.core.type.codec.UdtCodec; import com.datastax.oss.driver.internal.core.type.codec.UuidCodec; import com.datastax.oss.driver.internal.core.type.codec.VarIntCodec; +import com.datastax.oss.driver.internal.core.type.codec.VectorCodec; import com.datastax.oss.driver.shaded.guava.common.base.Charsets; import com.datastax.oss.driver.shaded.guava.common.base.Preconditions; import edu.umd.cs.findbugs.annotations.NonNull; @@ -205,6 +210,17 @@ public static TypeCodec tupleOf(@NonNull TupleType cqlType) { return new TupleCodec(cqlType); } + public static TypeCodec> vectorOf( + @NonNull VectorType type, @NonNull TypeCodec subtypeCodec) { + return new VectorCodec( + DataTypes.vectorOf(subtypeCodec.getCqlType(), type.getDimensions()), subtypeCodec); + } + + public static TypeCodec> vectorOf( + int dimensions, @NonNull TypeCodec subtypeCodec) { + return new VectorCodec(DataTypes.vectorOf(subtypeCodec.getCqlType(), dimensions), subtypeCodec); + } + /** * Builds a new codec that maps a CQL user defined type to the driver's {@link UdtValue}, for the * given type definition. diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/registry/CodecRegistry.java b/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/registry/CodecRegistry.java index 9eddfe6bb3a..36472f34c79 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/registry/CodecRegistry.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/registry/CodecRegistry.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/registry/MutableCodecRegistry.java b/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/registry/MutableCodecRegistry.java index 67d79cc138f..7f5d1fb9813 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/registry/MutableCodecRegistry.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/type/codec/registry/MutableCodecRegistry.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/type/reflect/GenericType.java b/core/src/main/java/com/datastax/oss/driver/api/core/type/reflect/GenericType.java index a1977e39f23..d22b6f1bfaf 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/type/reflect/GenericType.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/type/reflect/GenericType.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,6 +18,7 @@ package com.datastax.oss.driver.api.core.type.reflect; import com.datastax.oss.driver.api.core.data.CqlDuration; +import com.datastax.oss.driver.api.core.data.CqlVector; import com.datastax.oss.driver.api.core.data.GettableByIndex; import com.datastax.oss.driver.api.core.data.TupleValue; import com.datastax.oss.driver.api.core.data.UdtValue; @@ -147,6 +150,21 @@ public static GenericType> setOf(@NonNull GenericType elementType) return new GenericType<>(token); } + @NonNull + public static GenericType> vectorOf(@NonNull Class elementType) { + TypeToken> token = + new TypeToken>() {}.where( + new TypeParameter() {}, TypeToken.of(elementType)); + return new GenericType<>(token); + } + + @NonNull + public static GenericType> vectorOf(@NonNull GenericType elementType) { + TypeToken> token = + new TypeToken>() {}.where(new TypeParameter() {}, elementType.token); + return new GenericType<>(token); + } + @NonNull public static GenericType> mapOf( @NonNull Class keyType, @NonNull Class valueType) { diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/type/reflect/GenericTypeParameter.java b/core/src/main/java/com/datastax/oss/driver/api/core/type/reflect/GenericTypeParameter.java index d62e8890600..3bf0e3537e0 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/type/reflect/GenericTypeParameter.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/type/reflect/GenericTypeParameter.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/api/core/uuid/Uuids.java b/core/src/main/java/com/datastax/oss/driver/api/core/uuid/Uuids.java index 35cc37e8e7a..8dae31f3734 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/core/uuid/Uuids.java +++ b/core/src/main/java/com/datastax/oss/driver/api/core/uuid/Uuids.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -28,7 +30,6 @@ import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; -import java.util.Calendar; import java.util.Date; import java.util.Enumeration; import java.util.HashSet; @@ -36,7 +37,7 @@ import java.util.Properties; import java.util.Random; import java.util.Set; -import java.util.TimeZone; +import java.util.SplittableRandom; import java.util.UUID; import java.util.concurrent.atomic.AtomicLong; import org.slf4j.Logger; @@ -112,7 +113,16 @@ public final class Uuids { private Uuids() {} - private static final long START_EPOCH = makeEpoch(); + /** + * UUID v1 timestamps must be expressed relatively to October 15th, 1582 – the day when Gregorian + * calendar was introduced. This constant captures that moment in time expressed in milliseconds + * before the Unix epoch. It can be obtained by calling: + * + *

    +   *   Instant.parse("1582-10-15T00:00:00Z").toEpochMilli();
    +   * 
    + */ + private static final long START_EPOCH_MILLIS = -12219292800000L; // Lazily initialize clock seq + node value at time of first access. Quarkus will attempt to // initialize this class at deployment time which prevents us from just setting this value @@ -156,19 +166,6 @@ private long get() { private static final AtomicLong lastTimestamp = new AtomicLong(0L); - private static long makeEpoch() { - // UUID v1 timestamps must be in 100-nanoseconds interval since 00:00:00.000 15 Oct 1582. - Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT-0")); - c.set(Calendar.YEAR, 1582); - c.set(Calendar.MONTH, Calendar.OCTOBER); - c.set(Calendar.DAY_OF_MONTH, 15); - c.set(Calendar.HOUR_OF_DAY, 0); - c.set(Calendar.MINUTE, 0); - c.set(Calendar.SECOND, 0); - c.set(Calendar.MILLISECOND, 0); - return c.getTimeInMillis(); - } - private static long makeNode() { // We don't have access to the MAC address (in pure JAVA at least) but need to generate a node @@ -263,11 +260,61 @@ private static long makeClockSeqAndNode() { /** * Creates a new random (version 4) UUID. * - *

    This method is just a convenience for {@link UUID#randomUUID()}. + *

    This method has received a new implementation as of driver 4.10. Unlike the JDK's + * {@link UUID#randomUUID()} method, it does not use anymore the cryptographic {@link + * java.security.SecureRandom} number generator. Instead, it uses the non-cryptographic {@link + * Random} class, with a different seed at every invocation. + * + *

    Using a non-cryptographic generator has two advantages: + * + *

      + *
    1. UUID generation is much faster than with {@link UUID#randomUUID()}; + *
    2. Contrary to {@link UUID#randomUUID()}, UUID generation with this method does not require + * I/O and is not a blocking call, which makes this method better suited for non-blocking + * applications. + *
    + * + * Of course, this method is intended for usage where cryptographic strength is not required, such + * as when generating row identifiers for insertion in the database. If you still need + * cryptographic strength, consider using {@link Uuids#random(Random)} instead, and pass an + * instance of {@link java.security.SecureRandom}. */ @NonNull public static UUID random() { - return UUID.randomUUID(); + return random(new Random()); + } + + /** + * Creates a new random (version 4) UUID using the provided {@link Random} instance. + * + *

    This method offers more flexibility than {@link #random()} as it allows to customize the + * {@link Random} instance to use, and also offers the possibility to reuse instances across + * successive calls. Reusing Random instances is the norm when using {@link + * java.util.concurrent.ThreadLocalRandom}, for instance; however other Random implementations may + * perform poorly under heavy thread contention. + * + *

    Note: some Random implementations, such as {@link java.security.SecureRandom}, may trigger + * I/O activity during random number generation; these instances should not be used in + * non-blocking contexts. + */ + @NonNull + public static UUID random(@NonNull Random random) { + byte[] data = new byte[16]; + random.nextBytes(data); + return buildUuid(data, 4); + } + + /** + * Creates a new random (version 4) UUID using the provided {@link SplittableRandom} instance. + * + *

    This method should be preferred to {@link #random()} when UUID generation happens in massive + * parallel computations, such as when using the ForkJoin framework. Note that {@link + * SplittableRandom} instances are not thread-safe. + */ + @NonNull + public static UUID random(@NonNull SplittableRandom random) { + byte[] data = toBytes(random.nextLong(), random.nextLong()); + return buildUuid(data, 4); } /** @@ -344,7 +391,7 @@ public static UUID nameBased(@NonNull UUID namespace, @NonNull byte[] name, int MessageDigest md = newMessageDigest(version); md.update(toBytes(namespace)); md.update(name); - return buildNamedUuid(md.digest(), version); + return buildUuid(md.digest(), version); } /** @@ -390,7 +437,7 @@ public static UUID nameBased(@NonNull byte[] namespaceAndName, int version) { } MessageDigest md = newMessageDigest(version); md.update(namespaceAndName); - return buildNamedUuid(md.digest(), version); + return buildUuid(md.digest(), version); } @NonNull @@ -408,7 +455,7 @@ private static MessageDigest newMessageDigest(int version) { } @NonNull - private static UUID buildNamedUuid(@NonNull byte[] data, int version) { + private static UUID buildUuid(@NonNull byte[] data, int version) { // clear and set version data[6] &= (byte) 0x0f; data[6] |= (byte) (version << 4); @@ -433,12 +480,16 @@ private static UUID fromBytes(byte[] data) { } private static byte[] toBytes(UUID uuid) { - byte[] out = new byte[16]; long msb = uuid.getMostSignificantBits(); + long lsb = uuid.getLeastSignificantBits(); + return toBytes(msb, lsb); + } + + private static byte[] toBytes(long msb, long lsb) { + byte[] out = new byte[16]; for (int i = 0; i < 8; i++) { out[i] = (byte) (msb >> ((7 - i) * 8)); } - long lsb = uuid.getLeastSignificantBits(); for (int i = 8; i < 16; i++) { out[i] = (byte) (lsb >> ((15 - i) * 8)); } @@ -462,6 +513,12 @@ private static byte[] toBytes(UUID uuid) { * * If you simply need to perform a range query on a {@code timeuuid} column, use the "fake" UUID * generated by {@link #startOf(long)} and {@link #endOf(long)}. + * + *

    Usage with non-blocking threads: beware that this method may block the calling thread on its + * very first invocation, because the node part of time-based UUIDs needs to be computed at that + * moment, and the computation may require the loading of native libraries. If that is a problem, + * consider invoking this method once from a thread that is allowed to block. Subsequent + * invocations are guaranteed not to block. */ @NonNull public static UUID timeBased() { @@ -535,7 +592,7 @@ public static long unixTimestamp(@NonNull UUID uuid) { uuid.version())); } long timestamp = uuid.timestamp(); - return (timestamp / 10000) + START_EPOCH; + return (timestamp / 10000) + START_EPOCH_MILLIS; } // Use {@link System#currentTimeMillis} for a base time in milliseconds, and if we are in the same @@ -572,7 +629,7 @@ private static long getCurrentTimestamp() { @VisibleForTesting static long fromUnixTimestamp(long tstamp) { - return (tstamp - START_EPOCH) * 10000; + return (tstamp - START_EPOCH_MILLIS) * 10000; } private static long millisOf(long timestamp) { diff --git a/core/src/main/java/com/datastax/oss/driver/api/package-info.java b/core/src/main/java/com/datastax/oss/driver/api/package-info.java index b783940b313..7b2219647b2 100644 --- a/core/src/main/java/com/datastax/oss/driver/api/package-info.java +++ b/core/src/main/java/com/datastax/oss/driver/api/package-info.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/AsyncPagingIterableWrapper.java b/core/src/main/java/com/datastax/oss/driver/internal/core/AsyncPagingIterableWrapper.java index fb69bbcfccf..055ab26909f 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/AsyncPagingIterableWrapper.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/AsyncPagingIterableWrapper.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/ConsistencyLevelRegistry.java b/core/src/main/java/com/datastax/oss/driver/internal/core/ConsistencyLevelRegistry.java index c9353df9b55..7b66a61636c 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/ConsistencyLevelRegistry.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/ConsistencyLevelRegistry.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -29,6 +31,8 @@ public interface ConsistencyLevelRegistry { int nameToCode(String name); + ConsistencyLevel nameToLevel(String name); + /** @return all the values known to this driver instance. */ Iterable getValues(); } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/ContactPoints.java b/core/src/main/java/com/datastax/oss/driver/internal/core/ContactPoints.java index 110e49be067..bb65661b72f 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/ContactPoints.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/ContactPoints.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -17,14 +19,11 @@ import com.datastax.oss.driver.api.core.metadata.EndPoint; import com.datastax.oss.driver.internal.core.metadata.DefaultEndPoint; +import com.datastax.oss.driver.internal.core.util.AddressUtils; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableSet; import com.datastax.oss.driver.shaded.guava.common.collect.Sets; -import java.net.InetAddress; import java.net.InetSocketAddress; -import java.net.UnknownHostException; -import java.util.Arrays; import java.util.Collections; -import java.util.HashSet; import java.util.List; import java.util.Set; import org.slf4j.Logger; @@ -39,7 +38,22 @@ public static Set merge( Set result = Sets.newHashSet(programmaticContactPoints); for (String spec : configContactPoints) { - for (InetSocketAddress address : extract(spec, resolve)) { + + Set addresses = Collections.emptySet(); + try { + addresses = AddressUtils.extract(spec, resolve); + } catch (RuntimeException e) { + LOG.warn("Ignoring invalid contact point {} ({})", spec, e.getMessage(), e); + } + + if (addresses.size() > 1) { + LOG.info( + "Contact point {} resolves to multiple addresses, will use them all ({})", + spec, + addresses); + } + + for (InetSocketAddress address : addresses) { DefaultEndPoint endPoint = new DefaultEndPoint(address); boolean wasNew = result.add(endPoint); if (!wasNew) { @@ -49,43 +63,4 @@ public static Set merge( } return ImmutableSet.copyOf(result); } - - private static Set extract(String spec, boolean resolve) { - int separator = spec.lastIndexOf(':'); - if (separator < 0) { - LOG.warn("Ignoring invalid contact point {} (expecting host:port)", spec); - return Collections.emptySet(); - } - - String host = spec.substring(0, separator); - String portSpec = spec.substring(separator + 1); - int port; - try { - port = Integer.parseInt(portSpec); - } catch (NumberFormatException e) { - LOG.warn("Ignoring invalid contact point {} (expecting a number, got {})", spec, portSpec); - return Collections.emptySet(); - } - if (!resolve) { - return ImmutableSet.of(InetSocketAddress.createUnresolved(host, port)); - } else { - try { - InetAddress[] inetAddresses = InetAddress.getAllByName(host); - if (inetAddresses.length > 1) { - LOG.info( - "Contact point {} resolves to multiple addresses, will use them all ({})", - spec, - Arrays.deepToString(inetAddresses)); - } - Set result = new HashSet<>(); - for (InetAddress inetAddress : inetAddresses) { - result.add(new InetSocketAddress(inetAddress, port)); - } - return result; - } catch (UnknownHostException e) { - LOG.warn("Ignoring invalid contact point {} (unknown host {})", spec, host); - return Collections.emptySet(); - } - } - } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/CqlIdentifiers.java b/core/src/main/java/com/datastax/oss/driver/internal/core/CqlIdentifiers.java index c685d9d69c8..a00da0e4b1a 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/CqlIdentifiers.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/CqlIdentifiers.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/DefaultConsistencyLevelRegistry.java b/core/src/main/java/com/datastax/oss/driver/internal/core/DefaultConsistencyLevelRegistry.java index ba833674292..b563ad5facc 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/DefaultConsistencyLevelRegistry.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/DefaultConsistencyLevelRegistry.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -46,6 +48,11 @@ public int nameToCode(String name) { return NAME_TO_CODE.get(name); } + @Override + public ConsistencyLevel nameToLevel(String name) { + return DefaultConsistencyLevel.valueOf(name); + } + @Override public Iterable getValues() { return VALUES; diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/DefaultMavenCoordinates.java b/core/src/main/java/com/datastax/oss/driver/internal/core/DefaultMavenCoordinates.java index a3d529a23cf..8280ae8fec5 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/DefaultMavenCoordinates.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/DefaultMavenCoordinates.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/DefaultProtocolFeature.java b/core/src/main/java/com/datastax/oss/driver/internal/core/DefaultProtocolFeature.java index 4a756820faa..5d79f4ed0a5 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/DefaultProtocolFeature.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/DefaultProtocolFeature.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/DefaultProtocolVersionRegistry.java b/core/src/main/java/com/datastax/oss/driver/internal/core/DefaultProtocolVersionRegistry.java index 2dff6ff22f8..80850e8e95a 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/DefaultProtocolVersionRegistry.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/DefaultProtocolVersionRegistry.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -61,6 +63,9 @@ public class DefaultProtocolVersionRegistry implements ProtocolVersionRegistry { @VisibleForTesting static final Version DSE_6_0_0 = Objects.requireNonNull(Version.parse("6.0.0")); + @VisibleForTesting + static final Version DSE_7_0_0 = Objects.requireNonNull(Version.parse("7.0.0")); + private final String logPrefix; public DefaultProtocolVersionRegistry(String logPrefix) { @@ -150,9 +155,12 @@ public ProtocolVersion highestCommon(Collection nodes) { } else if (dseVersion.compareTo(DSE_6_0_0) < 0) { // DSE 5.1 removeHigherThan(DefaultProtocolVersion.V4, DseProtocolVersion.DSE_V1, candidates); - } else { + } 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(); @@ -181,9 +189,12 @@ public ProtocolVersion highestCommon(Collection nodes) { } else if (cassandraVersion.compareTo(Version.V2_2_0) < 0) { // 2.1.0 removeHigherThan(DefaultProtocolVersion.V3, null, candidates); - } else { + } 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); } } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/PagingIterableWrapper.java b/core/src/main/java/com/datastax/oss/driver/internal/core/PagingIterableWrapper.java index 55d12bb10ee..1f79f673d02 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/PagingIterableWrapper.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/PagingIterableWrapper.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/ProtocolFeature.java b/core/src/main/java/com/datastax/oss/driver/internal/core/ProtocolFeature.java index 7f4e286ea17..bf73f7bbb16 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/ProtocolFeature.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/ProtocolFeature.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/ProtocolVersionRegistry.java b/core/src/main/java/com/datastax/oss/driver/internal/core/ProtocolVersionRegistry.java index 1cb7ecfe242..eff1d099905 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/ProtocolVersionRegistry.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/ProtocolVersionRegistry.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/addresstranslation/Ec2MultiRegionAddressTranslator.java b/core/src/main/java/com/datastax/oss/driver/internal/core/addresstranslation/Ec2MultiRegionAddressTranslator.java index 055da787381..88e6cdb3bb2 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/addresstranslation/Ec2MultiRegionAddressTranslator.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/addresstranslation/Ec2MultiRegionAddressTranslator.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/addresstranslation/FixedHostNameAddressTranslator.java b/core/src/main/java/com/datastax/oss/driver/internal/core/addresstranslation/FixedHostNameAddressTranslator.java new file mode 100644 index 00000000000..5cc6c2518fb --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/addresstranslation/FixedHostNameAddressTranslator.java @@ -0,0 +1,60 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.addresstranslation; + +import static com.datastax.oss.driver.api.core.config.DefaultDriverOption.ADDRESS_TRANSLATOR_ADVERTISED_HOSTNAME; + +import com.datastax.oss.driver.api.core.addresstranslation.AddressTranslator; +import com.datastax.oss.driver.api.core.context.DriverContext; +import edu.umd.cs.findbugs.annotations.NonNull; +import java.net.InetSocketAddress; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This translator always returns same hostname, no matter what IP address a node has but still + * using its native transport port. + * + *

    The translator can be used for scenarios when all nodes are behind some kind of proxy, and it + * is not tailored for one concrete use case. One can use this, for example, for AWS PrivateLink as + * all nodes would be exposed to consumer - behind one hostname pointing to AWS Endpoint. + */ +public class FixedHostNameAddressTranslator implements AddressTranslator { + + private static final Logger LOG = LoggerFactory.getLogger(FixedHostNameAddressTranslator.class); + + private final String advertisedHostname; + private final String logPrefix; + + public FixedHostNameAddressTranslator(@NonNull DriverContext context) { + logPrefix = context.getSessionName(); + advertisedHostname = + context.getConfig().getDefaultProfile().getString(ADDRESS_TRANSLATOR_ADVERTISED_HOSTNAME); + } + + @NonNull + @Override + public InetSocketAddress translate(@NonNull InetSocketAddress address) { + final int port = address.getPort(); + LOG.debug("[{}] Resolved {}:{} to {}:{}", logPrefix, address, port, advertisedHostname, port); + return new InetSocketAddress(advertisedHostname, port); + } + + @Override + public void close() {} +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/addresstranslation/PassThroughAddressTranslator.java b/core/src/main/java/com/datastax/oss/driver/internal/core/addresstranslation/PassThroughAddressTranslator.java index 7628d6a0eda..0922821be8c 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/addresstranslation/PassThroughAddressTranslator.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/addresstranslation/PassThroughAddressTranslator.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/addresstranslation/Subnet.java b/core/src/main/java/com/datastax/oss/driver/internal/core/addresstranslation/Subnet.java new file mode 100644 index 00000000000..7c25e94e2f9 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/addresstranslation/Subnet.java @@ -0,0 +1,176 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.addresstranslation; + +import com.datastax.oss.driver.shaded.guava.common.annotations.VisibleForTesting; +import com.datastax.oss.driver.shaded.guava.common.base.Splitter; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.Arrays; +import java.util.List; + +class Subnet { + private final byte[] subnet; + private final byte[] networkMask; + private final byte[] upper; + private final byte[] lower; + + private Subnet(byte[] subnet, byte[] networkMask) { + this.subnet = subnet; + this.networkMask = networkMask; + + byte[] upper = new byte[subnet.length]; + byte[] lower = new byte[subnet.length]; + for (int i = 0; i < subnet.length; i++) { + upper[i] = (byte) (subnet[i] | ~networkMask[i]); + lower[i] = (byte) (subnet[i] & networkMask[i]); + } + this.upper = upper; + this.lower = lower; + } + + static Subnet parse(String subnetCIDR) throws UnknownHostException { + List parts = Splitter.on("/").splitToList(subnetCIDR); + if (parts.size() != 2) { + throw new IllegalArgumentException("Invalid subnet: " + subnetCIDR); + } + + boolean isIPv6 = parts.get(0).contains(":"); + byte[] subnet = InetAddress.getByName(parts.get(0)).getAddress(); + if (isIPv4(subnet) && isIPv6) { + subnet = toIPv6(subnet); + } + int prefixLength = Integer.parseInt(parts.get(1)); + validatePrefixLength(subnet, prefixLength); + + byte[] networkMask = toNetworkMask(subnet, prefixLength); + validateSubnetIsPrefixBlock(subnet, networkMask, subnetCIDR); + return new Subnet(subnet, networkMask); + } + + private static byte[] toNetworkMask(byte[] subnet, int prefixLength) { + int fullBytes = prefixLength / 8; + int remainingBits = prefixLength % 8; + byte[] mask = new byte[subnet.length]; + Arrays.fill(mask, 0, fullBytes, (byte) 0xFF); + if (remainingBits > 0) { + mask[fullBytes] = (byte) (0xFF << (8 - remainingBits)); + } + return mask; + } + + private static void validatePrefixLength(byte[] subnet, int prefixLength) { + int max_prefix_length = subnet.length * 8; + if (prefixLength < 0 || max_prefix_length < prefixLength) { + throw new IllegalArgumentException( + String.format( + "Prefix length %s must be within [0; %s]", prefixLength, max_prefix_length)); + } + } + + private static void validateSubnetIsPrefixBlock( + byte[] subnet, byte[] networkMask, String subnetCIDR) { + byte[] prefixBlock = toPrefixBlock(subnet, networkMask); + if (!Arrays.equals(subnet, prefixBlock)) { + throw new IllegalArgumentException( + String.format("Subnet %s must be represented as a network prefix block", subnetCIDR)); + } + } + + private static byte[] toPrefixBlock(byte[] subnet, byte[] networkMask) { + byte[] prefixBlock = new byte[subnet.length]; + for (int i = 0; i < subnet.length; i++) { + prefixBlock[i] = (byte) (subnet[i] & networkMask[i]); + } + return prefixBlock; + } + + @VisibleForTesting + byte[] getSubnet() { + return Arrays.copyOf(subnet, subnet.length); + } + + @VisibleForTesting + byte[] getNetworkMask() { + return Arrays.copyOf(networkMask, networkMask.length); + } + + byte[] getUpper() { + return Arrays.copyOf(upper, upper.length); + } + + byte[] getLower() { + return Arrays.copyOf(lower, lower.length); + } + + boolean isIPv4() { + return isIPv4(subnet); + } + + boolean isIPv6() { + return isIPv6(subnet); + } + + boolean contains(byte[] ip) { + if (isIPv4() && !isIPv4(ip)) { + return false; + } + if (isIPv6() && isIPv4(ip)) { + ip = toIPv6(ip); + } + if (subnet.length != ip.length) { + throw new IllegalArgumentException( + "IP version is unknown: " + Arrays.toString(toZeroBasedByteArray(ip))); + } + for (int i = 0; i < subnet.length; i++) { + if (subnet[i] != (byte) (ip[i] & networkMask[i])) { + return false; + } + } + return true; + } + + private static boolean isIPv4(byte[] ip) { + return ip.length == 4; + } + + private static boolean isIPv6(byte[] ip) { + return ip.length == 16; + } + + private static byte[] toIPv6(byte[] ipv4) { + byte[] ipv6 = new byte[16]; + ipv6[10] = (byte) 0xFF; + ipv6[11] = (byte) 0xFF; + System.arraycopy(ipv4, 0, ipv6, 12, 4); + return ipv6; + } + + @Override + public String toString() { + return Arrays.toString(toZeroBasedByteArray(subnet)); + } + + private static int[] toZeroBasedByteArray(byte[] bytes) { + int[] res = new int[bytes.length]; + for (int i = 0; i < bytes.length; i++) { + res[i] = bytes[i] & 0xFF; + } + return res; + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/addresstranslation/SubnetAddress.java b/core/src/main/java/com/datastax/oss/driver/internal/core/addresstranslation/SubnetAddress.java new file mode 100644 index 00000000000..105e776a507 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/addresstranslation/SubnetAddress.java @@ -0,0 +1,65 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.addresstranslation; + +import java.net.InetSocketAddress; +import java.net.UnknownHostException; + +class SubnetAddress { + private final Subnet subnet; + private final InetSocketAddress address; + + SubnetAddress(String subnetCIDR, InetSocketAddress address) { + try { + this.subnet = Subnet.parse(subnetCIDR); + } catch (UnknownHostException e) { + throw new RuntimeException(e); + } + this.address = address; + } + + InetSocketAddress getAddress() { + return this.address; + } + + boolean isOverlapping(SubnetAddress other) { + Subnet thisSubnet = this.subnet; + Subnet otherSubnet = other.subnet; + return thisSubnet.contains(otherSubnet.getLower()) + || thisSubnet.contains(otherSubnet.getUpper()) + || otherSubnet.contains(thisSubnet.getLower()) + || otherSubnet.contains(thisSubnet.getUpper()); + } + + boolean contains(InetSocketAddress address) { + return subnet.contains(address.getAddress().getAddress()); + } + + boolean isIPv4() { + return subnet.isIPv4(); + } + + boolean isIPv6() { + return subnet.isIPv6(); + } + + @Override + public String toString() { + return "SubnetAddress[subnet=" + subnet + ", address=" + address + "]"; + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/addresstranslation/SubnetAddressTranslator.java b/core/src/main/java/com/datastax/oss/driver/internal/core/addresstranslation/SubnetAddressTranslator.java new file mode 100644 index 00000000000..85f29e3fadd --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/addresstranslation/SubnetAddressTranslator.java @@ -0,0 +1,148 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.addresstranslation; + +import static com.datastax.oss.driver.api.core.config.DefaultDriverOption.ADDRESS_TRANSLATOR_DEFAULT_ADDRESS; +import static com.datastax.oss.driver.api.core.config.DefaultDriverOption.ADDRESS_TRANSLATOR_RESOLVE_ADDRESSES; +import static com.datastax.oss.driver.api.core.config.DefaultDriverOption.ADDRESS_TRANSLATOR_SUBNET_ADDRESSES; + +import com.datastax.oss.driver.api.core.addresstranslation.AddressTranslator; +import com.datastax.oss.driver.api.core.context.DriverContext; +import com.datastax.oss.driver.internal.core.util.AddressUtils; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.Nullable; +import java.net.InetSocketAddress; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This translator returns the proxy address of the private subnet containing the Cassandra node IP, + * or default address if no matching subnets, or passes through the original node address if no + * default configured. + * + *

    The translator can be used for scenarios when all nodes are behind some kind of proxy, and + * that proxy is different for nodes located in different subnets (eg. when Cassandra is deployed in + * multiple datacenters/regions). One can use this, for example, for Cassandra on Kubernetes with + * different Cassandra datacenters deployed to different Kubernetes clusters. + */ +public class SubnetAddressTranslator implements AddressTranslator { + private static final Logger LOG = LoggerFactory.getLogger(SubnetAddressTranslator.class); + + private final List subnetAddresses; + + @SuppressWarnings("OptionalUsedAsFieldOrParameterType") + private final Optional defaultAddress; + + private final String logPrefix; + + public SubnetAddressTranslator(@NonNull DriverContext context) { + logPrefix = context.getSessionName(); + boolean resolveAddresses = + context + .getConfig() + .getDefaultProfile() + .getBoolean(ADDRESS_TRANSLATOR_RESOLVE_ADDRESSES, false); + this.subnetAddresses = + context.getConfig().getDefaultProfile().getStringMap(ADDRESS_TRANSLATOR_SUBNET_ADDRESSES) + .entrySet().stream() + .map( + e -> { + // Quoted and/or containing forward slashes map keys in reference.conf are read to + // strings with additional quotes, eg. 100.64.0.0/15 -> '100.64.0."0/15"' or + // "100.64.0.0/15" -> '"100.64.0.0/15"' + String subnetCIDR = e.getKey().replaceAll("\"", ""); + String address = e.getValue(); + return new SubnetAddress(subnetCIDR, parseAddress(address, resolveAddresses)); + }) + .collect(Collectors.toList()); + this.defaultAddress = + Optional.ofNullable( + context + .getConfig() + .getDefaultProfile() + .getString(ADDRESS_TRANSLATOR_DEFAULT_ADDRESS, null)) + .map(address -> parseAddress(address, resolveAddresses)); + + validateSubnetsAreOfSameProtocol(this.subnetAddresses); + validateSubnetsAreNotOverlapping(this.subnetAddresses); + } + + private static void validateSubnetsAreOfSameProtocol(List subnets) { + for (int i = 0; i < subnets.size() - 1; i++) { + for (int j = i + 1; j < subnets.size(); j++) { + SubnetAddress subnet1 = subnets.get(i); + SubnetAddress subnet2 = subnets.get(j); + if (subnet1.isIPv4() != subnet2.isIPv4() && subnet1.isIPv6() != subnet2.isIPv6()) { + throw new IllegalArgumentException( + String.format( + "Configured subnets are of the different protocols: %s, %s", subnet1, subnet2)); + } + } + } + } + + private static void validateSubnetsAreNotOverlapping(List subnets) { + for (int i = 0; i < subnets.size() - 1; i++) { + for (int j = i + 1; j < subnets.size(); j++) { + SubnetAddress subnet1 = subnets.get(i); + SubnetAddress subnet2 = subnets.get(j); + if (subnet1.isOverlapping(subnet2)) { + throw new IllegalArgumentException( + String.format("Configured subnets are overlapping: %s, %s", subnet1, subnet2)); + } + } + } + } + + @NonNull + @Override + public InetSocketAddress translate(@NonNull InetSocketAddress address) { + InetSocketAddress translatedAddress = null; + for (SubnetAddress subnetAddress : subnetAddresses) { + if (subnetAddress.contains(address)) { + translatedAddress = subnetAddress.getAddress(); + } + } + if (translatedAddress == null && defaultAddress.isPresent()) { + translatedAddress = defaultAddress.get(); + } + if (translatedAddress == null) { + translatedAddress = address; + } + LOG.debug("[{}] Translated {} to {}", logPrefix, address, translatedAddress); + return translatedAddress; + } + + @Override + public void close() {} + + @Nullable + private InetSocketAddress parseAddress(String address, boolean resolve) { + try { + InetSocketAddress parsedAddress = AddressUtils.extract(address, resolve).iterator().next(); + LOG.debug("[{}] Parsed {} to {}", logPrefix, address, parsedAddress); + return parsedAddress; + } catch (RuntimeException e) { + throw new IllegalArgumentException( + String.format("Invalid address %s (%s)", address, e.getMessage()), e); + } + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/adminrequest/AdminRequestHandler.java b/core/src/main/java/com/datastax/oss/driver/internal/core/adminrequest/AdminRequestHandler.java index 60e033c344d..5078428c21a 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/adminrequest/AdminRequestHandler.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/adminrequest/AdminRequestHandler.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -47,7 +49,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** Handles the lifecyle of an admin request (such as a node refresh or schema refresh query). */ +/** Handles the lifecycle of an admin request (such as a node refresh or schema refresh query). */ @ThreadSafe public class AdminRequestHandler implements ResponseCallback { private static final Logger LOG = LoggerFactory.getLogger(AdminRequestHandler.class); diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/adminrequest/AdminResult.java b/core/src/main/java/com/datastax/oss/driver/internal/core/adminrequest/AdminResult.java index 6c567ef7174..686cc05c6b0 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/adminrequest/AdminResult.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/adminrequest/AdminResult.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/adminrequest/AdminRow.java b/core/src/main/java/com/datastax/oss/driver/internal/core/adminrequest/AdminRow.java index c4c98a79bd5..6e32ea845fb 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/adminrequest/AdminRow.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/adminrequest/AdminRow.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/adminrequest/ThrottledAdminRequestHandler.java b/core/src/main/java/com/datastax/oss/driver/internal/core/adminrequest/ThrottledAdminRequestHandler.java index a7d872cc1ee..40ab21b759a 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/adminrequest/ThrottledAdminRequestHandler.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/adminrequest/ThrottledAdminRequestHandler.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/adminrequest/UnexpectedResponseException.java b/core/src/main/java/com/datastax/oss/driver/internal/core/adminrequest/UnexpectedResponseException.java index f23a7e90537..c842b655411 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/adminrequest/UnexpectedResponseException.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/adminrequest/UnexpectedResponseException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/adminrequest/package-info.java b/core/src/main/java/com/datastax/oss/driver/internal/core/adminrequest/package-info.java index e12c4db8514..55ab14c8981 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/adminrequest/package-info.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/adminrequest/package-info.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/auth/PlainTextAuthProvider.java b/core/src/main/java/com/datastax/oss/driver/internal/core/auth/PlainTextAuthProvider.java index de951b881f1..f2dfdf14171 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/auth/PlainTextAuthProvider.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/auth/PlainTextAuthProvider.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -39,14 +41,18 @@ * username = cassandra * password = cassandra * - * // If connecting to Datastax Enterprise, this additional option allows proxy authentication + * // If connecting to DataStax Enterprise, this additional option allows proxy authentication * // (login as another user or role) * authorization-id = userOrRole * } * } * * - * See {@code reference.conf} (in the manual or core driver JAR) for more details. + * The authentication provider cannot be changed at runtime; however, the credentials can be changed + * at runtime: the new ones will be used for new connection attempts once the configuration gets + * {@linkplain com.datastax.oss.driver.api.core.config.DriverConfigLoader#reload() reloaded}. + * + *

    See {@code reference.conf} (in the manual or core driver JAR) for more details. */ @ThreadSafe public class PlainTextAuthProvider extends PlainTextAuthProviderBase { diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/auth/ProgrammaticPlainTextAuthProvider.java b/core/src/main/java/com/datastax/oss/driver/internal/core/auth/ProgrammaticPlainTextAuthProvider.java deleted file mode 100644 index ba0bc4b41db..00000000000 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/auth/ProgrammaticPlainTextAuthProvider.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.datastax.oss.driver.internal.core.auth; - -import com.datastax.oss.driver.api.core.auth.PlainTextAuthProviderBase; -import com.datastax.oss.driver.api.core.metadata.EndPoint; -import com.datastax.oss.driver.api.core.session.SessionBuilder; -import edu.umd.cs.findbugs.annotations.NonNull; -import net.jcip.annotations.ThreadSafe; - -/** - * Alternative plaintext auth provider that receives the credentials programmatically instead of - * pulling them from the configuration. - * - * @see SessionBuilder#withAuthCredentials(String, String) - * @see SessionBuilder#withAuthCredentials(String, String, String) - */ -@ThreadSafe -public class ProgrammaticPlainTextAuthProvider extends PlainTextAuthProviderBase { - private final String username; - private final String password; - private final String authorizationId; - - /** Builds an instance for simple username/password authentication. */ - public ProgrammaticPlainTextAuthProvider(String username, String password) { - this(username, password, ""); - } - - /** - * Builds an instance for username/password authentication, and proxy authentication with the - * given authorizationId. - * - *

    This feature is only available with Datastax Enterprise. If the target server is Apache - * Cassandra, the authorizationId will be ignored. - */ - public ProgrammaticPlainTextAuthProvider( - String username, String password, String authorizationId) { - // This will typically be built before the session so we don't know the log prefix yet. Pass an - // empty string, it's only used in one log message. - super(""); - this.username = username; - this.password = password; - this.authorizationId = authorizationId; - } - - @NonNull - @Override - protected Credentials getCredentials( - @NonNull EndPoint endPoint, @NonNull String serverAuthenticator) { - return new Credentials( - username.toCharArray(), password.toCharArray(), authorizationId.toCharArray()); - } -} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/ChannelEvent.java b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/ChannelEvent.java index a2cb5d35956..970ea061ec7 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/ChannelEvent.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/ChannelEvent.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/ChannelFactory.java b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/ChannelFactory.java index 4e2defdce49..66a5c4edc0e 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/ChannelFactory.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/ChannelFactory.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -272,98 +274,121 @@ ChannelInitializer initializer( DriverChannelOptions options, NodeMetricUpdater nodeMetricUpdater, CompletableFuture resultFuture) { - return new ChannelInitializer() { - @Override - protected void initChannel(Channel channel) { - try { - DriverExecutionProfile defaultConfig = context.getConfig().getDefaultProfile(); - - long setKeyspaceTimeoutMillis = - defaultConfig - .getDuration(DefaultDriverOption.CONNECTION_SET_KEYSPACE_TIMEOUT) - .toMillis(); - int maxFrameLength = - (int) defaultConfig.getBytes(DefaultDriverOption.PROTOCOL_MAX_FRAME_LENGTH); - int maxRequestsPerConnection = - defaultConfig.getInt(DefaultDriverOption.CONNECTION_MAX_REQUESTS); - int maxOrphanRequests = - defaultConfig.getInt(DefaultDriverOption.CONNECTION_MAX_ORPHAN_REQUESTS); - if (maxOrphanRequests >= maxRequestsPerConnection) { - if (LOGGED_ORPHAN_WARNING.compareAndSet(false, true)) { - LOG.warn( - "[{}] Invalid value for {}: {}. It must be lower than {}. " - + "Defaulting to {} (1/4 of max-requests) instead.", - logPrefix, - DefaultDriverOption.CONNECTION_MAX_ORPHAN_REQUESTS.getPath(), - maxOrphanRequests, - DefaultDriverOption.CONNECTION_MAX_REQUESTS.getPath(), - maxRequestsPerConnection / 4); - } - maxOrphanRequests = maxRequestsPerConnection / 4; - } + return new ChannelFactoryInitializer( + endPoint, protocolVersion, options, nodeMetricUpdater, resultFuture); + }; + + class ChannelFactoryInitializer extends ChannelInitializer { + + private final EndPoint endPoint; + private final ProtocolVersion protocolVersion; + private final DriverChannelOptions options; + private final NodeMetricUpdater nodeMetricUpdater; + private final CompletableFuture resultFuture; + + ChannelFactoryInitializer( + EndPoint endPoint, + ProtocolVersion protocolVersion, + DriverChannelOptions options, + NodeMetricUpdater nodeMetricUpdater, + CompletableFuture resultFuture) { + + this.endPoint = endPoint; + this.protocolVersion = protocolVersion; + this.options = options; + this.nodeMetricUpdater = nodeMetricUpdater; + this.resultFuture = resultFuture; + } - InFlightHandler inFlightHandler = - new InFlightHandler( - protocolVersion, - new StreamIdGenerator(maxRequestsPerConnection), - maxOrphanRequests, - setKeyspaceTimeoutMillis, - channel.newPromise(), - options.eventCallback, - options.ownerLogPrefix); - HeartbeatHandler heartbeatHandler = new HeartbeatHandler(defaultConfig); - ProtocolInitHandler initHandler = - new ProtocolInitHandler( - context, - protocolVersion, - clusterName, - endPoint, - options, - heartbeatHandler, - productType == null); - - ChannelPipeline pipeline = channel.pipeline(); - context - .getSslHandlerFactory() - .map(f -> f.newSslHandler(channel, endPoint)) - .map(h -> pipeline.addLast(SSL_HANDLER_NAME, h)); - - // Only add meter handlers on the pipeline if metrics are enabled. - SessionMetricUpdater sessionMetricUpdater = - context.getMetricsFactory().getSessionUpdater(); - if (nodeMetricUpdater.isEnabled(DefaultNodeMetric.BYTES_RECEIVED, null) - || sessionMetricUpdater.isEnabled(DefaultSessionMetric.BYTES_RECEIVED, null)) { - pipeline.addLast( - INBOUND_TRAFFIC_METER_NAME, - new InboundTrafficMeter(nodeMetricUpdater, sessionMetricUpdater)); + @Override + protected void initChannel(Channel channel) { + try { + DriverExecutionProfile defaultConfig = context.getConfig().getDefaultProfile(); + + long setKeyspaceTimeoutMillis = + defaultConfig + .getDuration(DefaultDriverOption.CONNECTION_SET_KEYSPACE_TIMEOUT) + .toMillis(); + int maxFrameLength = + (int) defaultConfig.getBytes(DefaultDriverOption.PROTOCOL_MAX_FRAME_LENGTH); + int maxRequestsPerConnection = + defaultConfig.getInt(DefaultDriverOption.CONNECTION_MAX_REQUESTS); + int maxOrphanRequests = + defaultConfig.getInt(DefaultDriverOption.CONNECTION_MAX_ORPHAN_REQUESTS); + if (maxOrphanRequests >= maxRequestsPerConnection) { + if (LOGGED_ORPHAN_WARNING.compareAndSet(false, true)) { + LOG.warn( + "[{}] Invalid value for {}: {}. It must be lower than {}. " + + "Defaulting to {} (1/4 of max-requests) instead.", + logPrefix, + DefaultDriverOption.CONNECTION_MAX_ORPHAN_REQUESTS.getPath(), + maxOrphanRequests, + DefaultDriverOption.CONNECTION_MAX_REQUESTS.getPath(), + maxRequestsPerConnection / 4); } + maxOrphanRequests = maxRequestsPerConnection / 4; + } - if (nodeMetricUpdater.isEnabled(DefaultNodeMetric.BYTES_SENT, null) - || sessionMetricUpdater.isEnabled(DefaultSessionMetric.BYTES_SENT, null)) { - pipeline.addLast( - OUTBOUND_TRAFFIC_METER_NAME, - new OutboundTrafficMeter(nodeMetricUpdater, sessionMetricUpdater)); - } + InFlightHandler inFlightHandler = + new InFlightHandler( + protocolVersion, + new StreamIdGenerator(maxRequestsPerConnection), + maxOrphanRequests, + setKeyspaceTimeoutMillis, + channel.newPromise(), + options.eventCallback, + options.ownerLogPrefix); + HeartbeatHandler heartbeatHandler = new HeartbeatHandler(defaultConfig); + ProtocolInitHandler initHandler = + new ProtocolInitHandler( + context, + protocolVersion, + clusterName, + endPoint, + options, + heartbeatHandler, + productType == null); + + ChannelPipeline pipeline = channel.pipeline(); + context + .getSslHandlerFactory() + .map(f -> f.newSslHandler(channel, endPoint)) + .map(h -> pipeline.addLast(SSL_HANDLER_NAME, h)); + + // Only add meter handlers on the pipeline if metrics are enabled. + SessionMetricUpdater sessionMetricUpdater = context.getMetricsFactory().getSessionUpdater(); + if (nodeMetricUpdater.isEnabled(DefaultNodeMetric.BYTES_RECEIVED, null) + || sessionMetricUpdater.isEnabled(DefaultSessionMetric.BYTES_RECEIVED, null)) { + pipeline.addLast( + INBOUND_TRAFFIC_METER_NAME, + new InboundTrafficMeter(nodeMetricUpdater, sessionMetricUpdater)); + } - pipeline - .addLast( - FRAME_TO_BYTES_ENCODER_NAME, - new FrameEncoder(context.getFrameCodec(), maxFrameLength)) - .addLast( - BYTES_TO_FRAME_DECODER_NAME, - new FrameDecoder(context.getFrameCodec(), maxFrameLength)) - // Note: HeartbeatHandler is inserted here once init completes - .addLast(INFLIGHT_HANDLER_NAME, inFlightHandler) - .addLast(INIT_HANDLER_NAME, initHandler); - - context.getNettyOptions().afterChannelInitialized(channel); - } catch (Throwable t) { - // If the init handler throws an exception, Netty swallows it and closes the channel. We - // want to propagate it instead, so fail the outer future (the result of connect()). - resultFuture.completeExceptionally(t); - throw t; + if (nodeMetricUpdater.isEnabled(DefaultNodeMetric.BYTES_SENT, null) + || sessionMetricUpdater.isEnabled(DefaultSessionMetric.BYTES_SENT, null)) { + pipeline.addLast( + OUTBOUND_TRAFFIC_METER_NAME, + new OutboundTrafficMeter(nodeMetricUpdater, sessionMetricUpdater)); } + + pipeline + .addLast( + FRAME_TO_BYTES_ENCODER_NAME, + new FrameEncoder(context.getFrameCodec(), maxFrameLength)) + .addLast( + BYTES_TO_FRAME_DECODER_NAME, + new FrameDecoder(context.getFrameCodec(), maxFrameLength)) + // Note: HeartbeatHandler is inserted here once init completes + .addLast(INFLIGHT_HANDLER_NAME, inFlightHandler) + .addLast(INIT_HANDLER_NAME, initHandler); + + context.getNettyOptions().afterChannelInitialized(channel); + } catch (Throwable t) { + // If the init handler throws an exception, Netty swallows it and closes the channel. We + // want to propagate it instead, so fail the outer future (the result of connect()). + resultFuture.completeExceptionally(t); + throw t; } - }; + } } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/ChannelHandlerRequest.java b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/ChannelHandlerRequest.java index e6a20c0d233..3ba3d70eb8d 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/ChannelHandlerRequest.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/ChannelHandlerRequest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/ClusterNameMismatchException.java b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/ClusterNameMismatchException.java index 04abdfb0368..8e47db3fb1b 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/ClusterNameMismatchException.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/ClusterNameMismatchException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/ConnectInitHandler.java b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/ConnectInitHandler.java index ae88d86b4f2..789981b4832 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/ConnectInitHandler.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/ConnectInitHandler.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/DefaultWriteCoalescer.java b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/DefaultWriteCoalescer.java index 204f1d77b3d..232fa83be44 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/DefaultWriteCoalescer.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/DefaultWriteCoalescer.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/DriverChannel.java b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/DriverChannel.java index 12bb6bbd95f..e40aa6f3097 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/DriverChannel.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/DriverChannel.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -47,9 +49,9 @@ @ThreadSafe public class DriverChannel { - static final AttributeKey CLUSTER_NAME_KEY = AttributeKey.newInstance("cluster_name"); + static final AttributeKey CLUSTER_NAME_KEY = AttributeKey.valueOf("cluster_name"); static final AttributeKey>> OPTIONS_KEY = - AttributeKey.newInstance("options"); + AttributeKey.valueOf("options"); @SuppressWarnings("RedundantStringConstructorCall") static final Object GRACEFUL_CLOSE_MESSAGE = new String("GRACEFUL_CLOSE_MESSAGE"); diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/DriverChannelOptions.java b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/DriverChannelOptions.java index 258f1ab0c42..208cf52ac22 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/DriverChannelOptions.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/DriverChannelOptions.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/EventCallback.java b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/EventCallback.java index df85d8ca7b0..0ac71233fdd 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/EventCallback.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/EventCallback.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/HeartbeatHandler.java b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/HeartbeatHandler.java index 605de2ad5f9..3dac60f5216 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/HeartbeatHandler.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/HeartbeatHandler.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/InFlightHandler.java b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/InFlightHandler.java index eb6bce925c9..90b02f358cd 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/InFlightHandler.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/InFlightHandler.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -197,14 +199,14 @@ private void startGracefulShutdown(ChannelHandlerContext ctx) { LOG.debug("[{}] No pending queries, completing graceful shutdown now", logPrefix); ctx.channel().close(); } else { - // remove heartbeat handler from pipeline if present. + // Remove heartbeat handler from pipeline if present. ChannelHandler heartbeatHandler = ctx.pipeline().get(ChannelFactory.HEARTBEAT_HANDLER_NAME); if (heartbeatHandler != null) { ctx.pipeline().remove(heartbeatHandler); } LOG.debug("[{}] There are pending queries, delaying graceful shutdown", logPrefix); closingGracefully = true; - closeStartedFuture.setSuccess(); + closeStartedFuture.trySuccess(); } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/InboundTrafficMeter.java b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/InboundTrafficMeter.java index eea4b8a6179..518f398a808 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/InboundTrafficMeter.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/InboundTrafficMeter.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/OutboundTrafficMeter.java b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/OutboundTrafficMeter.java index e07bcac99ed..768eb047b9d 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/OutboundTrafficMeter.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/OutboundTrafficMeter.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/PassThroughWriteCoalescer.java b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/PassThroughWriteCoalescer.java index d8870bc3813..4e3f7d61f66 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/PassThroughWriteCoalescer.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/PassThroughWriteCoalescer.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/ProtocolInitHandler.java b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/ProtocolInitHandler.java index 9d4969040d6..8a426f7b368 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/ProtocolInitHandler.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/ProtocolInitHandler.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -79,7 +81,7 @@ class ProtocolInitHandler extends ConnectInitHandler { private final HeartbeatHandler heartbeatHandler; private String logPrefix; private ChannelHandlerContext ctx; - private boolean querySupportedOptions; + private final boolean querySupportedOptions; /** * @param querySupportedOptions whether to send OPTIONS as the first message, to request which @@ -326,9 +328,11 @@ void onResponse(Message response) { (step == Step.OPTIONS && querySupportedOptions) || step == Step.STARTUP; boolean serverOrProtocolError = error.code == ErrorCode.PROTOCOL_ERROR || error.code == ErrorCode.SERVER_ERROR; - if (firstRequest - && serverOrProtocolError - && error.message.contains("Invalid or unsupported protocol version")) { + boolean badProtocolVersionMessage = + error.message.contains("Invalid or unsupported protocol version") + // JAVA-2925: server is behind driver and considers the proposed version as beta + || error.message.contains("Beta version of the protocol used"); + if (firstRequest && serverOrProtocolError && badProtocolVersionMessage) { fail( UnsupportedProtocolVersionException.forSingleAttempt( endPoint, initialProtocolVersion)); diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/ResponseCallback.java b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/ResponseCallback.java index e8fcd87247f..5a0e9e5eb86 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/ResponseCallback.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/ResponseCallback.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/StreamIdGenerator.java b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/StreamIdGenerator.java index 934eeefc061..3384bc57c94 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/StreamIdGenerator.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/StreamIdGenerator.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -34,7 +36,7 @@ class StreamIdGenerator { private final int maxAvailableIds; // unset = available, set = borrowed (note that this is the opposite of the 3.x implementation) private final BitSet ids; - private AtomicInteger availableIds; + private final AtomicInteger availableIds; StreamIdGenerator(int maxAvailableIds) { this.maxAvailableIds = maxAvailableIds; diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/WriteCoalescer.java b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/WriteCoalescer.java index 03fa691049d..03391c57809 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/WriteCoalescer.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/WriteCoalescer.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/package-info.java b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/package-info.java index ecf6b6bc5af..d8514bdb88c 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/channel/package-info.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/channel/package-info.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/config/ConfigChangeEvent.java b/core/src/main/java/com/datastax/oss/driver/internal/core/config/ConfigChangeEvent.java index a4dd8fd67c0..d2898d39925 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/config/ConfigChangeEvent.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/config/ConfigChangeEvent.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/config/DerivedExecutionProfile.java b/core/src/main/java/com/datastax/oss/driver/internal/core/config/DerivedExecutionProfile.java index c5af1aca472..39c37d78c10 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/config/DerivedExecutionProfile.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/config/DerivedExecutionProfile.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/config/DriverOptionConfigBuilder.java b/core/src/main/java/com/datastax/oss/driver/internal/core/config/DriverOptionConfigBuilder.java index 2bf872e8159..5775fcbe507 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/config/DriverOptionConfigBuilder.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/config/DriverOptionConfigBuilder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/config/cloud/CloudConfig.java b/core/src/main/java/com/datastax/oss/driver/internal/core/config/cloud/CloudConfig.java index e2207e3db95..1a1076e9d78 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/config/cloud/CloudConfig.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/config/cloud/CloudConfig.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/config/cloud/CloudConfigFactory.java b/core/src/main/java/com/datastax/oss/driver/internal/core/config/cloud/CloudConfigFactory.java index f7386dcc390..817b3263d25 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/config/cloud/CloudConfigFactory.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/config/cloud/CloudConfigFactory.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -227,7 +229,6 @@ protected BufferedReader fetchProxyMetadata( HttpsURLConnection connection = (HttpsURLConnection) metadataServiceUrl.openConnection(); connection.setSSLSocketFactory(sslContext.getSocketFactory()); connection.setRequestMethod("GET"); - connection.setRequestProperty("host", "localhost"); return new BufferedReader( new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8)); } catch (ConnectException e) { diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/config/composite/CompositeDriverConfig.java b/core/src/main/java/com/datastax/oss/driver/internal/core/config/composite/CompositeDriverConfig.java index da4dbe645e3..9a74d00df4f 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/config/composite/CompositeDriverConfig.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/config/composite/CompositeDriverConfig.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/config/composite/CompositeDriverConfigLoader.java b/core/src/main/java/com/datastax/oss/driver/internal/core/config/composite/CompositeDriverConfigLoader.java index 1f20683b9bb..23baf458c85 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/config/composite/CompositeDriverConfigLoader.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/config/composite/CompositeDriverConfigLoader.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/config/composite/CompositeDriverExecutionProfile.java b/core/src/main/java/com/datastax/oss/driver/internal/core/config/composite/CompositeDriverExecutionProfile.java index 5d7df7b417f..147d9e0bdb4 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/config/composite/CompositeDriverExecutionProfile.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/config/composite/CompositeDriverExecutionProfile.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -21,6 +23,7 @@ import com.datastax.oss.driver.shaded.guava.common.base.Preconditions; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableSortedSet; import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.Nullable; import java.time.Duration; import java.util.List; import java.util.Map; @@ -35,8 +38,8 @@ public class CompositeDriverExecutionProfile implements DriverExecutionProfile { private final DriverConfig fallbackConfig; private final String profileName; - private volatile DriverExecutionProfile primaryProfile; - private volatile DriverExecutionProfile fallbackProfile; + @Nullable private volatile DriverExecutionProfile primaryProfile; + @Nullable private volatile DriverExecutionProfile fallbackProfile; public CompositeDriverExecutionProfile( @NonNull DriverConfig primaryConfig, @@ -89,8 +92,13 @@ public String getName() { @Override public boolean isDefined(@NonNull DriverOption option) { - return (primaryProfile != null && primaryProfile.isDefined(option)) - || (fallbackProfile != null && fallbackProfile.isDefined(option)); + DriverExecutionProfile primaryProfile = this.primaryProfile; + if (primaryProfile != null && primaryProfile.isDefined(option)) { + return true; + } else { + DriverExecutionProfile fallbackProfile = this.fallbackProfile; + return fallbackProfile != null && fallbackProfile.isDefined(option); + } } @Override @@ -181,21 +189,34 @@ public List getDurationList(@NonNull DriverOption option) { private ValueT get( @NonNull DriverOption option, BiFunction getter) { + DriverExecutionProfile primaryProfile = this.primaryProfile; if (primaryProfile != null && primaryProfile.isDefined(option)) { return getter.apply(primaryProfile, option); - } else if (fallbackProfile != null && fallbackProfile.isDefined(option)) { - return getter.apply(fallbackProfile, option); } else { - throw new IllegalArgumentException("Unknown option: " + option); + DriverExecutionProfile fallbackProfile = this.fallbackProfile; + if (fallbackProfile != null && fallbackProfile.isDefined(option)) { + return getter.apply(fallbackProfile, option); + } else { + throw new IllegalArgumentException("Unknown option: " + option); + } } } @NonNull @Override public SortedSet> entrySet() { - SortedSet> result = new TreeSet<>(Map.Entry.comparingByKey()); - result.addAll(fallbackProfile.entrySet()); - result.addAll(primaryProfile.entrySet()); - return ImmutableSortedSet.copyOf(result); + DriverExecutionProfile primaryProfile = this.primaryProfile; + DriverExecutionProfile fallbackProfile = this.fallbackProfile; + if (primaryProfile != null && fallbackProfile != null) { + SortedSet> result = new TreeSet<>(Map.Entry.comparingByKey()); + result.addAll(fallbackProfile.entrySet()); + result.addAll(primaryProfile.entrySet()); + return ImmutableSortedSet.copyOf(Map.Entry.comparingByKey(), result); + } else if (primaryProfile != null) { + return primaryProfile.entrySet(); + } else { + assert fallbackProfile != null; + return fallbackProfile.entrySet(); + } } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/config/map/MapBasedDriverConfig.java b/core/src/main/java/com/datastax/oss/driver/internal/core/config/map/MapBasedDriverConfig.java index 6b189e43f3e..74adbf120ca 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/config/map/MapBasedDriverConfig.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/config/map/MapBasedDriverConfig.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/config/map/MapBasedDriverConfigLoader.java b/core/src/main/java/com/datastax/oss/driver/internal/core/config/map/MapBasedDriverConfigLoader.java index 85fcad563c1..14f959e5dc0 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/config/map/MapBasedDriverConfigLoader.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/config/map/MapBasedDriverConfigLoader.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/config/map/MapBasedDriverExecutionProfile.java b/core/src/main/java/com/datastax/oss/driver/internal/core/config/map/MapBasedDriverExecutionProfile.java index 339d27a6687..4234befd94b 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/config/map/MapBasedDriverExecutionProfile.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/config/map/MapBasedDriverExecutionProfile.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/config/typesafe/DefaultDriverConfigLoader.java b/core/src/main/java/com/datastax/oss/driver/internal/core/config/typesafe/DefaultDriverConfigLoader.java index 9b068443874..f1bfbea8249 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/config/typesafe/DefaultDriverConfigLoader.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/config/typesafe/DefaultDriverConfigLoader.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -30,12 +32,16 @@ import com.datastax.oss.driver.internal.core.util.concurrent.RunOrSchedule; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; +import com.typesafe.config.ConfigParseOptions; import edu.umd.cs.findbugs.annotations.NonNull; import io.netty.util.concurrent.EventExecutor; import io.netty.util.concurrent.ScheduledFuture; +import java.io.File; +import java.net.URL; import java.time.Duration; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; +import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import net.jcip.annotations.ThreadSafe; @@ -65,6 +71,67 @@ public class DefaultDriverConfigLoader implements DriverConfigLoader { .getConfig(DEFAULT_ROOT_PATH); }; + @NonNull + public static DefaultDriverConfigLoader fromClasspath( + @NonNull String resourceBaseName, @NonNull ClassLoader appClassLoader) { + return new DefaultDriverConfigLoader( + () -> { + ConfigFactory.invalidateCaches(); + Config config = + ConfigFactory.defaultOverrides() + .withFallback( + ConfigFactory.parseResourcesAnySyntax( + resourceBaseName, + ConfigParseOptions.defaults().setClassLoader(appClassLoader))) + .withFallback(ConfigFactory.defaultReference(CqlSession.class.getClassLoader())) + .resolve(); + return config.getConfig(DEFAULT_ROOT_PATH); + }); + } + + @NonNull + public static DriverConfigLoader fromFile(@NonNull File file) { + return new DefaultDriverConfigLoader( + () -> { + ConfigFactory.invalidateCaches(); + Config config = + ConfigFactory.defaultOverrides() + .withFallback(ConfigFactory.parseFileAnySyntax(file)) + .withFallback(ConfigFactory.defaultReference(CqlSession.class.getClassLoader())) + .resolve(); + return config.getConfig(DEFAULT_ROOT_PATH); + }); + } + + @NonNull + public static DriverConfigLoader fromUrl(@NonNull URL url) { + return new DefaultDriverConfigLoader( + () -> { + ConfigFactory.invalidateCaches(); + Config config = + ConfigFactory.defaultOverrides() + .withFallback(ConfigFactory.parseURL(url)) + .withFallback(ConfigFactory.defaultReference(CqlSession.class.getClassLoader())) + .resolve(); + return config.getConfig(DEFAULT_ROOT_PATH); + }); + } + + @NonNull + public static DefaultDriverConfigLoader fromString(@NonNull String contents) { + return new DefaultDriverConfigLoader( + () -> { + ConfigFactory.invalidateCaches(); + Config config = + ConfigFactory.defaultOverrides() + .withFallback(ConfigFactory.parseString(contents)) + .withFallback(ConfigFactory.defaultReference(CqlSession.class.getClassLoader())) + .resolve(); + return config.getConfig(DEFAULT_ROOT_PATH); + }, + false); + } + private final Supplier configSupplier; private final TypesafeDriverConfig driverConfig; private final boolean supportsReloading; @@ -171,8 +238,14 @@ public Supplier getConfigSupplier() { @Override public void close() { SingleThreaded singleThreaded = this.singleThreaded; - if (singleThreaded != null) { - RunOrSchedule.on(singleThreaded.adminExecutor, singleThreaded::close); + if (singleThreaded != null && !singleThreaded.adminExecutor.terminationFuture().isDone()) { + try { + RunOrSchedule.on(singleThreaded.adminExecutor, singleThreaded::close); + } catch (RejectedExecutionException e) { + // Checking the future is racy, there is still a tiny window that could get us here. + // We can safely ignore this error because, if the execution is rejected, the periodic + // reload task, if any, has been already cancelled. + } } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/config/typesafe/DefaultDriverConfigLoaderBuilder.java b/core/src/main/java/com/datastax/oss/driver/internal/core/config/typesafe/DefaultDriverConfigLoaderBuilder.java index 33d6d409bf1..3096fd85ffb 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/config/typesafe/DefaultDriverConfigLoaderBuilder.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/config/typesafe/DefaultDriverConfigLoaderBuilder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/config/typesafe/DefaultProgrammaticDriverConfigLoaderBuilder.java b/core/src/main/java/com/datastax/oss/driver/internal/core/config/typesafe/DefaultProgrammaticDriverConfigLoaderBuilder.java index 69f71b61643..2a7f6379362 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/config/typesafe/DefaultProgrammaticDriverConfigLoaderBuilder.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/config/typesafe/DefaultProgrammaticDriverConfigLoaderBuilder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -20,13 +22,13 @@ import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; import com.datastax.oss.driver.api.core.config.DriverOption; import com.datastax.oss.driver.api.core.config.ProgrammaticDriverConfigLoaderBuilder; -import com.datastax.oss.protocol.internal.util.collection.NullAllowingImmutableMap; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import com.typesafe.config.ConfigValueFactory; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; import java.time.Duration; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; @@ -43,8 +45,7 @@ public class DefaultProgrammaticDriverConfigLoaderBuilder // Do not remove root path here, it must be done after merging configs .withFallback(ConfigFactory.defaultReference(CqlSession.class.getClassLoader())); - private final NullAllowingImmutableMap.Builder values = - NullAllowingImmutableMap.builder(); + private final Map values = new HashMap<>(); private final Supplier fallbackSupplier; private final String rootPath; @@ -260,7 +261,7 @@ public DriverConfigLoader build() { private Config buildConfig() { Config config = ConfigFactory.empty(); - for (Map.Entry entry : values.build().entrySet()) { + for (Map.Entry entry : values.entrySet()) { config = config.withValue(entry.getKey(), ConfigValueFactory.fromAnyRef(entry.getValue())); } return config; diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/config/typesafe/TypesafeDriverConfig.java b/core/src/main/java/com/datastax/oss/driver/internal/core/config/typesafe/TypesafeDriverConfig.java index cc3f841436b..e1d8c779f2c 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/config/typesafe/TypesafeDriverConfig.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/config/typesafe/TypesafeDriverConfig.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -21,7 +23,6 @@ import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; import com.datastax.oss.driver.api.core.config.DriverOption; import com.datastax.oss.driver.internal.core.util.Loggers; -import com.datastax.oss.driver.shaded.guava.common.base.Preconditions; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap; import com.typesafe.config.Config; import com.typesafe.config.ConfigObject; @@ -32,6 +33,7 @@ import edu.umd.cs.findbugs.annotations.NonNull; import java.net.URL; import java.util.Map; +import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import net.jcip.annotations.ThreadSafe; import org.slf4j.Logger; @@ -50,6 +52,8 @@ public class TypesafeDriverConfig implements DriverConfig { private final Map defaultOverrides = new ConcurrentHashMap<>(); + private final TypesafeDriverExecutionProfile.Base defaultProfile; + public TypesafeDriverConfig(Config config) { this.lastLoadedConfig = config; Map profileConfigs = extractProfiles(config); @@ -62,6 +66,7 @@ public TypesafeDriverConfig(Config config) { new TypesafeDriverExecutionProfile.Base(entry.getKey(), entry.getValue())); } this.profiles = builder.build(); + this.defaultProfile = profiles.get(DriverExecutionProfile.DEFAULT_NAME); } /** @return whether the configuration changed */ @@ -136,14 +141,22 @@ private Map extractProfiles(Config sourceConfig) { return result.build(); } + @Override + public DriverExecutionProfile getDefaultProfile() { + return defaultProfile; + } + @NonNull @Override public DriverExecutionProfile getProfile(@NonNull String profileName) { - Preconditions.checkArgument( - profiles.containsKey(profileName), - "Unknown profile '%s'. Check your configuration.", - profileName); - return profiles.get(profileName); + if (profileName.equals(DriverExecutionProfile.DEFAULT_NAME)) { + return defaultProfile; + } + return Optional.ofNullable(profiles.get(profileName)) + .orElseThrow( + () -> + new IllegalArgumentException( + String.format("Unknown profile '%s'. Check your configuration.", profileName))); } @NonNull diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/config/typesafe/TypesafeDriverExecutionProfile.java b/core/src/main/java/com/datastax/oss/driver/internal/core/config/typesafe/TypesafeDriverExecutionProfile.java index 63fe6de2bd8..b7dd5abe42e 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/config/typesafe/TypesafeDriverExecutionProfile.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/config/typesafe/TypesafeDriverExecutionProfile.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -30,7 +32,6 @@ import java.time.Duration; import java.util.AbstractMap; import java.util.Collections; -import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Set; @@ -278,7 +279,7 @@ public Object getComparisonKey(@NonNull DriverOption option) { @Override public SortedSet> entrySet() { ImmutableSortedSet.Builder> builder = - ImmutableSortedSet.orderedBy(Comparator.comparing(Map.Entry::getKey)); + ImmutableSortedSet.orderedBy(Map.Entry.comparingByKey()); for (Map.Entry entry : getEffectiveOptions().entrySet()) { builder.add(new AbstractMap.SimpleEntry<>(entry.getKey(), entry.getValue().unwrapped())); } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/config/typesafe/package-info.java b/core/src/main/java/com/datastax/oss/driver/internal/core/config/typesafe/package-info.java index f59350afff5..72e0ba5ae3d 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/config/typesafe/package-info.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/config/typesafe/package-info.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/connection/ConstantReconnectionPolicy.java b/core/src/main/java/com/datastax/oss/driver/internal/core/connection/ConstantReconnectionPolicy.java index ccead526906..03edb38f8d4 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/connection/ConstantReconnectionPolicy.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/connection/ConstantReconnectionPolicy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/connection/ExponentialReconnectionPolicy.java b/core/src/main/java/com/datastax/oss/driver/internal/core/connection/ExponentialReconnectionPolicy.java index 2320dee255a..5fa04cb63d6 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/connection/ExponentialReconnectionPolicy.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/connection/ExponentialReconnectionPolicy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/context/DefaultDriverContext.java b/core/src/main/java/com/datastax/oss/driver/internal/core/context/DefaultDriverContext.java index 5857b0b9be7..3074bda2398 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/context/DefaultDriverContext.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/context/DefaultDriverContext.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -15,18 +17,11 @@ */ package com.datastax.oss.driver.internal.core.context; +import static com.datastax.oss.driver.internal.core.util.Dependency.JACKSON; + import com.datastax.dse.driver.api.core.config.DseDriverOption; -import com.datastax.dse.driver.api.core.type.codec.DseTypeCodecs; import com.datastax.dse.driver.internal.core.InsightsClientLifecycleListener; -import com.datastax.dse.driver.internal.core.cql.continuous.ContinuousCqlRequestAsyncProcessor; -import com.datastax.dse.driver.internal.core.cql.continuous.ContinuousCqlRequestSyncProcessor; -import com.datastax.dse.driver.internal.core.cql.continuous.reactive.ContinuousCqlRequestReactiveProcessor; -import com.datastax.dse.driver.internal.core.cql.reactive.CqlRequestReactiveProcessor; -import com.datastax.dse.driver.internal.core.graph.GraphRequestAsyncProcessor; -import com.datastax.dse.driver.internal.core.graph.GraphRequestSyncProcessor; -import com.datastax.dse.driver.internal.core.graph.GraphSupportChecker; -import com.datastax.dse.driver.internal.core.graph.reactive.ReactiveGraphRequestProcessor; -import com.datastax.dse.driver.internal.core.tracker.MultiplexingRequestTracker; +import com.datastax.dse.driver.internal.core.type.codec.DseTypeCodecsRegistrar; import com.datastax.dse.protocol.internal.DseProtocolV1ClientCodecs; import com.datastax.dse.protocol.internal.DseProtocolV2ClientCodecs; import com.datastax.dse.protocol.internal.ProtocolV4ClientCodecsForDse; @@ -39,6 +34,7 @@ import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; import com.datastax.oss.driver.api.core.connection.ReconnectionPolicy; import com.datastax.oss.driver.api.core.loadbalancing.LoadBalancingPolicy; +import com.datastax.oss.driver.api.core.loadbalancing.NodeDistanceEvaluator; import com.datastax.oss.driver.api.core.metadata.Node; import com.datastax.oss.driver.api.core.metadata.NodeStateListener; import com.datastax.oss.driver.api.core.metadata.schema.SchemaChangeListener; @@ -48,6 +44,7 @@ import com.datastax.oss.driver.api.core.specex.SpeculativeExecutionPolicy; import com.datastax.oss.driver.api.core.ssl.SslEngineFactory; import com.datastax.oss.driver.api.core.time.TimestampGenerator; +import com.datastax.oss.driver.api.core.tracker.RequestIdGenerator; import com.datastax.oss.driver.api.core.tracker.RequestTracker; import com.datastax.oss.driver.api.core.type.codec.TypeCodec; import com.datastax.oss.driver.api.core.type.codec.registry.CodecRegistry; @@ -60,15 +57,15 @@ import com.datastax.oss.driver.internal.core.channel.DefaultWriteCoalescer; import com.datastax.oss.driver.internal.core.channel.WriteCoalescer; import com.datastax.oss.driver.internal.core.control.ControlConnection; -import com.datastax.oss.driver.internal.core.cql.CqlPrepareAsyncProcessor; -import com.datastax.oss.driver.internal.core.cql.CqlPrepareSyncProcessor; -import com.datastax.oss.driver.internal.core.cql.CqlRequestAsyncProcessor; -import com.datastax.oss.driver.internal.core.cql.CqlRequestSyncProcessor; import com.datastax.oss.driver.internal.core.metadata.CloudTopologyMonitor; import com.datastax.oss.driver.internal.core.metadata.DefaultTopologyMonitor; import com.datastax.oss.driver.internal.core.metadata.LoadBalancingPolicyWrapper; import com.datastax.oss.driver.internal.core.metadata.MetadataManager; +import com.datastax.oss.driver.internal.core.metadata.MultiplexingNodeStateListener; +import com.datastax.oss.driver.internal.core.metadata.NoopNodeStateListener; import com.datastax.oss.driver.internal.core.metadata.TopologyMonitor; +import com.datastax.oss.driver.internal.core.metadata.schema.MultiplexingSchemaChangeListener; +import com.datastax.oss.driver.internal.core.metadata.schema.NoopSchemaChangeListener; import com.datastax.oss.driver.internal.core.metadata.schema.parsing.DefaultSchemaParserFactory; import com.datastax.oss.driver.internal.core.metadata.schema.parsing.SchemaParserFactory; import com.datastax.oss.driver.internal.core.metadata.schema.queries.DefaultSchemaQueriesFactory; @@ -77,21 +74,24 @@ import com.datastax.oss.driver.internal.core.metadata.token.DefaultTokenFactoryRegistry; import com.datastax.oss.driver.internal.core.metadata.token.ReplicationStrategyFactory; import com.datastax.oss.driver.internal.core.metadata.token.TokenFactoryRegistry; +import com.datastax.oss.driver.internal.core.metrics.MetricIdGenerator; import com.datastax.oss.driver.internal.core.metrics.MetricsFactory; import com.datastax.oss.driver.internal.core.pool.ChannelPoolFactory; import com.datastax.oss.driver.internal.core.protocol.BuiltInCompressors; import com.datastax.oss.driver.internal.core.protocol.ByteBufPrimitiveCodec; import com.datastax.oss.driver.internal.core.servererrors.DefaultWriteTypeRegistry; import com.datastax.oss.driver.internal.core.servererrors.WriteTypeRegistry; +import com.datastax.oss.driver.internal.core.session.BuiltInRequestProcessors; import com.datastax.oss.driver.internal.core.session.PoolManager; import com.datastax.oss.driver.internal.core.session.RequestProcessor; import com.datastax.oss.driver.internal.core.session.RequestProcessorRegistry; import com.datastax.oss.driver.internal.core.ssl.JdkSslHandlerFactory; import com.datastax.oss.driver.internal.core.ssl.SslHandlerFactory; +import com.datastax.oss.driver.internal.core.tracker.MultiplexingRequestTracker; import com.datastax.oss.driver.internal.core.tracker.NoopRequestTracker; import com.datastax.oss.driver.internal.core.tracker.RequestLogFormatter; import com.datastax.oss.driver.internal.core.type.codec.registry.DefaultCodecRegistry; -import com.datastax.oss.driver.internal.core.util.DependencyCheck; +import com.datastax.oss.driver.internal.core.util.DefaultDependencyChecker; import com.datastax.oss.driver.internal.core.util.Reflection; import com.datastax.oss.driver.internal.core.util.concurrent.CycleDetector; import com.datastax.oss.driver.internal.core.util.concurrent.LazyReference; @@ -100,6 +100,7 @@ import com.datastax.oss.protocol.internal.PrimitiveCodec; import com.datastax.oss.protocol.internal.ProtocolV3ClientCodecs; import com.datastax.oss.protocol.internal.ProtocolV5ClientCodecs; +import com.datastax.oss.protocol.internal.ProtocolV6ClientCodecs; import com.datastax.oss.protocol.internal.SegmentCodec; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; @@ -212,13 +213,16 @@ public class DefaultDriverContext implements InternalDriverContext { new LazyReference<>("poolManager", this::buildPoolManager, cycleDetector); private final LazyReference metricsFactoryRef = new LazyReference<>("metricsFactory", this::buildMetricsFactory, cycleDetector); + private final LazyReference metricIdGeneratorRef = + new LazyReference<>("metricIdGenerator", this::buildMetricIdGenerator, cycleDetector); private final LazyReference requestThrottlerRef = new LazyReference<>("requestThrottler", this::buildRequestThrottler, cycleDetector); - private final LazyReference> startupOptionsRef = - new LazyReference<>("startupOptions", this::buildStartupOptions, cycleDetector); + private final LazyReference startupOptionsRef = + new LazyReference<>("startupOptionsFactory", this::buildStartupOptionsFactory, cycleDetector); private final LazyReference nodeStateListenerRef; private final LazyReference schemaChangeListenerRef; private final LazyReference requestTrackerRef; + private final LazyReference> requestIdGeneratorRef; private final LazyReference> authProviderRef; private final LazyReference> lifecycleListenersRef = new LazyReference<>("lifecycleListeners", this::buildLifecycleListeners, cycleDetector); @@ -233,6 +237,7 @@ public class DefaultDriverContext implements InternalDriverContext { private final RequestTracker requestTrackerFromBuilder; private final Map localDatacentersFromBuilder; private final Map> nodeFiltersFromBuilder; + private final Map nodeDistanceEvaluatorsFromBuilder; private final ClassLoader classLoader; private final InetSocketAddress cloudProxyAddress; private final LazyReference requestLogFormatterRef = @@ -279,12 +284,20 @@ public DefaultDriverContext( this.requestTrackerRef = new LazyReference<>( "requestTracker", () -> buildRequestTracker(requestTrackerFromBuilder), cycleDetector); + this.requestIdGeneratorRef = + new LazyReference<>( + "requestIdGenerator", + () -> buildRequestIdGenerator(programmaticArguments.getRequestIdGenerator()), + cycleDetector); this.sslEngineFactoryRef = new LazyReference<>( "sslEngineFactory", () -> buildSslEngineFactory(programmaticArguments.getSslEngineFactory()), cycleDetector); - this.nodeFiltersFromBuilder = programmaticArguments.getNodeFilters(); + @SuppressWarnings("deprecation") + Map> nodeFilters = programmaticArguments.getNodeFilters(); + this.nodeFiltersFromBuilder = nodeFilters; + this.nodeDistanceEvaluatorsFromBuilder = programmaticArguments.getNodeDistanceEvaluators(); this.classLoader = programmaticArguments.getClassLoader(); this.cloudProxyAddress = programmaticArguments.getCloudProxyAddress(); this.startupClientId = programmaticArguments.getStartupClientId(); @@ -329,16 +342,15 @@ public DefaultDriverContext( } /** - * Builds a map of options to send in a Startup message. + * Returns builder of options to send in a Startup message. * * @see #getStartupOptions() */ - protected Map buildStartupOptions() { + protected StartupOptionsBuilder buildStartupOptionsFactory() { return new StartupOptionsBuilder(this) .withClientId(startupClientId) .withApplicationName(startupApplicationName) - .withApplicationVersion(startupApplicationVersion) - .build(); + .withApplicationVersion(startupApplicationVersion); } protected Map buildLoadBalancingPolicies() { @@ -443,6 +455,7 @@ protected FrameCodec buildFrameCodec() { new ProtocolV3ClientCodecs(), new ProtocolV4ClientCodecsForDse(), new ProtocolV5ClientCodecs(), + new ProtocolV6ClientCodecs(), new DseProtocolV1ClientCodecs(), new DseProtocolV2ClientCodecs()); } @@ -503,65 +516,10 @@ protected ControlConnection buildControlConnection() { } protected RequestProcessorRegistry buildRequestProcessorRegistry() { - String logPrefix = getSessionName(); - - List> processors = new ArrayList<>(); - - // regular requests (sync and async) - CqlRequestAsyncProcessor cqlRequestAsyncProcessor = new CqlRequestAsyncProcessor(); - CqlRequestSyncProcessor cqlRequestSyncProcessor = - new CqlRequestSyncProcessor(cqlRequestAsyncProcessor); - processors.add(cqlRequestAsyncProcessor); - processors.add(cqlRequestSyncProcessor); - - // prepare requests (sync and async) - CqlPrepareAsyncProcessor cqlPrepareAsyncProcessor = new CqlPrepareAsyncProcessor(); - CqlPrepareSyncProcessor cqlPrepareSyncProcessor = - new CqlPrepareSyncProcessor(cqlPrepareAsyncProcessor); - processors.add(cqlPrepareAsyncProcessor); - processors.add(cqlPrepareSyncProcessor); - - // continuous requests (sync and async) - ContinuousCqlRequestAsyncProcessor continuousCqlRequestAsyncProcessor = - new ContinuousCqlRequestAsyncProcessor(); - ContinuousCqlRequestSyncProcessor continuousCqlRequestSyncProcessor = - new ContinuousCqlRequestSyncProcessor(continuousCqlRequestAsyncProcessor); - processors.add(continuousCqlRequestAsyncProcessor); - processors.add(continuousCqlRequestSyncProcessor); - - // graph requests (sync and async) - GraphRequestAsyncProcessor graphRequestAsyncProcessor = null; - if (DependencyCheck.TINKERPOP.isPresent()) { - graphRequestAsyncProcessor = new GraphRequestAsyncProcessor(this, new GraphSupportChecker()); - GraphRequestSyncProcessor graphRequestSyncProcessor = - new GraphRequestSyncProcessor(graphRequestAsyncProcessor); - processors.add(graphRequestAsyncProcessor); - processors.add(graphRequestSyncProcessor); - } else { - LOG.info( - "Could not register Graph extensions; " - + "this is normal if Tinkerpop was explicitly excluded from classpath"); - } - - // reactive requests (regular, continuous and graph) - if (DependencyCheck.REACTIVE_STREAMS.isPresent()) { - CqlRequestReactiveProcessor cqlRequestReactiveProcessor = - new CqlRequestReactiveProcessor(cqlRequestAsyncProcessor); - ContinuousCqlRequestReactiveProcessor continuousCqlRequestReactiveProcessor = - new ContinuousCqlRequestReactiveProcessor(continuousCqlRequestAsyncProcessor); - processors.add(cqlRequestReactiveProcessor); - processors.add(continuousCqlRequestReactiveProcessor); - if (graphRequestAsyncProcessor != null) { - ReactiveGraphRequestProcessor reactiveGraphRequestProcessor = - new ReactiveGraphRequestProcessor(graphRequestAsyncProcessor); - processors.add(reactiveGraphRequestProcessor); - } - } else { - LOG.info( - "Could not register Reactive extensions; " - + "this is normal if Reactive Streams was explicitly excluded from classpath"); - } - return new RequestProcessorRegistry(logPrefix, processors.toArray(new RequestProcessor[0])); + List> processors = + BuiltInRequestProcessors.createDefaultProcessors(this); + return new RequestProcessorRegistry( + getSessionName(), processors.toArray(new RequestProcessor[0])); } protected CodecRegistry buildCodecRegistry(ProgrammaticArguments arguments) { @@ -570,14 +528,7 @@ protected CodecRegistry buildCodecRegistry(ProgrammaticArguments arguments) { registry = new DefaultCodecRegistry(this.sessionName); } registry.register(arguments.getTypeCodecs()); - registry.register(DseTypeCodecs.DATE_RANGE); - if (DependencyCheck.ESRI.isPresent()) { - registry.register(DseTypeCodecs.LINE_STRING, DseTypeCodecs.POINT, DseTypeCodecs.POLYGON); - } else { - LOG.info( - "Could not register Geo codecs; " - + "this is normal if ESRI was explicitly excluded from classpath"); - } + DseTypeCodecsRegistrar.registerDseCodecs(registry); return registry; } @@ -617,6 +568,20 @@ protected MetricsFactory buildMetricsFactory() { DefaultDriverOption.METRICS_FACTORY_CLASS))); } + protected MetricIdGenerator buildMetricIdGenerator() { + return Reflection.buildFromConfig( + this, + DefaultDriverOption.METRICS_ID_GENERATOR_CLASS, + MetricIdGenerator.class, + "com.datastax.oss.driver.internal.core.metrics") + .orElseThrow( + () -> + new IllegalArgumentException( + String.format( + "Missing metric descriptor, check your config (%s)", + DefaultDriverOption.METRICS_ID_GENERATOR_CLASS))); + } + protected RequestThrottler buildRequestThrottler() { return Reflection.buildFromConfig( this, @@ -633,66 +598,134 @@ protected RequestThrottler buildRequestThrottler() { protected NodeStateListener buildNodeStateListener( NodeStateListener nodeStateListenerFromBuilder) { - return (nodeStateListenerFromBuilder != null) - ? nodeStateListenerFromBuilder - : Reflection.buildFromConfig( - this, - DefaultDriverOption.METADATA_NODE_STATE_LISTENER_CLASS, - NodeStateListener.class, - "com.datastax.oss.driver.internal.core.metadata") - .orElseThrow( - () -> - new IllegalArgumentException( - String.format( - "Missing node state listener, check your configuration (%s)", - DefaultDriverOption.METADATA_NODE_STATE_LISTENER_CLASS))); + List listeners = new ArrayList<>(); + if (nodeStateListenerFromBuilder != null) { + listeners.add(nodeStateListenerFromBuilder); + } + DefaultDriverOption newOption = DefaultDriverOption.METADATA_NODE_STATE_LISTENER_CLASSES; + @SuppressWarnings("deprecation") + DefaultDriverOption legacyOption = DefaultDriverOption.METADATA_NODE_STATE_LISTENER_CLASS; + DriverExecutionProfile profile = config.getDefaultProfile(); + if (profile.isDefined(newOption)) { + listeners.addAll( + Reflection.buildFromConfigList( + this, + newOption, + NodeStateListener.class, + "com.datastax.oss.driver.internal.core.metadata")); + } + if (profile.isDefined(legacyOption)) { + LOG.warn( + "Option {} has been deprecated and will be removed in a future release; please use option {} instead.", + legacyOption, + newOption); + Reflection.buildFromConfig( + this, + legacyOption, + NodeStateListener.class, + "com.datastax.oss.driver.internal.core.metadata") + .ifPresent(listeners::add); + } + if (listeners.isEmpty()) { + return new NoopNodeStateListener(this); + } else if (listeners.size() == 1) { + return listeners.get(0); + } else { + return new MultiplexingNodeStateListener(listeners); + } } protected SchemaChangeListener buildSchemaChangeListener( SchemaChangeListener schemaChangeListenerFromBuilder) { - return (schemaChangeListenerFromBuilder != null) - ? schemaChangeListenerFromBuilder - : Reflection.buildFromConfig( - this, - DefaultDriverOption.METADATA_SCHEMA_CHANGE_LISTENER_CLASS, - SchemaChangeListener.class, - "com.datastax.oss.driver.internal.core.metadata.schema") - .orElseThrow( - () -> - new IllegalArgumentException( - String.format( - "Missing schema change listener, check your configuration (%s)", - DefaultDriverOption.METADATA_SCHEMA_CHANGE_LISTENER_CLASS))); + List listeners = new ArrayList<>(); + if (schemaChangeListenerFromBuilder != null) { + listeners.add(schemaChangeListenerFromBuilder); + } + DefaultDriverOption newOption = DefaultDriverOption.METADATA_SCHEMA_CHANGE_LISTENER_CLASSES; + @SuppressWarnings("deprecation") + DefaultDriverOption legacyOption = DefaultDriverOption.METADATA_SCHEMA_CHANGE_LISTENER_CLASS; + DriverExecutionProfile profile = config.getDefaultProfile(); + if (profile.isDefined(newOption)) { + listeners.addAll( + Reflection.buildFromConfigList( + this, + newOption, + SchemaChangeListener.class, + "com.datastax.oss.driver.internal.core.metadata.schema")); + } + if (profile.isDefined(legacyOption)) { + LOG.warn( + "Option {} has been deprecated and will be removed in a future release; please use option {} instead.", + legacyOption, + newOption); + Reflection.buildFromConfig( + this, + legacyOption, + SchemaChangeListener.class, + "com.datastax.oss.driver.internal.core.metadata.schema") + .ifPresent(listeners::add); + } + if (listeners.isEmpty()) { + return new NoopSchemaChangeListener(this); + } else if (listeners.size() == 1) { + return listeners.get(0); + } else { + return new MultiplexingSchemaChangeListener(listeners); + } } protected RequestTracker buildRequestTracker(RequestTracker requestTrackerFromBuilder) { - RequestTracker requestTrackerFromConfig = - (requestTrackerFromBuilder != null) - ? requestTrackerFromBuilder - : Reflection.buildFromConfig( - this, - DefaultDriverOption.REQUEST_TRACKER_CLASS, - RequestTracker.class, - "com.datastax.oss.driver.internal.core.tracker") - .orElseThrow( - () -> - new IllegalArgumentException( - String.format( - "Missing request tracker, check your configuration (%s)", - DefaultDriverOption.REQUEST_TRACKER_CLASS))); - - // The default LBP needs to add its own tracker - if (requestTrackerFromConfig instanceof MultiplexingRequestTracker) { - return requestTrackerFromConfig; + List trackers = new ArrayList<>(); + if (requestTrackerFromBuilder != null) { + trackers.add(requestTrackerFromBuilder); + } + for (LoadBalancingPolicy lbp : this.getLoadBalancingPolicies().values()) { + lbp.getRequestTracker().ifPresent(trackers::add); + } + DefaultDriverOption newOption = DefaultDriverOption.REQUEST_TRACKER_CLASSES; + @SuppressWarnings("deprecation") + DefaultDriverOption legacyOption = DefaultDriverOption.REQUEST_TRACKER_CLASS; + DriverExecutionProfile profile = config.getDefaultProfile(); + if (profile.isDefined(newOption)) { + trackers.addAll( + Reflection.buildFromConfigList( + this, + newOption, + RequestTracker.class, + "com.datastax.oss.driver.internal.core.tracker")); + } + if (profile.isDefined(legacyOption)) { + LOG.warn( + "Option {} has been deprecated and will be removed in a future release; please use option {} instead.", + legacyOption, + newOption); + Reflection.buildFromConfig( + this, + legacyOption, + RequestTracker.class, + "com.datastax.oss.driver.internal.core.tracker") + .ifPresent(trackers::add); + } + if (trackers.isEmpty()) { + return new NoopRequestTracker(this); + } else if (trackers.size() == 1) { + return trackers.get(0); } else { - MultiplexingRequestTracker multiplexingRequestTracker = new MultiplexingRequestTracker(); - if (!(requestTrackerFromConfig instanceof NoopRequestTracker)) { - multiplexingRequestTracker.register(requestTrackerFromConfig); - } - return multiplexingRequestTracker; + return new MultiplexingRequestTracker(trackers); } } + protected Optional buildRequestIdGenerator( + RequestIdGenerator requestIdGenerator) { + return (requestIdGenerator != null) + ? Optional.of(requestIdGenerator) + : Reflection.buildFromConfig( + this, + DefaultDriverOption.REQUEST_ID_GENERATOR_CLASS, + RequestIdGenerator.class, + "com.datastax.oss.driver.internal.core.tracker"); + } + protected Optional buildAuthProvider(AuthProvider authProviderFromBuilder) { return (authProviderFromBuilder != null) ? Optional.of(authProviderFromBuilder) @@ -705,7 +738,7 @@ protected Optional buildAuthProvider(AuthProvider authProviderFrom } protected List buildLifecycleListeners() { - if (DependencyCheck.JACKSON.isPresent()) { + if (DefaultDependencyChecker.isPresent(JACKSON)) { return Collections.singletonList(new InsightsClientLifecycleListener(this, initStackTrace)); } else { if (config.getDefaultProfile().getBoolean(DseDriverOption.MONITOR_REPORTING_ENABLED)) { @@ -927,6 +960,12 @@ public MetricsFactory getMetricsFactory() { return metricsFactoryRef.get(); } + @NonNull + @Override + public MetricIdGenerator getMetricIdGenerator() { + return metricIdGeneratorRef.get(); + } + @NonNull @Override public RequestThrottler getRequestThrottler() { @@ -951,6 +990,12 @@ public RequestTracker getRequestTracker() { return requestTrackerRef.get(); } + @NonNull + @Override + public Optional getRequestIdGenerator() { + return requestIdGeneratorRef.get(); + } + @Nullable @Override public String getLocalDatacenter(@NonNull String profileName) { @@ -959,10 +1004,17 @@ public String getLocalDatacenter(@NonNull String profileName) { @Nullable @Override + @Deprecated public Predicate getNodeFilter(@NonNull String profileName) { return nodeFiltersFromBuilder.get(profileName); } + @Nullable + @Override + public NodeDistanceEvaluator getNodeDistanceEvaluator(@NonNull String profileName) { + return nodeDistanceEvaluatorsFromBuilder.get(profileName); + } + @Nullable @Override public ClassLoader getClassLoader() { @@ -984,7 +1036,8 @@ public ProtocolVersion getProtocolVersion() { @NonNull @Override public Map getStartupOptions() { - return startupOptionsRef.get(); + // startup options are calculated dynamically and may vary per connection + return startupOptionsRef.get().build(); } protected RequestLogFormatter buildRequestLogFormatter() { diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/context/DefaultNettyOptions.java b/core/src/main/java/com/datastax/oss/driver/internal/core/context/DefaultNettyOptions.java index aefd6d55bde..763a71f8b12 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/context/DefaultNettyOptions.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/context/DefaultNettyOptions.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -108,12 +110,20 @@ public DefaultNettyOptions(InternalDriverContext context) { + "Please set advanced.netty.timer.tick-duration to 100 ms or higher.", tickDuration.toMillis()); } - timer = + this.timer = createTimer(timerThreadFactory, tickDuration); + } + + private HashedWheelTimer createTimer(ThreadFactory timerThreadFactory, Duration tickDuration) { + HashedWheelTimer timer = new HashedWheelTimer( timerThreadFactory, tickDuration.toNanos(), TimeUnit.NANOSECONDS, config.getInt(DefaultDriverOption.NETTY_TIMER_TICKS_PER_WHEEL)); + // Start the background thread eagerly during session initialization because + // it is a blocking operation. + timer.start(); + return timer; } @Override @@ -190,7 +200,7 @@ public Future onClose() { } @Override - public synchronized Timer getTimer() { + public Timer getTimer() { return timer; } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/context/EventBus.java b/core/src/main/java/com/datastax/oss/driver/internal/core/context/EventBus.java index b61e1cf8149..dd9ccaa9979 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/context/EventBus.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/context/EventBus.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/context/InternalDriverContext.java b/core/src/main/java/com/datastax/oss/driver/internal/core/context/InternalDriverContext.java index 3b17b98deef..81349b0c665 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/context/InternalDriverContext.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/context/InternalDriverContext.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,6 +18,7 @@ package com.datastax.oss.driver.internal.core.context; import com.datastax.oss.driver.api.core.context.DriverContext; +import com.datastax.oss.driver.api.core.loadbalancing.NodeDistanceEvaluator; import com.datastax.oss.driver.api.core.metadata.Node; import com.datastax.oss.driver.api.core.session.SessionBuilder; import com.datastax.oss.driver.internal.core.ConsistencyLevelRegistry; @@ -30,6 +33,7 @@ import com.datastax.oss.driver.internal.core.metadata.schema.queries.SchemaQueriesFactory; import com.datastax.oss.driver.internal.core.metadata.token.ReplicationStrategyFactory; import com.datastax.oss.driver.internal.core.metadata.token.TokenFactoryRegistry; +import com.datastax.oss.driver.internal.core.metrics.MetricIdGenerator; import com.datastax.oss.driver.internal.core.metrics.MetricsFactory; import com.datastax.oss.driver.internal.core.pool.ChannelPoolFactory; import com.datastax.oss.driver.internal.core.servererrors.WriteTypeRegistry; @@ -125,6 +129,9 @@ public interface InternalDriverContext extends DriverContext { @NonNull MetricsFactory getMetricsFactory(); + @NonNull + MetricIdGenerator getMetricIdGenerator(); + /** * The value that was passed to {@link SessionBuilder#withLocalDatacenter(String,String)} for this * particular profile. If it was specified through the configuration instead, this method will @@ -137,10 +144,22 @@ public interface InternalDriverContext extends DriverContext { * This is the filter from {@link SessionBuilder#withNodeFilter(String, Predicate)}. If the filter * for this profile was specified through the configuration instead, this method will return * {@code null}. + * + * @deprecated Use {@link #getNodeDistanceEvaluator(String)} instead. */ @Nullable + @Deprecated Predicate getNodeFilter(@NonNull String profileName); + /** + * This is the node distance evaluator from {@link + * SessionBuilder#withNodeDistanceEvaluator(String, NodeDistanceEvaluator)}. If the evaluator for + * this profile was specified through the configuration instead, this method will return {@code + * null}. + */ + @Nullable + NodeDistanceEvaluator getNodeDistanceEvaluator(@NonNull String profileName); + /** * The {@link ClassLoader} to use to reflectively load class names defined in configuration. If * null, the driver attempts to use the same {@link ClassLoader} that loaded the core driver diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/context/LifecycleListener.java b/core/src/main/java/com/datastax/oss/driver/internal/core/context/LifecycleListener.java index 4f7e6f84527..39993e7094f 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/context/LifecycleListener.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/context/LifecycleListener.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/context/NettyOptions.java b/core/src/main/java/com/datastax/oss/driver/internal/core/context/NettyOptions.java index 12f8506883a..5b4ff4dcec8 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/context/NettyOptions.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/context/NettyOptions.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/context/StartupOptionsBuilder.java b/core/src/main/java/com/datastax/oss/driver/internal/core/context/StartupOptionsBuilder.java index a29e6bc7661..89a9266b3ac 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/context/StartupOptionsBuilder.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/context/StartupOptionsBuilder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -17,24 +19,34 @@ import com.datastax.dse.driver.api.core.config.DseDriverOption; import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; +import com.datastax.oss.driver.api.core.loadbalancing.LoadBalancingPolicy; import com.datastax.oss.driver.api.core.session.Session; import com.datastax.oss.driver.api.core.uuid.Uuids; +import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap; import com.datastax.oss.protocol.internal.request.Startup; import com.datastax.oss.protocol.internal.util.collection.NullAllowingImmutableMap; +import com.fasterxml.jackson.databind.ObjectMapper; import edu.umd.cs.findbugs.annotations.Nullable; import java.util.Map; +import java.util.Optional; import java.util.UUID; import net.jcip.annotations.Immutable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; @Immutable public class StartupOptionsBuilder { public static final String DRIVER_NAME_KEY = "DRIVER_NAME"; public static final String DRIVER_VERSION_KEY = "DRIVER_VERSION"; + public static final String DRIVER_BAGGAGE = "DRIVER_BAGGAGE"; public static final String APPLICATION_NAME_KEY = "APPLICATION_NAME"; public static final String APPLICATION_VERSION_KEY = "APPLICATION_VERSION"; public static final String CLIENT_ID_KEY = "CLIENT_ID"; + private static final Logger LOG = LoggerFactory.getLogger(StartupOptionsBuilder.class); + private static final ObjectMapper mapper = new ObjectMapper(); + protected final InternalDriverContext context; private UUID clientId; private String applicationName; @@ -117,6 +129,7 @@ public Map build() { if (applicationVersion != null) { builder.put(APPLICATION_VERSION_KEY, applicationVersion); } + driverBaggage().ifPresent(s -> builder.put(DRIVER_BAGGAGE, s)); return builder.build(); } @@ -140,4 +153,21 @@ protected String getDriverName() { protected String getDriverVersion() { return Session.OSS_DRIVER_COORDINATES.getVersion().toString(); } + + private Optional driverBaggage() { + ImmutableMap.Builder builder = new ImmutableMap.Builder<>(); + for (Map.Entry entry : + context.getLoadBalancingPolicies().entrySet()) { + Map config = entry.getValue().getStartupConfiguration(); + if (!config.isEmpty()) { + builder.put(entry.getKey(), config); + } + } + try { + return Optional.of(mapper.writeValueAsString(builder.build())); + } catch (Exception e) { + LOG.warn("Failed to construct startup driver baggage", e); + return Optional.empty(); + } + } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/control/ControlConnection.java b/core/src/main/java/com/datastax/oss/driver/internal/core/control/ControlConnection.java index 294bfd7e060..5c29a9b704b 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/control/ControlConnection.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/control/ControlConnection.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -251,8 +253,8 @@ private class SingleThreaded { private final Reconnection reconnection; private DriverChannelOptions channelOptions; // The last events received for each node - private final Map lastDistanceEvents = new WeakHashMap<>(); - private final Map lastStateEvents = new WeakHashMap<>(); + private final Map lastNodeDistance = new WeakHashMap<>(); + private final Map lastNodeState = new WeakHashMap<>(); private SingleThreaded(InternalDriverContext context) { this.context = context; @@ -303,9 +305,7 @@ private void init( connect( nodes, null, - () -> { - initFuture.complete(null); - }, + () -> initFuture.complete(null), error -> { if (isAuthFailure(error)) { LOG.warn( @@ -366,8 +366,8 @@ private void connect( .whenCompleteAsync( (channel, error) -> { try { - DistanceEvent lastDistanceEvent = lastDistanceEvents.get(node); - NodeStateEvent lastStateEvent = lastStateEvents.get(node); + NodeDistance lastDistance = lastNodeDistance.get(node); + NodeState lastState = lastNodeState.get(node); if (error != null) { if (closeWasCalled || initFuture.isCancelled()) { onSuccess.run(); // abort, we don't really care about the result @@ -406,8 +406,7 @@ private void connect( channel); channel.forceClose(); onSuccess.run(); - } else if (lastDistanceEvent != null - && lastDistanceEvent.distance == NodeDistance.IGNORED) { + } else if (lastDistance == NodeDistance.IGNORED) { LOG.debug( "[{}] New channel opened ({}) but node became ignored, " + "closing and trying next node", @@ -415,9 +414,9 @@ private void connect( channel); channel.forceClose(); connect(nodes, errors, onSuccess, onFailure); - } else if (lastStateEvent != null - && (lastStateEvent.newState == null /*(removed)*/ - || lastStateEvent.newState == NodeState.FORCED_DOWN)) { + } else if (lastNodeState.containsKey(node) + && (lastState == null /*(removed)*/ + || lastState == NodeState.FORCED_DOWN)) { LOG.debug( "[{}] New channel opened ({}) but node was removed or forced down, " + "closing and trying next node", @@ -427,13 +426,15 @@ private void connect( connect(nodes, errors, onSuccess, onFailure); } else { LOG.debug("[{}] New channel opened {}", logPrefix, channel); - // Make sure previous channel gets closed (it may still be open if - // reconnection was forced) DriverChannel previousChannel = ControlConnection.this.channel; + ControlConnection.this.channel = channel; if (previousChannel != null) { + // We were reconnecting: make sure previous channel gets closed (it may + // still be open if reconnection was forced) + LOG.debug( + "[{}] Forcefully closing previous channel {}", logPrefix, channel); previousChannel.forceClose(); } - ControlConnection.this.channel = channel; context.getEventBus().fire(ChannelEvent.channelOpened(node)); channel .closeFuture() @@ -505,9 +506,21 @@ private void onSuccessfulReconnect() { private void onChannelClosed(DriverChannel channel, Node node) { assert adminExecutor.inEventLoop(); if (!closeWasCalled) { - LOG.debug("[{}] Lost channel {}", logPrefix, channel); context.getEventBus().fire(ChannelEvent.channelClosed(node)); - reconnection.start(); + // If this channel is the current control channel, we must start a + // reconnection attempt to get a new control channel. + if (channel == ControlConnection.this.channel) { + LOG.debug( + "[{}] The current control channel {} was closed, scheduling reconnection", + logPrefix, + channel); + reconnection.start(); + } else { + LOG.trace( + "[{}] A previous control channel {} was closed, reconnection not required", + logPrefix, + channel); + } } } @@ -520,7 +533,7 @@ private void reconnectNow() { private void onDistanceEvent(DistanceEvent event) { assert adminExecutor.inEventLoop(); - this.lastDistanceEvents.put(event.node, event); + this.lastNodeDistance.put(event.node, event.distance); if (event.distance == NodeDistance.IGNORED && channel != null && !channel.closeFuture().isDone() @@ -535,7 +548,7 @@ private void onDistanceEvent(DistanceEvent event) { private void onStateEvent(NodeStateEvent event) { assert adminExecutor.inEventLoop(); - this.lastStateEvents.put(event.node, event); + this.lastNodeState.put(event.node, event.newState); if ((event.newState == null /*(removed)*/ || event.newState == NodeState.FORCED_DOWN) && channel != null && !channel.closeFuture().isDone() diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/Conversions.java b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/Conversions.java index 2dc6e5ddc46..ff9384b3e24 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/Conversions.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/Conversions.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -37,8 +39,11 @@ import com.datastax.oss.driver.api.core.metadata.Node; import com.datastax.oss.driver.api.core.metadata.schema.ColumnMetadata; import com.datastax.oss.driver.api.core.metadata.schema.RelationMetadata; +import com.datastax.oss.driver.api.core.retry.RetryPolicy; import com.datastax.oss.driver.api.core.servererrors.AlreadyExistsException; import com.datastax.oss.driver.api.core.servererrors.BootstrappingException; +import com.datastax.oss.driver.api.core.servererrors.CASWriteUnknownException; +import com.datastax.oss.driver.api.core.servererrors.CDCWriteFailureException; import com.datastax.oss.driver.api.core.servererrors.CoordinatorException; import com.datastax.oss.driver.api.core.servererrors.FunctionFailureException; import com.datastax.oss.driver.api.core.servererrors.InvalidConfigurationInQueryException; @@ -55,6 +60,7 @@ import com.datastax.oss.driver.api.core.servererrors.WriteFailureException; import com.datastax.oss.driver.api.core.servererrors.WriteTimeoutException; import com.datastax.oss.driver.api.core.session.Request; +import com.datastax.oss.driver.api.core.specex.SpeculativeExecutionPolicy; import com.datastax.oss.driver.api.core.type.codec.registry.CodecRegistry; import com.datastax.oss.driver.internal.core.ConsistencyLevelRegistry; import com.datastax.oss.driver.internal.core.DefaultProtocolFeature; @@ -73,6 +79,7 @@ import com.datastax.oss.protocol.internal.response.Error; import com.datastax.oss.protocol.internal.response.Result; import com.datastax.oss.protocol.internal.response.error.AlreadyExists; +import com.datastax.oss.protocol.internal.response.error.CASWriteUnknown; import com.datastax.oss.protocol.internal.response.error.ReadFailure; import com.datastax.oss.protocol.internal.response.error.ReadTimeout; import com.datastax.oss.protocol.internal.response.error.Unavailable; @@ -86,6 +93,7 @@ import com.datastax.oss.protocol.internal.util.collection.NullAllowingImmutableList; import com.datastax.oss.protocol.internal.util.collection.NullAllowingImmutableMap; import java.nio.ByteBuffer; +import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -459,7 +467,7 @@ public static CoordinatorException toThrowable( unavailable.required, unavailable.alive); case ProtocolConstants.ErrorCode.OVERLOADED: - return new OverloadedException(node); + return new OverloadedException(node, errorMessage.message); case ProtocolConstants.ErrorCode.IS_BOOTSTRAPPING: return new BootstrappingException(node); case ProtocolConstants.ErrorCode.TRUNCATE_ERROR: @@ -502,6 +510,15 @@ public static CoordinatorException toThrowable( context.getWriteTypeRegistry().fromName(writeFailure.writeType), writeFailure.numFailures, writeFailure.reasonMap); + case ProtocolConstants.ErrorCode.CDC_WRITE_FAILURE: + return new CDCWriteFailureException(node, errorMessage.message); + case ProtocolConstants.ErrorCode.CAS_WRITE_UNKNOWN: + CASWriteUnknown casFailure = (CASWriteUnknown) errorMessage; + return new CASWriteUnknownException( + node, + context.getConsistencyLevelRegistry().codeToLevel(casFailure.consistencyLevel), + casFailure.received, + casFailure.blockFor); case ProtocolConstants.ErrorCode.SYNTAX_ERROR: return new SyntaxError(node, errorMessage.message); case ProtocolConstants.ErrorCode.UNAUTHORIZED: @@ -517,4 +534,60 @@ public static CoordinatorException toThrowable( return new ProtocolError(node, "Unknown error code: " + errorMessage.code); } } + + /** Use {@link #resolveIdempotence(Request, DriverExecutionProfile)} instead. */ + @Deprecated + public static boolean resolveIdempotence(Request request, InternalDriverContext context) { + return resolveIdempotence(request, resolveExecutionProfile(request, context)); + } + + public static boolean resolveIdempotence( + Request request, DriverExecutionProfile executionProfile) { + Boolean requestIsIdempotent = request.isIdempotent(); + return (requestIsIdempotent == null) + ? executionProfile.getBoolean(DefaultDriverOption.REQUEST_DEFAULT_IDEMPOTENCE) + : requestIsIdempotent; + } + + /** Use {@link #resolveRequestTimeout(Request, DriverExecutionProfile)} instead. */ + @Deprecated + public static Duration resolveRequestTimeout(Request request, InternalDriverContext context) { + return resolveRequestTimeout(request, resolveExecutionProfile(request, context)); + } + + public static Duration resolveRequestTimeout( + Request request, DriverExecutionProfile executionProfile) { + Duration timeout = request.getTimeout(); + return timeout != null + ? timeout + : executionProfile.getDuration(DefaultDriverOption.REQUEST_TIMEOUT); + } + + /** Use {@link #resolveRetryPolicy(InternalDriverContext, DriverExecutionProfile)} instead. */ + @Deprecated + public static RetryPolicy resolveRetryPolicy(Request request, InternalDriverContext context) { + DriverExecutionProfile executionProfile = resolveExecutionProfile(request, context); + return context.getRetryPolicy(executionProfile.getName()); + } + + public static RetryPolicy resolveRetryPolicy( + InternalDriverContext context, DriverExecutionProfile executionProfile) { + return context.getRetryPolicy(executionProfile.getName()); + } + + /** + * Use {@link #resolveSpeculativeExecutionPolicy(InternalDriverContext, DriverExecutionProfile)} + * instead. + */ + @Deprecated + public static SpeculativeExecutionPolicy resolveSpeculativeExecutionPolicy( + Request request, InternalDriverContext context) { + DriverExecutionProfile executionProfile = resolveExecutionProfile(request, context); + return context.getSpeculativeExecutionPolicy(executionProfile.getName()); + } + + public static SpeculativeExecutionPolicy resolveSpeculativeExecutionPolicy( + InternalDriverContext context, DriverExecutionProfile executionProfile) { + return context.getSpeculativeExecutionPolicy(executionProfile.getName()); + } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlPrepareAsyncProcessor.java b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlPrepareAsyncProcessor.java index 4e0b51fe482..a3d11cff054 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlPrepareAsyncProcessor.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlPrepareAsyncProcessor.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -18,31 +20,115 @@ import com.datastax.oss.driver.api.core.cql.PrepareRequest; import com.datastax.oss.driver.api.core.cql.PreparedStatement; import com.datastax.oss.driver.api.core.session.Request; +import com.datastax.oss.driver.api.core.type.DataType; +import com.datastax.oss.driver.api.core.type.ListType; +import com.datastax.oss.driver.api.core.type.MapType; +import com.datastax.oss.driver.api.core.type.SetType; +import com.datastax.oss.driver.api.core.type.TupleType; +import com.datastax.oss.driver.api.core.type.UserDefinedType; import com.datastax.oss.driver.api.core.type.reflect.GenericType; +import com.datastax.oss.driver.internal.core.context.DefaultDriverContext; import com.datastax.oss.driver.internal.core.context.InternalDriverContext; +import com.datastax.oss.driver.internal.core.metadata.schema.events.TypeChangeEvent; import com.datastax.oss.driver.internal.core.session.DefaultSession; import com.datastax.oss.driver.internal.core.session.RequestProcessor; import com.datastax.oss.driver.internal.core.util.concurrent.CompletableFutures; +import com.datastax.oss.driver.internal.core.util.concurrent.RunOrSchedule; +import com.datastax.oss.driver.shaded.guava.common.base.Functions; import com.datastax.oss.driver.shaded.guava.common.cache.Cache; import com.datastax.oss.driver.shaded.guava.common.cache.CacheBuilder; +import com.datastax.oss.driver.shaded.guava.common.collect.Iterables; +import com.datastax.oss.protocol.internal.ProtocolConstants; +import edu.umd.cs.findbugs.annotations.NonNull; +import io.netty.util.concurrent.EventExecutor; +import java.util.Map; +import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutionException; +import java.util.function.Function; import net.jcip.annotations.ThreadSafe; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; @ThreadSafe public class CqlPrepareAsyncProcessor implements RequestProcessor> { + private static final Logger LOG = LoggerFactory.getLogger(CqlPrepareAsyncProcessor.class); + protected final Cache> cache; public CqlPrepareAsyncProcessor() { - this(CacheBuilder.newBuilder().weakValues().build()); + this(Optional.empty()); + } + + public CqlPrepareAsyncProcessor(@NonNull Optional context) { + this(context, Functions.identity()); } protected CqlPrepareAsyncProcessor( - Cache> cache) { - this.cache = cache; + Optional context, + Function, CacheBuilder> decorator) { + + CacheBuilder baseCache = CacheBuilder.newBuilder().weakValues(); + this.cache = decorator.apply(baseCache).build(); + context.ifPresent( + (ctx) -> { + LOG.info("Adding handler to invalidate cached prepared statements on type changes"); + EventExecutor adminExecutor = ctx.getNettyOptions().adminEventExecutorGroup().next(); + ctx.getEventBus() + .register( + TypeChangeEvent.class, RunOrSchedule.on(adminExecutor, this::onTypeChanged)); + }); + } + + private static boolean typeMatches(UserDefinedType oldType, DataType typeToCheck) { + + switch (typeToCheck.getProtocolCode()) { + case ProtocolConstants.DataType.UDT: + UserDefinedType udtType = (UserDefinedType) typeToCheck; + return udtType.equals(oldType) + ? true + : Iterables.any(udtType.getFieldTypes(), (testType) -> typeMatches(oldType, testType)); + case ProtocolConstants.DataType.LIST: + ListType listType = (ListType) typeToCheck; + return typeMatches(oldType, listType.getElementType()); + case ProtocolConstants.DataType.SET: + SetType setType = (SetType) typeToCheck; + return typeMatches(oldType, setType.getElementType()); + case ProtocolConstants.DataType.MAP: + MapType mapType = (MapType) typeToCheck; + return typeMatches(oldType, mapType.getKeyType()) + || typeMatches(oldType, mapType.getValueType()); + case ProtocolConstants.DataType.TUPLE: + TupleType tupleType = (TupleType) typeToCheck; + return Iterables.any( + tupleType.getComponentTypes(), (testType) -> typeMatches(oldType, testType)); + default: + return false; + } + } + + private void onTypeChanged(TypeChangeEvent event) { + for (Map.Entry> entry : + this.cache.asMap().entrySet()) { + + try { + PreparedStatement stmt = entry.getValue().get(); + if (Iterables.any( + stmt.getResultSetDefinitions(), (def) -> typeMatches(event.oldType, def.getType())) + || Iterables.any( + stmt.getVariableDefinitions(), + (def) -> typeMatches(event.oldType, def.getType()))) { + + this.cache.invalidate(entry.getKey()); + this.cache.cleanUp(); + } + } catch (Exception e) { + LOG.info("Exception while invalidating prepared statement cache due to UDT change", e); + } + } } @Override @@ -76,7 +162,9 @@ public CompletionStage process( }); } } - return result; + // Return a defensive copy. So if a client cancels its request, the cache won't be impacted + // nor a potential concurrent request. + return result.thenApply(x -> x); // copy() is available only since Java 9 } catch (ExecutionException e) { return CompletableFutures.failedFuture(e.getCause()); } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlPrepareHandler.java b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlPrepareHandler.java index 33ce8de23ee..1ee1f303ab2 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlPrepareHandler.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlPrepareHandler.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -18,6 +20,7 @@ import com.datastax.oss.driver.api.core.AllNodesFailedException; import com.datastax.oss.driver.api.core.CqlIdentifier; import com.datastax.oss.driver.api.core.DriverTimeoutException; +import com.datastax.oss.driver.api.core.NodeUnavailableException; import com.datastax.oss.driver.api.core.ProtocolVersion; import com.datastax.oss.driver.api.core.RequestThrottlingException; import com.datastax.oss.driver.api.core.config.DefaultDriverOption; @@ -28,6 +31,7 @@ import com.datastax.oss.driver.api.core.metrics.DefaultSessionMetric; import com.datastax.oss.driver.api.core.retry.RetryDecision; import com.datastax.oss.driver.api.core.retry.RetryPolicy; +import com.datastax.oss.driver.api.core.retry.RetryVerdict; import com.datastax.oss.driver.api.core.servererrors.BootstrappingException; import com.datastax.oss.driver.api.core.servererrors.CoordinatorException; import com.datastax.oss.driver.api.core.servererrors.FunctionFailureException; @@ -79,19 +83,16 @@ public class CqlPrepareHandler implements Throttled { private final long startTimeNanos; private final String logPrefix; - private final PrepareRequest request; + private final PrepareRequest initialRequest; private final DefaultSession session; private final InternalDriverContext context; - private final DriverExecutionProfile executionProfile; private final Queue queryPlan; protected final CompletableFuture result; - private final Message message; private final Timer timer; - private final Duration timeout; private final Timeout scheduledTimeout; - private final RetryPolicy retryPolicy; private final RequestThrottler throttler; private final Boolean prepareOnAllNodes; + private final DriverExecutionProfile executionProfile; private volatile InitialPrepareCallback initialCallback; // The errors on the nodes that were already tried (lazily initialized on the first error). @@ -108,15 +109,14 @@ protected CqlPrepareHandler( this.logPrefix = sessionLogPrefix + "|" + this.hashCode(); LOG.trace("[{}] Creating new handler for prepare request {}", logPrefix, request); - this.request = request; + this.initialRequest = request; this.session = session; this.context = context; - this.executionProfile = Conversions.resolveExecutionProfile(request, context); + executionProfile = Conversions.resolveExecutionProfile(request, context); this.queryPlan = context .getLoadBalancingPolicyWrapper() .newQueryPlan(request, executionProfile.getName(), session); - this.retryPolicy = context.getRetryPolicy(executionProfile.getName()); this.result = new CompletableFuture<>(); this.result.exceptionally( @@ -124,28 +124,16 @@ protected CqlPrepareHandler( try { if (t instanceof CancellationException) { cancelTimeout(); + context.getRequestThrottler().signalCancel(this); } } catch (Throwable t2) { Loggers.warnWithException(LOG, "[{}] Uncaught exception", logPrefix, t2); } return null; }); - 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); - } - this.message = - new Prepare(request.getQuery(), (keyspace == null) ? null : keyspace.asInternal()); this.timer = context.getNettyOptions().getTimer(); - this.timeout = - request.getTimeout() != null - ? request.getTimeout() - : executionProfile.getDuration(DefaultDriverOption.REQUEST_TIMEOUT); + Duration timeout = Conversions.resolveRequestTimeout(request, executionProfile); this.scheduledTimeout = scheduleTimeout(timeout); this.prepareOnAllNodes = executionProfile.getBoolean(DefaultDriverOption.PREPARE_ON_ALL_NODES); @@ -155,6 +143,8 @@ protected CqlPrepareHandler( @Override public void onThrottleReady(boolean wasDelayed) { + DriverExecutionProfile executionProfile = + Conversions.resolveExecutionProfile(initialRequest, context); if (wasDelayed) { session .getMetricUpdater() @@ -164,7 +154,7 @@ public void onThrottleReady(boolean wasDelayed) { System.nanoTime() - startTimeNanos, TimeUnit.NANOSECONDS); } - sendRequest(null, 0); + sendRequest(initialRequest, null, 0); } public CompletableFuture handle() { @@ -193,7 +183,7 @@ private void cancelTimeout() { } } - private void sendRequest(Node node, int retryCount) { + private void sendRequest(PrepareRequest request, Node node, int retryCount) { if (result.isDone()) { return; } @@ -203,6 +193,8 @@ private void sendRequest(Node node, int retryCount) { channel = session.getChannel(node, logPrefix); if (channel != null) { break; + } else { + recordError(node, new NodeUnavailableException(node)); } } } @@ -210,13 +202,29 @@ private void sendRequest(Node node, int retryCount) { setFinalError(AllNodesFailedException.fromErrors(this.errors)); } else { InitialPrepareCallback initialPrepareCallback = - new InitialPrepareCallback(node, channel, retryCount); + new InitialPrepareCallback(request, node, channel, retryCount); + + Prepare message = toPrepareMessage(request); + channel .write(message, false, request.getCustomPayload(), initialPrepareCallback) .addListener(initialPrepareCallback); } } + @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()); + } + private void recordError(Node node, Throwable error) { // Use a local variable to do only a single single volatile read in the nominal case List> errorsSnapshot = this.errors; @@ -231,19 +239,19 @@ private void recordError(Node node, Throwable error) { errorsSnapshot.add(new AbstractMap.SimpleEntry<>(node, error)); } - private void setFinalResult(Prepared prepared) { + private void setFinalResult(PrepareRequest request, Prepared response) { // Whatever happens below, we're done with this stream id throttler.signalSuccess(this); DefaultPreparedStatement preparedStatement = - Conversions.toPreparedStatement(prepared, request, context); + Conversions.toPreparedStatement(response, request, context); session .getRepreparePayloads() .put(preparedStatement.getId(), preparedStatement.getRepreparePayload()); if (prepareOnAllNodes) { - prepareOnOtherNodes() + prepareOnOtherNodes(request) .thenRun( () -> { LOG.trace( @@ -261,19 +269,19 @@ private void setFinalResult(Prepared prepared) { } } - private CompletionStage prepareOnOtherNodes() { + private CompletionStage prepareOnOtherNodes(PrepareRequest request) { List> otherNodesFutures = new ArrayList<>(); // Only process the rest of the query plan. Any node before that is either the coordinator, or // a node that failed (we assume that retrying right now has little chance of success). for (Node node : queryPlan) { - otherNodesFutures.add(prepareOnOtherNode(node)); + otherNodesFutures.add(prepareOnOtherNode(request, node)); } return CompletableFutures.allDone(otherNodesFutures); } // Try to reprepare on another node, after the initial query has succeeded. Errors are not // blocking, the preparation will be retried later on that node. Simply warn and move on. - private CompletionStage prepareOnOtherNode(Node node) { + private CompletionStage prepareOnOtherNode(PrepareRequest request, Node node) { LOG.trace("[{}] Repreparing on {}", logPrefix, node); DriverChannel channel = session.getChannel(node, logPrefix); if (channel == null) { @@ -284,9 +292,9 @@ private CompletionStage prepareOnOtherNode(Node node) { ThrottledAdminRequestHandler.prepare( channel, false, - message, + toPrepareMessage(request), request.getCustomPayload(), - timeout, + Conversions.resolveRequestTimeout(request, executionProfile), throttler, session.getMetricUpdater(), logPrefix); @@ -307,6 +315,8 @@ private CompletionStage prepareOnOtherNode(Node node) { @Override public void onThrottleFailure(@NonNull RequestThrottlingException error) { + DriverExecutionProfile executionProfile = + Conversions.resolveExecutionProfile(initialRequest, context); session .getMetricUpdater() .incrementCounter(DefaultSessionMetric.THROTTLING_ERRORS, executionProfile.getName()); @@ -326,13 +336,16 @@ private void setFinalError(Throwable error) { private class InitialPrepareCallback implements ResponseCallback, GenericFutureListener> { + private final PrepareRequest request; private final Node node; private final DriverChannel channel; // How many times we've invoked the retry policy and it has returned a "retry" decision (0 for // the first attempt of each execution). private final int retryCount; - private InitialPrepareCallback(Node node, DriverChannel channel, int retryCount) { + private InitialPrepareCallback( + PrepareRequest request, Node node, DriverChannel channel, int retryCount) { + this.request = request; this.node = node; this.channel = channel; this.retryCount = retryCount; @@ -348,7 +361,7 @@ public void operationComplete(Future future) { node, future.cause().toString()); recordError(node, future.cause()); - sendRequest(null, retryCount); // try next host + sendRequest(request, null, retryCount); // try next host } else { if (result.isDone()) { // Might happen if the timeout just fired @@ -369,7 +382,7 @@ public void onResponse(Frame responseFrame) { Message responseMessage = responseFrame.message; if (responseMessage instanceof Prepared) { LOG.trace("[{}] Got result, completing", logPrefix); - setFinalResult((Prepared) responseMessage); + setFinalResult(request, (Prepared) responseMessage); } else if (responseMessage instanceof Error) { LOG.trace("[{}] Got error response, processing", logPrefix); processErrorResponse((Error) responseMessage); @@ -399,7 +412,7 @@ private void processErrorResponse(Error errorMessage) { if (error instanceof BootstrappingException) { LOG.trace("[{}] {} is bootstrapping, trying next node", logPrefix, node); recordError(node, error); - sendRequest(null, retryCount); + sendRequest(request, null, retryCount); } else if (error instanceof QueryValidationException || error instanceof FunctionFailureException || error instanceof ProtocolError) { @@ -408,21 +421,23 @@ private void processErrorResponse(Error errorMessage) { } else { // Because prepare requests are known to always be idempotent, we call the retry policy // directly, without checking the flag. - RetryDecision decision = retryPolicy.onErrorResponse(request, error, retryCount); - processRetryDecision(decision, error); + RetryPolicy retryPolicy = Conversions.resolveRetryPolicy(context, executionProfile); + RetryVerdict verdict = retryPolicy.onErrorResponseVerdict(request, error, retryCount); + processRetryVerdict(verdict, error); } } - private void processRetryDecision(RetryDecision decision, Throwable error) { + private void processRetryVerdict(RetryVerdict verdict, Throwable error) { + RetryDecision decision = verdict.getRetryDecision(); LOG.trace("[{}] Processing retry decision {}", logPrefix, decision); switch (decision) { case RETRY_SAME: recordError(node, error); - sendRequest(node, retryCount + 1); + sendRequest(verdict.getRetryRequest(request), node, retryCount + 1); break; case RETRY_NEXT: recordError(node, error); - sendRequest(null, retryCount + 1); + sendRequest(verdict.getRetryRequest(request), null, retryCount + 1); break; case RETHROW: setFinalError(error); @@ -442,15 +457,16 @@ public void onFailure(Throwable error) { return; } LOG.trace("[{}] Request failure, processing: {}", logPrefix, error.toString()); - RetryDecision decision; + RetryVerdict verdict; try { - decision = retryPolicy.onRequestAborted(request, error, retryCount); + RetryPolicy retryPolicy = Conversions.resolveRetryPolicy(context, executionProfile); + verdict = retryPolicy.onRequestAbortedVerdict(request, error, retryCount); } catch (Throwable cause) { setFinalError( new IllegalStateException("Unexpected error while invoking the retry policy", cause)); return; } - processRetryDecision(decision, error); + processRetryVerdict(verdict, error); } public void cancel() { diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlPrepareSyncProcessor.java b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlPrepareSyncProcessor.java index 90e20f72394..0896df07140 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlPrepareSyncProcessor.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlPrepareSyncProcessor.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlRequestAsyncProcessor.java b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlRequestAsyncProcessor.java index 837c0062602..3013848372b 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlRequestAsyncProcessor.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlRequestAsyncProcessor.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlRequestHandler.java b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlRequestHandler.java index 0f973964694..6842547b11a 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlRequestHandler.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlRequestHandler.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -19,6 +21,7 @@ import com.datastax.oss.driver.api.core.CqlIdentifier; import com.datastax.oss.driver.api.core.DriverException; import com.datastax.oss.driver.api.core.DriverTimeoutException; +import com.datastax.oss.driver.api.core.NodeUnavailableException; import com.datastax.oss.driver.api.core.RequestThrottlingException; import com.datastax.oss.driver.api.core.config.DefaultDriverOption; import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; @@ -29,8 +32,8 @@ import com.datastax.oss.driver.api.core.metadata.Node; import com.datastax.oss.driver.api.core.metrics.DefaultNodeMetric; import com.datastax.oss.driver.api.core.metrics.DefaultSessionMetric; -import com.datastax.oss.driver.api.core.retry.RetryDecision; import com.datastax.oss.driver.api.core.retry.RetryPolicy; +import com.datastax.oss.driver.api.core.retry.RetryVerdict; import com.datastax.oss.driver.api.core.servererrors.BootstrappingException; import com.datastax.oss.driver.api.core.servererrors.CoordinatorException; import com.datastax.oss.driver.api.core.servererrors.FunctionFailureException; @@ -41,7 +44,7 @@ import com.datastax.oss.driver.api.core.servererrors.WriteTimeoutException; import com.datastax.oss.driver.api.core.session.throttling.RequestThrottler; import com.datastax.oss.driver.api.core.session.throttling.Throttled; -import com.datastax.oss.driver.api.core.specex.SpeculativeExecutionPolicy; +import com.datastax.oss.driver.api.core.tracker.RequestIdGenerator; import com.datastax.oss.driver.api.core.tracker.RequestTracker; import com.datastax.oss.driver.internal.core.adminrequest.ThrottledAdminRequestHandler; import com.datastax.oss.driver.internal.core.adminrequest.UnexpectedResponseException; @@ -56,7 +59,8 @@ import com.datastax.oss.driver.internal.core.tracker.NoopRequestTracker; import com.datastax.oss.driver.internal.core.tracker.RequestLogger; import com.datastax.oss.driver.internal.core.util.Loggers; -import com.datastax.oss.driver.internal.core.util.collection.QueryPlan; +import com.datastax.oss.driver.internal.core.util.collection.SimpleQueryPlan; +import com.datastax.oss.driver.shaded.guava.common.base.Joiner; import com.datastax.oss.protocol.internal.Frame; import com.datastax.oss.protocol.internal.Message; import com.datastax.oss.protocol.internal.ProtocolConstants; @@ -80,6 +84,7 @@ import java.util.AbstractMap; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Queue; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; @@ -98,15 +103,12 @@ public class CqlRequestHandler implements Throttled { private static final long NANOTIME_NOT_MEASURED_YET = -1; private final long startTimeNanos; - private final String logPrefix; - private final Statement statement; + private final String handlerLogPrefix; + private final Statement initialStatement; private final DefaultSession session; private final CqlIdentifier keyspace; private final InternalDriverContext context; - @NonNull private final DriverExecutionProfile executionProfile; - private final boolean isIdempotent; protected final CompletableFuture result; - private final Message message; private final Timer timer; /** * How many speculative executions are currently running (including the initial execution). We @@ -121,72 +123,70 @@ public class CqlRequestHandler implements Throttled { */ private final AtomicInteger startedSpeculativeExecutionsCount; - private final Duration timeout; final Timeout scheduledTimeout; final List scheduledExecutions; private final List inFlightCallbacks; - private final RetryPolicy retryPolicy; - private final SpeculativeExecutionPolicy speculativeExecutionPolicy; private final RequestThrottler throttler; private final RequestTracker requestTracker; + private final Optional requestIdGenerator; private final SessionMetricUpdater sessionMetricUpdater; + private final DriverExecutionProfile executionProfile; // The errors on the nodes that were already tried (lazily initialized on the first error). // We don't use a map because nodes can appear multiple times. private volatile List> errors; + private final Joiner logPrefixJoiner = Joiner.on('|'); + private final String sessionName; + private final String sessionRequestId; + protected CqlRequestHandler( Statement statement, DefaultSession session, InternalDriverContext context, - String sessionLogPrefix) { + String sessionName) { this.startTimeNanos = System.nanoTime(); - this.logPrefix = sessionLogPrefix + "|" + this.hashCode(); - LOG.trace("[{}] Creating new handler for request {}", logPrefix, statement); - - this.statement = statement; + this.requestIdGenerator = context.getRequestIdGenerator(); + this.sessionName = sessionName; + this.sessionRequestId = + this.requestIdGenerator + .map(RequestIdGenerator::getSessionRequestId) + .orElse(Integer.toString(this.hashCode())); + this.handlerLogPrefix = logPrefixJoiner.join(sessionName, sessionRequestId); + LOG.trace("[{}] Creating new handler for request {}", handlerLogPrefix, statement); + + this.initialStatement = statement; this.session = session; this.keyspace = session.getKeyspace().orElse(null); this.context = context; - this.executionProfile = Conversions.resolveExecutionProfile(statement, context); - this.retryPolicy = context.getRetryPolicy(executionProfile.getName()); - this.speculativeExecutionPolicy = - context.getSpeculativeExecutionPolicy(executionProfile.getName()); - Boolean statementIsIdempotent = statement.isIdempotent(); - this.isIdempotent = - (statementIsIdempotent == null) - ? executionProfile.getBoolean(DefaultDriverOption.REQUEST_DEFAULT_IDEMPOTENCE) - : statementIsIdempotent; this.result = new CompletableFuture<>(); this.result.exceptionally( t -> { try { if (t instanceof CancellationException) { cancelScheduledTasks(); + context.getRequestThrottler().signalCancel(this); } } catch (Throwable t2) { - Loggers.warnWithException(LOG, "[{}] Uncaught exception", logPrefix, t2); + Loggers.warnWithException(LOG, "[{}] Uncaught exception", handlerLogPrefix, t2); } return null; }); - this.message = Conversions.toMessage(statement, executionProfile, context); - this.timer = context.getNettyOptions().getTimer(); - - this.timeout = - statement.getTimeout() != null - ? statement.getTimeout() - : executionProfile.getDuration(DefaultDriverOption.REQUEST_TIMEOUT); - this.scheduledTimeout = scheduleTimeout(timeout); this.activeExecutionsCount = new AtomicInteger(1); this.startedSpeculativeExecutionsCount = new AtomicInteger(0); - this.scheduledExecutions = isIdempotent ? new CopyOnWriteArrayList<>() : null; + this.scheduledExecutions = new CopyOnWriteArrayList<>(); this.inFlightCallbacks = new CopyOnWriteArrayList<>(); this.requestTracker = context.getRequestTracker(); this.sessionMetricUpdater = session.getMetricUpdater(); + this.timer = context.getNettyOptions().getTimer(); + this.executionProfile = Conversions.resolveExecutionProfile(initialStatement, context); + Duration timeout = Conversions.resolveRequestTimeout(statement, executionProfile); + this.scheduledTimeout = scheduleTimeout(timeout); + this.throttler = context.getRequestThrottler(); this.throttler.register(this); } @@ -204,12 +204,12 @@ public void onThrottleReady(boolean wasDelayed) { TimeUnit.NANOSECONDS); } Queue queryPlan = - this.statement.getNode() != null - ? new QueryPlan(this.statement.getNode()) + this.initialStatement.getNode() != null + ? new SimpleQueryPlan(this.initialStatement.getNode()) : context .getLoadBalancingPolicyWrapper() - .newQueryPlan(statement, executionProfile.getName(), session); - sendRequest(null, queryPlan, 0, 0, true); + .newQueryPlan(initialStatement, executionProfile.getName(), session); + sendRequest(initialStatement, null, queryPlan, 0, 0, true); } public CompletionStage handle() { @@ -222,6 +222,7 @@ private Timeout scheduleTimeout(Duration timeoutDuration) { return this.timer.newTimeout( (Timeout timeout1) -> setFinalError( + initialStatement, new DriverTimeoutException("Query timed out after " + timeoutDuration), null, -1), @@ -242,6 +243,7 @@ private Timeout scheduleTimeout(Duration timeoutDuration) { /** * Sends the request to the next available node. * + * @param statement The statement to execute. * @param retriedNode if not null, it will be attempted first before the rest of the query plan. * @param queryPlan the list of nodes to try (shared with all other executions) * @param currentExecutionIndex 0 for the initial execution, 1 for the first speculative one, etc. @@ -251,6 +253,7 @@ private Timeout scheduleTimeout(Duration timeoutDuration) { * @param scheduleNextExecution whether to schedule the next speculative execution */ private void sendRequest( + Statement statement, Node retriedNode, Queue queryPlan, int currentExecutionIndex, @@ -261,11 +264,13 @@ private void sendRequest( } Node node = retriedNode; DriverChannel channel = null; - if (node == null || (channel = session.getChannel(node, logPrefix)) == null) { + if (node == null || (channel = session.getChannel(node, handlerLogPrefix)) == null) { while (!result.isDone() && (node = queryPlan.poll()) != null) { - channel = session.getChannel(node, logPrefix); + channel = session.getChannel(node, handlerLogPrefix); if (channel != null) { break; + } else { + recordError(node, new NodeUnavailableException(node)); } } } @@ -273,18 +278,30 @@ private void sendRequest( // We've reached the end of the query plan without finding any node to write to if (!result.isDone() && activeExecutionsCount.decrementAndGet() == 0) { // We're the last execution so fail the result - setFinalError(AllNodesFailedException.fromErrors(this.errors), null, -1); + setFinalError(statement, AllNodesFailedException.fromErrors(this.errors), null, -1); } } else { + Statement finalStatement = statement; + String nodeRequestId = + this.requestIdGenerator + .map((g) -> g.getNodeRequestId(finalStatement, sessionRequestId)) + .orElse(Integer.toString(this.hashCode())); + statement = + this.requestIdGenerator + .map((g) -> g.getDecoratedStatement(finalStatement, nodeRequestId)) + .orElse(finalStatement); + NodeResponseCallback nodeResponseCallback = new NodeResponseCallback( + statement, node, queryPlan, channel, currentExecutionIndex, retryCount, scheduleNextExecution, - logPrefix); + logPrefixJoiner.join(this.sessionName, nodeRequestId, currentExecutionIndex)); + Message message = Conversions.toMessage(statement, executionProfile, context); channel .write(message, statement.isTracing(), statement.getCustomPayload(), nodeResponseCallback) .addListener(nodeResponseCallback); @@ -336,14 +353,23 @@ private void setFinalResult( // Only call nanoTime() if we're actually going to use it long completionTimeNanos = NANOTIME_NOT_MEASURED_YET, totalLatencyNanos = NANOTIME_NOT_MEASURED_YET; + if (!(requestTracker instanceof NoopRequestTracker)) { completionTimeNanos = System.nanoTime(); totalLatencyNanos = completionTimeNanos - startTimeNanos; long nodeLatencyNanos = completionTimeNanos - callback.nodeStartTimeNanos; requestTracker.onNodeSuccess( - statement, nodeLatencyNanos, executionProfile, callback.node, logPrefix); + callback.statement, + nodeLatencyNanos, + executionProfile, + callback.node, + handlerLogPrefix); requestTracker.onSuccess( - statement, totalLatencyNanos, executionProfile, callback.node, logPrefix); + callback.statement, + totalLatencyNanos, + executionProfile, + callback.node, + handlerLogPrefix); } if (sessionMetricUpdater.isEnabled( DefaultSessionMetric.CQL_REQUESTS, executionProfile.getName())) { @@ -362,14 +388,15 @@ private void setFinalResult( if (!executionInfo.getWarnings().isEmpty() && executionProfile.getBoolean(DefaultDriverOption.REQUEST_LOG_WARNINGS) && LOG.isWarnEnabled()) { - logServerWarnings(executionInfo.getWarnings()); + logServerWarnings(callback.statement, executionProfile, executionInfo.getWarnings()); } } catch (Throwable error) { - setFinalError(error, callback.node, -1); + setFinalError(callback.statement, error, callback.node, -1); } } - private void logServerWarnings(List warnings) { + private void logServerWarnings( + Statement statement, DriverExecutionProfile executionProfile, List warnings) { // use the RequestLogFormatter to format the query StringBuilder statementString = new StringBuilder(); context @@ -403,7 +430,7 @@ private ExecutionInfo buildExecutionInfo( ByteBuffer pagingState = (resultMessage instanceof Rows) ? ((Rows) resultMessage).getMetadata().pagingState : null; return new DefaultExecutionInfo( - statement, + callback.statement, callback.node, startedSpeculativeExecutionsCount.get(), callback.execution, @@ -420,10 +447,10 @@ private ExecutionInfo buildExecutionInfo( public void onThrottleFailure(@NonNull RequestThrottlingException error) { sessionMetricUpdater.incrementCounter( DefaultSessionMetric.THROTTLING_ERRORS, executionProfile.getName()); - setFinalError(error, null, -1); + setFinalError(initialStatement, error, null, -1); } - private void setFinalError(Throwable error, Node node, int execution) { + private void setFinalError(Statement statement, Throwable error, Node node, int execution) { if (error instanceof DriverException) { ((DriverException) error) .setExecutionInfo( @@ -444,7 +471,8 @@ private void setFinalError(Throwable error, Node node, int execution) { cancelScheduledTasks(); if (!(requestTracker instanceof NoopRequestTracker)) { long latencyNanos = System.nanoTime() - startTimeNanos; - requestTracker.onError(statement, error, latencyNanos, executionProfile, node, logPrefix); + requestTracker.onError( + statement, error, latencyNanos, executionProfile, node, handlerLogPrefix); } if (error instanceof DriverTimeoutException) { throttler.signalTimeout(this); @@ -465,6 +493,7 @@ private class NodeResponseCallback implements ResponseCallback, GenericFutureListener> { private final long nodeStartTimeNanos = System.nanoTime(); + private final Statement statement; private final Node node; private final Queue queryPlan; private final DriverChannel channel; @@ -478,6 +507,7 @@ private class NodeResponseCallback private final String logPrefix; private NodeResponseCallback( + Statement statement, Node node, Queue queryPlan, DriverChannel channel, @@ -485,13 +515,14 @@ private NodeResponseCallback( int retryCount, boolean scheduleNextExecution, String logPrefix) { + this.statement = statement; this.node = node; this.queryPlan = queryPlan; this.channel = channel; this.execution = execution; this.retryCount = retryCount; this.scheduleNextExecution = scheduleNextExecution; - this.logPrefix = logPrefix + "|" + execution; + this.logPrefix = logPrefix; } // this gets invoked once the write completes. @@ -502,7 +533,7 @@ public void operationComplete(Future future) throws Exception { if (error instanceof EncoderException && error.getCause() instanceof FrameTooLongException) { trackNodeError(node, error.getCause(), NANOTIME_NOT_MEASURED_YET); - setFinalError(error.getCause(), node, execution); + setFinalError(statement, error.getCause(), node, execution); } else { LOG.trace( "[{}] Failed to send request on {}, trying next node (cause: {})", @@ -515,7 +546,12 @@ public void operationComplete(Future future) throws Exception { .getMetricUpdater() .incrementCounter(DefaultNodeMetric.UNSENT_REQUESTS, executionProfile.getName()); sendRequest( - null, queryPlan, execution, retryCount, scheduleNextExecution); // try next node + statement, + null, + queryPlan, + execution, + retryCount, + scheduleNextExecution); // try next node } } else { LOG.trace("[{}] Request sent on {}", logPrefix, channel); @@ -525,13 +561,14 @@ public void operationComplete(Future future) throws Exception { cancel(); } else { inFlightCallbacks.add(this); - if (scheduleNextExecution && isIdempotent) { + if (scheduleNextExecution + && Conversions.resolveIdempotence(statement, executionProfile)) { int nextExecution = execution + 1; long nextDelay; try { nextDelay = - speculativeExecutionPolicy.nextExecution( - node, keyspace, statement, nextExecution); + Conversions.resolveSpeculativeExecutionPolicy(context, executionProfile) + .nextExecution(node, keyspace, statement, nextExecution); } catch (Throwable cause) { // This is a bug in the policy, but not fatal since we have at least one other // execution already running. Don't fail the whole request. @@ -563,7 +600,7 @@ private void scheduleSpeculativeExecution(int index, long delay) { if (!result.isDone()) { LOG.trace( "[{}] Starting speculative execution {}", - CqlRequestHandler.this.logPrefix, + CqlRequestHandler.this.handlerLogPrefix, index); activeExecutionsCount.incrementAndGet(); startedSpeculativeExecutionsCount.incrementAndGet(); @@ -573,7 +610,7 @@ private void scheduleSpeculativeExecution(int index, long delay) { .getMetricUpdater() .incrementCounter( DefaultNodeMetric.SPECULATIVE_EXECUTIONS, executionProfile.getName()); - sendRequest(null, queryPlan, index, 0, true); + sendRequest(statement, null, queryPlan, index, 0, true); } }, delay, @@ -645,11 +682,14 @@ public void onResponse(Frame responseFrame) { new IllegalStateException("Unexpected response " + responseMessage), nodeResponseTimeNanos); setFinalError( - new IllegalStateException("Unexpected response " + responseMessage), node, execution); + statement, + new IllegalStateException("Unexpected response " + responseMessage), + node, + execution); } } catch (Throwable t) { trackNodeError(node, t, nodeResponseTimeNanos); - setFinalError(t, node, execution); + setFinalError(statement, t, node, execution); } } @@ -675,7 +715,7 @@ private void processErrorResponse(Error errorMessage) { true, reprepareMessage, repreparePayload.customPayload, - timeout, + Conversions.resolveRequestTimeout(statement, executionProfile), throttler, sessionMetricUpdater, logPrefix); @@ -696,19 +736,19 @@ private void processErrorResponse(Error errorMessage) { || prepareError instanceof ProtocolError) { LOG.trace("[{}] Unrecoverable error on reprepare, rethrowing", logPrefix); trackNodeError(node, prepareError, NANOTIME_NOT_MEASURED_YET); - setFinalError(prepareError, node, execution); + setFinalError(statement, prepareError, node, execution); return null; } } } else if (exception instanceof RequestThrottlingException) { trackNodeError(node, exception, NANOTIME_NOT_MEASURED_YET); - setFinalError(exception, node, execution); + setFinalError(statement, exception, node, execution); return null; } recordError(node, exception); trackNodeError(node, exception, NANOTIME_NOT_MEASURED_YET); LOG.trace("[{}] Reprepare failed, trying next node", logPrefix); - sendRequest(null, queryPlan, execution, retryCount, false); + sendRequest(statement, null, queryPlan, execution, retryCount, false); } else { if (!repreparedId.equals(idToReprepare)) { IllegalStateException illegalStateException = @@ -721,10 +761,10 @@ private void processErrorResponse(Error errorMessage) { Bytes.toHexString(idToReprepare), Bytes.toHexString(repreparedId))); trackNodeError(node, illegalStateException, NANOTIME_NOT_MEASURED_YET); - setFinalError(illegalStateException, node, execution); + setFinalError(statement, illegalStateException, node, execution); } LOG.trace("[{}] Reprepare sucessful, retrying", logPrefix); - sendRequest(node, queryPlan, execution, retryCount, false); + sendRequest(statement, node, queryPlan, execution, retryCount, false); } return null; }); @@ -736,20 +776,21 @@ private void processErrorResponse(Error errorMessage) { LOG.trace("[{}] {} is bootstrapping, trying next node", logPrefix, node); recordError(node, error); trackNodeError(node, error, NANOTIME_NOT_MEASURED_YET); - sendRequest(null, queryPlan, execution, retryCount, false); + sendRequest(statement, null, queryPlan, execution, retryCount, false); } else if (error instanceof QueryValidationException || error instanceof FunctionFailureException || error instanceof ProtocolError) { LOG.trace("[{}] Unrecoverable error, rethrowing", logPrefix); metricUpdater.incrementCounter(DefaultNodeMetric.OTHER_ERRORS, executionProfile.getName()); trackNodeError(node, error, NANOTIME_NOT_MEASURED_YET); - setFinalError(error, node, execution); + setFinalError(statement, error, node, execution); } else { - RetryDecision decision; + RetryPolicy retryPolicy = Conversions.resolveRetryPolicy(context, executionProfile); + RetryVerdict verdict; if (error instanceof ReadTimeoutException) { ReadTimeoutException readTimeout = (ReadTimeoutException) error; - decision = - retryPolicy.onReadTimeout( + verdict = + retryPolicy.onReadTimeoutVerdict( statement, readTimeout.getConsistencyLevel(), readTimeout.getBlockFor(), @@ -758,32 +799,32 @@ private void processErrorResponse(Error errorMessage) { retryCount); updateErrorMetrics( metricUpdater, - decision, + verdict, DefaultNodeMetric.READ_TIMEOUTS, DefaultNodeMetric.RETRIES_ON_READ_TIMEOUT, DefaultNodeMetric.IGNORES_ON_READ_TIMEOUT); } else if (error instanceof WriteTimeoutException) { WriteTimeoutException writeTimeout = (WriteTimeoutException) error; - decision = - isIdempotent - ? retryPolicy.onWriteTimeout( + verdict = + Conversions.resolveIdempotence(statement, executionProfile) + ? retryPolicy.onWriteTimeoutVerdict( statement, writeTimeout.getConsistencyLevel(), writeTimeout.getWriteType(), writeTimeout.getBlockFor(), writeTimeout.getReceived(), retryCount) - : RetryDecision.RETHROW; + : RetryVerdict.RETHROW; updateErrorMetrics( metricUpdater, - decision, + verdict, DefaultNodeMetric.WRITE_TIMEOUTS, DefaultNodeMetric.RETRIES_ON_WRITE_TIMEOUT, DefaultNodeMetric.IGNORES_ON_WRITE_TIMEOUT); } else if (error instanceof UnavailableException) { UnavailableException unavailable = (UnavailableException) error; - decision = - retryPolicy.onUnavailable( + verdict = + retryPolicy.onUnavailableVerdict( statement, unavailable.getConsistencyLevel(), unavailable.getRequired(), @@ -791,42 +832,54 @@ private void processErrorResponse(Error errorMessage) { retryCount); updateErrorMetrics( metricUpdater, - decision, + verdict, DefaultNodeMetric.UNAVAILABLES, DefaultNodeMetric.RETRIES_ON_UNAVAILABLE, DefaultNodeMetric.IGNORES_ON_UNAVAILABLE); } else { - decision = - isIdempotent - ? retryPolicy.onErrorResponse(statement, error, retryCount) - : RetryDecision.RETHROW; + verdict = + Conversions.resolveIdempotence(statement, executionProfile) + ? retryPolicy.onErrorResponseVerdict(statement, error, retryCount) + : RetryVerdict.RETHROW; updateErrorMetrics( metricUpdater, - decision, + verdict, DefaultNodeMetric.OTHER_ERRORS, DefaultNodeMetric.RETRIES_ON_OTHER_ERROR, DefaultNodeMetric.IGNORES_ON_OTHER_ERROR); } - processRetryDecision(decision, error); + processRetryVerdict(verdict, error); } } - private void processRetryDecision(RetryDecision decision, Throwable error) { - LOG.trace("[{}] Processing retry decision {}", logPrefix, decision); - switch (decision) { + private void processRetryVerdict(RetryVerdict verdict, Throwable error) { + LOG.trace("[{}] Processing retry decision {}", logPrefix, verdict); + switch (verdict.getRetryDecision()) { case RETRY_SAME: recordError(node, error); trackNodeError(node, error, NANOTIME_NOT_MEASURED_YET); - sendRequest(node, queryPlan, execution, retryCount + 1, false); + sendRequest( + verdict.getRetryRequest(statement), + node, + queryPlan, + execution, + retryCount + 1, + false); break; case RETRY_NEXT: recordError(node, error); trackNodeError(node, error, NANOTIME_NOT_MEASURED_YET); - sendRequest(null, queryPlan, execution, retryCount + 1, false); + sendRequest( + verdict.getRetryRequest(statement), + null, + queryPlan, + execution, + retryCount + 1, + false); break; case RETHROW: trackNodeError(node, error, NANOTIME_NOT_MEASURED_YET); - setFinalError(error, node, execution); + setFinalError(statement, error, node, execution); break; case IGNORE: setFinalResult(Void.INSTANCE, null, true, this); @@ -836,12 +889,12 @@ private void processRetryDecision(RetryDecision decision, Throwable error) { private void updateErrorMetrics( NodeMetricUpdater metricUpdater, - RetryDecision decision, + RetryVerdict verdict, DefaultNodeMetric error, DefaultNodeMetric retriesOnError, DefaultNodeMetric ignoresOnError) { metricUpdater.incrementCounter(error, executionProfile.getName()); - switch (decision) { + switch (verdict.getRetryDecision()) { case RETRY_SAME: case RETRY_NEXT: metricUpdater.incrementCounter(DefaultNodeMetric.RETRIES, executionProfile.getName()); @@ -863,24 +916,27 @@ public void onFailure(Throwable error) { return; } LOG.trace("[{}] Request failure, processing: {}", logPrefix, error); - RetryDecision decision; - if (!isIdempotent || error instanceof FrameTooLongException) { - decision = RetryDecision.RETHROW; + RetryVerdict verdict; + if (!Conversions.resolveIdempotence(statement, executionProfile) + || error instanceof FrameTooLongException) { + verdict = RetryVerdict.RETHROW; } else { try { - decision = retryPolicy.onRequestAborted(statement, error, retryCount); + RetryPolicy retryPolicy = Conversions.resolveRetryPolicy(context, executionProfile); + verdict = retryPolicy.onRequestAbortedVerdict(statement, error, retryCount); } catch (Throwable cause) { setFinalError( + statement, new IllegalStateException("Unexpected error while invoking the retry policy", cause), null, execution); return; } } - processRetryDecision(decision, error); + processRetryVerdict(verdict, error); updateErrorMetrics( ((DefaultNode) node).getMetricUpdater(), - decision, + verdict, DefaultNodeMetric.ABORTED_REQUESTS, DefaultNodeMetric.RETRIES_ON_ABORTED, DefaultNodeMetric.IGNORES_ON_ABORTED); diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlRequestSyncProcessor.java b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlRequestSyncProcessor.java index 53cddc7772b..d3bd40149fb 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlRequestSyncProcessor.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlRequestSyncProcessor.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultAsyncResultSet.java b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultAsyncResultSet.java index f0b8d5ee4d9..243e9aeb775 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultAsyncResultSet.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultAsyncResultSet.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultBatchStatement.java b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultBatchStatement.java index 94d704c51ad..38b6cf242a1 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultBatchStatement.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultBatchStatement.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultBoundStatement.java b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultBoundStatement.java index 4e0b8af3fac..3cf99c1be6e 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultBoundStatement.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultBoundStatement.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -358,7 +360,8 @@ public ByteBuffer getRoutingKey() { if (indices.isEmpty()) { return null; } else if (indices.size() == 1) { - return getBytesUnsafe(indices.get(0)); + int index = indices.get(0); + return isSet(index) ? getBytesUnsafe(index) : null; } else { ByteBuffer[] components = new ByteBuffer[indices.size()]; for (int i = 0; i < components.length; i++) { diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultColumnDefinition.java b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultColumnDefinition.java index 94df9234eaa..e003637c07f 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultColumnDefinition.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultColumnDefinition.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultColumnDefinitions.java b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultColumnDefinitions.java index d77b8e884b2..58304cb4f67 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultColumnDefinitions.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultColumnDefinitions.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultExecutionInfo.java b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultExecutionInfo.java index 08ac81154ff..3ab57ddc598 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultExecutionInfo.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultExecutionInfo.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultPagingState.java b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultPagingState.java index f1c9a3fb9b3..71243285e3e 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultPagingState.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultPagingState.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultPrepareRequest.java b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultPrepareRequest.java index 149a4cb3017..7f87dbe5b51 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultPrepareRequest.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultPrepareRequest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultPreparedStatement.java b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultPreparedStatement.java index f20c62d1c32..e45e1e5add0 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultPreparedStatement.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultPreparedStatement.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultQueryTrace.java b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultQueryTrace.java index ace33098647..db95cc408b6 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultQueryTrace.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultQueryTrace.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultRow.java b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultRow.java index 68fa9842269..d6bf39ab9c0 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultRow.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultRow.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultSimpleStatement.java b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultSimpleStatement.java index 4efc80a7dcc..c763860479e 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultSimpleStatement.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultSimpleStatement.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultTraceEvent.java b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultTraceEvent.java index 28998769936..9bf7ff7c8ee 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultTraceEvent.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/DefaultTraceEvent.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/EmptyColumnDefinitions.java b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/EmptyColumnDefinitions.java index e6c84a4dfa5..53cfee98b3e 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/EmptyColumnDefinitions.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/EmptyColumnDefinitions.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/MultiPageResultSet.java b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/MultiPageResultSet.java index e80b442726d..2115a127dc6 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/MultiPageResultSet.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/MultiPageResultSet.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/PagingIterableSpliterator.java b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/PagingIterableSpliterator.java index 7ed10778f56..742699d2c1e 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/PagingIterableSpliterator.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/PagingIterableSpliterator.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/QueryTraceFetcher.java b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/QueryTraceFetcher.java index ab32fb4c5af..7ea54aa3b0e 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/QueryTraceFetcher.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/QueryTraceFetcher.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/ResultSets.java b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/ResultSets.java index 50fe6127c5f..eb15d92acc5 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/ResultSets.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/ResultSets.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/SinglePageResultSet.java b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/SinglePageResultSet.java index d22e634938d..eb33da3f430 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/cql/SinglePageResultSet.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/cql/SinglePageResultSet.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/data/DefaultTupleValue.java b/core/src/main/java/com/datastax/oss/driver/internal/core/data/DefaultTupleValue.java index 129f5e4a429..77cfa759237 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/data/DefaultTupleValue.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/data/DefaultTupleValue.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/data/DefaultUdtValue.java b/core/src/main/java/com/datastax/oss/driver/internal/core/data/DefaultUdtValue.java index 572269687bf..c9bf986fcc8 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/data/DefaultUdtValue.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/data/DefaultUdtValue.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/data/IdentifierIndex.java b/core/src/main/java/com/datastax/oss/driver/internal/core/data/IdentifierIndex.java index 17411c4e6d8..d35c164eb84 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/data/IdentifierIndex.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/data/IdentifierIndex.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -20,9 +22,11 @@ import com.datastax.oss.driver.api.core.data.GettableById; import com.datastax.oss.driver.api.core.data.GettableByName; import com.datastax.oss.driver.internal.core.util.Strings; -import com.datastax.oss.driver.shaded.guava.common.collect.LinkedListMultimap; +import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableListMultimap; import com.datastax.oss.driver.shaded.guava.common.collect.ListMultimap; +import java.util.Iterator; import java.util.List; +import java.util.Locale; import net.jcip.annotations.Immutable; /** @@ -39,17 +43,23 @@ public class IdentifierIndex { private final ListMultimap byCaseInsensitiveName; public IdentifierIndex(List ids) { - this.byId = LinkedListMultimap.create(ids.size()); - this.byCaseSensitiveName = LinkedListMultimap.create(ids.size()); - this.byCaseInsensitiveName = LinkedListMultimap.create(ids.size()); + ImmutableListMultimap.Builder byId = ImmutableListMultimap.builder(); + ImmutableListMultimap.Builder byCaseSensitiveName = + ImmutableListMultimap.builder(); + ImmutableListMultimap.Builder byCaseInsensitiveName = + ImmutableListMultimap.builder(); int i = 0; for (CqlIdentifier id : ids) { byId.put(id, i); byCaseSensitiveName.put(id.asInternal(), i); - byCaseInsensitiveName.put(id.asInternal().toLowerCase(), i); + byCaseInsensitiveName.put(id.asInternal().toLowerCase(Locale.ROOT), i); i += 1; } + + this.byId = byId.build(); + this.byCaseSensitiveName = byCaseSensitiveName.build(); + this.byCaseInsensitiveName = byCaseInsensitiveName.build(); } /** @@ -59,7 +69,7 @@ public IdentifierIndex(List ids) { public List allIndicesOf(String name) { return Strings.isDoubleQuoted(name) ? byCaseSensitiveName.get(Strings.unDoubleQuote(name)) - : byCaseInsensitiveName.get(name.toLowerCase()); + : byCaseInsensitiveName.get(name.toLowerCase(Locale.ROOT)); } /** @@ -67,8 +77,8 @@ public List allIndicesOf(String name) { * AccessibleByName}, or -1 if it's not in the list. */ public int firstIndexOf(String name) { - List indices = allIndicesOf(name); - return indices.isEmpty() ? -1 : indices.get(0); + Iterator indices = allIndicesOf(name).iterator(); + return indices.hasNext() ? indices.next() : -1; } /** Returns all occurrences of a given identifier. */ @@ -78,7 +88,7 @@ public List allIndicesOf(CqlIdentifier id) { /** Returns the first occurrence of a given identifier, or -1 if it's not in the list. */ public int firstIndexOf(CqlIdentifier id) { - List indices = allIndicesOf(id); - return indices.isEmpty() ? -1 : indices.get(0); + Iterator indices = allIndicesOf(id).iterator(); + return indices.hasNext() ? indices.next() : -1; } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/data/ValuesHelper.java b/core/src/main/java/com/datastax/oss/driver/internal/core/data/ValuesHelper.java index f4556559c7b..24490ca2509 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/data/ValuesHelper.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/data/ValuesHelper.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/BasicLoadBalancingPolicy.java b/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/BasicLoadBalancingPolicy.java index 23b921a6eb9..a02a5eb3148 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/BasicLoadBalancingPolicy.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/BasicLoadBalancingPolicy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -15,11 +17,15 @@ */ package com.datastax.oss.driver.internal.core.loadbalancing; +import com.datastax.oss.driver.api.core.ConsistencyLevel; import com.datastax.oss.driver.api.core.CqlIdentifier; +import com.datastax.oss.driver.api.core.config.DefaultDriverOption; import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; import com.datastax.oss.driver.api.core.context.DriverContext; +import com.datastax.oss.driver.api.core.cql.Statement; import com.datastax.oss.driver.api.core.loadbalancing.LoadBalancingPolicy; import com.datastax.oss.driver.api.core.loadbalancing.NodeDistance; +import com.datastax.oss.driver.api.core.loadbalancing.NodeDistanceEvaluator; import com.datastax.oss.driver.api.core.metadata.Node; import com.datastax.oss.driver.api.core.metadata.NodeState; import com.datastax.oss.driver.api.core.metadata.TokenMap; @@ -27,24 +33,35 @@ import com.datastax.oss.driver.api.core.session.Request; import com.datastax.oss.driver.api.core.session.Session; import com.datastax.oss.driver.internal.core.context.InternalDriverContext; -import com.datastax.oss.driver.internal.core.loadbalancing.helper.DefaultNodeFilterHelper; +import com.datastax.oss.driver.internal.core.loadbalancing.helper.DefaultNodeDistanceEvaluatorHelper; import com.datastax.oss.driver.internal.core.loadbalancing.helper.OptionalLocalDcHelper; +import com.datastax.oss.driver.internal.core.loadbalancing.nodeset.DcAgnosticNodeSet; +import com.datastax.oss.driver.internal.core.loadbalancing.nodeset.MultiDcNodeSet; +import com.datastax.oss.driver.internal.core.loadbalancing.nodeset.NodeSet; +import com.datastax.oss.driver.internal.core.loadbalancing.nodeset.SingleDcNodeSet; import com.datastax.oss.driver.internal.core.util.ArrayUtils; +import com.datastax.oss.driver.internal.core.util.collection.CompositeQueryPlan; +import com.datastax.oss.driver.internal.core.util.collection.LazyQueryPlan; import com.datastax.oss.driver.internal.core.util.collection.QueryPlan; -import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableSet; +import com.datastax.oss.driver.internal.core.util.collection.SimpleQueryPlan; +import com.datastax.oss.driver.shaded.guava.common.base.Predicates; +import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap; +import com.datastax.oss.driver.shaded.guava.common.collect.Lists; +import com.datastax.oss.driver.shaded.guava.common.collect.Sets; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; import java.nio.ByteBuffer; import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.Queue; import java.util.Set; import java.util.UUID; -import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.IntUnaryOperator; -import java.util.function.Predicate; import net.jcip.annotations.ThreadSafe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -88,54 +105,111 @@ public class BasicLoadBalancingPolicy implements LoadBalancingPolicy { private static final Logger LOG = LoggerFactory.getLogger(BasicLoadBalancingPolicy.class); protected static final IntUnaryOperator INCREMENT = i -> (i == Integer.MAX_VALUE) ? 0 : i + 1; + private static final Object[] EMPTY_NODES = new Object[0]; @NonNull protected final InternalDriverContext context; @NonNull protected final DriverExecutionProfile profile; @NonNull protected final String logPrefix; protected final AtomicInteger roundRobinAmount = new AtomicInteger(); - protected final CopyOnWriteArraySet liveNodes = new CopyOnWriteArraySet<>(); + + private final int maxNodesPerRemoteDc; + private final boolean allowDcFailoverForLocalCl; + private final ConsistencyLevel defaultConsistencyLevel; // private because they should be set in init() and never be modified after private volatile DistanceReporter distanceReporter; - private volatile Predicate filter; + private volatile NodeDistanceEvaluator nodeDistanceEvaluator; private volatile String localDc; + private volatile NodeSet liveNodes; + private final LinkedHashSet preferredRemoteDcs; public BasicLoadBalancingPolicy(@NonNull DriverContext context, @NonNull String profileName) { this.context = (InternalDriverContext) context; profile = context.getConfig().getProfile(profileName); logPrefix = context.getSessionName() + "|" + profileName; - } + maxNodesPerRemoteDc = + profile.getInt(DefaultDriverOption.LOAD_BALANCING_DC_FAILOVER_MAX_NODES_PER_REMOTE_DC); + allowDcFailoverForLocalCl = + profile.getBoolean( + DefaultDriverOption.LOAD_BALANCING_DC_FAILOVER_ALLOW_FOR_LOCAL_CONSISTENCY_LEVELS); + defaultConsistencyLevel = + this.context + .getConsistencyLevelRegistry() + .nameToLevel(profile.getString(DefaultDriverOption.REQUEST_CONSISTENCY)); - /** @return The local datacenter, if known; empty otherwise. */ - public Optional getLocalDatacenter() { - return Optional.ofNullable(localDc); + preferredRemoteDcs = + new LinkedHashSet<>( + profile.getStringList( + DefaultDriverOption.LOAD_BALANCING_DC_FAILOVER_PREFERRED_REMOTE_DCS)); } /** - * @return An immutable copy of the nodes currently considered as live; if the local datacenter is - * known, this set will contain only nodes belonging to that datacenter. + * Returns the local datacenter name, if known; empty otherwise. + * + *

    When this method returns null, then datacenter awareness is completely disabled. All + * non-ignored nodes will be considered "local" regardless of their actual datacenters, and will + * have equal chances of being selected for query plans. + * + *

    After the policy is {@linkplain #init(Map, DistanceReporter) initialized} this method will + * return the local datacenter that was discovered by calling {@link #discoverLocalDc(Map)}. + * Before initialization, this method always returns null. */ - public Set getLiveNodes() { - return ImmutableSet.copyOf(liveNodes); + @Nullable + public String getLocalDatacenter() { + return localDc; + } + + @NonNull + @Override + public Map getStartupConfiguration() { + ImmutableMap.Builder builder = new ImmutableMap.Builder<>(); + if (localDc != null) { + builder.put("localDc", localDc); + } else { + // Local data center may not be discovered prior to connection pool initialization. + // In such scenario, return configured local data center name. + // Note that when using DC inferring load balancing policy, startup configuration + // may not show local DC name, because it will be discovered only once control connection + // is established and datacenter of contact points known. + Optional configuredDc = + new OptionalLocalDcHelper(context, profile, logPrefix).configuredLocalDc(); + configuredDc.ifPresent(d -> builder.put("localDc", d)); + } + if (!preferredRemoteDcs.isEmpty()) { + builder.put("preferredRemoteDcs", preferredRemoteDcs); + } + if (allowDcFailoverForLocalCl) { + builder.put("allowDcFailoverForLocalCl", allowDcFailoverForLocalCl); + } + if (maxNodesPerRemoteDc > 0) { + builder.put("maxNodesPerRemoteDc", maxNodesPerRemoteDc); + } + return ImmutableMap.of(BasicLoadBalancingPolicy.class.getSimpleName(), builder.build()); + } + + /** @return The nodes currently considered as live. */ + protected NodeSet getLiveNodes() { + return liveNodes; } @Override public void init(@NonNull Map nodes, @NonNull DistanceReporter distanceReporter) { this.distanceReporter = distanceReporter; localDc = discoverLocalDc(nodes).orElse(null); - filter = createNodeFilter(localDc, nodes); + nodeDistanceEvaluator = createNodeDistanceEvaluator(localDc, nodes); + liveNodes = + localDc == null + ? new DcAgnosticNodeSet() + : maxNodesPerRemoteDc <= 0 ? new SingleDcNodeSet(localDc) : new MultiDcNodeSet(); for (Node node : nodes.values()) { - if (filter.test(node)) { - distanceReporter.setDistance(node, NodeDistance.LOCAL); - if (node.getState() != NodeState.DOWN) { - // This includes state == UNKNOWN. If the node turns out to be unreachable, this will be - // detected when we try to open a pool to it, it will get marked down and this will be - // signaled back to this policy - liveNodes.add(node); - } - } else { - distanceReporter.setDistance(node, NodeDistance.IGNORED); + NodeDistance distance = computeNodeDistance(node); + distanceReporter.setDistance(node, distance); + if (distance != NodeDistance.IGNORED && node.getState() != NodeState.DOWN) { + // This includes state == UNKNOWN. If the node turns out to be unreachable, this will be + // detected when we try to open a pool to it, it will get marked down and this will be + // signaled back to this policy, which will then remove it from the live set. + liveNodes.add(node); } } } @@ -151,6 +225,10 @@ public void init(@NonNull Map nodes, @NonNull DistanceReporter dista * Optional#empty empty}, if they require a local datacenter to be defined in order to operate * properly. * + *

    If this method returns empty, then datacenter awareness will be completely disabled. All + * non-ignored nodes will be considered "local" regardless of their actual datacenters, and will + * have equal chances of being selected for query plans. + * * @param nodes All the nodes that were known to exist in the cluster (regardless of their state) * when the load balancing policy was initialized. This argument is provided in case * implementors need to inspect the cluster topology to discover the local datacenter. @@ -164,7 +242,7 @@ protected Optional discoverLocalDc(@NonNull Map nodes) { } /** - * Creates a new node filter to use with this policy. + * Creates a new node distance evaluator to use with this policy. * *

    This method is called only once, during {@linkplain LoadBalancingPolicy#init(Map, * LoadBalancingPolicy.DistanceReporter) initialization}, and only after local datacenter @@ -173,21 +251,21 @@ protected Optional discoverLocalDc(@NonNull Map nodes) { * @param localDc The local datacenter that was just discovered, or null if none found. * @param nodes All the nodes that were known to exist in the cluster (regardless of their state) * when the load balancing policy was initialized. This argument is provided in case - * implementors need to inspect the cluster topology to create the node filter. - * @return the node filter to use. + * implementors need to inspect the cluster topology to create the evaluator. + * @return the distance evaluator to use. */ @NonNull - protected Predicate createNodeFilter( + protected NodeDistanceEvaluator createNodeDistanceEvaluator( @Nullable String localDc, @NonNull Map nodes) { - return new DefaultNodeFilterHelper(context, profile, logPrefix) - .createNodeFilter(localDc, nodes); + return new DefaultNodeDistanceEvaluatorHelper(context, profile, logPrefix) + .createNodeDistanceEvaluator(localDc, nodes); } @NonNull @Override public Queue newQueryPlan(@Nullable Request request, @Nullable Session session) { // Take a snapshot since the set is concurrent: - Object[] currentNodes = liveNodes.toArray(); + Object[] currentNodes = liveNodes.dc(localDc).toArray(); Set allReplicas = getReplicas(request, session); int replicaCount = 0; // in currentNodes @@ -216,7 +294,8 @@ public Queue newQueryPlan(@Nullable Request request, @Nullable Session ses currentNodes.length - replicaCount, roundRobinAmount.getAndUpdate(INCREMENT)); - return new QueryPlan(currentNodes); + QueryPlan plan = currentNodes.length == 0 ? QueryPlan.EMPTY : new SimpleQueryPlan(currentNodes); + return maybeAddDcFailover(request, plan); } @NonNull @@ -233,9 +312,9 @@ protected Set getReplicas(@Nullable Request request, @Nullable Session ses // Note: we're on the hot path and the getXxx methods are potentially more than simple getters, // so we only call each method when strictly necessary (which is why the code below looks a bit // weird). - CqlIdentifier keyspace = null; - Token token = null; - ByteBuffer key = null; + CqlIdentifier keyspace; + Token token; + ByteBuffer key; try { keyspace = request.getKeyspace(); if (keyspace == null) { @@ -265,34 +344,99 @@ protected Set getReplicas(@Nullable Request request, @Nullable Session ses : tokenMap.getReplicas(keyspace, key); } + @NonNull + protected Queue maybeAddDcFailover(@Nullable Request request, @NonNull Queue local) { + if (maxNodesPerRemoteDc <= 0 || localDc == null) { + return local; + } + if (!allowDcFailoverForLocalCl && request instanceof Statement) { + Statement statement = (Statement) request; + ConsistencyLevel consistency = statement.getConsistencyLevel(); + if (consistency == null) { + consistency = defaultConsistencyLevel; + } + if (consistency.isDcLocal()) { + return local; + } + } + if (preferredRemoteDcs.isEmpty()) { + return new CompositeQueryPlan(local, buildRemoteQueryPlanAll()); + } + return new CompositeQueryPlan(local, buildRemoteQueryPlanPreferred()); + } + + private QueryPlan buildRemoteQueryPlanAll() { + + return new LazyQueryPlan() { + @Override + protected Object[] computeNodes() { + + Object[] remoteNodes = + liveNodes.dcs().stream() + .filter(Predicates.not(Predicates.equalTo(localDc))) + .flatMap(dc -> liveNodes.dc(dc).stream().limit(maxNodesPerRemoteDc)) + .toArray(); + if (remoteNodes.length == 0) { + return EMPTY_NODES; + } + shuffleHead(remoteNodes, remoteNodes.length); + return remoteNodes; + } + }; + } + + private QueryPlan buildRemoteQueryPlanPreferred() { + + Set dcs = liveNodes.dcs(); + List orderedDcs = Lists.newArrayListWithCapacity(dcs.size()); + orderedDcs.addAll(preferredRemoteDcs); + orderedDcs.addAll(Sets.difference(dcs, preferredRemoteDcs)); + + QueryPlan[] queryPlans = + orderedDcs.stream() + .filter(Predicates.not(Predicates.equalTo(localDc))) + .map( + (dc) -> { + return new LazyQueryPlan() { + @Override + protected Object[] computeNodes() { + Object[] rv = liveNodes.dc(dc).stream().limit(maxNodesPerRemoteDc).toArray(); + if (rv.length == 0) { + return EMPTY_NODES; + } + shuffleHead(rv, rv.length); + return rv; + } + }; + }) + .toArray(QueryPlan[]::new); + + return new CompositeQueryPlan(queryPlans); + } + /** Exposed as a protected method so that it can be accessed by tests */ - protected void shuffleHead(Object[] currentNodes, int replicaCount) { - ArrayUtils.shuffleHead(currentNodes, replicaCount); + protected void shuffleHead(Object[] currentNodes, int headLength) { + ArrayUtils.shuffleHead(currentNodes, headLength); } @Override public void onAdd(@NonNull Node node) { - if (filter.test(node)) { - LOG.debug("[{}] {} was added, setting distance to LOCAL", logPrefix, node); - // Setting to a non-ignored distance triggers the session to open a pool, which will in turn - // set the node UP when the first channel gets opened. - distanceReporter.setDistance(node, NodeDistance.LOCAL); - } else { - distanceReporter.setDistance(node, NodeDistance.IGNORED); - } + NodeDistance distance = computeNodeDistance(node); + // Setting to a non-ignored distance triggers the session to open a pool, which will in turn + // set the node UP when the first channel gets opened, then #onUp will be called, and the + // node will be eventually added to the live set. + distanceReporter.setDistance(node, distance); + LOG.debug("[{}] {} was added, setting distance to {}", logPrefix, node, distance); } @Override public void onUp(@NonNull Node node) { - if (filter.test(node)) { - // Normally this is already the case, but the filter could be dynamic and have ignored the - // node previously. - distanceReporter.setDistance(node, NodeDistance.LOCAL); - if (liveNodes.add(node)) { - LOG.debug("[{}] {} came back UP, added to live set", logPrefix, node); - } - } else { - distanceReporter.setDistance(node, NodeDistance.IGNORED); + NodeDistance distance = computeNodeDistance(node); + if (node.getDistance() != distance) { + distanceReporter.setDistance(node, distance); + } + if (distance != NodeDistance.IGNORED && liveNodes.add(node)) { + LOG.debug("[{}] {} came back UP, added to live set", logPrefix, node); } } @@ -310,6 +454,43 @@ public void onRemove(@NonNull Node node) { } } + /** + * Computes the distance of the given node. + * + *

    This method is called during {@linkplain #init(Map, DistanceReporter) initialization}, when + * a node {@linkplain #onAdd(Node) is added}, and when a node {@linkplain #onUp(Node) is back UP}. + */ + protected NodeDistance computeNodeDistance(@NonNull Node node) { + // We interrogate the custom evaluator every time since it could be dynamic + // and change its verdict between two invocations of this method. + NodeDistance distance = nodeDistanceEvaluator.evaluateDistance(node, localDc); + if (distance != null) { + return distance; + } + // no local DC defined: all nodes are considered LOCAL. + if (localDc == null) { + return NodeDistance.LOCAL; + } + // otherwise, the node is LOCAL if its datacenter is the local datacenter. + if (Objects.equals(node.getDatacenter(), localDc)) { + return NodeDistance.LOCAL; + } + // otherwise, the node will be either REMOTE or IGNORED, depending + // on how many remote nodes we accept per DC. + if (maxNodesPerRemoteDc > 0) { + Object[] remoteNodes = liveNodes.dc(node.getDatacenter()).toArray(); + for (int i = 0; i < maxNodesPerRemoteDc; i++) { + if (i == remoteNodes.length) { + // there is still room for one more REMOTE node in this DC + return NodeDistance.REMOTE; + } else if (remoteNodes[i] == node) { + return NodeDistance.REMOTE; + } + } + } + return NodeDistance.IGNORED; + } + @Override public void close() { // nothing to do diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/DcInferringLoadBalancingPolicy.java b/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/DcInferringLoadBalancingPolicy.java index 39b17aa5154..1d978091c9d 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/DcInferringLoadBalancingPolicy.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/DcInferringLoadBalancingPolicy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/DefaultLoadBalancingPolicy.java b/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/DefaultLoadBalancingPolicy.java index bc609c2ece3..8e1c1fe5039 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/DefaultLoadBalancingPolicy.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/DefaultLoadBalancingPolicy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -18,7 +20,6 @@ import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.MINUTES; -import com.datastax.dse.driver.internal.core.tracker.MultiplexingRequestTracker; import com.datastax.oss.driver.api.core.config.DefaultDriverOption; import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; import com.datastax.oss.driver.api.core.context.DriverContext; @@ -31,15 +32,21 @@ import com.datastax.oss.driver.internal.core.session.DefaultSession; import com.datastax.oss.driver.internal.core.util.ArrayUtils; import com.datastax.oss.driver.internal.core.util.collection.QueryPlan; +import com.datastax.oss.driver.internal.core.util.collection.SimpleQueryPlan; +import com.datastax.oss.driver.shaded.guava.common.annotations.VisibleForTesting; +import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap; +import com.datastax.oss.driver.shaded.guava.common.collect.MapMaker; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; import java.util.BitSet; import java.util.Map; import java.util.Optional; +import java.util.OptionalLong; import java.util.Queue; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicLongArray; import net.jcip.annotations.ThreadSafe; @@ -94,7 +101,7 @@ public class DefaultLoadBalancingPolicy extends BasicLoadBalancingPolicy impleme private static final int MAX_IN_FLIGHT_THRESHOLD = 10; private static final long RESPONSE_COUNT_RESET_INTERVAL_NANOS = MILLISECONDS.toNanos(200); - protected final Map responseTimes = new ConcurrentHashMap<>(); + protected final ConcurrentMap responseTimes; protected final Map upTimes = new ConcurrentHashMap<>(); private final boolean avoidSlowReplicas; @@ -102,13 +109,16 @@ public DefaultLoadBalancingPolicy(@NonNull DriverContext context, @NonNull Strin super(context, profileName); this.avoidSlowReplicas = profile.getBoolean(DefaultDriverOption.LOAD_BALANCING_POLICY_SLOW_AVOIDANCE, true); + this.responseTimes = new MapMaker().weakKeys().makeMap(); } + @NonNull @Override - public void init(@NonNull Map nodes, @NonNull DistanceReporter distanceReporter) { - super.init(nodes, distanceReporter); + public Optional getRequestTracker() { if (avoidSlowReplicas) { - ((MultiplexingRequestTracker) context.getRequestTracker()).register(this); + return Optional.of(this); + } else { + return Optional.empty(); } } @@ -126,7 +136,7 @@ public Queue newQueryPlan(@Nullable Request request, @Nullable Session ses } // Take a snapshot since the set is concurrent: - Object[] currentNodes = liveNodes.toArray(); + Object[] currentNodes = getLiveNodes().dc(getLocalDatacenter()).toArray(); Set allReplicas = getReplicas(request, session); int replicaCount = 0; // in currentNodes @@ -157,6 +167,7 @@ public Queue newQueryPlan(@Nullable Request request, @Nullable Session ses long now = nanoTime(); for (int i = 0; i < replicaCount; i++) { Node node = (Node) currentNodes[i]; + assert node != null; Long upTimeNanos = upTimes.get(node); if (upTimeNanos != null && now - upTimeNanos - NEWLY_UP_INTERVAL_NANOS < 0 @@ -225,7 +236,8 @@ > getInFlight((Node) currentNodes[1], session)) { currentNodes.length - replicaCount, roundRobinAmount.getAndUpdate(INCREMENT)); - return new QueryPlan(currentNodes); + QueryPlan plan = currentNodes.length == 0 ? QueryPlan.EMPTY : new SimpleQueryPlan(currentNodes); + return maybeAddDcFailover(request, plan); } @Override @@ -234,7 +246,7 @@ public void onNodeSuccess( long latencyNanos, @NonNull DriverExecutionProfile executionProfile, @NonNull Node node, - @NonNull String logPrefix) { + @NonNull String nodeRequestLogPrefix) { updateResponseTimes(node); } @@ -245,16 +257,10 @@ public void onNodeError( long latencyNanos, @NonNull DriverExecutionProfile executionProfile, @NonNull Node node, - @NonNull String logPrefix) { + @NonNull String nodeRequestLogPrefix) { updateResponseTimes(node); } - /** Exposed as a protected method so that it can be accessed by tests */ - @Override - protected void shuffleHead(Object[] currentNodes, int replicaCount) { - super.shuffleHead(currentNodes, replicaCount); - } - /** Exposed as a protected method so that it can be accessed by tests */ protected long nanoTime() { return System.nanoTime(); @@ -274,40 +280,19 @@ protected boolean isBusy(@NonNull Node node, @NonNull Session session) { } protected boolean isResponseRateInsufficient(@NonNull Node node, long now) { - // response rate is considered insufficient when less than 2 responses were obtained in - // the past interval delimited by RESPONSE_COUNT_RESET_INTERVAL_NANOS. - if (responseTimes.containsKey(node)) { - AtomicLongArray array = responseTimes.get(node); - if (array.length() == 2) { - long threshold = now - RESPONSE_COUNT_RESET_INTERVAL_NANOS; - long leastRecent = array.get(0); - return leastRecent - threshold < 0; - } - } - return true; + NodeResponseRateSample sample = responseTimes.get(node); + return !(sample == null || sample.hasSufficientResponses(now)); } + /** + * Synchronously updates the response times for the given node. It is synchronous because the + * {@link #DefaultLoadBalancingPolicy(com.datastax.oss.driver.api.core.context.DriverContext, + * java.lang.String) CacheLoader.load} assigned is synchronous. + * + * @param node The node to update. + */ protected void updateResponseTimes(@NonNull Node node) { - responseTimes.compute( - node, - (n, array) -> { - // The array stores at most two timestamps, since we don't need more; - // the first one is always the least recent one, and hence the one to inspect. - long now = nanoTime(); - if (array == null) { - array = new AtomicLongArray(1); - array.set(0, now); - } else if (array.length() == 1) { - long previous = array.get(0); - array = new AtomicLongArray(2); - array.set(0, previous); - array.set(1, now); - } else { - array.set(0, array.get(1)); - array.set(1, now); - } - return array; - }); + this.responseTimes.compute(node, (k, v) -> v == null ? new NodeResponseRateSample() : v.next()); } protected int getInFlight(@NonNull Node node, @NonNull Session session) { @@ -318,4 +303,61 @@ protected int getInFlight(@NonNull Node node, @NonNull Session session) { // processing them). return (pool == null) ? 0 : pool.getInFlight(); } + + protected class NodeResponseRateSample { + + @VisibleForTesting protected final long oldest; + @VisibleForTesting protected final OptionalLong newest; + + private NodeResponseRateSample() { + long now = nanoTime(); + this.oldest = now; + this.newest = OptionalLong.empty(); + } + + private NodeResponseRateSample(long oldestSample) { + this(oldestSample, nanoTime()); + } + + private NodeResponseRateSample(long oldestSample, long newestSample) { + this.oldest = oldestSample; + this.newest = OptionalLong.of(newestSample); + } + + @VisibleForTesting + protected NodeResponseRateSample(AtomicLongArray times) { + assert times.length() >= 1; + this.oldest = times.get(0); + this.newest = (times.length() > 1) ? OptionalLong.of(times.get(1)) : OptionalLong.empty(); + } + + // Our newest sample becomes the oldest in the next generation + private NodeResponseRateSample next() { + return new NodeResponseRateSample(this.getNewestValidSample(), nanoTime()); + } + + // If we have a pair of values return the newest, otherwise we have just one value... so just + // return it + private long getNewestValidSample() { + return this.newest.orElse(this.oldest); + } + + // response rate is considered insufficient when less than 2 responses were obtained in + // the past interval delimited by RESPONSE_COUNT_RESET_INTERVAL_NANOS. + private boolean hasSufficientResponses(long now) { + // If we only have one sample it's an automatic failure + if (!this.newest.isPresent()) return true; + long threshold = now - RESPONSE_COUNT_RESET_INTERVAL_NANOS; + return this.oldest - threshold >= 0; + } + } + + @NonNull + @Override + public Map getStartupConfiguration() { + Map parent = super.getStartupConfiguration(); + return ImmutableMap.of( + DefaultLoadBalancingPolicy.class.getSimpleName(), + parent.get(BasicLoadBalancingPolicy.class.getSimpleName())); + } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/helper/DefaultNodeDistanceEvaluatorHelper.java b/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/helper/DefaultNodeDistanceEvaluatorHelper.java new file mode 100644 index 00000000000..537497b83c8 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/helper/DefaultNodeDistanceEvaluatorHelper.java @@ -0,0 +1,114 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.loadbalancing.helper; + +import com.datastax.oss.driver.api.core.config.DefaultDriverOption; +import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; +import com.datastax.oss.driver.api.core.loadbalancing.NodeDistance; +import com.datastax.oss.driver.api.core.loadbalancing.NodeDistanceEvaluator; +import com.datastax.oss.driver.api.core.metadata.Node; +import com.datastax.oss.driver.internal.core.context.InternalDriverContext; +import com.datastax.oss.driver.internal.core.util.Reflection; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.Nullable; +import java.util.Map; +import java.util.UUID; +import java.util.function.Predicate; +import net.jcip.annotations.ThreadSafe; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A {@link NodeDistanceEvaluatorHelper} implementation that fetches the user-supplied evaluator, if + * any, from the programmatic configuration API, or else, from the driver configuration. If no + * user-supplied evaluator can be retrieved, a dummy evaluator will be used which always evaluates + * null distances. + */ +@ThreadSafe +public class DefaultNodeDistanceEvaluatorHelper implements NodeDistanceEvaluatorHelper { + + private static final Logger LOG = + LoggerFactory.getLogger(DefaultNodeDistanceEvaluatorHelper.class); + + @NonNull protected final InternalDriverContext context; + @NonNull protected final DriverExecutionProfile profile; + @NonNull protected final String logPrefix; + + public DefaultNodeDistanceEvaluatorHelper( + @NonNull InternalDriverContext context, + @NonNull DriverExecutionProfile profile, + @NonNull String logPrefix) { + this.context = context; + this.profile = profile; + this.logPrefix = logPrefix; + } + + @NonNull + @Override + public NodeDistanceEvaluator createNodeDistanceEvaluator( + @Nullable String localDc, @NonNull Map nodes) { + NodeDistanceEvaluator nodeDistanceEvaluatorFromConfig = nodeDistanceEvaluatorFromConfig(); + return (node, dc) -> { + NodeDistance distance = nodeDistanceEvaluatorFromConfig.evaluateDistance(node, dc); + if (distance != null) { + LOG.debug("[{}] Evaluator assigned distance {} to node {}", logPrefix, distance, node); + } else { + LOG.debug("[{}] Evaluator did not assign a distance to node {}", logPrefix, node); + } + return distance; + }; + } + + @NonNull + protected NodeDistanceEvaluator nodeDistanceEvaluatorFromConfig() { + NodeDistanceEvaluator evaluator = context.getNodeDistanceEvaluator(profile.getName()); + if (evaluator != null) { + LOG.debug("[{}] Node distance evaluator set programmatically", logPrefix); + } else { + evaluator = + Reflection.buildFromConfig( + context, + profile.getName(), + DefaultDriverOption.LOAD_BALANCING_DISTANCE_EVALUATOR_CLASS, + NodeDistanceEvaluator.class) + .orElse(null); + if (evaluator != null) { + LOG.debug("[{}] Node distance evaluator set from configuration", logPrefix); + } else { + @SuppressWarnings({"unchecked", "deprecation"}) + Predicate nodeFilterFromConfig = + Reflection.buildFromConfig( + context, + profile.getName(), + DefaultDriverOption.LOAD_BALANCING_FILTER_CLASS, + Predicate.class) + .orElse(null); + if (nodeFilterFromConfig != null) { + evaluator = new NodeFilterToDistanceEvaluatorAdapter(nodeFilterFromConfig); + LOG.debug( + "[{}] Node distance evaluator set from deprecated node filter configuration", + logPrefix); + } + } + } + if (evaluator == null) { + evaluator = PASS_THROUGH_DISTANCE_EVALUATOR; + } + return evaluator; + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/helper/DefaultNodeFilterHelper.java b/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/helper/DefaultNodeFilterHelper.java deleted file mode 100644 index 10630e58fad..00000000000 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/helper/DefaultNodeFilterHelper.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.datastax.oss.driver.internal.core.loadbalancing.helper; - -import com.datastax.oss.driver.api.core.config.DefaultDriverOption; -import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; -import com.datastax.oss.driver.api.core.metadata.Node; -import com.datastax.oss.driver.internal.core.context.InternalDriverContext; -import com.datastax.oss.driver.internal.core.util.Reflection; -import edu.umd.cs.findbugs.annotations.NonNull; -import edu.umd.cs.findbugs.annotations.Nullable; -import java.util.Map; -import java.util.UUID; -import java.util.function.Predicate; -import net.jcip.annotations.ThreadSafe; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * A {@link NodeFilterHelper} implementation that fetches the user-supplied filter, if any, from the - * programmatic configuration API, or else, from the driver configuration. If no user-supplied - * filter can be retrieved, a dummy filter will be used which accepts all nodes unconditionally. - * - *

    Note that, regardless of the filter supplied by the end user, if a local datacenter is defined - * the filter returned by this implementation will always reject nodes that report a datacenter - * different from the local one. - */ -@ThreadSafe -public class DefaultNodeFilterHelper implements NodeFilterHelper { - - private static final Logger LOG = LoggerFactory.getLogger(DefaultNodeFilterHelper.class); - - @NonNull protected final InternalDriverContext context; - @NonNull protected final DriverExecutionProfile profile; - @NonNull protected final String logPrefix; - - public DefaultNodeFilterHelper( - @NonNull InternalDriverContext context, - @NonNull DriverExecutionProfile profile, - @NonNull String logPrefix) { - this.context = context; - this.profile = profile; - this.logPrefix = logPrefix; - } - - @NonNull - @Override - public Predicate createNodeFilter( - @Nullable String localDc, @NonNull Map nodes) { - Predicate filterFromConfig = nodeFilterFromConfig(); - return node -> { - if (localDc != null && !localDc.equals(node.getDatacenter())) { - LOG.debug( - "[{}] Ignoring {} because it doesn't belong to the local DC {}", - logPrefix, - node, - localDc); - return false; - } else if (!filterFromConfig.test(node)) { - LOG.debug( - "[{}] Ignoring {} because it doesn't match the user-provided predicate", - logPrefix, - node); - return false; - } else { - return true; - } - }; - } - - @NonNull - protected Predicate nodeFilterFromConfig() { - Predicate filter = context.getNodeFilter(profile.getName()); - if (filter != null) { - LOG.debug("[{}] Node filter set programmatically", logPrefix); - } else { - @SuppressWarnings("unchecked") - Predicate filterFromConfig = - Reflection.buildFromConfig( - context, - profile.getName(), - DefaultDriverOption.LOAD_BALANCING_FILTER_CLASS, - Predicate.class) - .orElse(INCLUDE_ALL_NODES); - filter = filterFromConfig; - LOG.debug("[{}] Node filter set from configuration", logPrefix); - } - return filter; - } -} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/helper/InferringLocalDcHelper.java b/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/helper/InferringLocalDcHelper.java index 7261402ef3a..8608b855e8d 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/helper/InferringLocalDcHelper.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/helper/InferringLocalDcHelper.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/helper/LocalDcHelper.java b/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/helper/LocalDcHelper.java index 96b223a983c..183c7f90dec 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/helper/LocalDcHelper.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/helper/LocalDcHelper.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/helper/MandatoryLocalDcHelper.java b/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/helper/MandatoryLocalDcHelper.java index b772ed7c4de..9a0e9a2d4ce 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/helper/MandatoryLocalDcHelper.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/helper/MandatoryLocalDcHelper.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/helper/NodeFilterHelper.java b/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/helper/NodeDistanceEvaluatorHelper.java similarity index 56% rename from core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/helper/NodeFilterHelper.java rename to core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/helper/NodeDistanceEvaluatorHelper.java index 2b082bfe324..61e094b318a 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/helper/NodeFilterHelper.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/helper/NodeDistanceEvaluatorHelper.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,30 +18,31 @@ package com.datastax.oss.driver.internal.core.loadbalancing.helper; import com.datastax.oss.driver.api.core.loadbalancing.LoadBalancingPolicy; +import com.datastax.oss.driver.api.core.loadbalancing.NodeDistanceEvaluator; import com.datastax.oss.driver.api.core.metadata.Node; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; import java.util.Map; import java.util.UUID; -import java.util.function.Predicate; import net.jcip.annotations.ThreadSafe; @FunctionalInterface @ThreadSafe -public interface NodeFilterHelper { +public interface NodeDistanceEvaluatorHelper { - Predicate INCLUDE_ALL_NODES = n -> true; + NodeDistanceEvaluator PASS_THROUGH_DISTANCE_EVALUATOR = (node, localDc) -> null; /** - * Creates a new node filter. + * Creates a new node distance evaluator. * * @param localDc The local datacenter, or null if none defined. * @param nodes All the nodes that were known to exist in the cluster (regardless of their state) * when the load balancing policy was {@linkplain LoadBalancingPolicy#init(Map, * LoadBalancingPolicy.DistanceReporter) initialized}. This argument is provided in case - * implementors need to inspect the cluster topology to create the node filter. - * @return the node filter to use. + * implementors need to inspect the cluster topology to create the node distance evaluator. + * @return the node distance evaluator to use. */ @NonNull - Predicate createNodeFilter(@Nullable String localDc, @NonNull Map nodes); + NodeDistanceEvaluator createNodeDistanceEvaluator( + @Nullable String localDc, @NonNull Map nodes); } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/helper/NodeFilterToDistanceEvaluatorAdapter.java b/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/helper/NodeFilterToDistanceEvaluatorAdapter.java new file mode 100644 index 00000000000..902018fb7d4 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/helper/NodeFilterToDistanceEvaluatorAdapter.java @@ -0,0 +1,40 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.loadbalancing.helper; + +import com.datastax.oss.driver.api.core.loadbalancing.NodeDistance; +import com.datastax.oss.driver.api.core.loadbalancing.NodeDistanceEvaluator; +import com.datastax.oss.driver.api.core.metadata.Node; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.Nullable; +import java.util.function.Predicate; + +public class NodeFilterToDistanceEvaluatorAdapter implements NodeDistanceEvaluator { + + private final Predicate nodeFilter; + + public NodeFilterToDistanceEvaluatorAdapter(@NonNull Predicate nodeFilter) { + this.nodeFilter = nodeFilter; + } + + @Nullable + @Override + public NodeDistance evaluateDistance(@NonNull Node node, @Nullable String localDc) { + return nodeFilter.test(node) ? null : NodeDistance.IGNORED; + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/helper/OptionalLocalDcHelper.java b/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/helper/OptionalLocalDcHelper.java index e513b2b8b83..c6143f3fa16 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/helper/OptionalLocalDcHelper.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/helper/OptionalLocalDcHelper.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -63,19 +65,14 @@ public OptionalLocalDcHelper( @Override @NonNull public Optional discoverLocalDc(@NonNull Map nodes) { - String localDc = context.getLocalDatacenter(profile.getName()); - if (localDc != null) { - LOG.debug("[{}] Local DC set programmatically: {}", logPrefix, localDc); - checkLocalDatacenterCompatibility(localDc, context.getMetadataManager().getContactPoints()); - return Optional.of(localDc); - } else if (profile.isDefined(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER)) { - localDc = profile.getString(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER); - LOG.debug("[{}] Local DC set from configuration: {}", logPrefix, localDc); - checkLocalDatacenterCompatibility(localDc, context.getMetadataManager().getContactPoints()); - return Optional.of(localDc); + Optional localDc = configuredLocalDc(); + if (localDc.isPresent()) { + checkLocalDatacenterCompatibility( + localDc.get(), context.getMetadataManager().getContactPoints()); } else { - return Optional.empty(); + LOG.debug("[{}] Local DC not set, DC awareness will be disabled", logPrefix); } + return localDc; } /** @@ -83,26 +80,28 @@ public Optional discoverLocalDc(@NonNull Map nodes) { * configuration, or programmatically. * *

    The default implementation logs a warning when a contact point reports a datacenter - * different from the local one. + * different from the local one, and only for the default profile. * * @param localDc The local datacenter, as specified in the config, or programmatically. * @param contactPoints The contact points provided when creating the session. */ protected void checkLocalDatacenterCompatibility( @NonNull String localDc, Set contactPoints) { - Set badContactPoints = new LinkedHashSet<>(); - for (Node node : contactPoints) { - if (!Objects.equals(localDc, node.getDatacenter())) { - badContactPoints.add(node); + if (profile.getName().equals(DriverExecutionProfile.DEFAULT_NAME)) { + Set badContactPoints = new LinkedHashSet<>(); + for (Node node : contactPoints) { + if (!Objects.equals(localDc, node.getDatacenter())) { + badContactPoints.add(node); + } + } + if (!badContactPoints.isEmpty()) { + LOG.warn( + "[{}] You specified {} as the local DC, but some contact points are from a different DC: {}; " + + "please provide the correct local DC, or check your contact points", + logPrefix, + localDc, + formatNodesAndDcs(badContactPoints)); } - } - if (!badContactPoints.isEmpty()) { - LOG.warn( - "[{}] You specified {} as the local DC, but some contact points are from a different DC: {}; " - + "please provide the correct local DC, or check your contact points", - logPrefix, - localDc, - formatNodesAndDcs(badContactPoints)); } } @@ -133,4 +132,19 @@ protected String formatDcs(Iterable nodes) { } return String.join(", ", new TreeSet<>(l)); } + + /** @return Local data center set programmatically or from configuration file. */ + @NonNull + public Optional configuredLocalDc() { + String localDc = context.getLocalDatacenter(profile.getName()); + if (localDc != null) { + LOG.debug("[{}] Local DC set programmatically: {}", logPrefix, localDc); + return Optional.of(localDc); + } else if (profile.isDefined(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER)) { + localDc = profile.getString(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER); + LOG.debug("[{}] Local DC set from configuration: {}", logPrefix, localDc); + return Optional.of(localDc); + } + return Optional.empty(); + } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/nodeset/DcAgnosticNodeSet.java b/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/nodeset/DcAgnosticNodeSet.java new file mode 100644 index 00000000000..2a6e79023de --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/nodeset/DcAgnosticNodeSet.java @@ -0,0 +1,53 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.loadbalancing.nodeset; + +import com.datastax.oss.driver.api.core.metadata.Node; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.Nullable; +import java.util.Collections; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArraySet; +import net.jcip.annotations.ThreadSafe; + +@ThreadSafe +public class DcAgnosticNodeSet implements NodeSet { + + private final Set nodes = new CopyOnWriteArraySet<>(); + + @Override + public boolean add(@NonNull Node node) { + return nodes.add(node); + } + + @Override + public boolean remove(@NonNull Node node) { + return nodes.remove(node); + } + + @Override + @NonNull + public Set dc(@Nullable String dc) { + return nodes; + } + + @Override + public Set dcs() { + return Collections.emptySet(); + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/nodeset/MultiDcNodeSet.java b/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/nodeset/MultiDcNodeSet.java new file mode 100644 index 00000000000..37f02bec878 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/nodeset/MultiDcNodeSet.java @@ -0,0 +1,94 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.loadbalancing.nodeset; + +import com.datastax.oss.driver.api.core.metadata.Node; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.Nullable; +import java.util.Collections; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArraySet; +import java.util.concurrent.atomic.AtomicBoolean; +import net.jcip.annotations.ThreadSafe; + +@ThreadSafe +public class MultiDcNodeSet implements NodeSet { + + private static final String UNKNOWN_DC = ""; + + private final Map> nodes = new ConcurrentHashMap<>(); + + @Override + public boolean add(@NonNull Node node) { + AtomicBoolean added = new AtomicBoolean(); + nodes.compute( + getMapKey(node), + (key, current) -> { + if (current == null) { + // We use CopyOnWriteArraySet because we need + // 1) to preserve insertion order, and + // 2) a "snapshot"-style toArray() implementation + current = new CopyOnWriteArraySet<>(); + } + if (current.add(node)) { + added.set(true); + } + return current; + }); + return added.get(); + } + + @Override + public boolean remove(@NonNull Node node) { + AtomicBoolean removed = new AtomicBoolean(); + nodes.compute( + getMapKey(node), + (key, current) -> { + if (current != null) { + if (current.remove(node)) { + removed.set(true); + } + } + return current; + }); + return removed.get(); + } + + @Override + @NonNull + public Set dc(@Nullable String dc) { + return nodes.getOrDefault(getMapKey(dc), Collections.emptySet()); + } + + @Override + public Set dcs() { + return nodes.keySet(); + } + + @NonNull + private String getMapKey(@NonNull Node node) { + return getMapKey(node.getDatacenter()); + } + + @NonNull + private String getMapKey(@Nullable String dc) { + return dc == null ? UNKNOWN_DC : dc; + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/nodeset/NodeSet.java b/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/nodeset/NodeSet.java new file mode 100644 index 00000000000..66460e16a7c --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/nodeset/NodeSet.java @@ -0,0 +1,71 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.loadbalancing.nodeset; + +import com.datastax.oss.driver.api.core.metadata.Node; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.Nullable; +import java.util.Set; +import net.jcip.annotations.ThreadSafe; + +/** + * A thread-safe abstraction around a map of nodes per datacenter, to facilitate node management by + * load balancing policies. + */ +@ThreadSafe +public interface NodeSet { + + /** + * Adds the given node to this set. + * + *

    If this set was initialized with datacenter awareness, the node will be added to its + * datacenter's specific set; otherwise, the node is added to a general set containing all nodes + * in the cluster. + * + * @param node The node to add. + * @return true if the node was added, false otherwise (because it was already present). + */ + boolean add(@NonNull Node node); + + /** + * Removes the node from the set. + * + * @param node The node to remove. + * @return true if the node was removed, false otherwise (because it was not present). + */ + boolean remove(@NonNull Node node); + + /** + * Returns the current nodes in the given datacenter. + * + *

    If this set was initialized with datacenter awareness, the returned set will contain only + * nodes pertaining to the given datacenter; otherwise, the given datacenter name is ignored and + * the returned set will contain all nodes in the cluster. + * + * @param dc The datacenter name, or null if the datacenter name is not known, or irrelevant. + * @return the current nodes in the given datacenter. + */ + @NonNull + Set dc(@Nullable String dc); + + /** + * Returns the current datacenter names known to this set. If datacenter awareness has been + * disabled, this method returns an empty set. + */ + Set dcs(); +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/nodeset/SingleDcNodeSet.java b/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/nodeset/SingleDcNodeSet.java new file mode 100644 index 00000000000..21c89d46927 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/nodeset/SingleDcNodeSet.java @@ -0,0 +1,72 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.loadbalancing.nodeset; + +import com.datastax.oss.driver.api.core.metadata.Node; +import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableSet; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.Nullable; +import java.util.Collections; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArraySet; +import net.jcip.annotations.ThreadSafe; + +@ThreadSafe +public class SingleDcNodeSet implements NodeSet { + + private final Set nodes = new CopyOnWriteArraySet<>(); + + private final String dc; + private final Set dcs; + + public SingleDcNodeSet(@NonNull String dc) { + this.dc = dc; + dcs = ImmutableSet.of(dc); + } + + @Override + public boolean add(@NonNull Node node) { + if (Objects.equals(node.getDatacenter(), dc)) { + return nodes.add(node); + } + return false; + } + + @Override + public boolean remove(@NonNull Node node) { + if (Objects.equals(node.getDatacenter(), dc)) { + return nodes.remove(node); + } + return false; + } + + @Override + @NonNull + public Set dc(@Nullable String dc) { + if (Objects.equals(this.dc, dc)) { + return nodes; + } + return Collections.emptySet(); + } + + @Override + public Set dcs() { + return dcs; + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/AddNodeRefresh.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/AddNodeRefresh.java index e8806b7651a..ac68b92fef2 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/AddNodeRefresh.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/AddNodeRefresh.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/CloudTopologyMonitor.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/CloudTopologyMonitor.java index 6df0bf3e055..021824a9b16 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/CloudTopologyMonitor.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/CloudTopologyMonitor.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/DefaultEndPoint.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/DefaultEndPoint.java index 0f657b9bfcf..7ffbee8e4bb 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/DefaultEndPoint.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/DefaultEndPoint.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/DefaultMetadata.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/DefaultMetadata.java index c34486029fe..38f7e4a093e 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/DefaultMetadata.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/DefaultMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/DefaultNode.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/DefaultNode.java index 839a4a61231..28f9e2de81c 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/DefaultNode.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/DefaultNode.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/DefaultNodeInfo.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/DefaultNodeInfo.java index 7b34a33856d..8908f0be078 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/DefaultNodeInfo.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/DefaultNodeInfo.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/DefaultTopologyMonitor.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/DefaultTopologyMonitor.java index 87585199b77..f3dc988cfbc 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/DefaultTopologyMonitor.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/DefaultTopologyMonitor.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -32,6 +34,7 @@ import com.datastax.oss.driver.shaded.guava.common.annotations.VisibleForTesting; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableSet; +import com.datastax.oss.driver.shaded.guava.common.collect.Iterators; import com.datastax.oss.protocol.internal.ProtocolConstants; import com.datastax.oss.protocol.internal.response.Error; import edu.umd.cs.findbugs.annotations.NonNull; @@ -67,6 +70,10 @@ public class DefaultTopologyMonitor implements TopologyMonitor { // Assume topology queries never need paging private static final int INFINITE_PAGE_SIZE = -1; + // A few system.peers columns which get special handling below + private static final String NATIVE_PORT = "native_port"; + private static final String NATIVE_TRANSPORT_PORT = "native_transport_port"; + private final String logPrefix; private final InternalDriverContext context; private final ControlConnection controlConnection; @@ -492,28 +499,65 @@ private void savePort(DriverChannel channel) { @Nullable protected InetSocketAddress getBroadcastRpcAddress( @NonNull AdminRow row, @NonNull EndPoint localEndPoint) { - // in system.peers or system.local - InetAddress broadcastRpcInetAddress = row.getInetAddress("rpc_address"); + + InetAddress broadcastRpcInetAddress = null; + Iterator addrCandidates = + Iterators.forArray( + // in system.peers_v2 (Cassandra >= 4.0) + "native_address", + // DSE 6.8 introduced native_transport_address and native_transport_port for the + // listen address. + "native_transport_address", + // in system.peers or system.local + "rpc_address"); + + while (broadcastRpcInetAddress == null && addrCandidates.hasNext()) + broadcastRpcInetAddress = row.getInetAddress(addrCandidates.next()); + // This could only happen if system tables are corrupted, but handle gracefully if (broadcastRpcInetAddress == null) { - // in system.peers_v2 (Cassandra >= 4.0) - broadcastRpcInetAddress = row.getInetAddress("native_address"); - if (broadcastRpcInetAddress == null) { - // This could only happen if system tables are corrupted, but handle gracefully - return null; + LOG.warn( + "[{}] Unable to determine broadcast RPC IP address, returning null. " + + "This is likely due to a misconfiguration or invalid system tables. " + + "Please validate the contents of system.local and/or {}.", + logPrefix, + getPeerTableName()); + return null; + } + + Integer broadcastRpcPort = null; + Iterator portCandidates = + Iterators.forArray( + // in system.peers_v2 (Cassandra >= 4.0) + NATIVE_PORT, + // DSE 6.8 introduced native_transport_address and native_transport_port for the + // listen address. + NATIVE_TRANSPORT_PORT, + // system.local for Cassandra >= 4.0 + "rpc_port"); + + while ((broadcastRpcPort == null || broadcastRpcPort == 0) && portCandidates.hasNext()) { + + String colName = portCandidates.next(); + broadcastRpcPort = row.getInteger(colName); + // Support override for SSL port (if enabled) in DSE + if (NATIVE_TRANSPORT_PORT.equals(colName) && context.getSslEngineFactory().isPresent()) { + + String sslColName = colName + "_ssl"; + broadcastRpcPort = row.getInteger(sslColName); } } - // system.local for Cassandra >= 4.0 - Integer broadcastRpcPort = row.getInteger("rpc_port"); + // use the default port if no port information was found in the row; + // note that in rare situations, the default port might not be known, in which case we + // report zero, as advertised in the javadocs of Node and NodeInfo. if (broadcastRpcPort == null || broadcastRpcPort == 0) { - // system.peers_v2 - broadcastRpcPort = row.getInteger("native_port"); - if (broadcastRpcPort == null || broadcastRpcPort == 0) { - // use the default port if no port information was found in the row; - // note that in rare situations, the default port might not be known, in which case we - // report zero, as advertised in the javadocs of Node and NodeInfo. - broadcastRpcPort = port == -1 ? 0 : port; - } + + LOG.warn( + "[{}] Unable to determine broadcast RPC port. " + + "Trying to fall back to port used by the control connection.", + logPrefix); + broadcastRpcPort = port == -1 ? 0 : port; } + InetSocketAddress broadcastRpcAddress = new InetSocketAddress(broadcastRpcInetAddress, broadcastRpcPort); if (row.contains("peer") && broadcastRpcAddress.equals(localEndPoint.resolve())) { @@ -539,24 +583,16 @@ protected InetSocketAddress getBroadcastRpcAddress( * node's broadcast RPC address and host ID; otherwise the driver may not work properly. */ protected boolean isPeerValid(AdminRow peerRow) { - boolean hasPeersRpcAddress = !peerRow.isNull("rpc_address"); - boolean hasPeersV2RpcAddress = - !peerRow.isNull("native_address") && !peerRow.isNull("native_port"); - boolean hasRpcAddress = hasPeersV2RpcAddress || hasPeersRpcAddress; - boolean valid = - hasRpcAddress - && !peerRow.isNull("host_id") - && !peerRow.isNull("data_center") - && !peerRow.isNull("rack") - && !peerRow.isNull("tokens"); - if (!valid) { + if (PeerRowValidator.isValid(peerRow)) { + return true; + } else { LOG.warn( "[{}] Found invalid row in {} for peer: {}. " + "This is likely a gossip or snitch issue, this node will be ignored.", logPrefix, getPeerTableName(), peerRow.getInetAddress("peer")); + return false; } - return valid; } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/DistanceEvent.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/DistanceEvent.java index 638d4f3db99..5d58727484c 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/DistanceEvent.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/DistanceEvent.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/FullNodeListRefresh.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/FullNodeListRefresh.java index 14496bb3399..7388980c230 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/FullNodeListRefresh.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/FullNodeListRefresh.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/InitialNodeListRefresh.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/InitialNodeListRefresh.java index e676d9eb2ee..517bfca27fa 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/InitialNodeListRefresh.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/InitialNodeListRefresh.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,14 +18,16 @@ package com.datastax.oss.driver.internal.core.metadata; import com.datastax.oss.driver.api.core.metadata.EndPoint; -import com.datastax.oss.driver.api.core.metadata.Node; import com.datastax.oss.driver.internal.core.context.InternalDriverContext; import com.datastax.oss.driver.internal.core.metadata.token.TokenFactory; import com.datastax.oss.driver.internal.core.metadata.token.TokenFactoryRegistry; import com.datastax.oss.driver.shaded.guava.common.annotations.VisibleForTesting; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableList; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap; +import java.util.ArrayList; import java.util.HashMap; +import java.util.HashSet; +import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; @@ -61,22 +65,31 @@ public Result compute( TokenFactory tokenFactory = null; Map newNodes = new HashMap<>(); + // Contact point nodes don't have host ID as well as other info yet, so we fill them with node + // info found on first match by endpoint + Set matchedContactPoints = new HashSet<>(); + List addedNodes = new ArrayList<>(); for (NodeInfo nodeInfo : nodeInfos) { UUID hostId = nodeInfo.getHostId(); if (newNodes.containsKey(hostId)) { LOG.warn( "[{}] Found duplicate entries with host_id {} in system.peers, " - + "keeping only the first one", + + "keeping only the first one {}", logPrefix, - hostId); + hostId, + newNodes.get(hostId)); } else { EndPoint endPoint = nodeInfo.getEndPoint(); - DefaultNode node = findIn(contactPoints, endPoint); - if (node == null) { + DefaultNode contactPointNode = findContactPointNode(endPoint); + DefaultNode node; + if (contactPointNode == null || matchedContactPoints.contains(endPoint)) { node = new DefaultNode(endPoint, context); + addedNodes.add(node); LOG.debug("[{}] Adding new node {}", logPrefix, node); } else { + matchedContactPoints.add(contactPointNode.getEndPoint()); + node = contactPointNode; LOG.debug("[{}] Copying contact point {}", logPrefix, node); } if (tokenMapEnabled && tokenFactory == null && nodeInfo.getPartitioner() != null) { @@ -88,14 +101,11 @@ public Result compute( } ImmutableList.Builder eventsBuilder = ImmutableList.builder(); - - for (DefaultNode newNode : newNodes.values()) { - if (findIn(contactPoints, newNode.getEndPoint()) == null) { - eventsBuilder.add(NodeStateEvent.added(newNode)); - } + for (DefaultNode addedNode : addedNodes) { + eventsBuilder.add(NodeStateEvent.added(addedNode)); } for (DefaultNode contactPoint : contactPoints) { - if (findIn(newNodes.values(), contactPoint.getEndPoint()) == null) { + if (!matchedContactPoints.contains(contactPoint.getEndPoint())) { eventsBuilder.add(NodeStateEvent.removed(contactPoint)); } } @@ -106,10 +116,10 @@ public Result compute( eventsBuilder.build()); } - private DefaultNode findIn(Iterable nodes, EndPoint endPoint) { - for (Node node : nodes) { + private DefaultNode findContactPointNode(EndPoint endPoint) { + for (DefaultNode node : contactPoints) { if (node.getEndPoint().equals(endPoint)) { - return (DefaultNode) node; + return node; } } return null; diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/LoadBalancingPolicyWrapper.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/LoadBalancingPolicyWrapper.java index bdf0c392e0c..5c8473a3b67 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/LoadBalancingPolicyWrapper.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/LoadBalancingPolicyWrapper.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -36,6 +38,7 @@ import java.util.Map; import java.util.Queue; import java.util.Set; +import java.util.WeakHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.Lock; @@ -84,7 +87,7 @@ private enum State { private final String logPrefix; private final ReplayingEventFilter eventFilter = new ReplayingEventFilter<>(this::processNodeStateEvent); - private AtomicReference stateRef = new AtomicReference<>(State.BEFORE_INIT); + private final AtomicReference stateRef = new AtomicReference<>(State.BEFORE_INIT); public LoadBalancingPolicyWrapper( @NonNull InternalDriverContext context, @@ -103,7 +106,7 @@ public LoadBalancingPolicyWrapper( // Just an alias to make the rest of the code more readable this.policies = reporters.keySet(); - this.distances = new HashMap<>(); + this.distances = new WeakHashMap<>(); this.logPrefix = context.getSessionName(); context.getEventBus().register(NodeStateEvent.class, this::onNodeStateEvent); @@ -170,6 +173,7 @@ private void onNodeStateEvent(NodeStateEvent event) { // once it has gone through the filter private void processNodeStateEvent(NodeStateEvent event) { + DefaultNode node = event.node; switch (stateRef.get()) { case BEFORE_INIT: case DURING_INIT: @@ -179,13 +183,13 @@ private void processNodeStateEvent(NodeStateEvent event) { case RUNNING: for (LoadBalancingPolicy policy : policies) { if (event.newState == NodeState.UP) { - policy.onUp(event.node); + policy.onUp(node); } else if (event.newState == NodeState.DOWN || event.newState == NodeState.FORCED_DOWN) { - policy.onDown(event.node); + policy.onDown(node); } else if (event.newState == NodeState.UNKNOWN) { - policy.onAdd(event.node); + policy.onAdd(node); } else if (event.newState == null) { - policy.onRemove(event.node); + policy.onRemove(node); } else { LOG.warn("[{}] Unsupported event: {}", logPrefix, event); } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/MetadataManager.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/MetadataManager.java index 6db1db038bd..efb04bde5e1 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/MetadataManager.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/MetadataManager.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -25,6 +27,7 @@ import com.datastax.oss.driver.internal.core.context.InternalDriverContext; import com.datastax.oss.driver.internal.core.control.ControlConnection; import com.datastax.oss.driver.internal.core.metadata.schema.parsing.SchemaParserFactory; +import com.datastax.oss.driver.internal.core.metadata.schema.queries.KeyspaceFilter; import com.datastax.oss.driver.internal.core.metadata.schema.queries.SchemaQueriesFactory; import com.datastax.oss.driver.internal.core.metadata.schema.queries.SchemaRows; import com.datastax.oss.driver.internal.core.metadata.schema.refresh.SchemaRefresh; @@ -65,6 +68,7 @@ public class MetadataManager implements AsyncAutoCloseable { private volatile DefaultMetadata metadata; // only updated from adminExecutor private volatile boolean schemaEnabledInConfig; private volatile List refreshedKeyspaces; + private volatile KeyspaceFilter keyspaceFilter; private volatile Boolean schemaEnabledProgrammatically; private volatile boolean tokenMapEnabled; private volatile Set contactPoints; @@ -86,6 +90,7 @@ protected MetadataManager(InternalDriverContext context, DefaultMetadata initial this.refreshedKeyspaces = config.getStringList( DefaultDriverOption.METADATA_SCHEMA_REFRESHED_KEYSPACES, Collections.emptyList()); + this.keyspaceFilter = KeyspaceFilter.newInstance(logPrefix, refreshedKeyspaces); this.tokenMapEnabled = config.getBoolean(DefaultDriverOption.METADATA_TOKEN_MAP_ENABLED); context.getEventBus().register(ConfigChangeEvent.class, this::onConfigChanged); @@ -100,6 +105,7 @@ private void onConfigChanged(@SuppressWarnings("unused") ConfigChangeEvent event this.refreshedKeyspaces = config.getStringList( DefaultDriverOption.METADATA_SCHEMA_REFRESHED_KEYSPACES, Collections.emptyList()); + this.keyspaceFilter = KeyspaceFilter.newInstance(logPrefix, refreshedKeyspaces); this.tokenMapEnabled = config.getBoolean(DefaultDriverOption.METADATA_TOKEN_MAP_ENABLED); if ((!schemaEnabledBefore @@ -310,6 +316,7 @@ private class SingleThreaded { private SingleThreaded(InternalDriverContext context, DriverExecutionProfile config) { this.schemaRefreshDebouncer = new Debouncer<>( + logPrefix + "|metadata debouncer", adminExecutor, this::coalesceSchemaRequests, this::startSchemaRequest, @@ -372,8 +379,7 @@ private void refreshSchema( } // If this is an event, make sure it's not targeting a keyspace that we're ignoring. - boolean isRefreshedKeyspace = - keyspace == null || refreshedKeyspaces.isEmpty() || refreshedKeyspaces.contains(keyspace); + boolean isRefreshedKeyspace = keyspace == null || keyspaceFilter.includes(keyspace); if (isRefreshedKeyspace && (evenIfDisabled || isSchemaEnabled())) { acceptSchemaRequest(future, flushNow); @@ -431,30 +437,35 @@ private void startSchemaRequest(CompletableFuture refreshFu if (agreementError != null) { refreshFuture.completeExceptionally(agreementError); } else { - schemaQueriesFactory - .newInstance() - .execute() - .thenApplyAsync(this::parseAndApplySchemaRows, adminExecutor) - .whenComplete( - (newMetadata, metadataError) -> { - if (metadataError != null) { - refreshFuture.completeExceptionally(metadataError); - } else { - refreshFuture.complete( - new RefreshSchemaResult(newMetadata, schemaInAgreement)); - } - - firstSchemaRefreshFuture.complete(null); - - currentSchemaRefresh = null; - // If another refresh was enqueued during this one, run it now - if (queuedSchemaRefresh != null) { - CompletableFuture tmp = - this.queuedSchemaRefresh; - this.queuedSchemaRefresh = null; - startSchemaRequest(tmp); - } - }); + try { + schemaQueriesFactory + .newInstance() + .execute() + .thenApplyAsync(this::parseAndApplySchemaRows, adminExecutor) + .whenComplete( + (newMetadata, metadataError) -> { + if (metadataError != null) { + refreshFuture.completeExceptionally(metadataError); + } else { + refreshFuture.complete( + new RefreshSchemaResult(newMetadata, schemaInAgreement)); + } + + firstSchemaRefreshFuture.complete(null); + + currentSchemaRefresh = null; + // If another refresh was enqueued during this one, run it now + if (queuedSchemaRefresh != null) { + CompletableFuture tmp = + this.queuedSchemaRefresh; + this.queuedSchemaRefresh = null; + startSchemaRequest(tmp); + } + }); + } catch (Throwable t) { + LOG.debug("[{}] Exception getting new metadata", logPrefix, t); + refreshFuture.completeExceptionally(t); + } } }); } else if (queuedSchemaRefresh == null) { diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/MetadataRefresh.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/MetadataRefresh.java index aab77f2a756..fc31f317622 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/MetadataRefresh.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/MetadataRefresh.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/MultiplexingNodeStateListener.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/MultiplexingNodeStateListener.java new file mode 100644 index 00000000000..8ee6d04bbae --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/MultiplexingNodeStateListener.java @@ -0,0 +1,127 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.metadata; + +import com.datastax.oss.driver.api.core.metadata.Node; +import com.datastax.oss.driver.api.core.metadata.NodeStateListener; +import com.datastax.oss.driver.api.core.session.Session; +import com.datastax.oss.driver.internal.core.util.Loggers; +import edu.umd.cs.findbugs.annotations.NonNull; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.function.Consumer; +import net.jcip.annotations.ThreadSafe; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Combines multiple node state listeners into a single one. + * + *

    Any exception thrown by a child listener is caught and logged. + */ +@ThreadSafe +public class MultiplexingNodeStateListener implements NodeStateListener { + + private static final Logger LOG = LoggerFactory.getLogger(MultiplexingNodeStateListener.class); + + private final List listeners = new CopyOnWriteArrayList<>(); + + public MultiplexingNodeStateListener() {} + + public MultiplexingNodeStateListener(NodeStateListener... listeners) { + this(Arrays.asList(listeners)); + } + + public MultiplexingNodeStateListener(Collection listeners) { + addListeners(listeners); + } + + private void addListeners(Collection source) { + for (NodeStateListener listener : source) { + addListener(listener); + } + } + + private void addListener(NodeStateListener toAdd) { + Objects.requireNonNull(toAdd, "listener cannot be null"); + if (toAdd instanceof MultiplexingNodeStateListener) { + addListeners(((MultiplexingNodeStateListener) toAdd).listeners); + } else { + listeners.add(toAdd); + } + } + + public void register(@NonNull NodeStateListener listener) { + addListener(listener); + } + + @Override + public void onAdd(@NonNull Node node) { + invokeListeners(listener -> listener.onAdd(node), "onAdd"); + } + + @Override + public void onUp(@NonNull Node node) { + invokeListeners(listener -> listener.onUp(node), "onUp"); + } + + @Override + public void onDown(@NonNull Node node) { + invokeListeners(listener -> listener.onDown(node), "onDown"); + } + + @Override + public void onRemove(@NonNull Node node) { + invokeListeners(listener -> listener.onRemove(node), "onRemove"); + } + + @Override + public void onSessionReady(@NonNull Session session) { + invokeListeners(listener -> listener.onSessionReady(session), "onSessionReady"); + } + + @Override + public void close() throws Exception { + for (NodeStateListener listener : listeners) { + try { + listener.close(); + } catch (Exception e) { + Loggers.warnWithException( + LOG, "Unexpected error while closing node state listener {}.", listener, e); + } + } + } + + private void invokeListeners(@NonNull Consumer action, String event) { + for (NodeStateListener listener : listeners) { + try { + action.accept(listener); + } catch (Exception e) { + Loggers.warnWithException( + LOG, + "Unexpected error while notifying node state listener {} of an {} event.", + listener, + event, + e); + } + } + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/NodeInfo.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/NodeInfo.java index 8bafcfe52f9..6a9651d8376 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/NodeInfo.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/NodeInfo.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/NodeStateEvent.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/NodeStateEvent.java index 6365d65626f..2f5c3c1d230 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/NodeStateEvent.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/NodeStateEvent.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/NodeStateManager.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/NodeStateManager.java index dab95b58a3e..c8a52e4fa00 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/NodeStateManager.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/NodeStateManager.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -103,6 +105,7 @@ private SingleThreaded(InternalDriverContext context) { DriverExecutionProfile config = context.getConfig().getDefaultProfile(); this.topologyEventDebouncer = new Debouncer<>( + logPrefix + "|topology debouncer", adminExecutor, this::coalesceTopologyEvents, this::flushTopologyEvents, @@ -184,10 +187,10 @@ private void onDebouncedTopologyEvent(TopologyEvent event) { } } else { LOG.debug( - "[{}] Received UP event for unknown node {}, adding it", + "[{}] Received UP event for unknown node {}, refreshing node list", logPrefix, event.broadcastRpcAddress); - metadataManager.addNode(event.broadcastRpcAddress); + metadataManager.refreshNodes(); } break; case SUGGEST_DOWN: diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/NodesRefresh.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/NodesRefresh.java index 868fc53712e..befb55e3740 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/NodesRefresh.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/NodesRefresh.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/NoopNodeStateListener.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/NoopNodeStateListener.java index 2e70d8efb6a..b879e1f2104 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/NoopNodeStateListener.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/NoopNodeStateListener.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,29 +18,12 @@ package com.datastax.oss.driver.internal.core.metadata; import com.datastax.oss.driver.api.core.context.DriverContext; -import com.datastax.oss.driver.api.core.metadata.NodeStateListener; import com.datastax.oss.driver.api.core.metadata.NodeStateListenerBase; -import com.datastax.oss.driver.api.core.session.SessionBuilder; import net.jcip.annotations.ThreadSafe; /** - * Default node state listener implementation with empty methods. - * - *

    To activate this listener, modify the {@code advanced.node-state-listener} section in the - * driver configuration, for example: - * - *

    - * datastax-java-driver {
    - *   advanced.node-state-listener {
    - *     class = NoopNodeStateListener
    - *   }
    - * }
    - * 
    - * - * See {@code reference.conf} (in the manual or core driver JAR) for more details. - * - *

    Note that if a listener is specified programmatically with {@link - * SessionBuilder#withNodeStateListener(NodeStateListener)}, the configuration is ignored. + * Default node state listener implementation with empty methods. This implementation is used when + * no listeners were registered, neither programmatically nor through the configuration. */ @ThreadSafe public class NoopNodeStateListener extends NodeStateListenerBase { diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/PeerRowValidator.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/PeerRowValidator.java new file mode 100644 index 00000000000..4782d72abbb --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/PeerRowValidator.java @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.datastax.oss.driver.internal.core.metadata; + +import com.datastax.oss.driver.internal.core.adminrequest.AdminRow; +import edu.umd.cs.findbugs.annotations.NonNull; +import net.jcip.annotations.ThreadSafe; + +@ThreadSafe +public class PeerRowValidator { + + /** Returns {@code true} if the given peer row is valid, and {@code false} otherwise. */ + public static boolean isValid(@NonNull AdminRow peerRow) { + + boolean hasPeersRpcAddress = !peerRow.isNull("rpc_address"); + boolean hasPeersV2RpcAddress = + !peerRow.isNull("native_address") && !peerRow.isNull("native_port"); + boolean hasRpcAddress = hasPeersRpcAddress || hasPeersV2RpcAddress; + + return hasRpcAddress + && !peerRow.isNull("host_id") + && !peerRow.isNull("data_center") + && !peerRow.isNull("rack") + && !peerRow.isNull("tokens") + && !peerRow.isNull("schema_version"); + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/RemoveNodeRefresh.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/RemoveNodeRefresh.java index 5135d04fda4..46de1989278 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/RemoveNodeRefresh.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/RemoveNodeRefresh.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/SchemaAgreementChecker.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/SchemaAgreementChecker.java index 61f75c573ab..c5935dba4bb 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/SchemaAgreementChecker.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/SchemaAgreementChecker.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -32,6 +34,7 @@ import java.time.Duration; import java.util.Iterator; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.UUID; import java.util.concurrent.CompletableFuture; @@ -105,8 +108,7 @@ private void sendQueries() { } else { CompletionStage localQuery = query("SELECT schema_version FROM system.local WHERE key='local'"); - CompletionStage peersQuery = - query("SELECT host_id, schema_version FROM system.peers"); + CompletionStage peersQuery = query("SELECT * FROM system.peers"); localQuery .thenCombine(peersQuery, this::extractSchemaVersions) @@ -142,31 +144,10 @@ private Set extractSchemaVersions(AdminResult controlNodeResult, AdminResu Map nodes = context.getMetadataManager().getMetadata().getNodes(); for (AdminRow peerRow : peersResult) { - UUID hostId = peerRow.getUuid("host_id"); - if (hostId == null) { - LOG.warn( - "[{}] Missing host_id in system.peers row, excluding from schema agreement check", - logPrefix); - continue; - } - UUID schemaVersion = peerRow.getUuid("schema_version"); - if (schemaVersion == null) { - LOG.warn( - "[{}] Missing schema_version in system.peers row for {}, " - + "excluding from schema agreement check", - logPrefix, - hostId); - continue; - } - Node node = nodes.get(hostId); - if (node == null) { - LOG.warn("[{}] Unknown peer {}, excluding from schema agreement check", logPrefix, hostId); - continue; - } else if (node.getState() != NodeState.UP) { - LOG.debug("[{}] Peer {} is down, excluding from schema agreement check", logPrefix, hostId); - continue; + if (isPeerValid(peerRow, nodes)) { + UUID schemaVersion = Objects.requireNonNull(peerRow.getUuid("schema_version")); + schemaVersions.add(schemaVersion); } - schemaVersions.add(schemaVersion); } return schemaVersions.build(); } @@ -207,4 +188,25 @@ protected CompletionStage query(String queryString) { channel, queryString, queryTimeout, INFINITE_PAGE_SIZE, logPrefix) .start(); } + + protected boolean isPeerValid(AdminRow peerRow, Map nodes) { + if (PeerRowValidator.isValid(peerRow)) { + UUID hostId = peerRow.getUuid("host_id"); + Node node = nodes.get(hostId); + if (node == null) { + LOG.warn("[{}] Unknown peer {}, excluding from schema agreement check", logPrefix, hostId); + return false; + } else if (node.getState() != NodeState.UP) { + LOG.debug("[{}] Peer {} is down, excluding from schema agreement check", logPrefix, hostId); + return false; + } + return true; + } else { + LOG.warn( + "[{}] Found invalid system.peers row for peer: {}, excluding from schema agreement check.", + logPrefix, + peerRow.getInetAddress("peer")); + return false; + } + } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/SniEndPoint.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/SniEndPoint.java index 5c2918e1f34..d1ab8eec98d 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/SniEndPoint.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/SniEndPoint.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -17,16 +19,17 @@ import com.datastax.oss.driver.api.core.metadata.EndPoint; import com.datastax.oss.driver.shaded.guava.common.primitives.UnsignedBytes; +import edu.umd.cs.findbugs.annotations.NonNull; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.Arrays; import java.util.Comparator; import java.util.Objects; -import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicInteger; public class SniEndPoint implements EndPoint { - private static final AtomicLong OFFSET = new AtomicLong(); + private static final AtomicInteger OFFSET = new AtomicInteger(); private final InetSocketAddress proxyAddress; private final String serverName; @@ -48,6 +51,7 @@ public String getServerName() { return serverName; } + @NonNull @Override public InetSocketAddress resolve() { try { @@ -60,7 +64,10 @@ public InetSocketAddress resolve() { // The order of the returned address is unspecified. Sort by IP to make sure we get a true // round-robin Arrays.sort(aRecords, IP_COMPARATOR); - int index = (aRecords.length == 1) ? 0 : (int) OFFSET.getAndIncrement() % aRecords.length; + int index = + (aRecords.length == 1) + ? 0 + : OFFSET.getAndUpdate(x -> x == Integer.MAX_VALUE ? 0 : x + 1) % aRecords.length; return new InetSocketAddress(aRecords[index], proxyAddress.getPort()); } catch (UnknownHostException e) { throw new IllegalArgumentException( @@ -93,6 +100,7 @@ public String toString() { return proxyAddress.toString() + ":" + serverName; } + @NonNull @Override public String asMetricPrefix() { String hostString = proxyAddress.getHostString(); diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/TokensChangedRefresh.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/TokensChangedRefresh.java index 174ed029d7a..6f60e9a790b 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/TokensChangedRefresh.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/TokensChangedRefresh.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/TopologyEvent.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/TopologyEvent.java index 4f11fa4b182..c7ea8c93088 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/TopologyEvent.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/TopologyEvent.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/TopologyMonitor.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/TopologyMonitor.java index f74bcd943a4..e7741f11196 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/TopologyMonitor.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/TopologyMonitor.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/DefaultAggregateMetadata.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/DefaultAggregateMetadata.java index 61a325abdd0..669f925af65 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/DefaultAggregateMetadata.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/DefaultAggregateMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/DefaultColumnMetadata.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/DefaultColumnMetadata.java index 311c5220db4..3d0c6209880 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/DefaultColumnMetadata.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/DefaultColumnMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/DefaultFunctionMetadata.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/DefaultFunctionMetadata.java index 9370ffb4ea2..75b343d77b1 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/DefaultFunctionMetadata.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/DefaultFunctionMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/DefaultIndexMetadata.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/DefaultIndexMetadata.java index ef3a382b071..8ff0263fcc8 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/DefaultIndexMetadata.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/DefaultIndexMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/DefaultKeyspaceMetadata.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/DefaultKeyspaceMetadata.java index ca61e89e315..3d443dd8c16 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/DefaultKeyspaceMetadata.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/DefaultKeyspaceMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/DefaultTableMetadata.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/DefaultTableMetadata.java index e877e322993..4c339f89299 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/DefaultTableMetadata.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/DefaultTableMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -142,7 +144,8 @@ public boolean equals(Object other) { && Objects.equals(this.partitionKey, that.getPartitionKey()) && Objects.equals(this.clusteringColumns, that.getClusteringColumns()) && Objects.equals(this.columns, that.getColumns()) - && Objects.equals(this.indexes, that.getIndexes()); + && Objects.equals(this.indexes, that.getIndexes()) + && Objects.equals(this.options, that.getOptions()); } else { return false; } @@ -159,7 +162,8 @@ public int hashCode() { partitionKey, clusteringColumns, columns, - indexes); + indexes, + options); } @Override diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/DefaultViewMetadata.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/DefaultViewMetadata.java index 520e7d416a0..2c5e5a9603e 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/DefaultViewMetadata.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/DefaultViewMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/MultiplexingSchemaChangeListener.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/MultiplexingSchemaChangeListener.java new file mode 100644 index 00000000000..eebe16364d1 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/MultiplexingSchemaChangeListener.java @@ -0,0 +1,211 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.metadata.schema; + +import com.datastax.oss.driver.api.core.metadata.schema.AggregateMetadata; +import com.datastax.oss.driver.api.core.metadata.schema.FunctionMetadata; +import com.datastax.oss.driver.api.core.metadata.schema.KeyspaceMetadata; +import com.datastax.oss.driver.api.core.metadata.schema.SchemaChangeListener; +import com.datastax.oss.driver.api.core.metadata.schema.TableMetadata; +import com.datastax.oss.driver.api.core.metadata.schema.ViewMetadata; +import com.datastax.oss.driver.api.core.session.Session; +import com.datastax.oss.driver.api.core.type.UserDefinedType; +import com.datastax.oss.driver.internal.core.util.Loggers; +import edu.umd.cs.findbugs.annotations.NonNull; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.function.Consumer; +import net.jcip.annotations.ThreadSafe; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Combines multiple schema change listeners into a single one. + * + *

    Any exception thrown by a child listener is caught and logged. + */ +@ThreadSafe +public class MultiplexingSchemaChangeListener implements SchemaChangeListener { + + private static final Logger LOG = LoggerFactory.getLogger(MultiplexingSchemaChangeListener.class); + + private final List listeners = new CopyOnWriteArrayList<>(); + + public MultiplexingSchemaChangeListener() {} + + public MultiplexingSchemaChangeListener(SchemaChangeListener... listeners) { + this(Arrays.asList(listeners)); + } + + public MultiplexingSchemaChangeListener(Collection listeners) { + addListeners(listeners); + } + + private void addListeners(Collection source) { + for (SchemaChangeListener listener : source) { + addListener(listener); + } + } + + private void addListener(SchemaChangeListener toAdd) { + Objects.requireNonNull(toAdd, "listener cannot be null"); + if (toAdd instanceof MultiplexingSchemaChangeListener) { + addListeners(((MultiplexingSchemaChangeListener) toAdd).listeners); + } else { + listeners.add(toAdd); + } + } + + public void register(@NonNull SchemaChangeListener listener) { + addListener(listener); + } + + @Override + public void onKeyspaceCreated(@NonNull KeyspaceMetadata keyspace) { + invokeListeners(listener -> listener.onKeyspaceCreated(keyspace), "onKeyspaceCreated"); + } + + @Override + public void onKeyspaceDropped(@NonNull KeyspaceMetadata keyspace) { + invokeListeners(listener -> listener.onKeyspaceDropped(keyspace), "onKeyspaceDropped"); + } + + @Override + public void onKeyspaceUpdated( + @NonNull KeyspaceMetadata current, @NonNull KeyspaceMetadata previous) { + invokeListeners(listener -> listener.onKeyspaceUpdated(current, previous), "onKeyspaceUpdated"); + } + + @Override + public void onTableCreated(@NonNull TableMetadata table) { + invokeListeners(listener -> listener.onTableCreated(table), "onTableCreated"); + } + + @Override + public void onTableDropped(@NonNull TableMetadata table) { + invokeListeners(listener -> listener.onTableDropped(table), "onTableDropped"); + } + + @Override + public void onTableUpdated(@NonNull TableMetadata current, @NonNull TableMetadata previous) { + invokeListeners(listener -> listener.onTableUpdated(current, previous), "onTableUpdated"); + } + + @Override + public void onUserDefinedTypeCreated(@NonNull UserDefinedType type) { + invokeListeners( + listener -> listener.onUserDefinedTypeCreated(type), "onUserDefinedTypeCreated"); + } + + @Override + public void onUserDefinedTypeDropped(@NonNull UserDefinedType type) { + invokeListeners( + listener -> listener.onUserDefinedTypeDropped(type), "onUserDefinedTypeDropped"); + } + + @Override + public void onUserDefinedTypeUpdated( + @NonNull UserDefinedType current, @NonNull UserDefinedType previous) { + invokeListeners( + listener -> listener.onUserDefinedTypeUpdated(current, previous), + "onUserDefinedTypeUpdated"); + } + + @Override + public void onFunctionCreated(@NonNull FunctionMetadata function) { + invokeListeners(listener -> listener.onFunctionCreated(function), "onFunctionCreated"); + } + + @Override + public void onFunctionDropped(@NonNull FunctionMetadata function) { + invokeListeners(listener -> listener.onFunctionDropped(function), "onFunctionDropped"); + } + + @Override + public void onFunctionUpdated( + @NonNull FunctionMetadata current, @NonNull FunctionMetadata previous) { + invokeListeners(listener -> listener.onFunctionUpdated(current, previous), "onFunctionUpdated"); + } + + @Override + public void onAggregateCreated(@NonNull AggregateMetadata aggregate) { + invokeListeners(listener -> listener.onAggregateCreated(aggregate), "onAggregateCreated"); + } + + @Override + public void onAggregateDropped(@NonNull AggregateMetadata aggregate) { + invokeListeners(listener -> listener.onAggregateDropped(aggregate), "onAggregateDropped"); + } + + @Override + public void onAggregateUpdated( + @NonNull AggregateMetadata current, @NonNull AggregateMetadata previous) { + invokeListeners( + listener -> listener.onAggregateUpdated(current, previous), "onAggregateUpdated"); + } + + @Override + public void onViewCreated(@NonNull ViewMetadata view) { + invokeListeners(listener -> listener.onViewCreated(view), "onViewCreated"); + } + + @Override + public void onViewDropped(@NonNull ViewMetadata view) { + invokeListeners(listener -> listener.onViewDropped(view), "onViewDropped"); + } + + @Override + public void onViewUpdated(@NonNull ViewMetadata current, @NonNull ViewMetadata previous) { + invokeListeners(listener -> listener.onViewUpdated(current, previous), "onViewUpdated"); + } + + @Override + public void onSessionReady(@NonNull Session session) { + invokeListeners(listener -> listener.onSessionReady(session), "onSessionReady"); + } + + @Override + public void close() throws Exception { + for (SchemaChangeListener listener : listeners) { + try { + listener.close(); + } catch (Exception e) { + Loggers.warnWithException( + LOG, "Unexpected error while closing schema change listener {}.", listener, e); + } + } + } + + private void invokeListeners(@NonNull Consumer action, String event) { + for (SchemaChangeListener listener : listeners) { + try { + action.accept(listener); + } catch (Exception e) { + Loggers.warnWithException( + LOG, + "Unexpected error while notifying schema change listener {} of an {} event.", + listener, + event, + e); + } + } + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/NoopSchemaChangeListener.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/NoopSchemaChangeListener.java index 2df3935a80f..76fed2e5d24 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/NoopSchemaChangeListener.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/NoopSchemaChangeListener.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,29 +18,12 @@ package com.datastax.oss.driver.internal.core.metadata.schema; import com.datastax.oss.driver.api.core.context.DriverContext; -import com.datastax.oss.driver.api.core.metadata.schema.SchemaChangeListener; import com.datastax.oss.driver.api.core.metadata.schema.SchemaChangeListenerBase; -import com.datastax.oss.driver.api.core.session.SessionBuilder; import net.jcip.annotations.ThreadSafe; /** - * Default schema change listener implementation with empty methods. - * - *

    To activate this listener, modify the {@code advanced.schema-change-listener} section in the - * driver configuration, for example: - * - *

    - * datastax-java-driver {
    - *   advanced.schema-change-listener {
    - *     class = NoopSchemaChangeListener
    - *   }
    - * }
    - * 
    - * - * See {@code reference.conf} (in the manual or core driver JAR) for more details. - * - *

    Note that if a listener is specified programmatically with {@link - * SessionBuilder#withSchemaChangeListener(SchemaChangeListener)}, the configuration is ignored. + * Default schema change listener implementation with empty methods. This implementation is used + * when no listeners were registered, neither programmatically nor through the configuration. */ @ThreadSafe public class NoopSchemaChangeListener extends SchemaChangeListenerBase { diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/SchemaChangeType.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/SchemaChangeType.java index f27d68923f6..5f01d019ee0 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/SchemaChangeType.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/SchemaChangeType.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/ScriptBuilder.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/ScriptBuilder.java index d3c9114b740..b762f35b885 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/ScriptBuilder.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/ScriptBuilder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/ShallowUserDefinedType.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/ShallowUserDefinedType.java index 2d3c86c069f..069ce3752b2 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/ShallowUserDefinedType.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/ShallowUserDefinedType.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/events/AggregateChangeEvent.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/events/AggregateChangeEvent.java index a3d682f72df..fe175a98579 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/events/AggregateChangeEvent.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/events/AggregateChangeEvent.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/events/FunctionChangeEvent.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/events/FunctionChangeEvent.java index 8c5da87a30f..4ab4f0946ec 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/events/FunctionChangeEvent.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/events/FunctionChangeEvent.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/events/KeyspaceChangeEvent.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/events/KeyspaceChangeEvent.java index ef448934ddd..0bd2a9d75af 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/events/KeyspaceChangeEvent.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/events/KeyspaceChangeEvent.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/events/TableChangeEvent.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/events/TableChangeEvent.java index 16d67b8f06b..0902cf4e5b8 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/events/TableChangeEvent.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/events/TableChangeEvent.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/events/TypeChangeEvent.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/events/TypeChangeEvent.java index 2575d2e6b45..f8048570ac2 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/events/TypeChangeEvent.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/events/TypeChangeEvent.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/events/ViewChangeEvent.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/events/ViewChangeEvent.java index 84f6a4d1e61..91e59d287f1 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/events/ViewChangeEvent.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/events/ViewChangeEvent.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/AggregateParser.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/AggregateParser.java index 1e74a1ee9a7..d1f8640a744 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/AggregateParser.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/AggregateParser.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/CassandraSchemaParser.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/CassandraSchemaParser.java index 04b6f69edec..9749a921aae 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/CassandraSchemaParser.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/CassandraSchemaParser.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/DataTypeClassNameCompositeParser.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/DataTypeClassNameCompositeParser.java index 225004ca9ab..1037ccda1ae 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/DataTypeClassNameCompositeParser.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/DataTypeClassNameCompositeParser.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/DataTypeClassNameParser.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/DataTypeClassNameParser.java index 6b4a5ec11fe..bf252d0bc57 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/DataTypeClassNameParser.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/DataTypeClassNameParser.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -32,6 +34,7 @@ import com.datastax.oss.protocol.internal.util.Bytes; import java.util.ArrayList; import java.util.Collections; +import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -162,6 +165,13 @@ private DataType parse( return new DefaultTupleType(componentTypesBuilder.build(), attachmentPoint); } + if (next.startsWith("org.apache.cassandra.db.marshal.VectorType")) { + Iterator rawTypes = parser.getTypeParameters().iterator(); + DataType subtype = parse(rawTypes.next(), userTypes, attachmentPoint, logPrefix); + int dimensions = Integer.parseInt(rawTypes.next()); + return DataTypes.vectorOf(subtype, dimensions); + } + DataType type = NATIVE_TYPES_BY_CLASS_NAME.get(next); return type == null ? DataTypes.custom(toParse) : type; } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/DataTypeCqlNameParser.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/DataTypeCqlNameParser.java index b511c8cadc1..8d5e068b431 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/DataTypeCqlNameParser.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/DataTypeCqlNameParser.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -22,12 +24,14 @@ import com.datastax.oss.driver.internal.core.context.InternalDriverContext; import com.datastax.oss.driver.internal.core.metadata.schema.ShallowUserDefinedType; import com.datastax.oss.driver.internal.core.type.DefaultTupleType; +import com.datastax.oss.driver.internal.core.type.DefaultVectorType; import com.datastax.oss.driver.internal.core.type.codec.ParseUtils; import com.datastax.oss.driver.shaded.guava.common.annotations.VisibleForTesting; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableList; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap; import java.util.ArrayList; import java.util.List; +import java.util.Locale; import java.util.Map; import net.jcip.annotations.ThreadSafe; @@ -68,7 +72,7 @@ private DataType parse( return DataTypes.custom(type); } - DataType nativeType = NATIVE_TYPES_BY_NAME.get(type.toLowerCase()); + DataType nativeType = NATIVE_TYPES_BY_NAME.get(type.toLowerCase(Locale.ROOT)); if (nativeType != null) { return nativeType; } @@ -136,6 +140,16 @@ private DataType parse( return new DefaultTupleType(componentTypesBuilder.build(), context); } + if (type.equalsIgnoreCase("vector")) { + if (parameters.size() != 2) { + throw new IllegalArgumentException( + String.format("Expecting two parameters for vector custom type, got %s", parameters)); + } + DataType subType = parse(parameters.get(0), keyspaceId, false, userTypes, context); + int dimensions = Integer.parseInt(parameters.get(1)); + return new DefaultVectorType(subType, dimensions); + } + throw new IllegalArgumentException("Could not parse type name " + toParse); } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/DataTypeParser.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/DataTypeParser.java index 42ee4c37b05..0f191d08a53 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/DataTypeParser.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/DataTypeParser.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/DefaultSchemaParserFactory.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/DefaultSchemaParserFactory.java index 29c6356979d..5fa64027be5 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/DefaultSchemaParserFactory.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/DefaultSchemaParserFactory.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/FunctionParser.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/FunctionParser.java index edd5a6bfe8f..54786e999ac 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/FunctionParser.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/FunctionParser.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/RawColumn.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/RawColumn.java index 1d221cae20e..331f4841f79 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/RawColumn.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/RawColumn.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/RelationParser.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/RelationParser.java index c756b235ec6..86c914459d7 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/RelationParser.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/RelationParser.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/SchemaParser.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/SchemaParser.java index beb02894a0d..109ebea45c1 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/SchemaParser.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/SchemaParser.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/SchemaParserFactory.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/SchemaParserFactory.java index c61e8933c89..93db1472e4d 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/SchemaParserFactory.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/SchemaParserFactory.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/SimpleJsonParser.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/SimpleJsonParser.java index 097569830c0..e979a8fd822 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/SimpleJsonParser.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/SimpleJsonParser.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/TableParser.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/TableParser.java index 3a020ca26e1..a3bda428ef3 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/TableParser.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/TableParser.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/UserDefinedTypeParser.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/UserDefinedTypeParser.java index f04b6c9a807..442f46ee432 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/UserDefinedTypeParser.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/UserDefinedTypeParser.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/ViewParser.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/ViewParser.java index 06fc7d354fb..52773ea1c45 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/ViewParser.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/ViewParser.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/Cassandra21SchemaQueries.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/Cassandra21SchemaQueries.java index 0fb5d160717..7577fd1bb92 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/Cassandra21SchemaQueries.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/Cassandra21SchemaQueries.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/Cassandra22SchemaQueries.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/Cassandra22SchemaQueries.java index 8fbc50c9aae..ff09917b3c7 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/Cassandra22SchemaQueries.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/Cassandra22SchemaQueries.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/Cassandra3SchemaQueries.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/Cassandra3SchemaQueries.java index 3b0172f1c25..8c36d0f4217 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/Cassandra3SchemaQueries.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/Cassandra3SchemaQueries.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/Cassandra4SchemaQueries.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/Cassandra4SchemaQueries.java index 79e3aa0eb42..e2de0b419ed 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/Cassandra4SchemaQueries.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/Cassandra4SchemaQueries.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/CassandraSchemaQueries.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/CassandraSchemaQueries.java index e0bece6929b..92ab2501c12 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/CassandraSchemaQueries.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/CassandraSchemaQueries.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -48,7 +50,7 @@ public abstract class CassandraSchemaQueries implements SchemaQueries { private final String logPrefix; private final Duration timeout; private final int pageSize; - private final String whereClause; + private final KeyspaceFilter keyspaceFilter; // The future we return from execute, completes when all the queries are done. private final CompletableFuture schemaRowsFuture = new CompletableFuture<>(); private final long startTimeNs = System.nanoTime(); @@ -69,25 +71,8 @@ protected CassandraSchemaQueries( List refreshedKeyspaces = config.getStringList( DefaultDriverOption.METADATA_SCHEMA_REFRESHED_KEYSPACES, Collections.emptyList()); - this.whereClause = buildWhereClause(refreshedKeyspaces); - } - - private static String buildWhereClause(List refreshedKeyspaces) { - if (refreshedKeyspaces.isEmpty()) { - return ""; - } else { - StringBuilder builder = new StringBuilder(" WHERE keyspace_name in ("); - boolean first = true; - for (String keyspace : refreshedKeyspaces) { - if (first) { - first = false; - } else { - builder.append(","); - } - builder.append('\'').append(keyspace).append('\''); - } - return builder.append(")").toString(); - } + assert refreshedKeyspaces != null; // per the default value + this.keyspaceFilter = KeyspaceFilter.newInstance(logPrefix, refreshedKeyspaces); } protected abstract String selectKeyspacesQuery(); @@ -125,7 +110,8 @@ public CompletionStage execute() { private void executeOnAdminExecutor() { assert adminExecutor.inEventLoop(); - schemaRowsBuilder = new CassandraSchemaRows.Builder(node, logPrefix); + schemaRowsBuilder = new CassandraSchemaRows.Builder(node, keyspaceFilter, logPrefix); + String whereClause = keyspaceFilter.getWhereClause(); query(selectKeyspacesQuery() + whereClause, schemaRowsBuilder::withKeyspaces); query(selectTypesQuery() + whereClause, schemaRowsBuilder::withTypes); diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/CassandraSchemaRows.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/CassandraSchemaRows.java index 01a380308c4..95af0739300 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/CassandraSchemaRows.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/CassandraSchemaRows.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -170,6 +172,7 @@ public static class Builder { private final Node node; private final DataTypeParser dataTypeParser; private final String tableNameColumn; + private final KeyspaceFilter keyspaceFilter; private final String logPrefix; private final ImmutableList.Builder keyspacesBuilder = ImmutableList.builder(); private final ImmutableList.Builder virtualKeyspacesBuilder = ImmutableList.builder(); @@ -196,8 +199,9 @@ public static class Builder { private final Map> edgesBuilders = new LinkedHashMap<>(); - public Builder(Node node, String logPrefix) { + public Builder(Node node, KeyspaceFilter keyspaceFilter, String logPrefix) { this.node = node; + this.keyspaceFilter = keyspaceFilter; this.logPrefix = logPrefix; if (isCassandraV3OrAbove(node)) { this.tableNameColumn = "table_name"; @@ -229,12 +233,16 @@ private static boolean isCassandraV3OrAbove(Node node) { } public Builder withKeyspaces(Iterable rows) { - keyspacesBuilder.addAll(rows); + for (AdminRow row : rows) { + put(keyspacesBuilder, row); + } return this; } public Builder withVirtualKeyspaces(Iterable rows) { - virtualKeyspacesBuilder.addAll(rows); + for (AdminRow row : rows) { + put(virtualKeyspacesBuilder, row); + } return this; } @@ -315,12 +323,21 @@ public Builder withEdges(Iterable rows) { return this; } + private void put(ImmutableList.Builder builder, AdminRow row) { + String keyspace = row.getString("keyspace_name"); + if (keyspace == null) { + LOG.warn("[{}] Skipping system row with missing keyspace name", logPrefix); + } else if (keyspaceFilter.includes(keyspace)) { + builder.add(row); + } + } + private void putByKeyspace( AdminRow row, ImmutableMultimap.Builder builder) { String keyspace = row.getString("keyspace_name"); if (keyspace == null) { LOG.warn("[{}] Skipping system row with missing keyspace name", logPrefix); - } else { + } else if (keyspaceFilter.includes(keyspace)) { builder.put(CqlIdentifier.fromInternal(keyspace), row); } } @@ -334,7 +351,7 @@ private void putByKeyspaceAndTable( LOG.warn("[{}] Skipping system row with missing keyspace name", logPrefix); } else if (table == null) { LOG.warn("[{}] Skipping system row with missing table name", logPrefix); - } else { + } else if (keyspaceFilter.includes(keyspace)) { ImmutableMultimap.Builder builder = builders.computeIfAbsent( CqlIdentifier.fromInternal(keyspace), s -> ImmutableListMultimap.builder()); diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/DefaultSchemaQueriesFactory.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/DefaultSchemaQueriesFactory.java index 08f637e99e8..e537475ed7b 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/DefaultSchemaQueriesFactory.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/DefaultSchemaQueriesFactory.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/Dse68SchemaQueries.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/Dse68SchemaQueries.java index 40819c3827b..460df8b59e5 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/Dse68SchemaQueries.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/Dse68SchemaQueries.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/KeyspaceFilter.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/KeyspaceFilter.java new file mode 100644 index 00000000000..a483a904f6e --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/KeyspaceFilter.java @@ -0,0 +1,60 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.metadata.schema.queries; + +import edu.umd.cs.findbugs.annotations.NonNull; +import java.util.List; + +/** + * Filters keyspaces during schema metadata queries. + * + *

    Depending on the circumstances, we do it either on the server side with a WHERE IN clause that + * will be appended to every query, or on the client side with a predicate that will be applied to + * every fetched row. + */ +public interface KeyspaceFilter { + + static KeyspaceFilter newInstance(@NonNull String logPrefix, @NonNull List specs) { + if (specs.isEmpty()) { + return INCLUDE_ALL; + } else { + return new RuleBasedKeyspaceFilter(logPrefix, specs); + } + } + + /** The WHERE IN clause, or an empty string if there is no server-side filtering. */ + @NonNull + String getWhereClause(); + + /** The predicate that will be invoked for client-side filtering. */ + boolean includes(@NonNull String keyspace); + + KeyspaceFilter INCLUDE_ALL = + new KeyspaceFilter() { + @NonNull + @Override + public String getWhereClause() { + return ""; + } + + @Override + public boolean includes(@NonNull String keyspace) { + return true; + } + }; +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/RuleBasedKeyspaceFilter.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/RuleBasedKeyspaceFilter.java new file mode 100644 index 00000000000..38a8c116c45 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/RuleBasedKeyspaceFilter.java @@ -0,0 +1,203 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.metadata.schema.queries; + +import com.datastax.oss.driver.api.core.config.DefaultDriverOption; +import edu.umd.cs.findbugs.annotations.NonNull; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.function.Predicate; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Filters keyspaces during schema metadata queries. + * + *

    Depending on the circumstances, we do it either on the server side with a WHERE IN clause that + * will be appended to every query, or on the client side with a predicate that will be applied to + * every fetched row. + */ +class RuleBasedKeyspaceFilter implements KeyspaceFilter { + + private static final Logger LOG = LoggerFactory.getLogger(RuleBasedKeyspaceFilter.class); + + private static final Pattern EXACT_INCLUDE = Pattern.compile("\\w+"); + private static final Pattern EXACT_EXCLUDE = Pattern.compile("!\\s*(\\w+)"); + private static final Pattern REGEX_INCLUDE = Pattern.compile("/(.+)/"); + private static final Pattern REGEX_EXCLUDE = Pattern.compile("!\\s*/(.+)/"); + + private final String logPrefix; + private final String whereClause; + private final Set exactIncludes = new HashSet<>(); + private final Set exactExcludes = new HashSet<>(); + private final List> regexIncludes = new ArrayList<>(); + private final List> regexExcludes = new ArrayList<>(); + + private final boolean isDebugEnabled; + private final Set loggedKeyspaces; + + RuleBasedKeyspaceFilter(@NonNull String logPrefix, @NonNull List specs) { + assert !specs.isEmpty(); // see KeyspaceFilter#newInstance + + this.logPrefix = logPrefix; + for (String spec : specs) { + spec = spec.trim(); + Matcher matcher; + if (EXACT_INCLUDE.matcher(spec).matches()) { + exactIncludes.add(spec); + if (exactExcludes.remove(spec)) { + LOG.warn( + "[{}] '{}' is both included and excluded, ignoring the exclusion", logPrefix, spec); + } + } else if ((matcher = EXACT_EXCLUDE.matcher(spec)).matches()) { + String name = matcher.group(1); + if (exactIncludes.contains(name)) { + LOG.warn( + "[{}] '{}' is both included and excluded, ignoring the exclusion", logPrefix, name); + } else { + exactExcludes.add(name); + } + } else if ((matcher = REGEX_INCLUDE.matcher(spec)).matches()) { + compile(matcher.group(1)).map(regexIncludes::add); + } else if ((matcher = REGEX_EXCLUDE.matcher(spec)).matches()) { + compile(matcher.group(1)).map(regexExcludes::add); + } else { + LOG.warn( + "[{}] Error while parsing {}: invalid element '{}', skipping", + logPrefix, + DefaultDriverOption.METADATA_SCHEMA_REFRESHED_KEYSPACES.getPath(), + spec); + } + } + + if (!exactIncludes.isEmpty() && regexIncludes.isEmpty() && regexExcludes.isEmpty()) { + // We can filter on the server + whereClause = buildWhereClause(exactIncludes); + if (!exactExcludes.isEmpty()) { + // Proceed, but this is probably a mistake + LOG.warn( + "[{}] {} only has exact includes and excludes, the excludes are redundant", + logPrefix, + DefaultDriverOption.METADATA_SCHEMA_REFRESHED_KEYSPACES.getPath()); + } + LOG.debug("[{}] Filtering server-side with '{}'", logPrefix, whereClause); + } else { + whereClause = ""; + LOG.debug("[{}] No server-side filtering", logPrefix); + } + + isDebugEnabled = LOG.isDebugEnabled(); + loggedKeyspaces = isDebugEnabled ? new HashSet<>() : null; + } + + @NonNull + @Override + public String getWhereClause() { + return whereClause; + } + + @Override + public boolean includes(@NonNull String keyspace) { + if (exactIncludes.contains(keyspace)) { + log(keyspace, true, "it is included by name"); + return true; + } else if (exactExcludes.contains(keyspace)) { + log(keyspace, false, "it is excluded by name"); + return false; + } else if (regexIncludes.isEmpty()) { + if (regexExcludes.isEmpty()) { + log(keyspace, false, "it is not included by name"); + return false; + } else if (matchesAny(keyspace, regexExcludes)) { + log(keyspace, false, "it matches at least one regex exclude"); + return false; + } else { + log(keyspace, true, "it does not match any regex exclude"); + return true; + } + } else { // !regexIncludes.isEmpty() + if (regexExcludes.isEmpty()) { + if (matchesAny(keyspace, regexIncludes)) { + log(keyspace, true, "it matches at least one regex include"); + return true; + } else { + log(keyspace, false, "it does not match any regex include"); + return false; + } + } else { + if (matchesAny(keyspace, regexIncludes) && !matchesAny(keyspace, regexExcludes)) { + log(keyspace, true, "it matches at least one regex include, and no regex exclude"); + return true; + } else { + log(keyspace, false, "it matches either no regex include, or at least one regex exclude"); + return false; + } + } + } + } + + private void log(@NonNull String keyspace, boolean include, @NonNull String reason) { + if (isDebugEnabled && loggedKeyspaces.add(keyspace)) { + LOG.debug( + "[{}] Filtering {} '{}' because {}", logPrefix, include ? "in" : "out", keyspace, reason); + } + } + + private boolean matchesAny(String keyspace, List> rules) { + for (Predicate rule : rules) { + if (rule.test(keyspace)) { + return true; + } + } + return false; + } + + private Optional> compile(String regex) { + try { + return Optional.of(Pattern.compile(regex).asPredicate()); + } catch (PatternSyntaxException e) { + LOG.warn( + "[{}] Error while parsing {}: syntax error in regex /{}/ ({}), skipping", + this.logPrefix, + DefaultDriverOption.METADATA_SCHEMA_REFRESHED_KEYSPACES.getPath(), + regex, + e.getMessage()); + return Optional.empty(); + } + } + + private static String buildWhereClause(Set keyspaces) { + StringBuilder builder = new StringBuilder(" WHERE keyspace_name IN ("); + boolean first = true; + for (String keyspace : keyspaces) { + if (first) { + first = false; + } else { + builder.append(","); + } + builder.append('\'').append(keyspace).append('\''); + } + return builder.append(')').toString(); + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/SchemaQueries.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/SchemaQueries.java index 6ab89d190ca..613f43197e2 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/SchemaQueries.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/SchemaQueries.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/SchemaQueriesFactory.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/SchemaQueriesFactory.java index 5b85053767c..32d1ae684ef 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/SchemaQueriesFactory.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/SchemaQueriesFactory.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/SchemaRows.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/SchemaRows.java index 7948e0cf5b5..0507b8cffd1 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/SchemaRows.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/SchemaRows.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/refresh/SchemaRefresh.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/refresh/SchemaRefresh.java index 16d07e421ff..86a4d1912f4 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/refresh/SchemaRefresh.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/schema/refresh/SchemaRefresh.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/ByteOrderedToken.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/ByteOrderedToken.java index 3006151648a..ff7642d0c18 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/ByteOrderedToken.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/ByteOrderedToken.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/ByteOrderedTokenFactory.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/ByteOrderedTokenFactory.java index c53296f1878..5dc3aa3aa45 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/ByteOrderedTokenFactory.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/ByteOrderedTokenFactory.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/ByteOrderedTokenRange.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/ByteOrderedTokenRange.java index 529c5a93303..7e95b7c01c9 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/ByteOrderedTokenRange.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/ByteOrderedTokenRange.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/CanonicalNodeSetBuilder.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/CanonicalNodeSetBuilder.java index 6ab047896f5..099d8b55129 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/CanonicalNodeSetBuilder.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/CanonicalNodeSetBuilder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/DefaultReplicationStrategyFactory.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/DefaultReplicationStrategyFactory.java index 014dde6c9c4..a5da85195c6 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/DefaultReplicationStrategyFactory.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/DefaultReplicationStrategyFactory.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/DefaultTokenFactoryRegistry.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/DefaultTokenFactoryRegistry.java index 8717e4fb9d5..8226ddee2c7 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/DefaultTokenFactoryRegistry.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/DefaultTokenFactoryRegistry.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/DefaultTokenMap.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/DefaultTokenMap.java index 0eeb399d672..8c59fb73847 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/DefaultTokenMap.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/DefaultTokenMap.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/EverywhereReplicationStrategy.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/EverywhereReplicationStrategy.java index d7bb9b4cbde..1973c07f5f8 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/EverywhereReplicationStrategy.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/EverywhereReplicationStrategy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/KeyspaceTokenMap.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/KeyspaceTokenMap.java index 36bf7e15924..80bad8a36b1 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/KeyspaceTokenMap.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/KeyspaceTokenMap.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/LocalReplicationStrategy.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/LocalReplicationStrategy.java index 6b6007d14cd..916947e598c 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/LocalReplicationStrategy.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/LocalReplicationStrategy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/Murmur3Token.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/Murmur3Token.java index fdf67ad2461..1b3072d4f22 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/Murmur3Token.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/Murmur3Token.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/Murmur3TokenFactory.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/Murmur3TokenFactory.java index 252c59f671b..2d4dc975a63 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/Murmur3TokenFactory.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/Murmur3TokenFactory.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/Murmur3TokenRange.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/Murmur3TokenRange.java index 5586204375f..2a87cd2c3b6 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/Murmur3TokenRange.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/Murmur3TokenRange.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/NetworkTopologyReplicationStrategy.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/NetworkTopologyReplicationStrategy.java index b44e383c2b8..0ed81083ad6 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/NetworkTopologyReplicationStrategy.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/NetworkTopologyReplicationStrategy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/RandomToken.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/RandomToken.java index b9f6f2d2fb1..52e32fef522 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/RandomToken.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/RandomToken.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/RandomTokenFactory.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/RandomTokenFactory.java index b4e9fdaa28a..59f1bcc865b 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/RandomTokenFactory.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/RandomTokenFactory.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/RandomTokenRange.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/RandomTokenRange.java index 74dc36265de..d1a98a185db 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/RandomTokenRange.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/RandomTokenRange.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/ReplicationFactor.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/ReplicationFactor.java index f20a472d96b..966372da621 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/ReplicationFactor.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/ReplicationFactor.java @@ -1,12 +1,14 @@ package com.datastax.oss.driver.internal.core.metadata.token; /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/ReplicationStrategy.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/ReplicationStrategy.java index 2f76f720ccd..e16841e5107 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/ReplicationStrategy.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/ReplicationStrategy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/ReplicationStrategyFactory.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/ReplicationStrategyFactory.java index 2b7bff0316c..4f01d2ac920 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/ReplicationStrategyFactory.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/ReplicationStrategyFactory.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/SimpleReplicationStrategy.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/SimpleReplicationStrategy.java index 8ec2394deb4..db2c16112a1 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/SimpleReplicationStrategy.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/SimpleReplicationStrategy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/TokenFactory.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/TokenFactory.java index e727a36cbb2..8a1731be385 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/TokenFactory.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/TokenFactory.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/TokenFactoryRegistry.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/TokenFactoryRegistry.java index 740d14ce924..f7e31da9870 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/TokenFactoryRegistry.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/TokenFactoryRegistry.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/TokenRangeBase.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/TokenRangeBase.java index 92e2b55c43a..f63f9dd1ab4 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/TokenRangeBase.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/TokenRangeBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/AbstractMetricUpdater.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/AbstractMetricUpdater.java new file mode 100644 index 00000000000..3d7dc50a7c0 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/AbstractMetricUpdater.java @@ -0,0 +1,182 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.metrics; + +import com.datastax.oss.driver.api.core.config.DefaultDriverOption; +import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; +import com.datastax.oss.driver.api.core.metadata.Node; +import com.datastax.oss.driver.api.core.metrics.DefaultSessionMetric; +import com.datastax.oss.driver.api.core.session.throttling.RequestThrottler; +import com.datastax.oss.driver.internal.core.context.InternalDriverContext; +import com.datastax.oss.driver.internal.core.cql.CqlPrepareAsyncProcessor; +import com.datastax.oss.driver.internal.core.cql.CqlPrepareSyncProcessor; +import com.datastax.oss.driver.internal.core.pool.ChannelPool; +import com.datastax.oss.driver.internal.core.session.RequestProcessor; +import com.datastax.oss.driver.internal.core.session.throttling.ConcurrencyLimitingRequestThrottler; +import com.datastax.oss.driver.internal.core.session.throttling.RateLimitingRequestThrottler; +import com.datastax.oss.driver.shaded.guava.common.cache.Cache; +import edu.umd.cs.findbugs.annotations.Nullable; +import io.netty.util.Timeout; +import java.time.Duration; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public abstract class AbstractMetricUpdater implements MetricUpdater { + + private static final Logger LOG = LoggerFactory.getLogger(AbstractMetricUpdater.class); + + // Not final for testing purposes + public static Duration MIN_EXPIRE_AFTER = Duration.ofMinutes(5); + + protected final InternalDriverContext context; + protected final Set enabledMetrics; + + private final AtomicReference metricsExpirationTimeoutRef = new AtomicReference<>(); + private final Duration expireAfter; + + protected AbstractMetricUpdater(InternalDriverContext context, Set enabledMetrics) { + this.context = context; + this.enabledMetrics = enabledMetrics; + DriverExecutionProfile config = context.getConfig().getDefaultProfile(); + Duration expireAfter = config.getDuration(DefaultDriverOption.METRICS_NODE_EXPIRE_AFTER); + if (expireAfter.compareTo(MIN_EXPIRE_AFTER) < 0) { + LOG.warn( + "[{}] Value too low for {}: {}. Forcing to {} instead.", + context.getSessionName(), + DefaultDriverOption.METRICS_NODE_EXPIRE_AFTER.getPath(), + expireAfter, + MIN_EXPIRE_AFTER); + expireAfter = MIN_EXPIRE_AFTER; + } + this.expireAfter = expireAfter; + } + + @Override + public boolean isEnabled(MetricT metric, String profileName) { + return enabledMetrics.contains(metric); + } + + public Duration getExpireAfter() { + return expireAfter; + } + + protected int connectedNodes() { + int count = 0; + for (Node node : context.getMetadataManager().getMetadata().getNodes().values()) { + if (node.getOpenConnections() > 0) { + count++; + } + } + return count; + } + + protected int throttlingQueueSize() { + RequestThrottler requestThrottler = context.getRequestThrottler(); + if (requestThrottler instanceof ConcurrencyLimitingRequestThrottler) { + return ((ConcurrencyLimitingRequestThrottler) requestThrottler).getQueueSize(); + } + if (requestThrottler instanceof RateLimitingRequestThrottler) { + return ((RateLimitingRequestThrottler) requestThrottler).getQueueSize(); + } + LOG.warn( + "[{}] Metric {} does not support {}, it will always return 0", + context.getSessionName(), + DefaultSessionMetric.THROTTLING_QUEUE_SIZE.getPath(), + requestThrottler.getClass().getName()); + return 0; + } + + protected long preparedStatementCacheSize() { + Cache cache = getPreparedStatementCache(); + if (cache == null) { + LOG.warn( + "[{}] Metric {} is enabled in the config, " + + "but it looks like no CQL prepare processor is registered. " + + "The gauge will always return 0", + context.getSessionName(), + DefaultSessionMetric.CQL_PREPARED_CACHE_SIZE.getPath()); + return 0L; + } + return cache.size(); + } + + @Nullable + protected Cache getPreparedStatementCache() { + // By default, both the sync processor and the async ones are registered and they share the same + // cache. But with a custom processor registry, there could be only one of the two present. + for (RequestProcessor processor : context.getRequestProcessorRegistry().getProcessors()) { + if (processor instanceof CqlPrepareAsyncProcessor) { + return ((CqlPrepareAsyncProcessor) processor).getCache(); + } else if (processor instanceof CqlPrepareSyncProcessor) { + return ((CqlPrepareSyncProcessor) processor).getCache(); + } + } + return null; + } + + protected int availableStreamIds(Node node) { + ChannelPool pool = context.getPoolManager().getPools().get(node); + return (pool == null) ? 0 : pool.getAvailableIds(); + } + + protected int inFlightRequests(Node node) { + ChannelPool pool = context.getPoolManager().getPools().get(node); + return (pool == null) ? 0 : pool.getInFlight(); + } + + protected int orphanedStreamIds(Node node) { + ChannelPool pool = context.getPoolManager().getPools().get(node); + return (pool == null) ? 0 : pool.getOrphanedIds(); + } + + protected void startMetricsExpirationTimeout() { + metricsExpirationTimeoutRef.accumulateAndGet( + newTimeout(), + (current, update) -> { + if (current == null) { + return update; + } else { + update.cancel(); + return current; + } + }); + } + + protected void cancelMetricsExpirationTimeout() { + Timeout t = metricsExpirationTimeoutRef.getAndSet(null); + if (t != null) { + t.cancel(); + } + } + + protected Timeout newTimeout() { + return context + .getNettyOptions() + .getTimer() + .newTimeout( + t -> { + clearMetrics(); + cancelMetricsExpirationTimeout(); + }, + expireAfter.toNanos(), + TimeUnit.NANOSECONDS); + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/DefaultMetricId.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/DefaultMetricId.java new file mode 100644 index 00000000000..c1c2e80e387 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/DefaultMetricId.java @@ -0,0 +1,70 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.metrics; + +import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap; +import edu.umd.cs.findbugs.annotations.NonNull; +import java.util.Map; +import java.util.Objects; +import net.jcip.annotations.ThreadSafe; + +@ThreadSafe +public final class DefaultMetricId implements MetricId { + + private final String name; + private final ImmutableMap tags; + + public DefaultMetricId(String name, Map tags) { + this.name = Objects.requireNonNull(name, "name cannot be null"); + this.tags = ImmutableMap.copyOf(Objects.requireNonNull(tags, "tags cannot be null")); + } + + @NonNull + @Override + public String getName() { + return name; + } + + @NonNull + @Override + public Map getTags() { + return tags; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DefaultMetricId that = (DefaultMetricId) o; + return name.equals(that.name) && tags.equals(that.tags); + } + + @Override + public int hashCode() { + return Objects.hash(name, tags); + } + + @Override + public String toString() { + return name + tags; + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/DefaultMetricIdGenerator.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/DefaultMetricIdGenerator.java new file mode 100644 index 00000000000..d4bacb35df9 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/DefaultMetricIdGenerator.java @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.metrics; + +import com.datastax.oss.driver.api.core.config.DefaultDriverOption; +import com.datastax.oss.driver.api.core.context.DriverContext; +import com.datastax.oss.driver.api.core.metadata.Node; +import com.datastax.oss.driver.api.core.metrics.NodeMetric; +import com.datastax.oss.driver.api.core.metrics.SessionMetric; +import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap; +import edu.umd.cs.findbugs.annotations.NonNull; +import java.util.Objects; + +/** + * The default {@link MetricIdGenerator}. + * + *

    This generator generates unique names, containing the session name, the node endpoint (for + * node metrics), and the metric prefix. It does not generate tags. + */ +public class DefaultMetricIdGenerator implements MetricIdGenerator { + + private final String sessionPrefix; + private final String nodePrefix; + + @SuppressWarnings("unused") + public DefaultMetricIdGenerator(DriverContext context) { + String sessionName = context.getSessionName(); + String prefix = + Objects.requireNonNull( + context + .getConfig() + .getDefaultProfile() + .getString(DefaultDriverOption.METRICS_ID_GENERATOR_PREFIX, "")); + sessionPrefix = prefix.isEmpty() ? sessionName + '.' : prefix + '.' + sessionName + '.'; + nodePrefix = sessionPrefix + "nodes."; + } + + @NonNull + @Override + public MetricId sessionMetricId(@NonNull SessionMetric metric) { + return new DefaultMetricId(sessionPrefix + metric.getPath(), ImmutableMap.of()); + } + + @NonNull + @Override + public MetricId nodeMetricId(@NonNull Node node, @NonNull NodeMetric metric) { + return new DefaultMetricId( + nodePrefix + node.getEndPoint().asMetricPrefix() + '.' + metric.getPath(), + ImmutableMap.of()); + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/DefaultMetrics.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/DefaultMetrics.java index 6c9079bba8f..b15dc955760 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/DefaultMetrics.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/DefaultMetrics.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/DefaultMetricsFactory.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/DefaultMetricsFactory.java new file mode 100644 index 00000000000..7869f8a8af6 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/DefaultMetricsFactory.java @@ -0,0 +1,62 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.metrics; + +import static com.datastax.oss.driver.internal.core.util.Dependency.DROPWIZARD; + +import com.datastax.oss.driver.api.core.context.DriverContext; +import com.datastax.oss.driver.api.core.metadata.Node; +import com.datastax.oss.driver.api.core.metrics.Metrics; +import com.datastax.oss.driver.internal.core.util.DefaultDependencyChecker; +import java.util.Optional; +import net.jcip.annotations.ThreadSafe; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@ThreadSafe +public class DefaultMetricsFactory implements MetricsFactory { + + private static final Logger LOG = LoggerFactory.getLogger(DefaultMetricsFactory.class); + + private final MetricsFactory delegate; + + @SuppressWarnings("unused") + public DefaultMetricsFactory(DriverContext context) { + if (DefaultDependencyChecker.isPresent(DROPWIZARD)) { + this.delegate = new DropwizardMetricsFactory(context); + } else { + this.delegate = new NoopMetricsFactory(context); + } + LOG.debug("[{}] Using {}", context.getSessionName(), delegate.getClass().getSimpleName()); + } + + @Override + public Optional getMetrics() { + return delegate.getMetrics(); + } + + @Override + public SessionMetricUpdater getSessionUpdater() { + return delegate.getSessionUpdater(); + } + + @Override + public NodeMetricUpdater newNodeUpdater(Node node) { + return delegate.newNodeUpdater(node); + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/DefaultMetricsFactorySubstitutions.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/DefaultMetricsFactorySubstitutions.java new file mode 100644 index 00000000000..8332cdcca18 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/DefaultMetricsFactorySubstitutions.java @@ -0,0 +1,59 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.metrics; + +import static com.datastax.oss.driver.internal.core.util.Dependency.DROPWIZARD; + +import com.datastax.oss.driver.api.core.context.DriverContext; +import com.datastax.oss.driver.internal.core.util.GraalDependencyChecker; +import com.oracle.svm.core.annotate.Alias; +import com.oracle.svm.core.annotate.Delete; +import com.oracle.svm.core.annotate.Substitute; +import com.oracle.svm.core.annotate.TargetClass; +import com.oracle.svm.core.annotate.TargetElement; +import java.util.function.BooleanSupplier; + +@SuppressWarnings("unused") +public class DefaultMetricsFactorySubstitutions { + + @TargetClass(value = DefaultMetricsFactory.class, onlyWith = DropwizardMissing.class) + public static final class DefaultMetricsFactoryDropwizardMissing { + + @Alias + @TargetElement(name = "delegate") + @SuppressWarnings({"FieldCanBeLocal", "FieldMayBeFinal"}) + private MetricsFactory delegate; + + @Substitute + @TargetElement(name = TargetElement.CONSTRUCTOR_NAME) + public DefaultMetricsFactoryDropwizardMissing(DriverContext context) { + this.delegate = new NoopMetricsFactory(context); + } + } + + @TargetClass(value = DropwizardMetricsFactory.class, onlyWith = DropwizardMissing.class) + @Delete + public static final class DeleteDropwizardMetricsFactory {} + + public static class DropwizardMissing implements BooleanSupplier { + @Override + public boolean getAsBoolean() { + return !GraalDependencyChecker.isPresent(DROPWIZARD); + } + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/DropwizardMetricUpdater.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/DropwizardMetricUpdater.java index 0c47637d780..9377fb3a17e 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/DropwizardMetricUpdater.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/DropwizardMetricUpdater.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -15,110 +17,183 @@ */ package com.datastax.oss.driver.internal.core.metrics; +import com.codahale.metrics.Counter; +import com.codahale.metrics.Histogram; +import com.codahale.metrics.Meter; import com.codahale.metrics.Metric; import com.codahale.metrics.MetricRegistry; +import com.codahale.metrics.Reservoir; import com.codahale.metrics.Timer; import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; import com.datastax.oss.driver.api.core.config.DriverOption; +import com.datastax.oss.driver.internal.core.context.InternalDriverContext; +import edu.umd.cs.findbugs.annotations.Nullable; import java.time.Duration; import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; import net.jcip.annotations.ThreadSafe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @ThreadSafe -public abstract class DropwizardMetricUpdater implements MetricUpdater { +public abstract class DropwizardMetricUpdater extends AbstractMetricUpdater { private static final Logger LOG = LoggerFactory.getLogger(DropwizardMetricUpdater.class); - protected final Set enabledMetrics; protected final MetricRegistry registry; - protected DropwizardMetricUpdater(Set enabledMetrics, MetricRegistry registry) { - this.enabledMetrics = enabledMetrics; + protected final ConcurrentMap metrics = new ConcurrentHashMap<>(); + + protected final ConcurrentMap reservoirs = new ConcurrentHashMap<>(); + + protected DropwizardMetricUpdater( + InternalDriverContext context, Set enabledMetrics, MetricRegistry registry) { + super(context, enabledMetrics); this.registry = registry; } - protected abstract String buildFullName(MetricT metric, String profileName); + @SuppressWarnings({"unchecked", "TypeParameterUnusedInFormals"}) + public T getMetric( + MetricT metric, @SuppressWarnings("unused") String profileName) { + return (T) metrics.get(metric); + } @Override - public void incrementCounter(MetricT metric, String profileName, long amount) { + public void incrementCounter(MetricT metric, @Nullable String profileName, long amount) { if (isEnabled(metric, profileName)) { - registry.counter(buildFullName(metric, profileName)).inc(amount); + getOrCreateCounterFor(metric).inc(amount); } } @Override - public void updateHistogram(MetricT metric, String profileName, long value) { + public void updateHistogram(MetricT metric, @Nullable String profileName, long value) { if (isEnabled(metric, profileName)) { - registry.histogram(buildFullName(metric, profileName)).update(value); + getOrCreateHistogramFor(metric).update(value); } } @Override - public void markMeter(MetricT metric, String profileName, long amount) { + public void markMeter(MetricT metric, @Nullable String profileName, long amount) { if (isEnabled(metric, profileName)) { - registry.meter(buildFullName(metric, profileName)).mark(amount); + getOrCreateMeterFor(metric).mark(amount); } } @Override - public void updateTimer(MetricT metric, String profileName, long duration, TimeUnit unit) { + public void updateTimer( + MetricT metric, @Nullable String profileName, long duration, TimeUnit unit) { if (isEnabled(metric, profileName)) { - registry.timer(buildFullName(metric, profileName)).update(duration, unit); + getOrCreateTimerFor(metric).update(duration, unit); } } - @SuppressWarnings({"unchecked", "TypeParameterUnusedInFormals"}) - public T getMetric(MetricT metric, String profileName) { - return (T) registry.getMetrics().get(buildFullName(metric, profileName)); + @Override + public void clearMetrics() { + for (MetricT metric : metrics.keySet()) { + MetricId id = getMetricId(metric); + registry.remove(id.getName()); + } + metrics.clear(); + reservoirs.clear(); } - @Override - public boolean isEnabled(MetricT metric, String profileName) { - return enabledMetrics.contains(metric); + protected abstract MetricId getMetricId(MetricT metric); + + protected void initializeGauge( + MetricT metric, DriverExecutionProfile profile, Supplier supplier) { + if (isEnabled(metric, profile.getName())) { + metrics.computeIfAbsent( + metric, + m -> { + MetricId id = getMetricId(m); + return registry.gauge(id.getName(), () -> supplier::get); + }); + } } - protected void initializeDefaultCounter(MetricT metric, String profileName) { - if (isEnabled(metric, profileName)) { - // Just initialize eagerly so that the metric appears even when it has no data yet - registry.counter(buildFullName(metric, profileName)); + protected void initializeCounter(MetricT metric, DriverExecutionProfile profile) { + if (isEnabled(metric, profile.getName())) { + getOrCreateCounterFor(metric); } } protected void initializeHdrTimer( MetricT metric, - DriverExecutionProfile config, + DriverExecutionProfile profile, + DriverOption highestLatency, + DriverOption significantDigits, + DriverOption interval) { + if (isEnabled(metric, profile.getName())) { + reservoirs.computeIfAbsent( + metric, m -> createHdrReservoir(m, profile, highestLatency, significantDigits, interval)); + getOrCreateTimerFor(metric); + } + } + + protected Counter getOrCreateCounterFor(MetricT metric) { + return (Counter) + metrics.computeIfAbsent( + metric, + m -> { + MetricId id = getMetricId(m); + return registry.counter(id.getName()); + }); + } + + protected Meter getOrCreateMeterFor(MetricT metric) { + return (Meter) + metrics.computeIfAbsent( + metric, + m -> { + MetricId id = getMetricId(m); + return registry.meter(id.getName()); + }); + } + + protected Histogram getOrCreateHistogramFor(MetricT metric) { + return (Histogram) + metrics.computeIfAbsent( + metric, + m -> { + MetricId id = getMetricId(m); + return registry.histogram(id.getName()); + }); + } + + protected Timer getOrCreateTimerFor(MetricT metric) { + return (Timer) + metrics.computeIfAbsent( + metric, + m -> { + MetricId id = getMetricId(m); + Reservoir reservoir = reservoirs.get(metric); + Timer timer = reservoir == null ? new Timer() : new Timer(reservoir); + return registry.timer(id.getName(), () -> timer); + }); + } + + protected HdrReservoir createHdrReservoir( + MetricT metric, + DriverExecutionProfile profile, DriverOption highestLatencyOption, DriverOption significantDigitsOption, DriverOption intervalOption) { - String profileName = config.getName(); - if (isEnabled(metric, profileName)) { - String fullName = buildFullName(metric, profileName); - - Duration highestLatency = config.getDuration(highestLatencyOption); - final int significantDigits; - int d = config.getInt(significantDigitsOption); - if (d >= 0 && d <= 5) { - significantDigits = d; - } else { - LOG.warn( - "[{}] Configuration option {} is out of range (expected between 0 and 5, found {}); " - + "using 3 instead.", - fullName, - significantDigitsOption, - d); - significantDigits = 3; - } - Duration refreshInterval = config.getDuration(intervalOption); - - // Initialize eagerly to use the custom implementation - registry.timer( - fullName, - () -> - new Timer( - new HdrReservoir(highestLatency, significantDigits, refreshInterval, fullName))); + MetricId id = getMetricId(metric); + Duration highestLatency = profile.getDuration(highestLatencyOption); + int significantDigits = profile.getInt(significantDigitsOption); + if (significantDigits < 0 || significantDigits > 5) { + LOG.warn( + "[{}] Configuration option {} is out of range (expected between 0 and 5, " + + "found {}); using 3 instead.", + id.getName(), + significantDigitsOption, + significantDigits); + significantDigits = 3; } + Duration refreshInterval = profile.getDuration(intervalOption); + return new HdrReservoir(highestLatency, significantDigits, refreshInterval, id.getName()); } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/DropwizardMetricsFactory.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/DropwizardMetricsFactory.java index 5b81166668d..5f28f8f5060 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/DropwizardMetricsFactory.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/DropwizardMetricsFactory.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -20,18 +22,15 @@ import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; import com.datastax.oss.driver.api.core.context.DriverContext; import com.datastax.oss.driver.api.core.metadata.Node; +import com.datastax.oss.driver.api.core.metadata.NodeState; import com.datastax.oss.driver.api.core.metrics.Metrics; import com.datastax.oss.driver.api.core.metrics.NodeMetric; import com.datastax.oss.driver.api.core.metrics.SessionMetric; import com.datastax.oss.driver.internal.core.context.InternalDriverContext; -import com.datastax.oss.driver.shaded.guava.common.annotations.VisibleForTesting; -import com.datastax.oss.driver.shaded.guava.common.base.Ticker; -import com.datastax.oss.driver.shaded.guava.common.cache.Cache; -import com.datastax.oss.driver.shaded.guava.common.cache.CacheBuilder; -import com.datastax.oss.driver.shaded.guava.common.cache.RemovalNotification; +import com.datastax.oss.driver.internal.core.metadata.NodeStateEvent; +import com.datastax.oss.driver.internal.core.util.concurrent.RunOrSchedule; import edu.umd.cs.findbugs.annotations.Nullable; -import java.time.Duration; -import java.util.List; +import io.netty.util.concurrent.EventExecutor; import java.util.Optional; import java.util.Set; import net.jcip.annotations.ThreadSafe; @@ -42,44 +41,23 @@ public class DropwizardMetricsFactory implements MetricsFactory { private static final Logger LOG = LoggerFactory.getLogger(DropwizardMetricsFactory.class); - static final Duration LOWEST_ACCEPTABLE_EXPIRE_AFTER = Duration.ofMinutes(5); private final InternalDriverContext context; private final Set enabledNodeMetrics; private final MetricRegistry registry; @Nullable private final Metrics metrics; private final SessionMetricUpdater sessionUpdater; - private final Cache metricsCache; public DropwizardMetricsFactory(DriverContext context) { - this((InternalDriverContext) context, Ticker.systemTicker()); - } - - public DropwizardMetricsFactory(InternalDriverContext context, Ticker ticker) { - this.context = context; + this.context = (InternalDriverContext) context; String logPrefix = context.getSessionName(); DriverExecutionProfile config = context.getConfig().getDefaultProfile(); Set enabledSessionMetrics = - parseSessionMetricPaths(config.getStringList(DefaultDriverOption.METRICS_SESSION_ENABLED)); - Duration evictionTime = getAndValidateEvictionTime(config, logPrefix); + MetricPaths.parseSessionMetricPaths( + config.getStringList(DefaultDriverOption.METRICS_SESSION_ENABLED), logPrefix); this.enabledNodeMetrics = - parseNodeMetricPaths(config.getStringList(DefaultDriverOption.METRICS_NODE_ENABLED)); - - metricsCache = - CacheBuilder.newBuilder() - .ticker(ticker) - .expireAfterAccess(evictionTime) - .removalListener( - (RemovalNotification notification) -> { - LOG.debug( - "[{}] Removing metrics for node: {} from cache after {}", - logPrefix, - notification.getKey(), - evictionTime); - notification.getValue().cleanupNodeMetrics(); - }) - .build(); - + MetricPaths.parseNodeMetricPaths( + config.getStringList(DefaultDriverOption.METRICS_NODE_ENABLED), logPrefix); if (enabledSessionMetrics.isEmpty() && enabledNodeMetrics.isEmpty()) { LOG.debug("[{}] All metrics are disabled, Session.getMetrics will be empty", logPrefix); this.registry = null; @@ -87,7 +65,7 @@ public DropwizardMetricsFactory(InternalDriverContext context, Ticker ticker) { this.metrics = null; } else { // try to get the metric registry from the context - Object possibleMetricRegistry = context.getMetricRegistry(); + Object possibleMetricRegistry = this.context.getMetricRegistry(); if (possibleMetricRegistry == null) { // metrics are enabled, but a metric registry was not supplied to the context // create a registry object @@ -96,7 +74,7 @@ public DropwizardMetricsFactory(InternalDriverContext context, Ticker ticker) { if (possibleMetricRegistry instanceof MetricRegistry) { this.registry = (MetricRegistry) possibleMetricRegistry; DropwizardSessionMetricUpdater dropwizardSessionUpdater = - new DropwizardSessionMetricUpdater(enabledSessionMetrics, registry, context); + new DropwizardSessionMetricUpdater(this.context, enabledSessionMetrics, registry); this.sessionUpdater = dropwizardSessionUpdater; this.metrics = new DefaultMetrics(registry, dropwizardSessionUpdater); } else { @@ -108,25 +86,18 @@ public DropwizardMetricsFactory(InternalDriverContext context, Ticker ticker) { + possibleMetricRegistry.getClass().getName() + "'"); } + if (!enabledNodeMetrics.isEmpty()) { + EventExecutor adminEventExecutor = + this.context.getNettyOptions().adminEventExecutorGroup().next(); + this.context + .getEventBus() + .register( + NodeStateEvent.class, + RunOrSchedule.on(adminEventExecutor, this::processNodeStateEvent)); + } } } - @VisibleForTesting - static Duration getAndValidateEvictionTime(DriverExecutionProfile config, String logPrefix) { - Duration evictionTime = config.getDuration(DefaultDriverOption.METRICS_NODE_EXPIRE_AFTER); - - if (evictionTime.compareTo(LOWEST_ACCEPTABLE_EXPIRE_AFTER) < 0) { - LOG.warn( - "[{}] Value too low for {}: {}. Forcing to {} instead.", - logPrefix, - DefaultDriverOption.METRICS_NODE_EXPIRE_AFTER.getPath(), - evictionTime, - LOWEST_ACCEPTABLE_EXPIRE_AFTER); - } - - return evictionTime; - } - @Override public Optional getMetrics() { return Optional.ofNullable(metrics); @@ -142,19 +113,20 @@ public NodeMetricUpdater newNodeUpdater(Node node) { if (registry == null) { return NoopNodeMetricUpdater.INSTANCE; } else { - DropwizardNodeMetricUpdater dropwizardNodeMetricUpdater = - new DropwizardNodeMetricUpdater( - node, enabledNodeMetrics, registry, context, () -> metricsCache.getIfPresent(node)); - metricsCache.put(node, dropwizardNodeMetricUpdater); - return dropwizardNodeMetricUpdater; + return new DropwizardNodeMetricUpdater(node, context, enabledNodeMetrics, registry); } } - protected Set parseSessionMetricPaths(List paths) { - return MetricPaths.parseSessionMetricPaths(paths, context.getSessionName()); - } - - protected Set parseNodeMetricPaths(List paths) { - return MetricPaths.parseNodeMetricPaths(paths, context.getSessionName()); + protected void processNodeStateEvent(NodeStateEvent event) { + if (event.newState == NodeState.DOWN + || event.newState == NodeState.FORCED_DOWN + || event.newState == null) { + // node is DOWN or REMOVED + ((DropwizardNodeMetricUpdater) event.node.getMetricUpdater()).startMetricsExpirationTimeout(); + } else if (event.newState == NodeState.UP || event.newState == NodeState.UNKNOWN) { + // node is UP or ADDED + ((DropwizardNodeMetricUpdater) event.node.getMetricUpdater()) + .cancelMetricsExpirationTimeout(); + } } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/DropwizardNodeMetricUpdater.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/DropwizardNodeMetricUpdater.java index 7961d102659..2e5e6c8db3d 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/DropwizardNodeMetricUpdater.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/DropwizardNodeMetricUpdater.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -15,145 +17,81 @@ */ package com.datastax.oss.driver.internal.core.metrics; -import com.codahale.metrics.Gauge; -import com.codahale.metrics.Metric; import com.codahale.metrics.MetricRegistry; import com.datastax.dse.driver.api.core.config.DseDriverOption; import com.datastax.dse.driver.api.core.metrics.DseNodeMetric; import com.datastax.oss.driver.api.core.config.DefaultDriverOption; import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; -import com.datastax.oss.driver.api.core.metadata.EndPoint; import com.datastax.oss.driver.api.core.metadata.Node; import com.datastax.oss.driver.api.core.metrics.DefaultNodeMetric; import com.datastax.oss.driver.api.core.metrics.NodeMetric; import com.datastax.oss.driver.internal.core.context.InternalDriverContext; -import com.datastax.oss.driver.internal.core.pool.ChannelPool; import java.util.Set; -import java.util.concurrent.TimeUnit; -import java.util.function.Function; import net.jcip.annotations.ThreadSafe; @ThreadSafe public class DropwizardNodeMetricUpdater extends DropwizardMetricUpdater implements NodeMetricUpdater { - private final String metricNamePrefix; - private final Runnable signalMetricUpdated; + private final Node node; public DropwizardNodeMetricUpdater( Node node, - Set enabledMetrics, - MetricRegistry registry, InternalDriverContext context, - Runnable signalMetricUpdated) { - super(enabledMetrics, registry); - this.signalMetricUpdated = signalMetricUpdated; - this.metricNamePrefix = buildPrefix(context.getSessionName(), node.getEndPoint()); + Set enabledMetrics, + MetricRegistry registry) { + super(context, enabledMetrics, registry); + this.node = node; - DriverExecutionProfile config = context.getConfig().getDefaultProfile(); + DriverExecutionProfile profile = context.getConfig().getDefaultProfile(); + + initializeGauge(DefaultNodeMetric.OPEN_CONNECTIONS, profile, node::getOpenConnections); + initializeGauge(DefaultNodeMetric.AVAILABLE_STREAMS, profile, () -> availableStreamIds(node)); + initializeGauge(DefaultNodeMetric.IN_FLIGHT, profile, () -> inFlightRequests(node)); + initializeGauge(DefaultNodeMetric.ORPHANED_STREAMS, profile, () -> orphanedStreamIds(node)); + + initializeCounter(DefaultNodeMetric.UNSENT_REQUESTS, profile); + initializeCounter(DefaultNodeMetric.ABORTED_REQUESTS, profile); + initializeCounter(DefaultNodeMetric.WRITE_TIMEOUTS, profile); + initializeCounter(DefaultNodeMetric.READ_TIMEOUTS, profile); + initializeCounter(DefaultNodeMetric.UNAVAILABLES, profile); + initializeCounter(DefaultNodeMetric.OTHER_ERRORS, profile); + initializeCounter(DefaultNodeMetric.RETRIES, profile); + initializeCounter(DefaultNodeMetric.RETRIES_ON_ABORTED, profile); + initializeCounter(DefaultNodeMetric.RETRIES_ON_READ_TIMEOUT, profile); + initializeCounter(DefaultNodeMetric.RETRIES_ON_WRITE_TIMEOUT, profile); + initializeCounter(DefaultNodeMetric.RETRIES_ON_UNAVAILABLE, profile); + initializeCounter(DefaultNodeMetric.RETRIES_ON_OTHER_ERROR, profile); + initializeCounter(DefaultNodeMetric.IGNORES, profile); + initializeCounter(DefaultNodeMetric.IGNORES_ON_ABORTED, profile); + initializeCounter(DefaultNodeMetric.IGNORES_ON_READ_TIMEOUT, profile); + initializeCounter(DefaultNodeMetric.IGNORES_ON_WRITE_TIMEOUT, profile); + initializeCounter(DefaultNodeMetric.IGNORES_ON_UNAVAILABLE, profile); + initializeCounter(DefaultNodeMetric.IGNORES_ON_OTHER_ERROR, profile); + initializeCounter(DefaultNodeMetric.SPECULATIVE_EXECUTIONS, profile); + initializeCounter(DefaultNodeMetric.CONNECTION_INIT_ERRORS, profile); + initializeCounter(DefaultNodeMetric.AUTHENTICATION_ERRORS, profile); - if (enabledMetrics.contains(DefaultNodeMetric.OPEN_CONNECTIONS)) { - this.registry.register( - buildFullName(DefaultNodeMetric.OPEN_CONNECTIONS, null), - (Gauge) node::getOpenConnections); - } - initializePoolGauge( - DefaultNodeMetric.AVAILABLE_STREAMS, node, ChannelPool::getAvailableIds, context); - initializePoolGauge(DefaultNodeMetric.IN_FLIGHT, node, ChannelPool::getInFlight, context); - initializePoolGauge( - DefaultNodeMetric.ORPHANED_STREAMS, node, ChannelPool::getOrphanedIds, context); initializeHdrTimer( DefaultNodeMetric.CQL_MESSAGES, - config, + profile, DefaultDriverOption.METRICS_NODE_CQL_MESSAGES_HIGHEST, DefaultDriverOption.METRICS_NODE_CQL_MESSAGES_DIGITS, DefaultDriverOption.METRICS_NODE_CQL_MESSAGES_INTERVAL); - initializeDefaultCounter(DefaultNodeMetric.UNSENT_REQUESTS, null); - initializeDefaultCounter(DefaultNodeMetric.ABORTED_REQUESTS, null); - initializeDefaultCounter(DefaultNodeMetric.WRITE_TIMEOUTS, null); - initializeDefaultCounter(DefaultNodeMetric.READ_TIMEOUTS, null); - initializeDefaultCounter(DefaultNodeMetric.UNAVAILABLES, null); - initializeDefaultCounter(DefaultNodeMetric.OTHER_ERRORS, null); - initializeDefaultCounter(DefaultNodeMetric.RETRIES, null); - initializeDefaultCounter(DefaultNodeMetric.RETRIES_ON_ABORTED, null); - initializeDefaultCounter(DefaultNodeMetric.RETRIES_ON_READ_TIMEOUT, null); - initializeDefaultCounter(DefaultNodeMetric.RETRIES_ON_WRITE_TIMEOUT, null); - initializeDefaultCounter(DefaultNodeMetric.RETRIES_ON_UNAVAILABLE, null); - initializeDefaultCounter(DefaultNodeMetric.RETRIES_ON_OTHER_ERROR, null); - initializeDefaultCounter(DefaultNodeMetric.IGNORES, null); - initializeDefaultCounter(DefaultNodeMetric.IGNORES_ON_ABORTED, null); - initializeDefaultCounter(DefaultNodeMetric.IGNORES_ON_READ_TIMEOUT, null); - initializeDefaultCounter(DefaultNodeMetric.IGNORES_ON_WRITE_TIMEOUT, null); - initializeDefaultCounter(DefaultNodeMetric.IGNORES_ON_UNAVAILABLE, null); - initializeDefaultCounter(DefaultNodeMetric.IGNORES_ON_OTHER_ERROR, null); - initializeDefaultCounter(DefaultNodeMetric.SPECULATIVE_EXECUTIONS, null); - initializeDefaultCounter(DefaultNodeMetric.CONNECTION_INIT_ERRORS, null); - initializeDefaultCounter(DefaultNodeMetric.AUTHENTICATION_ERRORS, null); initializeHdrTimer( DseNodeMetric.GRAPH_MESSAGES, - context.getConfig().getDefaultProfile(), + profile, DseDriverOption.METRICS_NODE_GRAPH_MESSAGES_HIGHEST, DseDriverOption.METRICS_NODE_GRAPH_MESSAGES_DIGITS, DseDriverOption.METRICS_NODE_GRAPH_MESSAGES_INTERVAL); } @Override - public String buildFullName(NodeMetric metric, String profileName) { - return metricNamePrefix + metric.getPath(); - } - - private String buildPrefix(String sessionName, EndPoint endPoint) { - return sessionName + ".nodes." + endPoint.asMetricPrefix() + "."; - } - - @Override - public void incrementCounter(NodeMetric metric, String profileName, long amount) { - signalMetricUpdated.run(); - super.incrementCounter(metric, profileName, amount); - } - - @Override - public void updateHistogram(NodeMetric metric, String profileName, long value) { - signalMetricUpdated.run(); - super.updateHistogram(metric, profileName, value); - } - - @Override - public void markMeter(NodeMetric metric, String profileName, long amount) { - signalMetricUpdated.run(); - super.markMeter(metric, profileName, amount); - } - - @Override - public void updateTimer(NodeMetric metric, String profileName, long duration, TimeUnit unit) { - signalMetricUpdated.run(); - super.updateTimer(metric, profileName, duration, unit); - } - - @Override - @SuppressWarnings({"unchecked", "TypeParameterUnusedInFormals"}) - public T getMetric(NodeMetric metric, String profileName) { - signalMetricUpdated.run(); - return super.getMetric(metric, profileName); - } - - private void initializePoolGauge( - NodeMetric metric, - Node node, - Function reading, - InternalDriverContext context) { - if (enabledMetrics.contains(metric)) { - registry.register( - buildFullName(metric, null), - (Gauge) - () -> { - ChannelPool pool = context.getPoolManager().getPools().get(node); - return (pool == null) ? 0 : reading.apply(pool); - }); + protected MetricId getMetricId(NodeMetric metric) { + MetricId id = context.getMetricIdGenerator().nodeMetricId(node, metric); + if (!id.getTags().isEmpty()) { + throw new IllegalStateException("Cannot use metric tags with Dropwizard"); } - } - - public void cleanupNodeMetrics() { - registry.removeMatching((name, metric) -> name.startsWith(metricNamePrefix)); + return id; } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/DropwizardSessionMetricUpdater.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/DropwizardSessionMetricUpdater.java index 95d1a4fbaab..94e10ad6936 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/DropwizardSessionMetricUpdater.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/DropwizardSessionMetricUpdater.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -15,140 +17,68 @@ */ package com.datastax.oss.driver.internal.core.metrics; -import com.codahale.metrics.Gauge; import com.codahale.metrics.MetricRegistry; import com.datastax.dse.driver.api.core.config.DseDriverOption; import com.datastax.dse.driver.api.core.metrics.DseSessionMetric; import com.datastax.oss.driver.api.core.config.DefaultDriverOption; -import com.datastax.oss.driver.api.core.metadata.Node; +import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; import com.datastax.oss.driver.api.core.metrics.DefaultSessionMetric; import com.datastax.oss.driver.api.core.metrics.SessionMetric; -import com.datastax.oss.driver.api.core.session.throttling.RequestThrottler; import com.datastax.oss.driver.internal.core.context.InternalDriverContext; -import com.datastax.oss.driver.internal.core.cql.CqlPrepareAsyncProcessor; -import com.datastax.oss.driver.internal.core.cql.CqlPrepareSyncProcessor; -import com.datastax.oss.driver.internal.core.session.RequestProcessor; -import com.datastax.oss.driver.internal.core.session.throttling.ConcurrencyLimitingRequestThrottler; -import com.datastax.oss.driver.internal.core.session.throttling.RateLimitingRequestThrottler; -import com.datastax.oss.driver.shaded.guava.common.cache.Cache; -import edu.umd.cs.findbugs.annotations.Nullable; import java.util.Set; import net.jcip.annotations.ThreadSafe; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; @ThreadSafe public class DropwizardSessionMetricUpdater extends DropwizardMetricUpdater implements SessionMetricUpdater { - private static final Logger LOG = LoggerFactory.getLogger(DropwizardSessionMetricUpdater.class); + public DropwizardSessionMetricUpdater( + InternalDriverContext context, Set enabledMetrics, MetricRegistry registry) { + super(context, enabledMetrics, registry); - private final String metricNamePrefix; + DriverExecutionProfile profile = context.getConfig().getDefaultProfile(); - public DropwizardSessionMetricUpdater( - Set enabledMetrics, MetricRegistry registry, InternalDriverContext context) { - super(enabledMetrics, registry); - this.metricNamePrefix = context.getSessionName() + "."; + initializeGauge(DefaultSessionMetric.CONNECTED_NODES, profile, this::connectedNodes); + initializeGauge(DefaultSessionMetric.THROTTLING_QUEUE_SIZE, profile, this::throttlingQueueSize); + initializeGauge( + DefaultSessionMetric.CQL_PREPARED_CACHE_SIZE, profile, this::preparedStatementCacheSize); + + initializeCounter(DefaultSessionMetric.CQL_CLIENT_TIMEOUTS, profile); + initializeCounter(DefaultSessionMetric.THROTTLING_ERRORS, profile); + initializeCounter(DseSessionMetric.GRAPH_CLIENT_TIMEOUTS, profile); - if (enabledMetrics.contains(DefaultSessionMetric.CONNECTED_NODES)) { - this.registry.gauge( - buildFullName(DefaultSessionMetric.CONNECTED_NODES, null), - () -> - () -> { - int count = 0; - for (Node node : context.getMetadataManager().getMetadata().getNodes().values()) { - if (node.getOpenConnections() > 0) { - count += 1; - } - } - return count; - }); - } - if (enabledMetrics.contains(DefaultSessionMetric.THROTTLING_QUEUE_SIZE)) { - this.registry.gauge( - buildFullName(DefaultSessionMetric.THROTTLING_QUEUE_SIZE, null), - () -> buildQueueGauge(context.getRequestThrottler(), context.getSessionName())); - } - if (enabledMetrics.contains(DefaultSessionMetric.CQL_PREPARED_CACHE_SIZE)) { - this.registry.gauge( - buildFullName(DefaultSessionMetric.CQL_PREPARED_CACHE_SIZE, null), - () -> { - Cache cache = getPreparedStatementCache(context); - Gauge gauge; - if (cache == null) { - LOG.warn( - "[{}] Metric {} is enabled in the config, " - + "but it looks like no CQL prepare processor is registered. " - + "The gauge will always return 0", - context.getSessionName(), - DefaultSessionMetric.CQL_PREPARED_CACHE_SIZE.getPath()); - gauge = () -> 0L; - } else { - gauge = cache::size; - } - return gauge; - }); - } initializeHdrTimer( DefaultSessionMetric.CQL_REQUESTS, - context.getConfig().getDefaultProfile(), + profile, DefaultDriverOption.METRICS_SESSION_CQL_REQUESTS_HIGHEST, DefaultDriverOption.METRICS_SESSION_CQL_REQUESTS_DIGITS, DefaultDriverOption.METRICS_SESSION_CQL_REQUESTS_INTERVAL); - initializeDefaultCounter(DefaultSessionMetric.CQL_CLIENT_TIMEOUTS, null); initializeHdrTimer( DefaultSessionMetric.THROTTLING_DELAY, - context.getConfig().getDefaultProfile(), + profile, DefaultDriverOption.METRICS_SESSION_THROTTLING_HIGHEST, DefaultDriverOption.METRICS_SESSION_THROTTLING_DIGITS, DefaultDriverOption.METRICS_SESSION_THROTTLING_INTERVAL); - initializeDefaultCounter(DefaultSessionMetric.THROTTLING_ERRORS, null); initializeHdrTimer( DseSessionMetric.CONTINUOUS_CQL_REQUESTS, - context.getConfig().getDefaultProfile(), + profile, DseDriverOption.CONTINUOUS_PAGING_METRICS_SESSION_CQL_REQUESTS_HIGHEST, DseDriverOption.CONTINUOUS_PAGING_METRICS_SESSION_CQL_REQUESTS_DIGITS, DseDriverOption.CONTINUOUS_PAGING_METRICS_SESSION_CQL_REQUESTS_INTERVAL); - initializeDefaultCounter(DseSessionMetric.GRAPH_CLIENT_TIMEOUTS, null); initializeHdrTimer( DseSessionMetric.GRAPH_REQUESTS, - context.getConfig().getDefaultProfile(), + profile, DseDriverOption.METRICS_SESSION_GRAPH_REQUESTS_HIGHEST, DseDriverOption.METRICS_SESSION_GRAPH_REQUESTS_DIGITS, DseDriverOption.METRICS_SESSION_GRAPH_REQUESTS_INTERVAL); } @Override - public String buildFullName(SessionMetric metric, String profileName) { - return metricNamePrefix + metric.getPath(); - } - - private Gauge buildQueueGauge(RequestThrottler requestThrottler, String logPrefix) { - if (requestThrottler instanceof ConcurrencyLimitingRequestThrottler) { - return ((ConcurrencyLimitingRequestThrottler) requestThrottler)::getQueueSize; - } else if (requestThrottler instanceof RateLimitingRequestThrottler) { - return ((RateLimitingRequestThrottler) requestThrottler)::getQueueSize; - } else { - LOG.warn( - "[{}] Metric {} does not support {}, it will always return 0", - logPrefix, - DefaultSessionMetric.THROTTLING_QUEUE_SIZE.getPath(), - requestThrottler.getClass().getName()); - return () -> 0; - } - } - - @Nullable - private static Cache getPreparedStatementCache(InternalDriverContext context) { - // By default, both the sync processor and the async one are registered and they share the same - // cache. But with a custom processor registry, there could be only one of the two present. - for (RequestProcessor processor : context.getRequestProcessorRegistry().getProcessors()) { - if (processor instanceof CqlPrepareAsyncProcessor) { - return ((CqlPrepareAsyncProcessor) processor).getCache(); - } else if (processor instanceof CqlPrepareSyncProcessor) { - return ((CqlPrepareSyncProcessor) processor).getCache(); - } + protected MetricId getMetricId(SessionMetric metric) { + MetricId id = context.getMetricIdGenerator().sessionMetricId(metric); + if (!id.getTags().isEmpty()) { + throw new IllegalStateException("Cannot use metric tags with Dropwizard"); } - return null; + return id; } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/HdrReservoir.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/HdrReservoir.java index 44a004f8a60..c66fe1dbf8a 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/HdrReservoir.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/HdrReservoir.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/MetricId.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/MetricId.java new file mode 100644 index 00000000000..039fb96d34b --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/MetricId.java @@ -0,0 +1,49 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.metrics; + +import edu.umd.cs.findbugs.annotations.NonNull; +import java.util.Map; + +/** + * The identifier of a metric. + * + *

    The driver will use the reported name and tags to register the described metric against the + * current metric registry. + * + *

    A metric identifier is unique, that is, the combination of its name and its tags is expected + * to be unique for a given metric registry. + */ +public interface MetricId { + + /** + * Returns this metric name. + * + *

    Metric names can be any non-empty string, but it is recommended to create metric names that + * have path-like structures separated by a dot, e.g. {@code path.to.my.custom.metric}. Driver + * built-in implementations of this interface abide by this rule. + * + * @return The metric name; cannot be empty nor null. + */ + @NonNull + String getName(); + + /** @return The metric tags, or empty if no tag is defined; cannot be null. */ + @NonNull + Map getTags(); +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/MetricIdGenerator.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/MetricIdGenerator.java new file mode 100644 index 00000000000..7a33a81b966 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/MetricIdGenerator.java @@ -0,0 +1,49 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.metrics; + +import com.datastax.oss.driver.api.core.metadata.Node; +import com.datastax.oss.driver.api.core.metrics.NodeMetric; +import com.datastax.oss.driver.api.core.metrics.SessionMetric; +import edu.umd.cs.findbugs.annotations.NonNull; + +/** + * A {@link MetricIdGenerator} is used to generate the unique identifiers by which a metric should + * be registered against the current metrics registry. + * + *

    The driver ships with two implementations of this interface; {@code DefaultMetricIdGenerator} + * and {@code TaggingMetricIdGenerator}. + * + *

    {@code DefaultMetricIdGenerator} is the default implementation; it generates metric + * identifiers with unique names and no tags. + * + *

    {@code TaggingMetricIdGenerator} generates metric identifiers whose uniqueness stems from the + * combination of their names and tags. + * + *

    See the driver's {@code reference.conf} file. + */ +public interface MetricIdGenerator { + + /** Generates a {@link MetricId} for the given {@link SessionMetric}. */ + @NonNull + MetricId sessionMetricId(@NonNull SessionMetric metric); + + /** Generates a {@link MetricId} for the given {@link Node} and {@link NodeMetric}. */ + @NonNull + MetricId nodeMetricId(@NonNull Node node, @NonNull NodeMetric metric); +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/MetricPaths.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/MetricPaths.java index b95edc74f73..92b3fc569f7 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/MetricPaths.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/MetricPaths.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -30,7 +32,7 @@ public class MetricPaths { - private static final Logger LOG = LoggerFactory.getLogger(DropwizardMetricsFactory.class); + private static final Logger LOG = LoggerFactory.getLogger(MetricPaths.class); public static Set parseSessionMetricPaths(List paths, String logPrefix) { Set result = new HashSet<>(); diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/MetricUpdater.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/MetricUpdater.java index f8dc93460b5..c07d1b136af 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/MetricUpdater.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/MetricUpdater.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -15,6 +17,7 @@ */ package com.datastax.oss.driver.internal.core.metrics; +import edu.umd.cs.findbugs.annotations.Nullable; import java.util.concurrent.TimeUnit; /** @@ -25,21 +28,24 @@ */ public interface MetricUpdater { - void incrementCounter(MetricT metric, String profileName, long amount); + void incrementCounter(MetricT metric, @Nullable String profileName, long amount); - default void incrementCounter(MetricT metric, String profileName) { + default void incrementCounter(MetricT metric, @Nullable String profileName) { incrementCounter(metric, profileName, 1); } - void updateHistogram(MetricT metric, String profileName, long value); + // note: currently unused + void updateHistogram(MetricT metric, @Nullable String profileName, long value); - void markMeter(MetricT metric, String profileName, long amount); + void markMeter(MetricT metric, @Nullable String profileName, long amount); - default void markMeter(MetricT metric, String profileName) { + default void markMeter(MetricT metric, @Nullable String profileName) { markMeter(metric, profileName, 1); } - void updateTimer(MetricT metric, String profileName, long duration, TimeUnit unit); + void updateTimer(MetricT metric, @Nullable String profileName, long duration, TimeUnit unit); + + boolean isEnabled(MetricT metric, @Nullable String profileName); - boolean isEnabled(MetricT metric, String profileName); + void clearMetrics(); } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/MetricsFactory.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/MetricsFactory.java index 26440c42b6c..6440b79fb75 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/MetricsFactory.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/MetricsFactory.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/NodeMetricUpdater.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/NodeMetricUpdater.java index 4a145124d6a..93d003f0a03 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/NodeMetricUpdater.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/NodeMetricUpdater.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/NoopMetricsFactory.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/NoopMetricsFactory.java new file mode 100644 index 00000000000..59ebd3d314b --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/NoopMetricsFactory.java @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.metrics; + +import com.datastax.oss.driver.api.core.config.DefaultDriverOption; +import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; +import com.datastax.oss.driver.api.core.context.DriverContext; +import com.datastax.oss.driver.api.core.metadata.Node; +import com.datastax.oss.driver.api.core.metrics.Metrics; +import java.util.List; +import java.util.Optional; +import net.jcip.annotations.ThreadSafe; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@ThreadSafe +public class NoopMetricsFactory implements MetricsFactory { + + private static final Logger LOG = LoggerFactory.getLogger(NoopMetricsFactory.class); + + @SuppressWarnings("unused") + public NoopMetricsFactory(DriverContext context) { + String logPrefix = context.getSessionName(); + DriverExecutionProfile config = context.getConfig().getDefaultProfile(); + List enabledSessionMetrics = + config.getStringList(DefaultDriverOption.METRICS_SESSION_ENABLED); + List enabledNodeMetrics = + config.getStringList(DefaultDriverOption.METRICS_NODE_ENABLED); + if (!enabledSessionMetrics.isEmpty() || !enabledNodeMetrics.isEmpty()) { + LOG.warn( + "[{}] Some session-level or node-level metrics were enabled, " + + "but NoopMetricsFactory is being used: all metrics will be empty", + logPrefix); + } + } + + @Override + public Optional getMetrics() { + return Optional.empty(); + } + + @Override + public SessionMetricUpdater getSessionUpdater() { + return NoopSessionMetricUpdater.INSTANCE; + } + + @Override + public NodeMetricUpdater newNodeUpdater(Node node) { + return NoopNodeMetricUpdater.INSTANCE; + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/NoopNodeMetricUpdater.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/NoopNodeMetricUpdater.java index df0f8c9bfff..8d216990331 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/NoopNodeMetricUpdater.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/NoopNodeMetricUpdater.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -51,4 +53,9 @@ public boolean isEnabled(NodeMetric metric, String profileName) { // since methods don't do anything, return false return false; } + + @Override + public void clearMetrics() { + // nothing to do + } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/NoopSessionMetricUpdater.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/NoopSessionMetricUpdater.java index a4cd33b12b7..7099a8ddcac 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/NoopSessionMetricUpdater.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/NoopSessionMetricUpdater.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -51,4 +53,7 @@ public boolean isEnabled(SessionMetric metric, String profileName) { // since methods don't do anything, return false return false; } + + @Override + public void clearMetrics() {} } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/SessionMetricUpdater.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/SessionMetricUpdater.java index 8aaf82dcb71..b7fc51dd134 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/SessionMetricUpdater.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/SessionMetricUpdater.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/TaggingMetricIdGenerator.java b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/TaggingMetricIdGenerator.java new file mode 100644 index 00000000000..393651929c9 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/metrics/TaggingMetricIdGenerator.java @@ -0,0 +1,73 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.metrics; + +import com.datastax.oss.driver.api.core.config.DefaultDriverOption; +import com.datastax.oss.driver.api.core.context.DriverContext; +import com.datastax.oss.driver.api.core.metadata.Node; +import com.datastax.oss.driver.api.core.metrics.NodeMetric; +import com.datastax.oss.driver.api.core.metrics.SessionMetric; +import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap; +import edu.umd.cs.findbugs.annotations.NonNull; +import java.util.Objects; + +/** + * A {@link MetricIdGenerator} that generates metric identifiers using a combination of names and + * tags. + * + *

    Session metric identifiers contain a name starting with "session." and ending with the metric + * path, and a tag with the key "session" and the value of the current session name. + * + *

    Node metric identifiers contain a name starting with "nodes." and ending with the metric path, + * and two tags: one with the key "session" and the value of the current session name, the other + * with the key "node" and the value of the current node endpoint. + */ +public class TaggingMetricIdGenerator implements MetricIdGenerator { + + private final String sessionName; + private final String sessionPrefix; + private final String nodePrefix; + + @SuppressWarnings("unused") + public TaggingMetricIdGenerator(DriverContext context) { + sessionName = context.getSessionName(); + String prefix = + Objects.requireNonNull( + context + .getConfig() + .getDefaultProfile() + .getString(DefaultDriverOption.METRICS_ID_GENERATOR_PREFIX, "")); + sessionPrefix = prefix.isEmpty() ? "session." : prefix + ".session."; + nodePrefix = prefix.isEmpty() ? "nodes." : prefix + ".nodes."; + } + + @NonNull + @Override + public MetricId sessionMetricId(@NonNull SessionMetric metric) { + return new DefaultMetricId( + sessionPrefix + metric.getPath(), ImmutableMap.of("session", sessionName)); + } + + @NonNull + @Override + public MetricId nodeMetricId(@NonNull Node node, @NonNull NodeMetric metric) { + return new DefaultMetricId( + nodePrefix + metric.getPath(), + ImmutableMap.of("session", sessionName, "node", node.getEndPoint().toString())); + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/os/CpuInfo.java b/core/src/main/java/com/datastax/oss/driver/internal/core/os/CpuInfo.java index b5e2329954e..dffc23c4c8f 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/os/CpuInfo.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/os/CpuInfo.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/os/EmptyLibc.java b/core/src/main/java/com/datastax/oss/driver/internal/core/os/EmptyLibc.java index 88a8e94c73c..5b57a01564c 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/os/EmptyLibc.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/os/EmptyLibc.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/os/GraalGetpid.java b/core/src/main/java/com/datastax/oss/driver/internal/core/os/GraalGetpid.java index e910f3ce80a..fc9dd8d50c7 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/os/GraalGetpid.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/os/GraalGetpid.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -28,7 +30,7 @@ static class Directives implements CContext.Directives { @Override public List getHeaderFiles() { - return Collections.unmodifiableList(Collections.singletonList("")); + return Collections.singletonList(""); } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/os/GraalLibc.java b/core/src/main/java/com/datastax/oss/driver/internal/core/os/GraalLibc.java index e6dfadb6b7e..a6535c2c653 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/os/GraalLibc.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/os/GraalLibc.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/os/JnrLibc.java b/core/src/main/java/com/datastax/oss/driver/internal/core/os/JnrLibc.java index b67282ae1ce..25236dee837 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/os/JnrLibc.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/os/JnrLibc.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/os/JnrLibcSubstitution.java b/core/src/main/java/com/datastax/oss/driver/internal/core/os/JnrLibcSubstitution.java index 1139238f6c3..532001498f4 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/os/JnrLibcSubstitution.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/os/JnrLibcSubstitution.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/os/Libc.java b/core/src/main/java/com/datastax/oss/driver/internal/core/os/Libc.java index 5e4e5e91bd1..f3bda6a8c88 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/os/Libc.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/os/Libc.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/os/Native.java b/core/src/main/java/com/datastax/oss/driver/internal/core/os/Native.java index c2f8b03c740..e292914bb4b 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/os/Native.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/os/Native.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/pool/ChannelPool.java b/core/src/main/java/com/datastax/oss/driver/internal/core/pool/ChannelPool.java index 24891972763..6b7d06045bd 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/pool/ChannelPool.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/pool/ChannelPool.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -143,7 +145,6 @@ public boolean isInvalidKeyspace() { * request path, and we want to avoid complex check-then-act semantics; therefore this might * race and return a channel that is already closed, or {@code null}. In those cases, it is up * to the caller to fail fast and move to the next node. - *

    There is no need to return the channel. */ public DriverChannel next() { return channels.next(); diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/pool/ChannelPoolFactory.java b/core/src/main/java/com/datastax/oss/driver/internal/core/pool/ChannelPoolFactory.java index 24ba12ac3bc..b854f4c326c 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/pool/ChannelPoolFactory.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/pool/ChannelPoolFactory.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/pool/ChannelSet.java b/core/src/main/java/com/datastax/oss/driver/internal/core/pool/ChannelSet.java index cccaac6d9b9..b02e15819d9 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/pool/ChannelSet.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/pool/ChannelSet.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/BuiltInCompressors.java b/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/BuiltInCompressors.java index 5f6ad6ec270..74270caef91 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/BuiltInCompressors.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/BuiltInCompressors.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -19,6 +21,7 @@ import com.datastax.oss.driver.api.core.context.DriverContext; import com.datastax.oss.protocol.internal.Compressor; import io.netty.buffer.ByteBuf; +import java.util.Locale; /** * Provides a single entry point to create compressor instances in the driver. @@ -29,7 +32,7 @@ public class BuiltInCompressors { public static Compressor newInstance(String name, DriverContext context) { - switch (name.toLowerCase()) { + switch (name.toLowerCase(Locale.ROOT)) { case "lz4": return new Lz4Compressor(context); case "snappy": diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/ByteBufCompressor.java b/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/ByteBufCompressor.java index b3f3619a76c..95e6be07434 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/ByteBufCompressor.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/ByteBufCompressor.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/ByteBufPrimitiveCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/ByteBufPrimitiveCodec.java index b7fc6350636..1371009f989 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/ByteBufPrimitiveCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/ByteBufPrimitiveCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -114,8 +116,9 @@ public int readUnsignedShort(ByteBuf source) { public ByteBuffer readBytes(ByteBuf source) { int length = readInt(source); if (length < 0) return null; - ByteBuf slice = source.readSlice(length); - return ByteBuffer.wrap(readRawBytes(slice)); + byte[] bytes = new byte[length]; + source.readBytes(bytes); + return ByteBuffer.wrap(bytes); } @Override @@ -220,22 +223,6 @@ public void writeShortBytes(byte[] bytes, ByteBuf dest) { dest.writeBytes(bytes); } - // Reads *all* readable bytes from a buffer and return them. - // If the buffer is backed by an array, this will return the underlying array directly, without - // copy. - private static byte[] readRawBytes(ByteBuf buffer) { - if (buffer.hasArray() && buffer.readableBytes() == buffer.array().length) { - // Move the readerIndex just so we consistently consume the input - buffer.readerIndex(buffer.writerIndex()); - return buffer.array(); - } - - // Otherwise, just read the bytes in a new array - byte[] bytes = new byte[buffer.readableBytes()]; - buffer.readBytes(bytes); - return bytes; - } - private static String readString(ByteBuf source, int length) { try { String str = source.toString(source.readerIndex(), length, CharsetUtil.UTF_8); diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/ByteBufSegmentBuilder.java b/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/ByteBufSegmentBuilder.java index b7911de701c..9b112559aab 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/ByteBufSegmentBuilder.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/ByteBufSegmentBuilder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/BytesToSegmentDecoder.java b/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/BytesToSegmentDecoder.java index 6a816c202ca..03125bd33a5 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/BytesToSegmentDecoder.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/BytesToSegmentDecoder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/CompressorSubstitutions.java b/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/CompressorSubstitutions.java index e632a07a0ab..8a551a039db 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/CompressorSubstitutions.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/CompressorSubstitutions.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -15,13 +17,16 @@ */ package com.datastax.oss.driver.internal.core.protocol; +import static com.datastax.oss.driver.internal.core.util.Dependency.LZ4; + import com.datastax.oss.driver.api.core.config.DefaultDriverOption; import com.datastax.oss.driver.api.core.context.DriverContext; +import com.datastax.oss.driver.internal.core.util.GraalDependencyChecker; import com.datastax.oss.protocol.internal.Compressor; -import com.oracle.svm.core.annotate.Delete; import com.oracle.svm.core.annotate.Substitute; import com.oracle.svm.core.annotate.TargetClass; import io.netty.buffer.ByteBuf; +import java.util.Locale; import java.util.function.BooleanSupplier; /** @@ -32,13 +37,14 @@ * BuiltInCompressors#newInstance(String, DriverContext)} to throw an error if the user attempts to * configure it. */ +@SuppressWarnings("unused") public class CompressorSubstitutions { @TargetClass(value = BuiltInCompressors.class, onlyWith = Lz4Present.class) public static final class BuiltInCompressorsLz4Only { @Substitute public static Compressor newInstance(String name, DriverContext context) { - switch (name.toLowerCase()) { + switch (name.toLowerCase(Locale.ROOT)) { case "lz4": return new Lz4Compressor(context); case "snappy": @@ -59,7 +65,7 @@ public static Compressor newInstance(String name, DriverContext context public static final class NoBuiltInCompressors { @Substitute public static Compressor newInstance(String name, DriverContext context) { - switch (name.toLowerCase()) { + switch (name.toLowerCase(Locale.ROOT)) { case "lz4": throw new UnsupportedOperationException( "This native image was not built with support for LZ4 compression"); @@ -77,26 +83,10 @@ public static Compressor newInstance(String name, DriverContext context } } - @TargetClass(value = Lz4Compressor.class, onlyWith = Lz4Missing.class) - @Delete - public static final class DeleteLz4Compressor {} - - @TargetClass(value = SnappyCompressor.class) - @Delete - public static final class DeleteSnappyCompressor {} - public static class Lz4Present implements BooleanSupplier { - - private static final String LZ4_CLZ_NAME = "net.jpountz.lz4.LZ4Compressor"; - @Override public boolean getAsBoolean() { - try { - Class.forName(LZ4_CLZ_NAME); - return true; - } catch (ClassNotFoundException e) { - return false; - } + return GraalDependencyChecker.isPresent(LZ4); } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/FrameDecoder.java b/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/FrameDecoder.java index f9519e32035..20816ba581b 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/FrameDecoder.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/FrameDecoder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/FrameDecodingException.java b/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/FrameDecodingException.java index ffa59651eec..c209f3f263b 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/FrameDecodingException.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/FrameDecodingException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/FrameEncoder.java b/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/FrameEncoder.java index d1c37f28654..6504ab29728 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/FrameEncoder.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/FrameEncoder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/FrameToSegmentEncoder.java b/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/FrameToSegmentEncoder.java index 1e69247c85d..46c872f4adc 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/FrameToSegmentEncoder.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/FrameToSegmentEncoder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/Lz4Compressor.java b/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/Lz4Compressor.java index e3b2ce1a344..d376cefc216 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/Lz4Compressor.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/Lz4Compressor.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -15,8 +17,10 @@ */ package com.datastax.oss.driver.internal.core.protocol; +import static com.datastax.oss.driver.internal.core.util.Dependency.LZ4; + import com.datastax.oss.driver.api.core.context.DriverContext; -import com.datastax.oss.driver.internal.core.util.DependencyCheck; +import com.datastax.oss.driver.internal.core.util.DefaultDependencyChecker; import com.datastax.oss.driver.shaded.guava.common.annotations.VisibleForTesting; import io.netty.buffer.ByteBuf; import java.nio.ByteBuffer; @@ -41,7 +45,7 @@ public Lz4Compressor(DriverContext context) { @VisibleForTesting Lz4Compressor(String sessionName) { - if (DependencyCheck.LZ4.isPresent()) { + if (DefaultDependencyChecker.isPresent(LZ4)) { LZ4Factory lz4Factory = LZ4Factory.fastestInstance(); LOG.info("[{}] Using {}", sessionName, lz4Factory.toString()); this.compressor = lz4Factory.fastCompressor(); diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/SegmentToBytesEncoder.java b/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/SegmentToBytesEncoder.java index 6a4a35fddbd..c7845545df4 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/SegmentToBytesEncoder.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/SegmentToBytesEncoder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/SegmentToFrameDecoder.java b/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/SegmentToFrameDecoder.java index 13564e47bff..b15a17bb87f 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/SegmentToFrameDecoder.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/SegmentToFrameDecoder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -69,14 +71,19 @@ protected void decode( private void decodeSelfContained(Segment segment, List out) { ByteBuf payload = segment.payload; int frameCount = 0; - do { - Frame frame = frameCodec.decode(payload); - LOG.trace( - "[{}] Decoded response frame {} from self-contained segment", logPrefix, frame.streamId); - out.add(frame); - frameCount += 1; - } while (payload.isReadable()); - payload.release(); + try { + do { + Frame frame = frameCodec.decode(payload); + LOG.trace( + "[{}] Decoded response frame {} from self-contained segment", + logPrefix, + frame.streamId); + out.add(frame); + frameCount += 1; + } while (payload.isReadable()); + } finally { + payload.release(); + } LOG.trace("[{}] Done processing self-contained segment ({} frames)", logPrefix, frameCount); } @@ -89,28 +96,34 @@ private void decodeSlice(Segment segment, ByteBufAllocator allocator, L } accumulatedSlices.add(slice); accumulatedLength += slice.readableBytes(); + int accumulatedSlicesSize = accumulatedSlices.size(); LOG.trace( "[{}] Decoded slice {}, {}/{} bytes", logPrefix, - accumulatedSlices.size(), + accumulatedSlicesSize, accumulatedLength, targetLength); assert accumulatedLength <= targetLength; if (accumulatedLength == targetLength) { // We've received enough data to reassemble the whole message - CompositeByteBuf encodedFrame = allocator.compositeBuffer(accumulatedSlices.size()); + CompositeByteBuf encodedFrame = allocator.compositeBuffer(accumulatedSlicesSize); encodedFrame.addComponents(true, accumulatedSlices); - Frame frame = frameCodec.decode(encodedFrame); + Frame frame; + try { + frame = frameCodec.decode(encodedFrame); + } finally { + encodedFrame.release(); + // Reset our state + targetLength = UNKNOWN_LENGTH; + accumulatedSlices.clear(); + accumulatedLength = 0; + } LOG.trace( "[{}] Decoded response frame {} from {} slices", logPrefix, frame.streamId, - accumulatedSlices.size()); + accumulatedSlicesSize); out.add(frame); - // Reset our state - targetLength = UNKNOWN_LENGTH; - accumulatedSlices.clear(); - accumulatedLength = 0; } } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/SnappyCompressor.java b/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/SnappyCompressor.java index fbfd3eff9b2..21165d808b9 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/SnappyCompressor.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/SnappyCompressor.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,7 +18,8 @@ package com.datastax.oss.driver.internal.core.protocol; import com.datastax.oss.driver.api.core.context.DriverContext; -import com.datastax.oss.driver.internal.core.util.DependencyCheck; +import com.datastax.oss.driver.internal.core.util.DefaultDependencyChecker; +import com.datastax.oss.driver.internal.core.util.Dependency; import io.netty.buffer.ByteBuf; import java.io.IOException; import java.nio.ByteBuffer; @@ -34,7 +37,7 @@ public class SnappyCompressor extends ByteBufCompressor { public SnappyCompressor(@SuppressWarnings("unused") DriverContext context) { - if (!DependencyCheck.SNAPPY.isPresent()) { + if (!DefaultDependencyChecker.isPresent(Dependency.SNAPPY)) { throw new IllegalStateException( "Could not find the Snappy library on the classpath " + "(the driver declares it as an optional dependency, " diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/package-info.java b/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/package-info.java index a77aede1ecf..05da030eec3 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/package-info.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/protocol/package-info.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/retry/ConsistencyDowngradingRetryPolicy.java b/core/src/main/java/com/datastax/oss/driver/internal/core/retry/ConsistencyDowngradingRetryPolicy.java new file mode 100644 index 00000000000..dbf534459a3 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/retry/ConsistencyDowngradingRetryPolicy.java @@ -0,0 +1,376 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.retry; + +import static com.datastax.oss.driver.api.core.servererrors.WriteType.BATCH; +import static com.datastax.oss.driver.api.core.servererrors.WriteType.BATCH_LOG; +import static com.datastax.oss.driver.api.core.servererrors.WriteType.SIMPLE; +import static com.datastax.oss.driver.api.core.servererrors.WriteType.UNLOGGED_BATCH; + +import com.datastax.oss.driver.api.core.ConsistencyLevel; +import com.datastax.oss.driver.api.core.connection.ClosedConnectionException; +import com.datastax.oss.driver.api.core.connection.HeartbeatException; +import com.datastax.oss.driver.api.core.context.DriverContext; +import com.datastax.oss.driver.api.core.retry.RetryDecision; +import com.datastax.oss.driver.api.core.retry.RetryPolicy; +import com.datastax.oss.driver.api.core.retry.RetryVerdict; +import com.datastax.oss.driver.api.core.servererrors.CoordinatorException; +import com.datastax.oss.driver.api.core.servererrors.ReadFailureException; +import com.datastax.oss.driver.api.core.servererrors.WriteFailureException; +import com.datastax.oss.driver.api.core.servererrors.WriteType; +import com.datastax.oss.driver.api.core.session.Request; +import com.datastax.oss.driver.shaded.guava.common.annotations.VisibleForTesting; +import edu.umd.cs.findbugs.annotations.NonNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A retry policy that sometimes retries with a lower consistency level than the one initially + * requested. + * + *

    BEWARE: this policy may retry queries using a lower consistency level than the one + * initially requested. By doing so, it may break consistency guarantees. In other words, if you use + * this retry policy, there are cases (documented below) where a read at {@code QUORUM} may + * not see a preceding write at {@code QUORUM}. Furthermore, this policy doesn't always respect + * datacenter locality; for example, it may downgrade {@code LOCAL_QUORUM} to {@code ONE}, and thus + * could accidentally send a write that was intended for the local datacenter to another + * datacenter.Do not use this policy unless you have understood the cases where this can happen and + * are ok with that. + * + *

    This policy implements the same retries than the {@link DefaultRetryPolicy} policy. But on top + * of that, it also retries in the following cases: + * + *

      + *
    • On a read timeout: if the number of replicas that responded is greater than one, but lower + * than is required by the requested consistency level, the operation is retried at a lower + * consistency level. + *
    • On a write timeout: if the operation is a {@code WriteType.UNLOGGED_BATCH} and at least one + * replica acknowledged the write, the operation is retried at a lower consistency level. + * Furthermore, for other operations, if at least one replica acknowledged the write, the + * timeout is ignored. + *
    • On an unavailable exception: if at least one replica is alive, the operation is retried at + * a lower consistency level. + *
    + * + * The lower consistency level to use for retries is determined by the following rules: + * + *
      + *
    • if more than 3 replicas responded, use {@code THREE}. + *
    • if 1, 2 or 3 replicas responded, use the corresponding level {@code ONE}, {@code TWO} or + * {@code THREE}. + *
    + * + * Note that if the initial consistency level was {@code EACH_QUORUM}, Cassandra returns the number + * of live replicas in the datacenter that failed to reach consistency, not the overall + * number in the cluster. Therefore if this number is 0, we still retry at {@code ONE}, on the + * assumption that a host may still be up in another datacenter. + * + *

    The reasoning behind this retry policy is the following one. If, based on the information the + * Cassandra coordinator node returns, retrying the operation with the initially requested + * consistency has a chance to succeed, do it. Otherwise, if based on this information, we know that + * the initially requested consistency level cannot be achieved currently, then: + * + *

      + *
    • For writes, ignore the exception (thus silently failing the consistency requirement) if we + * know the write has been persisted on at least one replica. + *
    • For reads, try reading at a lower consistency level (thus silently failing the consistency + * requirement). + *
    + * + * In other words, this policy implements the idea that if the requested consistency level cannot be + * achieved, the next best thing for writes is to make sure the data is persisted, and that reading + * something is better than reading nothing, even if there is a risk of reading stale data. + */ +public class ConsistencyDowngradingRetryPolicy implements RetryPolicy { + + private static final Logger LOG = + LoggerFactory.getLogger(ConsistencyDowngradingRetryPolicy.class); + + @VisibleForTesting + public static final String VERDICT_ON_READ_TIMEOUT = + "[{}] Verdict on read timeout (consistency: {}, required responses: {}, " + + "received responses: {}, data retrieved: {}, retries: {}): {}"; + + @VisibleForTesting + public static final String VERDICT_ON_WRITE_TIMEOUT = + "[{}] Verdict on write timeout (consistency: {}, write type: {}, " + + "required acknowledgments: {}, received acknowledgments: {}, retries: {}): {}"; + + @VisibleForTesting + public static final String VERDICT_ON_UNAVAILABLE = + "[{}] Verdict on unavailable exception (consistency: {}, " + + "required replica: {}, alive replica: {}, retries: {}): {}"; + + @VisibleForTesting + public static final String VERDICT_ON_ABORTED = + "[{}] Verdict on aborted request (type: {}, message: '{}', retries: {}): {}"; + + @VisibleForTesting + public static final String VERDICT_ON_ERROR = + "[{}] Verdict on node error (type: {}, message: '{}', retries: {}): {}"; + + private final String logPrefix; + + @SuppressWarnings("unused") + public ConsistencyDowngradingRetryPolicy( + @NonNull DriverContext context, @NonNull String profileName) { + this(context.getSessionName() + "|" + profileName); + } + + public ConsistencyDowngradingRetryPolicy(@NonNull String logPrefix) { + this.logPrefix = logPrefix; + } + + /** + * {@inheritDoc} + * + *

    This implementation triggers a maximum of one retry. If less replicas responded than + * required by the consistency level (but at least one replica did respond), the operation is + * retried at a lower consistency level. If enough replicas responded but data was not retrieved, + * the operation is retried with the initial consistency level. Otherwise, an exception is thrown. + */ + @Override + public RetryVerdict onReadTimeoutVerdict( + @NonNull Request request, + @NonNull ConsistencyLevel cl, + int blockFor, + int received, + boolean dataPresent, + int retryCount) { + RetryVerdict verdict; + if (retryCount != 0) { + verdict = RetryVerdict.RETHROW; + } else if (cl.isSerial()) { + // CAS reads are not all that useful in terms of visibility of the writes since CAS write + // supports the normal consistency levels on the committing phase. So the main use case for + // CAS reads is probably for when you've timed out on a CAS write and want to make sure what + // happened. Downgrading in that case would be always wrong so we just special-case to + // rethrow. + verdict = RetryVerdict.RETHROW; + } else if (received < blockFor) { + verdict = maybeDowngrade(received, cl); + } else if (!dataPresent) { + // Retry with same CL since this usually means that enough replica are alive to satisfy the + // consistency but the coordinator picked a dead one for data retrieval, not having detected + // that replica as dead yet. + verdict = RetryVerdict.RETRY_SAME; + } else { + // This usually means a digest mismatch, in which case it's pointless to retry since + // the inconsistency has to be repaired first. + verdict = RetryVerdict.RETHROW; + } + if (LOG.isTraceEnabled()) { + LOG.trace( + VERDICT_ON_READ_TIMEOUT, + logPrefix, + cl, + blockFor, + received, + dataPresent, + retryCount, + verdict); + } + return verdict; + } + + /** + * {@inheritDoc} + * + *

    This implementation triggers a maximum of one retry. If {@code writeType == + * WriteType.BATCH_LOG}, the write is retried with the initial consistency level. If {@code + * writeType == WriteType.UNLOGGED_BATCH} and at least one replica acknowledged, the write is + * retried with a lower consistency level (with unlogged batch, a write timeout can always + * mean that part of the batch haven't been persisted at all, even if {@code receivedAcks > 0}). + * For other write types ({@code WriteType.SIMPLE} and {@code WriteType.BATCH}), if we know the + * write has been persisted on at least one replica, we ignore the exception. Otherwise, an + * exception is thrown. + */ + @Override + public RetryVerdict onWriteTimeoutVerdict( + @NonNull Request request, + @NonNull ConsistencyLevel cl, + @NonNull WriteType writeType, + int blockFor, + int received, + int retryCount) { + RetryVerdict verdict; + if (retryCount != 0) { + verdict = RetryVerdict.RETHROW; + } else if (SIMPLE.equals(writeType) || BATCH.equals(writeType)) { + // Since we provide atomicity, if at least one replica acknowledged the write, + // there is no point in retrying + verdict = received > 0 ? RetryVerdict.IGNORE : RetryVerdict.RETHROW; + } else if (UNLOGGED_BATCH.equals(writeType)) { + // Since only part of the batch could have been persisted, + // retry with whatever consistency should allow to persist all + verdict = maybeDowngrade(received, cl); + } else if (BATCH_LOG.equals(writeType)) { + verdict = RetryVerdict.RETRY_SAME; + } else { + verdict = RetryVerdict.RETHROW; + } + if (LOG.isTraceEnabled()) { + LOG.trace( + VERDICT_ON_WRITE_TIMEOUT, + logPrefix, + cl, + writeType, + blockFor, + received, + retryCount, + verdict); + } + return verdict; + } + + /** + * {@inheritDoc} + * + *

    This implementation triggers a maximum of one retry. If at least one replica is known to be + * alive, the operation is retried at a lower consistency level. + */ + @Override + public RetryVerdict onUnavailableVerdict( + @NonNull Request request, + @NonNull ConsistencyLevel cl, + int required, + int alive, + int retryCount) { + RetryVerdict verdict; + if (retryCount != 0) { + verdict = RetryVerdict.RETHROW; + } else if (cl.isSerial()) { + // JAVA-764: if the requested consistency level is serial, it means that the + // operation failed at the paxos phase of a LWT. + // Retry on the next host, on the assumption that the initial coordinator could be + // network-isolated. + verdict = RetryVerdict.RETRY_NEXT; + } else { + verdict = maybeDowngrade(alive, cl); + } + if (LOG.isTraceEnabled()) { + LOG.trace(VERDICT_ON_UNAVAILABLE, logPrefix, cl, required, alive, retryCount, verdict); + } + return verdict; + } + + @Override + public RetryVerdict onRequestAbortedVerdict( + @NonNull Request request, @NonNull Throwable error, int retryCount) { + RetryVerdict verdict = + error instanceof ClosedConnectionException || error instanceof HeartbeatException + ? RetryVerdict.RETRY_NEXT + : RetryVerdict.RETHROW; + if (LOG.isTraceEnabled()) { + LOG.trace( + VERDICT_ON_ABORTED, + logPrefix, + error.getClass().getSimpleName(), + error.getMessage(), + retryCount, + verdict); + } + return verdict; + } + + @Override + public RetryVerdict onErrorResponseVerdict( + @NonNull Request request, @NonNull CoordinatorException error, int retryCount) { + RetryVerdict verdict = + error instanceof WriteFailureException || error instanceof ReadFailureException + ? RetryVerdict.RETHROW + : RetryVerdict.RETRY_NEXT; + if (LOG.isTraceEnabled()) { + LOG.trace( + VERDICT_ON_ERROR, + logPrefix, + error.getClass().getSimpleName(), + error.getMessage(), + retryCount, + verdict); + } + return verdict; + } + + @Override + @Deprecated + public RetryDecision onReadTimeout( + @NonNull Request request, + @NonNull ConsistencyLevel cl, + int blockFor, + int received, + boolean dataPresent, + int retryCount) { + throw new UnsupportedOperationException("onReadTimeout"); + } + + @Override + @Deprecated + public RetryDecision onWriteTimeout( + @NonNull Request request, + @NonNull ConsistencyLevel cl, + @NonNull WriteType writeType, + int blockFor, + int received, + int retryCount) { + throw new UnsupportedOperationException("onWriteTimeout"); + } + + @Override + @Deprecated + public RetryDecision onUnavailable( + @NonNull Request request, + @NonNull ConsistencyLevel cl, + int required, + int alive, + int retryCount) { + throw new UnsupportedOperationException("onUnavailable"); + } + + @Override + @Deprecated + public RetryDecision onRequestAborted( + @NonNull Request request, @NonNull Throwable error, int retryCount) { + throw new UnsupportedOperationException("onRequestAborted"); + } + + @Override + @Deprecated + public RetryDecision onErrorResponse( + @NonNull Request request, @NonNull CoordinatorException error, int retryCount) { + throw new UnsupportedOperationException("onErrorResponse"); + } + + @Override + public void close() {} + + private RetryVerdict maybeDowngrade(int alive, ConsistencyLevel current) { + if (alive >= 3) { + return new ConsistencyDowngradingRetryVerdict(ConsistencyLevel.THREE); + } + if (alive == 2) { + return new ConsistencyDowngradingRetryVerdict(ConsistencyLevel.TWO); + } + // JAVA-1005: EACH_QUORUM does not report a global number of alive replicas + // so even if we get 0 alive replicas, there might be a node up in some other datacenter + if (alive == 1 || current.getProtocolCode() == ConsistencyLevel.EACH_QUORUM.getProtocolCode()) { + return new ConsistencyDowngradingRetryVerdict(ConsistencyLevel.ONE); + } + return RetryVerdict.RETHROW; + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/retry/ConsistencyDowngradingRetryVerdict.java b/core/src/main/java/com/datastax/oss/driver/internal/core/retry/ConsistencyDowngradingRetryVerdict.java new file mode 100644 index 00000000000..d78f80c7354 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/retry/ConsistencyDowngradingRetryVerdict.java @@ -0,0 +1,57 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.retry; + +import com.datastax.oss.driver.api.core.ConsistencyLevel; +import com.datastax.oss.driver.api.core.cql.Statement; +import com.datastax.oss.driver.api.core.retry.RetryDecision; +import com.datastax.oss.driver.api.core.retry.RetryVerdict; +import com.datastax.oss.driver.api.core.session.Request; +import edu.umd.cs.findbugs.annotations.NonNull; + +public class ConsistencyDowngradingRetryVerdict implements RetryVerdict { + + private final ConsistencyLevel consistencyLevel; + + public ConsistencyDowngradingRetryVerdict(@NonNull ConsistencyLevel consistencyLevel) { + this.consistencyLevel = consistencyLevel; + } + + @NonNull + @Override + public RetryDecision getRetryDecision() { + return RetryDecision.RETRY_SAME; + } + + @NonNull + @Override + public RequestT getRetryRequest(@NonNull RequestT previous) { + if (previous instanceof Statement) { + Statement statement = (Statement) previous; + @SuppressWarnings("unchecked") + RequestT toRetry = (RequestT) statement.setConsistencyLevel(consistencyLevel); + return toRetry; + } + return previous; + } + + @Override + public String toString() { + return getRetryDecision() + " at consistency " + consistencyLevel; + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/retry/DefaultRetryPolicy.java b/core/src/main/java/com/datastax/oss/driver/internal/core/retry/DefaultRetryPolicy.java index b988f66fce8..8cea1a564b5 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/retry/DefaultRetryPolicy.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/retry/DefaultRetryPolicy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -83,9 +85,7 @@ public class DefaultRetryPolicy implements RetryPolicy { private final String logPrefix; - public DefaultRetryPolicy( - @SuppressWarnings("unused") DriverContext context, - @SuppressWarnings("unused") String profileName) { + public DefaultRetryPolicy(DriverContext context, String profileName) { this.logPrefix = (context != null ? context.getSessionName() : null) + "|" + profileName; } @@ -102,6 +102,7 @@ public DefaultRetryPolicy( *

    Otherwise, the exception is rethrown. */ @Override + @Deprecated public RetryDecision onReadTimeout( @NonNull Request request, @NonNull ConsistencyLevel cl, @@ -135,6 +136,7 @@ public RetryDecision onReadTimeout( *

    Otherwise, the exception is rethrown. */ @Override + @Deprecated public RetryDecision onWriteTimeout( @NonNull Request request, @NonNull ConsistencyLevel cl, @@ -167,6 +169,7 @@ public RetryDecision onWriteTimeout( *

    Otherwise, the exception is rethrown. */ @Override + @Deprecated public RetryDecision onUnavailable( @NonNull Request request, @NonNull ConsistencyLevel cl, @@ -190,6 +193,7 @@ public RetryDecision onUnavailable( * (assuming a driver bug) in all other cases. */ @Override + @Deprecated public RetryDecision onRequestAborted( @NonNull Request request, @NonNull Throwable error, int retryCount) { @@ -212,6 +216,7 @@ public RetryDecision onRequestAborted( * node. */ @Override + @Deprecated public RetryDecision onErrorResponse( @NonNull Request request, @NonNull CoordinatorException error, int retryCount) { diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/retry/DefaultRetryVerdict.java b/core/src/main/java/com/datastax/oss/driver/internal/core/retry/DefaultRetryVerdict.java new file mode 100644 index 00000000000..e74651e30de --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/retry/DefaultRetryVerdict.java @@ -0,0 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.retry; + +import com.datastax.oss.driver.api.core.retry.RetryDecision; +import com.datastax.oss.driver.api.core.retry.RetryVerdict; +import edu.umd.cs.findbugs.annotations.NonNull; + +public class DefaultRetryVerdict implements RetryVerdict { + + private final RetryDecision decision; + + public DefaultRetryVerdict(@NonNull RetryDecision decision) { + this.decision = decision; + } + + @NonNull + @Override + public RetryDecision getRetryDecision() { + return decision; + } + + @Override + public String toString() { + return getRetryDecision().name(); + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/servererrors/DefaultWriteTypeRegistry.java b/core/src/main/java/com/datastax/oss/driver/internal/core/servererrors/DefaultWriteTypeRegistry.java index 598db8fbbbe..7abe49a98c0 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/servererrors/DefaultWriteTypeRegistry.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/servererrors/DefaultWriteTypeRegistry.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/servererrors/WriteTypeRegistry.java b/core/src/main/java/com/datastax/oss/driver/internal/core/servererrors/WriteTypeRegistry.java index 1634b3066bf..537c3922f0f 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/servererrors/WriteTypeRegistry.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/servererrors/WriteTypeRegistry.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/session/BuiltInRequestProcessors.java b/core/src/main/java/com/datastax/oss/driver/internal/core/session/BuiltInRequestProcessors.java new file mode 100644 index 00000000000..dc6e6a295a1 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/session/BuiltInRequestProcessors.java @@ -0,0 +1,120 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.session; + +import static com.datastax.oss.driver.internal.core.util.Dependency.REACTIVE_STREAMS; +import static com.datastax.oss.driver.internal.core.util.Dependency.TINKERPOP; + +import com.datastax.dse.driver.internal.core.cql.continuous.ContinuousCqlRequestAsyncProcessor; +import com.datastax.dse.driver.internal.core.cql.continuous.ContinuousCqlRequestSyncProcessor; +import com.datastax.dse.driver.internal.core.cql.continuous.reactive.ContinuousCqlRequestReactiveProcessor; +import com.datastax.dse.driver.internal.core.cql.reactive.CqlRequestReactiveProcessor; +import com.datastax.dse.driver.internal.core.graph.GraphRequestAsyncProcessor; +import com.datastax.dse.driver.internal.core.graph.GraphRequestSyncProcessor; +import com.datastax.dse.driver.internal.core.graph.GraphSupportChecker; +import com.datastax.dse.driver.internal.core.graph.reactive.ReactiveGraphRequestProcessor; +import com.datastax.oss.driver.internal.core.context.DefaultDriverContext; +import com.datastax.oss.driver.internal.core.cql.CqlPrepareAsyncProcessor; +import com.datastax.oss.driver.internal.core.cql.CqlPrepareSyncProcessor; +import com.datastax.oss.driver.internal.core.cql.CqlRequestAsyncProcessor; +import com.datastax.oss.driver.internal.core.cql.CqlRequestSyncProcessor; +import com.datastax.oss.driver.internal.core.util.DefaultDependencyChecker; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class BuiltInRequestProcessors { + + private static final Logger LOG = LoggerFactory.getLogger(BuiltInRequestProcessors.class); + + public static List> createDefaultProcessors(DefaultDriverContext context) { + List> processors = new ArrayList<>(); + addBasicProcessors(processors, context); + if (DefaultDependencyChecker.isPresent(TINKERPOP)) { + addGraphProcessors(context, processors); + } else { + LOG.debug("Tinkerpop was not found on the classpath: graph extensions will not be available"); + } + if (DefaultDependencyChecker.isPresent(REACTIVE_STREAMS)) { + addReactiveProcessors(processors); + } else { + LOG.debug( + "Reactive Streams was not found on the classpath: reactive extensions will not be available"); + } + if (DefaultDependencyChecker.isPresent(REACTIVE_STREAMS) + && DefaultDependencyChecker.isPresent(TINKERPOP)) { + addGraphReactiveProcessors(context, processors); + } + return processors; + } + + public static void addBasicProcessors( + List> processors, DefaultDriverContext context) { + // regular requests (sync and async) + CqlRequestAsyncProcessor cqlRequestAsyncProcessor = new CqlRequestAsyncProcessor(); + CqlRequestSyncProcessor cqlRequestSyncProcessor = + new CqlRequestSyncProcessor(cqlRequestAsyncProcessor); + processors.add(cqlRequestAsyncProcessor); + processors.add(cqlRequestSyncProcessor); + + // prepare requests (sync and async) + CqlPrepareAsyncProcessor cqlPrepareAsyncProcessor = + new CqlPrepareAsyncProcessor(Optional.of(context)); + CqlPrepareSyncProcessor cqlPrepareSyncProcessor = + new CqlPrepareSyncProcessor(cqlPrepareAsyncProcessor); + processors.add(cqlPrepareAsyncProcessor); + processors.add(cqlPrepareSyncProcessor); + + // continuous requests (sync and async) + ContinuousCqlRequestAsyncProcessor continuousCqlRequestAsyncProcessor = + new ContinuousCqlRequestAsyncProcessor(); + ContinuousCqlRequestSyncProcessor continuousCqlRequestSyncProcessor = + new ContinuousCqlRequestSyncProcessor(continuousCqlRequestAsyncProcessor); + processors.add(continuousCqlRequestAsyncProcessor); + processors.add(continuousCqlRequestSyncProcessor); + } + + public static void addGraphProcessors( + DefaultDriverContext context, List> processors) { + GraphRequestAsyncProcessor graphRequestAsyncProcessor = + new GraphRequestAsyncProcessor(context, new GraphSupportChecker()); + GraphRequestSyncProcessor graphRequestSyncProcessor = + new GraphRequestSyncProcessor(graphRequestAsyncProcessor); + processors.add(graphRequestAsyncProcessor); + processors.add(graphRequestSyncProcessor); + } + + public static void addReactiveProcessors(List> processors) { + CqlRequestReactiveProcessor cqlRequestReactiveProcessor = + new CqlRequestReactiveProcessor(new CqlRequestAsyncProcessor()); + ContinuousCqlRequestReactiveProcessor continuousCqlRequestReactiveProcessor = + new ContinuousCqlRequestReactiveProcessor(new ContinuousCqlRequestAsyncProcessor()); + processors.add(cqlRequestReactiveProcessor); + processors.add(continuousCqlRequestReactiveProcessor); + } + + public static void addGraphReactiveProcessors( + DefaultDriverContext context, List> processors) { + ReactiveGraphRequestProcessor reactiveGraphRequestProcessor = + new ReactiveGraphRequestProcessor( + new GraphRequestAsyncProcessor(context, new GraphSupportChecker())); + processors.add(reactiveGraphRequestProcessor); + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/session/BuiltInRequestProcessorsSubstitutions.java b/core/src/main/java/com/datastax/oss/driver/internal/core/session/BuiltInRequestProcessorsSubstitutions.java new file mode 100644 index 00000000000..b8bca431228 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/session/BuiltInRequestProcessorsSubstitutions.java @@ -0,0 +1,95 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.session; + +import static com.datastax.oss.driver.internal.core.util.Dependency.REACTIVE_STREAMS; +import static com.datastax.oss.driver.internal.core.util.Dependency.TINKERPOP; + +import com.datastax.oss.driver.internal.core.context.DefaultDriverContext; +import com.datastax.oss.driver.internal.core.util.GraalDependencyChecker; +import com.oracle.svm.core.annotate.Substitute; +import com.oracle.svm.core.annotate.TargetClass; +import java.util.ArrayList; +import java.util.List; +import java.util.function.BooleanSupplier; + +@SuppressWarnings("unused") +public class BuiltInRequestProcessorsSubstitutions { + + @TargetClass(value = BuiltInRequestProcessors.class, onlyWith = GraphMissingReactiveMissing.class) + public static final class BuiltInRequestProcessorsGraphMissingReactiveMissing { + + @Substitute + public static List> createDefaultProcessors( + DefaultDriverContext context) { + List> processors = new ArrayList<>(); + BuiltInRequestProcessors.addBasicProcessors(processors, context); + return processors; + } + } + + @TargetClass(value = BuiltInRequestProcessors.class, onlyWith = GraphMissingReactivePresent.class) + public static final class BuiltInRequestProcessorsGraphMissingReactivePresent { + + @Substitute + public static List> createDefaultProcessors( + DefaultDriverContext context) { + List> processors = new ArrayList<>(); + BuiltInRequestProcessors.addBasicProcessors(processors, context); + BuiltInRequestProcessors.addReactiveProcessors(processors); + return processors; + } + } + + @TargetClass(value = BuiltInRequestProcessors.class, onlyWith = GraphPresentReactiveMissing.class) + public static final class BuiltInRequestProcessorsGraphPresentReactiveMissing { + + @Substitute + public static List> createDefaultProcessors( + DefaultDriverContext context) { + List> processors = new ArrayList<>(); + BuiltInRequestProcessors.addBasicProcessors(processors, context); + BuiltInRequestProcessors.addGraphProcessors(context, processors); + return processors; + } + } + + public static class GraphMissingReactiveMissing implements BooleanSupplier { + @Override + public boolean getAsBoolean() { + return !GraalDependencyChecker.isPresent(TINKERPOP) + && !GraalDependencyChecker.isPresent(REACTIVE_STREAMS); + } + } + + public static class GraphMissingReactivePresent implements BooleanSupplier { + @Override + public boolean getAsBoolean() { + return !GraalDependencyChecker.isPresent(TINKERPOP) + && GraalDependencyChecker.isPresent(REACTIVE_STREAMS); + } + } + + public static class GraphPresentReactiveMissing implements BooleanSupplier { + @Override + public boolean getAsBoolean() { + return GraalDependencyChecker.isPresent(TINKERPOP) + && !GraalDependencyChecker.isPresent(REACTIVE_STREAMS); + } + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/session/DefaultSession.java b/core/src/main/java/com/datastax/oss/driver/internal/core/session/DefaultSession.java index 67b203b3724..b795c30fce7 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/session/DefaultSession.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/session/DefaultSession.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -32,10 +34,12 @@ import com.datastax.oss.driver.internal.core.channel.DriverChannel; import com.datastax.oss.driver.internal.core.context.InternalDriverContext; import com.datastax.oss.driver.internal.core.context.LifecycleListener; +import com.datastax.oss.driver.internal.core.metadata.DefaultNode; import com.datastax.oss.driver.internal.core.metadata.MetadataManager; import com.datastax.oss.driver.internal.core.metadata.MetadataManager.RefreshSchemaResult; import com.datastax.oss.driver.internal.core.metadata.NodeStateEvent; import com.datastax.oss.driver.internal.core.metadata.NodeStateManager; +import com.datastax.oss.driver.internal.core.metrics.NodeMetricUpdater; import com.datastax.oss.driver.internal.core.metrics.SessionMetricUpdater; import com.datastax.oss.driver.internal.core.pool.ChannelPool; import com.datastax.oss.driver.internal.core.util.Loggers; @@ -384,16 +388,30 @@ private void init(CqlIdentifier keyspace) { .getTopologyMonitor() .init() .thenCompose(v -> metadataManager.refreshNodes()) - .thenAccept(v -> afterInitialNodeListRefresh(keyspace)) - .exceptionally( - error -> { - initFuture.completeExceptionally(error); - RunOrSchedule.on(adminExecutor, this::close); - return null; + .thenCompose(v -> checkProtocolVersion()) + .thenCompose(v -> initialSchemaRefresh()) + .thenCompose(v -> initializePools(keyspace)) + .whenComplete( + (v, error) -> { + if (error == null) { + LOG.debug("[{}] Initialization complete, ready", logPrefix); + notifyListeners(); + initFuture.complete(DefaultSession.this); + } else { + LOG.debug("[{}] Initialization failed, force closing", logPrefix, error); + forceCloseAsync() + .whenComplete( + (v1, error1) -> { + if (error1 != null) { + error.addSuppressed(error1); + } + initFuture.completeExceptionally(error); + }); + } }); } - private void afterInitialNodeListRefresh(CqlIdentifier keyspace) { + private CompletionStage checkProtocolVersion() { try { boolean protocolWasForced = context.getConfig().getDefaultProfile().isDefined(DefaultDriverOption.PROTOCOL_VERSION); @@ -403,7 +421,7 @@ private void afterInitialNodeListRefresh(CqlIdentifier keyspace) { context .getProtocolVersionRegistry() .highestCommon(metadataManager.getMetadata().getNodes().values()); - if (!currentVersion.equals(bestVersion)) { + if (bestVersion.getCode() < currentVersion.getCode()) { LOG.info( "[{}] Negotiated protocol version {} for the initial contact point, " + "but other nodes only support {}, downgrading", @@ -417,50 +435,48 @@ private void afterInitialNodeListRefresh(CqlIdentifier keyspace) { // of the control queries use any protocol-dependent feature. // Keep going as-is, the control connection might switch to the "correct" version later // if it reconnects to another node. + } else if (bestVersion.getCode() > currentVersion.getCode()) { + LOG.info( + "[{}] Negotiated protocol version {} for the initial contact point, " + + "but cluster seems to support {}, keeping the negotiated version", + logPrefix, + currentVersion, + bestVersion); } } - metadataManager + return CompletableFuture.completedFuture(null); + } catch (Throwable throwable) { + return CompletableFutures.failedFuture(throwable); + } + } + + private CompletionStage initialSchemaRefresh() { + try { + return metadataManager .refreshSchema(null, false, true) - .whenComplete( - (metadata, error) -> { - if (error != null) { - Loggers.warnWithException( - LOG, - "[{}] Unexpected error while refreshing schema during initialization, " - + "keeping previous version", - logPrefix, - error); - } - afterInitialSchemaRefresh(keyspace); + .exceptionally( + error -> { + Loggers.warnWithException( + LOG, + "[{}] Unexpected error while refreshing schema during initialization, " + + "proceeding without schema metadata", + logPrefix, + error); + return null; }); } catch (Throwable throwable) { - initFuture.completeExceptionally(throwable); + return CompletableFutures.failedFuture(throwable); } } - private void afterInitialSchemaRefresh(CqlIdentifier keyspace) { + private CompletionStage initializePools(CqlIdentifier keyspace) { try { nodeStateManager.markInitialized(); context.getLoadBalancingPolicyWrapper().init(); context.getConfigLoader().onDriverInit(context); - LOG.debug("[{}] Initialization complete, ready", logPrefix); - poolManager - .init(keyspace) - .whenComplete( - (v, error) -> { - if (error != null) { - initFuture.completeExceptionally(error); - } else { - notifyListeners(); - initFuture.complete(DefaultSession.this); - } - }); + return poolManager.init(keyspace); } catch (Throwable throwable) { - forceCloseAsync() - .whenComplete( - (v, error) -> { - initFuture.completeExceptionally(throwable); - }); + return CompletableFutures.failedFuture(throwable); } } @@ -477,21 +493,52 @@ private void notifyListeners() { t); } } - context.getNodeStateListener().onSessionReady(DefaultSession.this); - schemaListenerNotifier.onSessionReady(DefaultSession.this); - context.getRequestTracker().onSessionReady(DefaultSession.this); + try { + context.getNodeStateListener().onSessionReady(DefaultSession.this); + } catch (Throwable t) { + Loggers.warnWithException( + LOG, + "[{}] Error while notifying {} of session ready", + logPrefix, + context.getNodeStateListener(), + t); + } + try { + schemaListenerNotifier.onSessionReady(DefaultSession.this); + } catch (Throwable t) { + Loggers.warnWithException( + LOG, + "[{}] Error while notifying {} of session ready", + logPrefix, + schemaListenerNotifier, + t); + } + try { + context.getRequestTracker().onSessionReady(DefaultSession.this); + } catch (Throwable t) { + Loggers.warnWithException( + LOG, + "[{}] Error while notifying {} of session ready", + logPrefix, + context.getRequestTracker(), + t); + } } private void onNodeStateChanged(NodeStateEvent event) { assert adminExecutor.inEventLoop(); - if (event.newState == null) { - context.getNodeStateListener().onRemove(event.node); + DefaultNode node = event.node; + if (node == null) { + LOG.debug( + "[{}] Node for this event was removed, ignoring state change: {}", logPrefix, event); + } else if (event.newState == null) { + context.getNodeStateListener().onRemove(node); } else if (event.oldState == null && event.newState == NodeState.UNKNOWN) { - context.getNodeStateListener().onAdd(event.node); + context.getNodeStateListener().onAdd(node); } else if (event.newState == NodeState.UP) { - context.getNodeStateListener().onUp(event.node); + context.getNodeStateListener().onUp(node); } else if (event.newState == NodeState.DOWN || event.newState == NodeState.FORCED_DOWN) { - context.getNodeStateListener().onDown(event.node); + context.getNodeStateListener().onDown(node); } } @@ -505,6 +552,14 @@ private void close() { closePolicies(); + // clear metrics to prevent memory leak + for (Node n : metadataManager.getMetadata().getNodes().values()) { + NodeMetricUpdater updater = ((DefaultNode) n).getMetricUpdater(); + if (updater != null) updater.clearMetrics(); + } + + if (metricUpdater != null) metricUpdater.clearMetrics(); + List> childrenCloseStages = new ArrayList<>(); for (AsyncAutoCloseable closeable : internalComponentsToClose()) { childrenCloseStages.add(closeable.closeAsync()); @@ -524,6 +579,14 @@ private void forceClose() { logPrefix, (closeWasCalled ? "" : "not ")); + // clear metrics to prevent memory leak + for (Node n : metadataManager.getMetadata().getNodes().values()) { + NodeMetricUpdater updater = ((DefaultNode) n).getMetricUpdater(); + if (updater != null) updater.clearMetrics(); + } + + if (metricUpdater != null) metricUpdater.clearMetrics(); + if (closeWasCalled) { // onChildrenClosed has already been scheduled for (AsyncAutoCloseable closeable : internalComponentsToClose()) { diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/session/PoolManager.java b/core/src/main/java/com/datastax/oss/driver/internal/core/session/PoolManager.java index 6127c00226d..661be017461 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/session/PoolManager.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/session/PoolManager.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -82,8 +84,7 @@ public class PoolManager implements AsyncAutoCloseable { // (e.g. DefaultPreparedStatement) which are handled at the protocol level (e.g. // CqlPrepareAsyncProcessor). We keep the two separate to avoid introducing a dependency from the // session to a particular processor implementation. - private ConcurrentMap repreparePayloads = - new MapMaker().weakValues().makeMap(); + private final ConcurrentMap repreparePayloads; private final String logPrefix; private final EventExecutor adminExecutor; @@ -95,6 +96,14 @@ public PoolManager(InternalDriverContext context) { this.adminExecutor = context.getNettyOptions().adminEventExecutorGroup().next(); this.config = context.getConfig().getDefaultProfile(); this.singleThreaded = new SingleThreaded(context); + + if (config.getBoolean(DefaultDriverOption.PREPARED_CACHE_WEAK_VALUES, true)) { + LOG.debug("[{}] Prepared statements cache configured to use weak values", logPrefix); + this.repreparePayloads = new MapMaker().weakValues().makeMap(); + } else { + LOG.debug("[{}] Prepared statements cache configured to use strong values", logPrefix); + this.repreparePayloads = new MapMaker().makeMap(); + } } public CompletionStage init(CqlIdentifier keyspace) { diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/session/ReprepareOnUp.java b/core/src/main/java/com/datastax/oss/driver/internal/core/session/ReprepareOnUp.java index c6059dcbc57..ee979473fd1 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/session/ReprepareOnUp.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/session/ReprepareOnUp.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/session/RepreparePayload.java b/core/src/main/java/com/datastax/oss/driver/internal/core/session/RepreparePayload.java index d1e09278a9f..7c4b10442a7 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/session/RepreparePayload.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/session/RepreparePayload.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/session/RequestProcessor.java b/core/src/main/java/com/datastax/oss/driver/internal/core/session/RequestProcessor.java index b61ccebb090..49599667d70 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/session/RequestProcessor.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/session/RequestProcessor.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/session/RequestProcessorRegistry.java b/core/src/main/java/com/datastax/oss/driver/internal/core/session/RequestProcessorRegistry.java index 30810164854..b993365d201 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/session/RequestProcessorRegistry.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/session/RequestProcessorRegistry.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/session/SchemaListenerNotifier.java b/core/src/main/java/com/datastax/oss/driver/internal/core/session/SchemaListenerNotifier.java index b2a1fc7fa83..51ba4d30624 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/session/SchemaListenerNotifier.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/session/SchemaListenerNotifier.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/session/SessionWrapper.java b/core/src/main/java/com/datastax/oss/driver/internal/core/session/SessionWrapper.java index c697718a2d0..1a1270b41c8 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/session/SessionWrapper.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/session/SessionWrapper.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/session/throttling/ConcurrencyLimitingRequestThrottler.java b/core/src/main/java/com/datastax/oss/driver/internal/core/session/throttling/ConcurrencyLimitingRequestThrottler.java index ebfc838f4ac..8146c5b113a 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/session/throttling/ConcurrencyLimitingRequestThrottler.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/session/throttling/ConcurrencyLimitingRequestThrottler.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -23,10 +25,10 @@ import com.datastax.oss.driver.api.core.session.throttling.Throttled; import com.datastax.oss.driver.shaded.guava.common.annotations.VisibleForTesting; import edu.umd.cs.findbugs.annotations.NonNull; -import java.util.ArrayDeque; +import edu.umd.cs.findbugs.annotations.Nullable; import java.util.Deque; -import java.util.concurrent.locks.ReentrantLock; -import net.jcip.annotations.GuardedBy; +import java.util.concurrent.ConcurrentLinkedDeque; +import java.util.concurrent.atomic.AtomicInteger; import net.jcip.annotations.ThreadSafe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -58,17 +60,12 @@ public class ConcurrencyLimitingRequestThrottler implements RequestThrottler { private final String logPrefix; private final int maxConcurrentRequests; private final int maxQueueSize; - - private final ReentrantLock lock = new ReentrantLock(); - - @GuardedBy("lock") - private int concurrentRequests; - - @GuardedBy("lock") - private Deque queue = new ArrayDeque<>(); - - @GuardedBy("lock") - private boolean closed; + private final AtomicInteger concurrentRequests = new AtomicInteger(0); + // CLQ is not O(1) for size(), as it forces a full iteration of the queue. So, we track + // the size of the queue explicitly. + private final Deque queue = new ConcurrentLinkedDeque<>(); + private final AtomicInteger queueSize = new AtomicInteger(0); + private volatile boolean closed = false; public ConcurrencyLimitingRequestThrottler(DriverContext context) { this.logPrefix = context.getSessionName(); @@ -85,40 +82,64 @@ public ConcurrencyLimitingRequestThrottler(DriverContext context) { @Override public void register(@NonNull Throttled request) { - lock.lock(); - try { - if (closed) { - LOG.trace("[{}] Rejecting request after shutdown", logPrefix); - fail(request, "The session is shutting down"); - } else if (queue.isEmpty() && concurrentRequests < maxConcurrentRequests) { - // We have capacity for one more concurrent request + if (closed) { + LOG.trace("[{}] Rejecting request after shutdown", logPrefix); + fail(request, "The session is shutting down"); + return; + } + + // Implementation note: Technically the "concurrent requests" or "queue size" + // could read transiently over the limit, but the queue itself will never grow + // beyond the limit since we always check for that condition and revert if + // over-limit. We do this instead of a CAS-loop to avoid the potential loop. + + // If no backlog exists AND we get capacity, we can execute immediately + if (queueSize.get() == 0) { + // Take a claim first, and then check if we are OK to proceed + int newConcurrent = concurrentRequests.incrementAndGet(); + if (newConcurrent <= maxConcurrentRequests) { LOG.trace("[{}] Starting newly registered request", logPrefix); - concurrentRequests += 1; request.onThrottleReady(false); - } else if (queue.size() < maxQueueSize) { - LOG.trace("[{}] Enqueuing request", logPrefix); - queue.add(request); + return; } else { - LOG.trace("[{}] Rejecting request because of full queue", logPrefix); - fail( - request, - String.format( - "The session has reached its maximum capacity " - + "(concurrent requests: %d, queue size: %d)", - maxConcurrentRequests, maxQueueSize)); + // We exceeded the limit, decrement the count and fall through to the queuing logic + concurrentRequests.decrementAndGet(); } - } finally { - lock.unlock(); + } + + // If we have a backlog, or we failed to claim capacity, try to enqueue + int newQueueSize = queueSize.incrementAndGet(); + if (newQueueSize <= maxQueueSize) { + LOG.trace("[{}] Enqueuing request", logPrefix); + queue.offer(request); + + // Double-check that we were still supposed to be enqueued; it is possible + // that the session was closed while we were enqueuing, it's also possible + // that it is right now removing the request, so we need to check both + if (closed) { + if (queue.remove(request)) { + queueSize.decrementAndGet(); + LOG.trace("[{}] Rejecting late request after shutdown", logPrefix); + fail(request, "The session is shutting down"); + } + } + } else { + LOG.trace("[{}] Rejecting request because of full queue", logPrefix); + queueSize.decrementAndGet(); + fail( + request, + String.format( + "The session has reached its maximum capacity " + + "(concurrent requests: %d, queue size: %d)", + maxConcurrentRequests, maxQueueSize)); } } @Override public void signalSuccess(@NonNull Throttled request) { - lock.lock(); - try { - onRequestDone(); - } finally { - lock.unlock(); + Throttled nextRequest = onRequestDoneAndDequeNext(); + if (nextRequest != null) { + nextRequest.onThrottleReady(true); } } @@ -129,75 +150,79 @@ public void signalError(@NonNull Throttled request, @NonNull Throwable error) { @Override public void signalTimeout(@NonNull Throttled request) { - lock.lock(); - try { - if (!closed) { - if (queue.remove(request)) { // The request timed out before it was active - LOG.trace("[{}] Removing timed out request from the queue", logPrefix); - } else { - onRequestDone(); - } + Throttled nextRequest = null; + if (!closed) { + if (queue.remove(request)) { // The request timed out before it was active + queueSize.decrementAndGet(); + LOG.trace("[{}] Removing timed out request from the queue", logPrefix); + } else { + nextRequest = onRequestDoneAndDequeNext(); } - } finally { - lock.unlock(); + } + + if (nextRequest != null) { + nextRequest.onThrottleReady(true); } } - @SuppressWarnings("GuardedBy") // this method is only called with the lock held - private void onRequestDone() { - assert lock.isHeldByCurrentThread(); + @Override + public void signalCancel(@NonNull Throttled request) { + Throttled nextRequest = null; if (!closed) { - if (queue.isEmpty()) { - concurrentRequests -= 1; + if (queue.remove(request)) { // The request has been cancelled before it was active + queueSize.decrementAndGet(); + LOG.trace("[{}] Removing cancelled request from the queue", logPrefix); } else { + nextRequest = onRequestDoneAndDequeNext(); + } + } + + if (nextRequest != null) { + nextRequest.onThrottleReady(true); + } + } + + @Nullable + private Throttled onRequestDoneAndDequeNext() { + if (!closed) { + Throttled nextRequest = queue.poll(); + if (nextRequest == null) { + concurrentRequests.decrementAndGet(); + } else { + queueSize.decrementAndGet(); LOG.trace("[{}] Starting dequeued request", logPrefix); - queue.poll().onThrottleReady(true); - // don't touch concurrentRequests since we finished one but started another + return nextRequest; } } + + // no next task was dequeued + return null; } @Override public void close() { - lock.lock(); - try { - closed = true; - LOG.debug("[{}] Rejecting {} queued requests after shutdown", logPrefix, queue.size()); - for (Throttled request : queue) { - fail(request, "The session is shutting down"); - } - } finally { - lock.unlock(); + closed = true; + + LOG.debug("[{}] Rejecting {} queued requests after shutdown", logPrefix, queueSize.get()); + Throttled request; + while ((request = queue.poll()) != null) { + queueSize.decrementAndGet(); + fail(request, "The session is shutting down"); } } public int getQueueSize() { - lock.lock(); - try { - return queue.size(); - } finally { - lock.unlock(); - } + return queueSize.get(); } @VisibleForTesting int getConcurrentRequests() { - lock.lock(); - try { - return concurrentRequests; - } finally { - lock.unlock(); - } + return concurrentRequests.get(); } @VisibleForTesting Deque getQueue() { - lock.lock(); - try { - return queue; - } finally { - lock.unlock(); - } + return queue; } private static void fail(Throttled request, String message) { diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/session/throttling/NanoClock.java b/core/src/main/java/com/datastax/oss/driver/internal/core/session/throttling/NanoClock.java index 65587e7c3a0..9a25059caef 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/session/throttling/NanoClock.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/session/throttling/NanoClock.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/session/throttling/PassThroughRequestThrottler.java b/core/src/main/java/com/datastax/oss/driver/internal/core/session/throttling/PassThroughRequestThrottler.java index 11fa2632a34..2210e4b26f1 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/session/throttling/PassThroughRequestThrottler.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/session/throttling/PassThroughRequestThrottler.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -67,6 +69,11 @@ public void signalTimeout(@NonNull Throttled request) { // nothing to do } + @Override + public void signalCancel(@NonNull Throttled request) { + // nothing to do + } + @Override public void close() throws IOException { // nothing to do diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/session/throttling/RateLimitingRequestThrottler.java b/core/src/main/java/com/datastax/oss/driver/internal/core/session/throttling/RateLimitingRequestThrottler.java index ab4035a4d46..03a693dc0fe 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/session/throttling/RateLimitingRequestThrottler.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/session/throttling/RateLimitingRequestThrottler.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -196,6 +198,18 @@ public void signalTimeout(@NonNull Throttled request) { } } + @Override + public void signalCancel(@NonNull Throttled request) { + lock.lock(); + try { + if (!closed && queue.remove(request)) { // The request has been cancelled before it was active + LOG.trace("[{}] Removing cancelled request from the queue", logPrefix); + } + } finally { + lock.unlock(); + } + } + @Override public void close() { lock.lock(); diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/specex/ConstantSpeculativeExecutionPolicy.java b/core/src/main/java/com/datastax/oss/driver/internal/core/specex/ConstantSpeculativeExecutionPolicy.java index a33b0d33cc9..5e84f6b1002 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/specex/ConstantSpeculativeExecutionPolicy.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/specex/ConstantSpeculativeExecutionPolicy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/specex/NoSpeculativeExecutionPolicy.java b/core/src/main/java/com/datastax/oss/driver/internal/core/specex/NoSpeculativeExecutionPolicy.java index b758e206c3a..2f6b17286e5 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/specex/NoSpeculativeExecutionPolicy.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/specex/NoSpeculativeExecutionPolicy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/ssl/DefaultSslEngineFactory.java b/core/src/main/java/com/datastax/oss/driver/internal/core/ssl/DefaultSslEngineFactory.java index e60088b7b25..343d3f9e4e7 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/ssl/DefaultSslEngineFactory.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/ssl/DefaultSslEngineFactory.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -20,16 +22,19 @@ import com.datastax.oss.driver.api.core.context.DriverContext; import com.datastax.oss.driver.api.core.metadata.EndPoint; import com.datastax.oss.driver.api.core.ssl.SslEngineFactory; +import com.datastax.oss.driver.shaded.guava.common.annotations.VisibleForTesting; import edu.umd.cs.findbugs.annotations.NonNull; import java.io.InputStream; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.file.Files; +import java.nio.file.Path; import java.nio.file.Paths; import java.security.KeyStore; import java.security.SecureRandom; +import java.time.Duration; import java.util.List; -import javax.net.ssl.KeyManagerFactory; +import java.util.Optional; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLParameters; @@ -52,6 +57,7 @@ * truststore-password = password123 * keystore-path = /path/to/client.keystore * keystore-password = password123 + * keystore-reload-interval = 30 minutes * } * } * @@ -64,6 +70,8 @@ public class DefaultSslEngineFactory implements SslEngineFactory { private final SSLContext sslContext; private final String[] cipherSuites; private final boolean requireHostnameValidation; + private final boolean allowDnsReverseLookupSan; + private ReloadingKeyManagerFactory kmf; /** Builds a new instance from the driver configuration. */ public DefaultSslEngineFactory(DriverContext driverContext) { @@ -82,6 +90,28 @@ public DefaultSslEngineFactory(DriverContext driverContext) { } this.requireHostnameValidation = config.getBoolean(DefaultDriverOption.SSL_HOSTNAME_VALIDATION, true); + this.allowDnsReverseLookupSan = + config.getBoolean(DefaultDriverOption.SSL_ALLOW_DNS_REVERSE_LOOKUP_SAN, true); + } + + @VisibleForTesting + protected String hostname(InetSocketAddress addr) { + return allowDnsReverseLookupSan ? hostMaybeFromDnsReverseLookup(addr) : hostNoLookup(addr); + } + + @VisibleForTesting + protected String hostMaybeFromDnsReverseLookup(InetSocketAddress addr) { + // See java.net.InetSocketAddress.getHostName: + // "This method may trigger a name service reverse lookup if the address was created with a + // literal IP address." + return addr.getHostName(); + } + + @VisibleForTesting + protected String hostNoLookup(InetSocketAddress addr) { + // See java.net.InetSocketAddress.getHostString: + // "This has the benefit of not attempting a reverse lookup" + return addr.getHostString(); } @NonNull @@ -91,7 +121,7 @@ public SSLEngine newSslEngine(@NonNull EndPoint remoteEndpoint) { SocketAddress remoteAddress = remoteEndpoint.resolve(); if (remoteAddress instanceof InetSocketAddress) { InetSocketAddress socketAddress = (InetSocketAddress) remoteAddress; - engine = sslContext.createSSLEngine(socketAddress.getHostName(), socketAddress.getPort()); + engine = sslContext.createSSLEngine(hostname(socketAddress), socketAddress.getPort()); } else { engine = sslContext.createSSLEngine(); } @@ -130,20 +160,8 @@ protected SSLContext buildContext(DriverExecutionProfile config) throws Exceptio } // initialize keystore if configured. - KeyManagerFactory kmf = null; if (config.isDefined(DefaultDriverOption.SSL_KEYSTORE_PATH)) { - try (InputStream ksf = - Files.newInputStream( - Paths.get(config.getString(DefaultDriverOption.SSL_KEYSTORE_PATH)))) { - KeyStore ks = KeyStore.getInstance("JKS"); - char[] password = - config.isDefined(DefaultDriverOption.SSL_KEYSTORE_PASSWORD) - ? config.getString(DefaultDriverOption.SSL_KEYSTORE_PASSWORD).toCharArray() - : null; - ks.load(ksf, password); - kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); - kmf.init(ks, password); - } + kmf = buildReloadingKeyManagerFactory(config); } context.init( @@ -157,8 +175,19 @@ protected SSLContext buildContext(DriverExecutionProfile config) throws Exceptio } } + private ReloadingKeyManagerFactory buildReloadingKeyManagerFactory(DriverExecutionProfile config) + throws Exception { + Path keystorePath = Paths.get(config.getString(DefaultDriverOption.SSL_KEYSTORE_PATH)); + String password = config.getString(DefaultDriverOption.SSL_KEYSTORE_PASSWORD, null); + Optional reloadInterval = + Optional.ofNullable( + config.getDuration(DefaultDriverOption.SSL_KEYSTORE_RELOAD_INTERVAL, null)); + + return ReloadingKeyManagerFactory.create(keystorePath, password, reloadInterval); + } + @Override public void close() throws Exception { - // nothing to do + if (kmf != null) kmf.close(); } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/ssl/JdkSslHandlerFactory.java b/core/src/main/java/com/datastax/oss/driver/internal/core/ssl/JdkSslHandlerFactory.java index 73cb73660fb..7661325005e 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/ssl/JdkSslHandlerFactory.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/ssl/JdkSslHandlerFactory.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/ssl/ReloadingKeyManagerFactory.java b/core/src/main/java/com/datastax/oss/driver/internal/core/ssl/ReloadingKeyManagerFactory.java new file mode 100644 index 00000000000..8a9e11bb2e9 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/ssl/ReloadingKeyManagerFactory.java @@ -0,0 +1,264 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.ssl; + +import com.datastax.oss.driver.shaded.guava.common.annotations.VisibleForTesting; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.Socket; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.Principal; +import java.security.PrivateKey; +import java.security.Provider; +import java.security.UnrecoverableKeyException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.time.Duration; +import java.util.Arrays; +import java.util.Optional; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import javax.net.ssl.KeyManager; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.KeyManagerFactorySpi; +import javax.net.ssl.ManagerFactoryParameters; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.X509ExtendedKeyManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ReloadingKeyManagerFactory extends KeyManagerFactory implements AutoCloseable { + private static final Logger logger = LoggerFactory.getLogger(ReloadingKeyManagerFactory.class); + private static final String KEYSTORE_TYPE = "JKS"; + private Path keystorePath; + private String keystorePassword; + private ScheduledExecutorService executor; + private final Spi spi; + + // We're using a single thread executor so this shouldn't need to be volatile, since all updates + // to lastDigest should come from the same thread + private volatile byte[] lastDigest; + + /** + * Create a new {@link ReloadingKeyManagerFactory} with the given keystore file and password, + * reloading from the file's content at the given interval. This function will do an initial + * reload before returning, to confirm that the file exists and is readable. + * + * @param keystorePath the keystore file to reload + * @param keystorePassword the keystore password + * @param reloadInterval the duration between reload attempts. Set to {@link Optional#empty()} to + * disable scheduled reloading. + * @return + */ + static ReloadingKeyManagerFactory create( + Path keystorePath, String keystorePassword, Optional reloadInterval) + throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, + CertificateException, IOException { + KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + + KeyStore ks; + try (InputStream ksf = Files.newInputStream(keystorePath)) { + ks = KeyStore.getInstance(KEYSTORE_TYPE); + ks.load(ksf, keystorePassword.toCharArray()); + } + kmf.init(ks, keystorePassword.toCharArray()); + + ReloadingKeyManagerFactory reloadingKeyManagerFactory = new ReloadingKeyManagerFactory(kmf); + reloadingKeyManagerFactory.start(keystorePath, keystorePassword, reloadInterval); + return reloadingKeyManagerFactory; + } + + @VisibleForTesting + protected ReloadingKeyManagerFactory(KeyManagerFactory initial) { + this( + new Spi((X509ExtendedKeyManager) initial.getKeyManagers()[0]), + initial.getProvider(), + initial.getAlgorithm()); + } + + private ReloadingKeyManagerFactory(Spi spi, Provider provider, String algorithm) { + super(spi, provider, algorithm); + this.spi = spi; + } + + private void start( + Path keystorePath, String keystorePassword, Optional reloadInterval) { + this.keystorePath = keystorePath; + this.keystorePassword = keystorePassword; + + // Ensure that reload is called once synchronously, to make sure the file exists etc. + reload(); + + if (!reloadInterval.isPresent() || reloadInterval.get().isZero()) { + final String msg = + "KeyStore reloading is disabled. If your Cassandra cluster requires client certificates, " + + "client application restarts are infrequent, and client certificates have short lifetimes, then your client " + + "may fail to re-establish connections to Cassandra hosts. To enable KeyStore reloading, see " + + "`advanced.ssl-engine-factory.keystore-reload-interval` in reference.conf."; + logger.info(msg); + } else { + logger.info("KeyStore reloading is enabled with interval {}", reloadInterval.get()); + + this.executor = + Executors.newScheduledThreadPool( + 1, + runnable -> { + Thread t = Executors.defaultThreadFactory().newThread(runnable); + t.setName(String.format("%s-%%d", this.getClass().getSimpleName())); + t.setDaemon(true); + return t; + }); + this.executor.scheduleWithFixedDelay( + this::reload, + reloadInterval.get().toMillis(), + reloadInterval.get().toMillis(), + TimeUnit.MILLISECONDS); + } + } + + @VisibleForTesting + void reload() { + try { + reload0(); + } catch (Exception e) { + String msg = + "Failed to reload KeyStore. If this continues to happen, your client may use stale identity" + + " certificates and fail to re-establish connections to Cassandra hosts."; + logger.warn(msg, e); + } + } + + private synchronized void reload0() + throws NoSuchAlgorithmException, IOException, KeyStoreException, CertificateException, + UnrecoverableKeyException { + logger.debug("Checking KeyStore file {} for updates", keystorePath); + + final byte[] keyStoreBytes = Files.readAllBytes(keystorePath); + final byte[] newDigest = digest(keyStoreBytes); + if (lastDigest != null && Arrays.equals(lastDigest, digest(keyStoreBytes))) { + logger.debug("KeyStore file content has not changed; skipping update"); + return; + } + + final KeyStore keyStore = KeyStore.getInstance(KEYSTORE_TYPE); + try (InputStream inputStream = new ByteArrayInputStream(keyStoreBytes)) { + keyStore.load(inputStream, keystorePassword.toCharArray()); + } + KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + kmf.init(keyStore, keystorePassword.toCharArray()); + logger.info("Detected updates to KeyStore file {}", keystorePath); + + this.spi.keyManager.set((X509ExtendedKeyManager) kmf.getKeyManagers()[0]); + this.lastDigest = newDigest; + } + + @Override + public void close() throws Exception { + if (executor != null) { + executor.shutdown(); + } + } + + private static byte[] digest(byte[] payload) throws NoSuchAlgorithmException { + final MessageDigest digest = MessageDigest.getInstance("SHA-256"); + return digest.digest(payload); + } + + private static class Spi extends KeyManagerFactorySpi { + DelegatingKeyManager keyManager; + + Spi(X509ExtendedKeyManager initial) { + this.keyManager = new DelegatingKeyManager(initial); + } + + @Override + protected void engineInit(KeyStore ks, char[] password) { + throw new UnsupportedOperationException(); + } + + @Override + protected void engineInit(ManagerFactoryParameters spec) { + throw new UnsupportedOperationException(); + } + + @Override + protected KeyManager[] engineGetKeyManagers() { + return new KeyManager[] {keyManager}; + } + } + + private static class DelegatingKeyManager extends X509ExtendedKeyManager { + AtomicReference delegate; + + DelegatingKeyManager(X509ExtendedKeyManager initial) { + delegate = new AtomicReference<>(initial); + } + + void set(X509ExtendedKeyManager keyManager) { + delegate.set(keyManager); + } + + @Override + public String chooseEngineClientAlias(String[] keyType, Principal[] issuers, SSLEngine engine) { + return delegate.get().chooseEngineClientAlias(keyType, issuers, engine); + } + + @Override + public String chooseEngineServerAlias(String keyType, Principal[] issuers, SSLEngine engine) { + return delegate.get().chooseEngineServerAlias(keyType, issuers, engine); + } + + @Override + public String[] getClientAliases(String keyType, Principal[] issuers) { + return delegate.get().getClientAliases(keyType, issuers); + } + + @Override + public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) { + return delegate.get().chooseClientAlias(keyType, issuers, socket); + } + + @Override + public String[] getServerAliases(String keyType, Principal[] issuers) { + return delegate.get().getServerAliases(keyType, issuers); + } + + @Override + public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) { + return delegate.get().chooseServerAlias(keyType, issuers, socket); + } + + @Override + public X509Certificate[] getCertificateChain(String alias) { + return delegate.get().getCertificateChain(alias); + } + + @Override + public PrivateKey getPrivateKey(String alias) { + return delegate.get().getPrivateKey(alias); + } + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/ssl/SniSslEngineFactory.java b/core/src/main/java/com/datastax/oss/driver/internal/core/ssl/SniSslEngineFactory.java index 7e4c82aa705..4d2cb69fbfc 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/ssl/SniSslEngineFactory.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/ssl/SniSslEngineFactory.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -36,9 +38,15 @@ public class SniSslEngineFactory implements SslEngineFactory { private final SSLContext sslContext; private final CopyOnWriteArrayList fakePorts = new CopyOnWriteArrayList<>(); + private final boolean allowDnsReverseLookupSan; public SniSslEngineFactory(SSLContext sslContext) { + this(sslContext, true); + } + + public SniSslEngineFactory(SSLContext sslContext, boolean allowDnsReverseLookupSan) { this.sslContext = sslContext; + this.allowDnsReverseLookupSan = allowDnsReverseLookupSan; } @NonNull @@ -69,8 +77,8 @@ public SSLEngine newSslEngine(@NonNull EndPoint remoteEndpoint) { // To avoid that, we create a unique "fake" port for every node. We still get session reuse for // a given node, but not across nodes. This is safe because the advisory port is only used for // session caching. - SSLEngine engine = - sslContext.createSSLEngine(address.getHostName(), getFakePort(sniServerName)); + String peerHost = allowDnsReverseLookupSan ? address.getHostName() : address.getHostString(); + SSLEngine engine = sslContext.createSSLEngine(peerHost, getFakePort(sniServerName)); engine.setUseClientMode(true); SSLParameters parameters = engine.getSSLParameters(); parameters.setServerNames(ImmutableList.of(new SNIHostName(sniServerName))); diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/ssl/SslHandlerFactory.java b/core/src/main/java/com/datastax/oss/driver/internal/core/ssl/SslHandlerFactory.java index 3a96b067ada..87bea563796 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/ssl/SslHandlerFactory.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/ssl/SslHandlerFactory.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/time/AtomicTimestampGenerator.java b/core/src/main/java/com/datastax/oss/driver/internal/core/time/AtomicTimestampGenerator.java index 28bd5fdf2e4..351ed96d66f 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/time/AtomicTimestampGenerator.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/time/AtomicTimestampGenerator.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -46,7 +48,7 @@ @ThreadSafe public class AtomicTimestampGenerator extends MonotonicTimestampGenerator { - private AtomicLong lastRef = new AtomicLong(0); + private final AtomicLong lastRef = new AtomicLong(0); public AtomicTimestampGenerator(DriverContext context) { super(context); diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/time/Clock.java b/core/src/main/java/com/datastax/oss/driver/internal/core/time/Clock.java index 4a12a788068..e576b13a74b 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/time/Clock.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/time/Clock.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -26,7 +28,14 @@ public interface Clock { Logger LOG = LoggerFactory.getLogger(Clock.class); - /** Returns the best implementation for the current platform. */ + /** + * Returns the best implementation for the current platform. + * + *

    Usage with non-blocking threads: beware that this method may block the calling thread on its + * very first invocation, because native libraries used by the driver will be loaded at that + * moment. If that is a problem, consider invoking this method once from a thread that is allowed + * to block. Subsequent invocations are guaranteed not to block. + */ static Clock getInstance(boolean forceJavaClock) { if (forceJavaClock) { LOG.info("Using Java system clock because this was explicitly required in the configuration"); diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/time/JavaClock.java b/core/src/main/java/com/datastax/oss/driver/internal/core/time/JavaClock.java index 449d298019f..b6dfbebcdb0 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/time/JavaClock.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/time/JavaClock.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/time/MonotonicTimestampGenerator.java b/core/src/main/java/com/datastax/oss/driver/internal/core/time/MonotonicTimestampGenerator.java index 9fa0bf482bf..99a520d02b1 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/time/MonotonicTimestampGenerator.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/time/MonotonicTimestampGenerator.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/time/NativeClock.java b/core/src/main/java/com/datastax/oss/driver/internal/core/time/NativeClock.java index 7e6caf73a05..51265ead820 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/time/NativeClock.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/time/NativeClock.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/time/ServerSideTimestampGenerator.java b/core/src/main/java/com/datastax/oss/driver/internal/core/time/ServerSideTimestampGenerator.java index 8f66b304e92..0df056deb04 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/time/ServerSideTimestampGenerator.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/time/ServerSideTimestampGenerator.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/time/ThreadLocalTimestampGenerator.java b/core/src/main/java/com/datastax/oss/driver/internal/core/time/ThreadLocalTimestampGenerator.java index 511a3a2e395..598ae5cbbc2 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/time/ThreadLocalTimestampGenerator.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/time/ThreadLocalTimestampGenerator.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/tracker/MultiplexingRequestTracker.java b/core/src/main/java/com/datastax/oss/driver/internal/core/tracker/MultiplexingRequestTracker.java new file mode 100644 index 00000000000..6fe2ba059bd --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/tracker/MultiplexingRequestTracker.java @@ -0,0 +1,174 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.tracker; + +import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; +import com.datastax.oss.driver.api.core.metadata.Node; +import com.datastax.oss.driver.api.core.session.Request; +import com.datastax.oss.driver.api.core.session.Session; +import com.datastax.oss.driver.api.core.tracker.RequestTracker; +import com.datastax.oss.driver.internal.core.util.Loggers; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.Nullable; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.function.Consumer; +import net.jcip.annotations.ThreadSafe; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Combines multiple request trackers into a single one. + * + *

    Any exception thrown by a child tracker is caught and logged. + */ +@ThreadSafe +public class MultiplexingRequestTracker implements RequestTracker { + + private static final Logger LOG = LoggerFactory.getLogger(MultiplexingRequestTracker.class); + + private final List trackers = new CopyOnWriteArrayList<>(); + + public MultiplexingRequestTracker() {} + + public MultiplexingRequestTracker(RequestTracker... trackers) { + this(Arrays.asList(trackers)); + } + + public MultiplexingRequestTracker(Collection trackers) { + addTrackers(trackers); + } + + private void addTrackers(Collection source) { + for (RequestTracker tracker : source) { + addTracker(tracker); + } + } + + private void addTracker(RequestTracker toAdd) { + Objects.requireNonNull(toAdd, "tracker cannot be null"); + if (toAdd instanceof MultiplexingRequestTracker) { + addTrackers(((MultiplexingRequestTracker) toAdd).trackers); + } else { + trackers.add(toAdd); + } + } + + public void register(@NonNull RequestTracker tracker) { + addTracker(tracker); + } + + @Override + public void onSuccess( + @NonNull Request request, + long latencyNanos, + @NonNull DriverExecutionProfile executionProfile, + @NonNull Node node, + @NonNull String sessionRequestLogPrefix) { + invokeTrackers( + tracker -> + tracker.onSuccess( + request, latencyNanos, executionProfile, node, sessionRequestLogPrefix), + sessionRequestLogPrefix, + "onSuccess"); + } + + @Override + public void onError( + @NonNull Request request, + @NonNull Throwable error, + long latencyNanos, + @NonNull DriverExecutionProfile executionProfile, + @Nullable Node node, + @NonNull String sessionRequestLogPrefix) { + invokeTrackers( + tracker -> + tracker.onError( + request, error, latencyNanos, executionProfile, node, sessionRequestLogPrefix), + sessionRequestLogPrefix, + "onError"); + } + + @Override + public void onNodeSuccess( + @NonNull Request request, + long latencyNanos, + @NonNull DriverExecutionProfile executionProfile, + @NonNull Node node, + @NonNull String nodeRequestLogPrefix) { + invokeTrackers( + tracker -> + tracker.onNodeSuccess( + request, latencyNanos, executionProfile, node, nodeRequestLogPrefix), + nodeRequestLogPrefix, + "onNodeSuccess"); + } + + @Override + public void onNodeError( + @NonNull Request request, + @NonNull Throwable error, + long latencyNanos, + @NonNull DriverExecutionProfile executionProfile, + @NonNull Node node, + @NonNull String nodeRequestLogPrefix) { + invokeTrackers( + tracker -> + tracker.onNodeError( + request, error, latencyNanos, executionProfile, node, nodeRequestLogPrefix), + nodeRequestLogPrefix, + "onNodeError"); + } + + @Override + public void onSessionReady(@NonNull Session session) { + invokeTrackers(tracker -> tracker.onSessionReady(session), session.getName(), "onSessionReady"); + } + + @Override + public void close() throws Exception { + for (RequestTracker tracker : trackers) { + try { + tracker.close(); + } catch (Exception e) { + Loggers.warnWithException( + LOG, "Unexpected error while closing request tracker {}.", tracker, e); + } + } + } + + private void invokeTrackers( + @NonNull Consumer action, String logPrefix, String event) { + for (RequestTracker tracker : trackers) { + try { + action.accept(tracker); + } catch (Exception e) { + Loggers.warnWithException( + LOG, + "[{}] Unexpected error while notifying request tracker {} of an {} event.", + logPrefix, + tracker, + event, + e); + } + } + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/tracker/NoopRequestTracker.java b/core/src/main/java/com/datastax/oss/driver/internal/core/tracker/NoopRequestTracker.java index 0cec5dd2691..3821c6ace2d 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/tracker/NoopRequestTracker.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/tracker/NoopRequestTracker.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -19,29 +21,13 @@ import com.datastax.oss.driver.api.core.context.DriverContext; import com.datastax.oss.driver.api.core.metadata.Node; import com.datastax.oss.driver.api.core.session.Request; -import com.datastax.oss.driver.api.core.session.SessionBuilder; import com.datastax.oss.driver.api.core.tracker.RequestTracker; import edu.umd.cs.findbugs.annotations.NonNull; import net.jcip.annotations.ThreadSafe; /** - * A no-op request tracker. - * - *

    To activate this tracker, modify the {@code advanced.request-tracker} section in the driver - * configuration, for example: - * - *

    - * datastax-java-driver {
    - *   advanced.request-tracker {
    - *     class = NoopRequestTracker
    - *   }
    - * }
    - * 
    - * - * See {@code reference.conf} (in the manual or core driver JAR) for more details. - * - *

    Note that if a tracker is specified programmatically with {@link - * SessionBuilder#withRequestTracker(RequestTracker)}, the configuration is ignored. + * Default request tracker implementation with empty methods. This implementation is used when no + * trackers were registered, neither programmatically nor through the configuration. */ @ThreadSafe public class NoopRequestTracker implements RequestTracker { @@ -56,7 +42,7 @@ public void onSuccess( long latencyNanos, @NonNull DriverExecutionProfile executionProfile, @NonNull Node node, - @NonNull String requestPrefix) { + @NonNull String sessionRequestLogPrefix) { // nothing to do } @@ -67,7 +53,7 @@ public void onError( long latencyNanos, @NonNull DriverExecutionProfile executionProfile, Node node, - @NonNull String requestPrefix) { + @NonNull String sessionRequestLogPrefix) { // nothing to do } @@ -78,7 +64,7 @@ public void onNodeError( long latencyNanos, @NonNull DriverExecutionProfile executionProfile, @NonNull Node node, - @NonNull String requestPrefix) { + @NonNull String nodeRequestLogPrefix) { // nothing to do } @@ -88,7 +74,7 @@ public void onNodeSuccess( long latencyNanos, @NonNull DriverExecutionProfile executionProfile, @NonNull Node node, - @NonNull String requestPrefix) { + @NonNull String nodeRequestLogPrefix) { // nothing to do } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/tracker/RequestLogFormatter.java b/core/src/main/java/com/datastax/oss/driver/internal/core/tracker/RequestLogFormatter.java index fd49a2e92d9..808d08e228d 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/tracker/RequestLogFormatter.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/tracker/RequestLogFormatter.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/tracker/RequestLogger.java b/core/src/main/java/com/datastax/oss/driver/internal/core/tracker/RequestLogger.java index bdd99fc5ab7..f242ff89c54 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/tracker/RequestLogger.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/tracker/RequestLogger.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -38,7 +40,7 @@ *

      * datastax-java-driver {
      *   advanced.request-tracker {
    - *     class = RequestLogger
    + *     classes = [RequestLogger]
      *     logs {
      *       success { enabled = true }
      *       slow { enabled = true, threshold = 1 second }
    @@ -56,7 +58,7 @@
      * See {@code reference.conf} (in the manual or core driver JAR) for more details.
      *
      * 

    Note that if a tracker is specified programmatically with {@link - * SessionBuilder#withRequestTracker(RequestTracker)}, the configuration is ignored. + * SessionBuilder#addRequestTracker(RequestTracker)}, the configuration is ignored. */ @ThreadSafe public class RequestLogger implements RequestTracker { @@ -84,7 +86,7 @@ public void onSuccess( long latencyNanos, @NonNull DriverExecutionProfile executionProfile, @NonNull Node node, - @NonNull String logPrefix) { + @NonNull String sessionRequestLogPrefix) { boolean successEnabled = executionProfile.getBoolean(DefaultDriverOption.REQUEST_LOGGER_SUCCESS_ENABLED, false); @@ -127,7 +129,7 @@ public void onSuccess( showValues, maxValues, maxValueLength, - logPrefix); + sessionRequestLogPrefix); } @Override @@ -137,7 +139,7 @@ public void onError( long latencyNanos, @NonNull DriverExecutionProfile executionProfile, Node node, - @NonNull String logPrefix) { + @NonNull String sessionRequestLogPrefix) { if (!executionProfile.getBoolean(DefaultDriverOption.REQUEST_LOGGER_ERROR_ENABLED, false)) { return; @@ -171,7 +173,7 @@ public void onError( maxValues, maxValueLength, showStackTraces, - logPrefix); + sessionRequestLogPrefix); } @Override @@ -181,7 +183,7 @@ public void onNodeError( long latencyNanos, @NonNull DriverExecutionProfile executionProfile, @NonNull Node node, - @NonNull String logPrefix) { + @NonNull String nodeRequestLogPrefix) { // Nothing to do } @@ -191,7 +193,7 @@ public void onNodeSuccess( long latencyNanos, @NonNull DriverExecutionProfile executionProfile, @NonNull Node node, - @NonNull String logPrefix) { + @NonNull String nodeRequestLogPrefix) { // Nothing to do } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/tracker/UuidRequestIdGenerator.java b/core/src/main/java/com/datastax/oss/driver/internal/core/tracker/UuidRequestIdGenerator.java new file mode 100644 index 00000000000..cc07d6717f4 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/tracker/UuidRequestIdGenerator.java @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.tracker; + +import com.datastax.oss.driver.api.core.context.DriverContext; +import com.datastax.oss.driver.api.core.session.Request; +import com.datastax.oss.driver.api.core.tracker.RequestIdGenerator; +import com.datastax.oss.driver.api.core.uuid.Uuids; +import edu.umd.cs.findbugs.annotations.NonNull; + +public class UuidRequestIdGenerator implements RequestIdGenerator { + public UuidRequestIdGenerator(DriverContext context) {} + + /** Generates a random v4 UUID. */ + @Override + public String getSessionRequestId() { + return Uuids.random().toString(); + } + + /** + * {session-request-id}-{random-uuid} All node requests for a session request will have the same + * session request id + */ + @Override + public String getNodeRequestId(@NonNull Request statement, @NonNull String parentId) { + return parentId + "-" + Uuids.random(); + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/tracker/W3CContextRequestIdGenerator.java b/core/src/main/java/com/datastax/oss/driver/internal/core/tracker/W3CContextRequestIdGenerator.java new file mode 100644 index 00000000000..fe15b93bc8e --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/tracker/W3CContextRequestIdGenerator.java @@ -0,0 +1,67 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.tracker; + +import com.datastax.oss.driver.api.core.context.DriverContext; +import com.datastax.oss.driver.api.core.session.Request; +import com.datastax.oss.driver.api.core.tracker.RequestIdGenerator; +import com.datastax.oss.driver.shaded.guava.common.io.BaseEncoding; +import edu.umd.cs.findbugs.annotations.NonNull; +import java.security.SecureRandom; +import java.util.Random; + +public class W3CContextRequestIdGenerator implements RequestIdGenerator { + + private final Random random = new SecureRandom(); + private final BaseEncoding baseEncoding = BaseEncoding.base16().lowerCase(); + private final String payloadKey; + + public W3CContextRequestIdGenerator(DriverContext context) { + payloadKey = RequestIdGenerator.super.getCustomPayloadKey(); + } + + public W3CContextRequestIdGenerator(String payloadKey) { + this.payloadKey = payloadKey; + } + + /** Random 16 bytes, e.g. "4bf92f3577b34da6a3ce929d0e0e4736" */ + @Override + public String getSessionRequestId() { + byte[] bytes = new byte[16]; + random.nextBytes(bytes); + return baseEncoding.encode(bytes); + } + + /** + * Following the format of W3C "traceparent" spec, + * https://www.w3.org/TR/trace-context/#traceparent-header-field-values e.g. + * "00-4bf92f3577b34da6a3ce929d0e0e4736-a3ce929d0e0e4736-01" All node requests in the same session + * request share the same "trace-id" field value + */ + @Override + public String getNodeRequestId(@NonNull Request statement, @NonNull String parentId) { + byte[] bytes = new byte[8]; + random.nextBytes(bytes); + return String.format("00-%s-%s-00", parentId, baseEncoding.encode(bytes)); + } + + @Override + public String getCustomPayloadKey() { + return this.payloadKey; + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/DataTypeHelper.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/DataTypeHelper.java index 97e23446227..1e02a6b8e82 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/DataTypeHelper.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/DataTypeHelper.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/DefaultCustomType.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/DefaultCustomType.java index 3b2f22ff302..7b9e03818ac 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/DefaultCustomType.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/DefaultCustomType.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/DefaultListType.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/DefaultListType.java index f8b93ed5696..6c21b44639e 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/DefaultListType.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/DefaultListType.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/DefaultMapType.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/DefaultMapType.java index 316975484e2..8da9f196f26 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/DefaultMapType.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/DefaultMapType.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/DefaultSetType.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/DefaultSetType.java index 285315a6b20..27641731c72 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/DefaultSetType.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/DefaultSetType.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/DefaultTupleType.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/DefaultTupleType.java index efecfdf540e..29b1b20436f 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/DefaultTupleType.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/DefaultTupleType.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/DefaultUserDefinedType.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/DefaultUserDefinedType.java index 8c2f91eba5c..6b1431dc699 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/DefaultUserDefinedType.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/DefaultUserDefinedType.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/DefaultVectorType.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/DefaultVectorType.java new file mode 100644 index 00000000000..0b1ced94769 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/DefaultVectorType.java @@ -0,0 +1,98 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.type; + +import com.datastax.oss.driver.api.core.detach.AttachmentPoint; +import com.datastax.oss.driver.api.core.type.DataType; +import com.datastax.oss.driver.api.core.type.VectorType; +import edu.umd.cs.findbugs.annotations.NonNull; +import java.util.Objects; +import net.jcip.annotations.Immutable; + +@Immutable +public class DefaultVectorType implements VectorType { + + public static final String VECTOR_CLASS_NAME = "org.apache.cassandra.db.marshal.VectorType"; + + private final DataType subtype; + private final int dimensions; + + public DefaultVectorType(DataType subtype, int dimensions) { + + this.dimensions = dimensions; + this.subtype = subtype; + } + + /* ============== ContainerType interface ============== */ + @Override + public DataType getElementType() { + return this.subtype; + } + + /* ============== VectorType interface ============== */ + @Override + public int getDimensions() { + return this.dimensions; + } + + /* ============== CustomType interface ============== */ + @NonNull + @Override + public String getClassName() { + return VECTOR_CLASS_NAME; + } + + @NonNull + @Override + public String asCql(boolean includeFrozen, boolean pretty) { + return String.format("vector<%s, %d>", getElementType().asCql(true, false), getDimensions()); + } + + /* ============== General class implementation ============== */ + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } else if (o instanceof DefaultVectorType) { + DefaultVectorType that = (DefaultVectorType) o; + return that.subtype.equals(this.subtype) && that.dimensions == this.dimensions; + } else { + return false; + } + } + + @Override + public int hashCode() { + return Objects.hash(DefaultVectorType.class, subtype, dimensions); + } + + @Override + public String toString() { + return String.format("Vector(%s, %d)", getElementType(), getDimensions()); + } + + @Override + public boolean isDetached() { + return false; + } + + @Override + public void attach(@NonNull AttachmentPoint attachmentPoint) { + // nothing to do + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/PrimitiveType.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/PrimitiveType.java index 909a58d053a..c6f815a7487 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/PrimitiveType.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/PrimitiveType.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -20,6 +22,7 @@ import com.datastax.oss.protocol.internal.ProtocolConstants; import edu.umd.cs.findbugs.annotations.NonNull; import java.io.Serializable; +import java.util.Locale; import net.jcip.annotations.Immutable; @Immutable @@ -67,7 +70,7 @@ public int hashCode() { @NonNull @Override public String asCql(boolean includeFrozen, boolean pretty) { - return codeName(protocolCode).toLowerCase(); + return codeName(protocolCode).toLowerCase(Locale.ROOT); } @Override diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/UserDefinedTypeBuilder.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/UserDefinedTypeBuilder.java index 7b3657da6fd..43e05f17690 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/UserDefinedTypeBuilder.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/UserDefinedTypeBuilder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/BigIntCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/BigIntCodec.java index 7ba465543bf..8496da17fa6 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/BigIntCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/BigIntCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -23,6 +25,7 @@ import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; import java.nio.ByteBuffer; +import java.util.Optional; import net.jcip.annotations.ThreadSafe; @ThreadSafe @@ -88,4 +91,10 @@ public Long parse(@Nullable String value) { String.format("Cannot parse 64-bits long value from \"%s\"", value)); } } + + @NonNull + @Override + public Optional serializedSize() { + return Optional.of(8); + } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/BlobCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/BlobCodec.java index 7c036e203cc..1f5fcd5eeaa 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/BlobCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/BlobCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/BooleanCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/BooleanCodec.java index 8768311f2ac..af388982be9 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/BooleanCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/BooleanCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -23,6 +25,7 @@ import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; import java.nio.ByteBuffer; +import java.util.Optional; import net.jcip.annotations.ThreadSafe; @ThreadSafe @@ -96,4 +99,10 @@ public Boolean parse(@Nullable String value) { String.format("Cannot parse boolean value from \"%s\"", value)); } } + + @NonNull + @Override + public Optional serializedSize() { + return Optional.of(1); + } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/CounterCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/CounterCodec.java index 3d0347eebe6..ab90ba09c20 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/CounterCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/CounterCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/CqlDurationCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/CqlDurationCodec.java index 0a1a49e7016..90f6f56cf06 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/CqlDurationCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/CqlDurationCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/CustomCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/CustomCodec.java index b1e1d204bfd..61a854e88d8 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/CustomCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/CustomCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/DateCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/DateCodec.java index 82c11e73dc4..2fc463ef7d2 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/DateCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/DateCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/DecimalCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/DecimalCodec.java index 49a128e423d..25650b733cd 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/DecimalCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/DecimalCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/DoubleCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/DoubleCodec.java index 91071c0d847..b01847517d9 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/DoubleCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/DoubleCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -23,6 +25,7 @@ import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; import java.nio.ByteBuffer; +import java.util.Optional; import net.jcip.annotations.ThreadSafe; @ThreadSafe @@ -88,4 +91,10 @@ public Double parse(@Nullable String value) { String.format("Cannot parse 64-bits double value from \"%s\"", value)); } } + + @NonNull + @Override + public Optional serializedSize() { + return Optional.of(8); + } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/FloatCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/FloatCodec.java index a3ff38a2b83..fd851edfad3 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/FloatCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/FloatCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -23,6 +25,7 @@ import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; import java.nio.ByteBuffer; +import java.util.Optional; import net.jcip.annotations.ThreadSafe; @ThreadSafe @@ -88,4 +91,10 @@ public Float parse(@Nullable String value) { String.format("Cannot parse 32-bits float value from \"%s\"", value)); } } + + @NonNull + @Override + public Optional serializedSize() { + return Optional.of(4); + } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/InetCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/InetCodec.java index efc7c254d21..167c7109bf9 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/InetCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/InetCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/IntCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/IntCodec.java index 702c9a40d2d..b11b164a445 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/IntCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/IntCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -23,6 +25,7 @@ import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; import java.nio.ByteBuffer; +import java.util.Optional; import net.jcip.annotations.ThreadSafe; @ThreadSafe @@ -88,4 +91,10 @@ public Integer parse(@Nullable String value) { String.format("Cannot parse 32-bits int value from \"%s\"", value)); } } + + @NonNull + @Override + public Optional serializedSize() { + return Optional.of(4); + } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/ListCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/ListCodec.java index a84f666b7d7..d587bbd5887 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/ListCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/ListCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/MapCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/MapCodec.java index d5f16b5336c..999f41bf207 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/MapCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/MapCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/ParseUtils.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/ParseUtils.java index c9a9970a87e..a52130a093d 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/ParseUtils.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/ParseUtils.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/SetCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/SetCodec.java index 41ddb40d6f3..fc4c0887516 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/SetCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/SetCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/SimpleBlobCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/SimpleBlobCodec.java index 07ace09adb3..9f90feb8e7c 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/SimpleBlobCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/SimpleBlobCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/SmallIntCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/SmallIntCodec.java index d8ec3c2d414..08beb0b34c5 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/SmallIntCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/SmallIntCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/StringCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/StringCodec.java index 40374dcbf69..2a9acdd8c47 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/StringCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/StringCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/TimeCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/TimeCodec.java index 5d862982acf..4977687342d 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/TimeCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/TimeCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/TimeUuidCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/TimeUuidCodec.java index a8866fada21..95744f63ee3 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/TimeUuidCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/TimeUuidCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/TimestampCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/TimestampCodec.java index 3798b68b482..964f774c8d9 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/TimestampCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/TimestampCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -31,6 +33,7 @@ import java.time.Instant; import java.time.ZoneId; import java.util.Date; +import java.util.Optional; import java.util.TimeZone; import net.jcip.annotations.ThreadSafe; @@ -291,4 +294,10 @@ public Instant parse(@Nullable String value) { String.format("Cannot parse timestamp value from \"%s\"", value)); } } + + @NonNull + @Override + public Optional serializedSize() { + return Optional.of(8); + } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/TinyIntCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/TinyIntCodec.java index 27241aa7833..13bf79b70d5 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/TinyIntCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/TinyIntCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/TupleCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/TupleCodec.java index f15764e3e3e..cc85266682c 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/TupleCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/TupleCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/UdtCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/UdtCodec.java index 15c993d76c3..5d0a379f761 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/UdtCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/UdtCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -28,10 +30,14 @@ import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import net.jcip.annotations.ThreadSafe; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; @ThreadSafe public class UdtCodec implements TypeCodec { + private static final Logger LOG = LoggerFactory.getLogger(UdtCodec.class); + private final UserDefinedType cqlType; public UdtCodec(@NonNull UserDefinedType cqlType) { @@ -104,11 +110,9 @@ public UdtValue decode(@Nullable ByteBuffer bytes, @NonNull ProtocolVersion prot UdtValue value = cqlType.newValue(); int i = 0; while (input.hasRemaining()) { - if (i > cqlType.getFieldTypes().size()) { - throw new IllegalArgumentException( - String.format( - "Too many fields in encoded UDT value, expected %d", - cqlType.getFieldTypes().size())); + if (i == cqlType.getFieldTypes().size()) { + LOG.debug("Encountered unexpected fields when parsing codec {}", cqlType); + break; } int elementSize = input.getInt(); ByteBuffer element; diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/UuidCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/UuidCodec.java index ba3ef0ab110..cc5f48dbe52 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/UuidCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/UuidCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -23,6 +25,7 @@ import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; import java.nio.ByteBuffer; +import java.util.Optional; import java.util.UUID; import net.jcip.annotations.ThreadSafe; @@ -93,4 +96,10 @@ public UUID parse(@Nullable String value) { String.format("Cannot parse UUID value from \"%s\"", value), e); } } + + @NonNull + @Override + public Optional serializedSize() { + return Optional.of(16); + } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/VarIntCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/VarIntCodec.java index eec3ee239b3..b04c959c704 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/VarIntCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/VarIntCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/VectorCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/VectorCodec.java new file mode 100644 index 00000000000..1f8ce1a7166 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/VectorCodec.java @@ -0,0 +1,203 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.type.codec; + +import com.datastax.oss.driver.api.core.ProtocolVersion; +import com.datastax.oss.driver.api.core.data.CqlVector; +import com.datastax.oss.driver.api.core.type.DataType; +import com.datastax.oss.driver.api.core.type.VectorType; +import com.datastax.oss.driver.api.core.type.codec.TypeCodec; +import com.datastax.oss.driver.api.core.type.reflect.GenericType; +import com.datastax.oss.driver.internal.core.type.DefaultVectorType; +import com.datastax.oss.driver.internal.core.type.util.VIntCoding; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.Nullable; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Optional; +import java.util.stream.Collectors; + +public class VectorCodec implements TypeCodec> { + + private final VectorType cqlType; + private final GenericType> javaType; + private final TypeCodec subtypeCodec; + + public VectorCodec(@NonNull VectorType cqlType, @NonNull TypeCodec subtypeCodec) { + this.cqlType = cqlType; + this.subtypeCodec = subtypeCodec; + this.javaType = GenericType.vectorOf(subtypeCodec.getJavaType()); + } + + public VectorCodec(int dimensions, @NonNull TypeCodec subtypeCodec) { + this(new DefaultVectorType(subtypeCodec.getCqlType(), dimensions), subtypeCodec); + } + + @NonNull + @Override + public GenericType> getJavaType() { + return this.javaType; + } + + @NonNull + @Override + public Optional serializedSize() { + return subtypeCodec.serializedSize().isPresent() + ? Optional.of(subtypeCodec.serializedSize().get() * cqlType.getDimensions()) + : Optional.empty(); + } + + @NonNull + @Override + public DataType getCqlType() { + return this.cqlType; + } + + @Nullable + @Override + public ByteBuffer encode( + @Nullable CqlVector value, @NonNull ProtocolVersion protocolVersion) { + boolean isVarSized = !subtypeCodec.serializedSize().isPresent(); + if (value == null || cqlType.getDimensions() <= 0) { + return null; + } + ByteBuffer[] valueBuffs = new ByteBuffer[cqlType.getDimensions()]; + Iterator values = value.iterator(); + int allValueBuffsSize = 0; + for (int i = 0; i < cqlType.getDimensions(); ++i) { + ByteBuffer valueBuff; + SubtypeT valueObj; + + try { + valueObj = values.next(); + } catch (NoSuchElementException nsee) { + throw new IllegalArgumentException( + String.format( + "Not enough elements; must provide elements for %d dimensions", + cqlType.getDimensions())); + } + + try { + valueBuff = this.subtypeCodec.encode(valueObj, protocolVersion); + } catch (ClassCastException e) { + throw new IllegalArgumentException("Invalid type for element: " + valueObj.getClass()); + } + if (valueBuff == null) { + throw new NullPointerException("Vector elements cannot encode to CQL NULL"); + } + int elementSize = valueBuff.limit(); + if (isVarSized) { + allValueBuffsSize += VIntCoding.computeVIntSize(elementSize); + } + allValueBuffsSize += elementSize; + valueBuff.rewind(); + valueBuffs[i] = valueBuff; + } + // if too many elements, throw + if (values.hasNext()) { + throw new IllegalArgumentException( + String.format( + "Too many elements; must provide elements for %d dimensions", + cqlType.getDimensions())); + } + /* Since we already did an early return for <= 0 dimensions above */ + assert valueBuffs.length > 0; + ByteBuffer rv = ByteBuffer.allocate(allValueBuffsSize); + for (int i = 0; i < cqlType.getDimensions(); ++i) { + if (isVarSized) { + VIntCoding.writeUnsignedVInt32(valueBuffs[i].remaining(), rv); + } + rv.put(valueBuffs[i]); + } + rv.flip(); + return rv; + } + + @Nullable + @Override + public CqlVector decode( + @Nullable ByteBuffer bytes, @NonNull ProtocolVersion protocolVersion) { + if (bytes == null || bytes.remaining() == 0) { + return null; + } + + // Upfront check for fixed-size types only + subtypeCodec + .serializedSize() + .ifPresent( + (fixed_size) -> { + if (bytes.remaining() != cqlType.getDimensions() * fixed_size) { + throw new IllegalArgumentException( + String.format( + "Expected elements of uniform size, observed %d elements with total bytes %d", + cqlType.getDimensions(), bytes.remaining())); + } + }); + ; + ByteBuffer slice = bytes.slice(); + List rv = new ArrayList(cqlType.getDimensions()); + for (int i = 0; i < cqlType.getDimensions(); ++i) { + + int size = + subtypeCodec + .serializedSize() + .orElseGet(() -> VIntCoding.getUnsignedVInt32(slice, slice.position())); + // If we aren't dealing with a fixed-size type we need to move the current slice position + // beyond the vint-encoded size of the current element. Ideally this would be + // serializedSize().ifNotPresent(Consumer) but the Optional API isn't doing us any favors + // there. + if (!subtypeCodec.serializedSize().isPresent()) + slice.position(slice.position() + VIntCoding.computeUnsignedVIntSize(size)); + int originalPosition = slice.position(); + slice.limit(originalPosition + size); + rv.add(this.subtypeCodec.decode(slice, protocolVersion)); + // Move to the start of the next element + slice.position(originalPosition + size); + // Reset the limit to the end of the buffer + slice.limit(slice.capacity()); + } + + // if too many elements, throw + if (slice.hasRemaining()) { + throw new IllegalArgumentException( + String.format( + "Too many elements; must provide elements for %d dimensions", + cqlType.getDimensions())); + } + + return CqlVector.newInstance(rv); + } + + @NonNull + @Override + public String format(CqlVector value) { + if (value == null) return "NULL"; + return value.stream().map(subtypeCodec::format).collect(Collectors.joining(", ", "[", "]")); + } + + @Nullable + @Override + public CqlVector parse(@Nullable String value) { + return (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL")) + ? null + : CqlVector.from(value, this.subtypeCodec); + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/OptionalCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/OptionalCodec.java index 2361495ad93..e62e244bf5e 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/OptionalCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/OptionalCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/AbstractListToArrayCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/AbstractListToArrayCodec.java index ce94f148600..fcf61a4e7b3 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/AbstractListToArrayCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/AbstractListToArrayCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/AbstractPrimitiveListToArrayCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/AbstractPrimitiveListToArrayCodec.java index 1e81af8edcf..3e5ece7c159 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/AbstractPrimitiveListToArrayCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/AbstractPrimitiveListToArrayCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/BooleanListToArrayCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/BooleanListToArrayCodec.java index fbf2e7c0db0..c9cc0baa41f 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/BooleanListToArrayCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/BooleanListToArrayCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/ByteListToArrayCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/ByteListToArrayCodec.java index 4f3d1f3fbc2..b811908e341 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/ByteListToArrayCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/ByteListToArrayCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/DoubleListToArrayCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/DoubleListToArrayCodec.java index c025a8fb390..fdf5befa635 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/DoubleListToArrayCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/DoubleListToArrayCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/FloatListToArrayCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/FloatListToArrayCodec.java index 05ead7ed364..b77e5d1243d 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/FloatListToArrayCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/FloatListToArrayCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/IntListToArrayCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/IntListToArrayCodec.java index 9aa039e53cf..cf464282b1e 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/IntListToArrayCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/IntListToArrayCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/LongListToArrayCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/LongListToArrayCodec.java index 9a8abbb778a..bde21d40272 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/LongListToArrayCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/LongListToArrayCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/ObjectListToArrayCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/ObjectListToArrayCodec.java index 999534950ce..8600ba3e9a5 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/ObjectListToArrayCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/ObjectListToArrayCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/ShortListToArrayCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/ShortListToArrayCodec.java index bbb9a93815c..13bb5733bf9 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/ShortListToArrayCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/ShortListToArrayCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/enums/EnumNameCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/enums/EnumNameCodec.java index f98412e21b5..56363ef819e 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/enums/EnumNameCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/enums/EnumNameCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/enums/EnumOrdinalCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/enums/EnumOrdinalCodec.java index d8a826ba74a..4d6ca26484e 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/enums/EnumOrdinalCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/enums/EnumOrdinalCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/json/JsonCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/json/JsonCodec.java index f95545f9855..a971d27b3f3 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/json/JsonCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/json/JsonCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/time/LocalTimestampCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/time/LocalTimestampCodec.java index 98bc54c5455..6b66b5d2049 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/time/LocalTimestampCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/time/LocalTimestampCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/time/PersistentZonedTimestampCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/time/PersistentZonedTimestampCodec.java index 0cb1681d344..c16a64b9ad9 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/time/PersistentZonedTimestampCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/time/PersistentZonedTimestampCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -98,7 +100,7 @@ protected TupleValue outerToInner(@Nullable ZonedDateTime value) { } else { Instant instant = value.toInstant(); String zoneId = value.getZone().toString(); - return getCqlType().newValue(instant, zoneId); + return this.getCqlType().newValue(instant, zoneId); } } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/time/TimestampMillisCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/time/TimestampMillisCodec.java index f4b78d4919f..12e3e839d2a 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/time/TimestampMillisCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/time/TimestampMillisCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -29,6 +31,7 @@ import java.time.Instant; import java.time.ZoneId; import java.util.Objects; +import java.util.Optional; import net.jcip.annotations.Immutable; /** @@ -112,4 +115,10 @@ public String format(@Nullable Long value) { Instant instant = value == null ? null : Instant.ofEpochMilli(value); return timestampCodec.format(instant); } + + @NonNull + @Override + public Optional serializedSize() { + return Optional.of(8); + } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/time/ZonedTimestampCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/time/ZonedTimestampCodec.java index 46015d25597..a0947ff3493 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/time/ZonedTimestampCodec.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/time/ZonedTimestampCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/vector/AbstractVectorToArrayCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/vector/AbstractVectorToArrayCodec.java new file mode 100644 index 00000000000..3e4e844783c --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/vector/AbstractVectorToArrayCodec.java @@ -0,0 +1,142 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.type.codec.extras.vector; + +import com.datastax.oss.driver.api.core.ProtocolVersion; +import com.datastax.oss.driver.api.core.type.DataType; +import com.datastax.oss.driver.api.core.type.VectorType; +import com.datastax.oss.driver.api.core.type.codec.TypeCodec; +import com.datastax.oss.driver.api.core.type.reflect.GenericType; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.Nullable; +import java.lang.reflect.Array; +import java.nio.ByteBuffer; +import java.util.Objects; + +/** Common super-class for all codecs which map a CQL vector type onto a primitive array */ +public abstract class AbstractVectorToArrayCodec implements TypeCodec { + + @NonNull protected final VectorType cqlType; + @NonNull protected final GenericType javaType; + + /** + * @param cqlType The CQL type. Must be a list type. + * @param arrayType The Java type. Must be an array class. + */ + protected AbstractVectorToArrayCodec( + @NonNull VectorType cqlType, @NonNull GenericType arrayType) { + this.cqlType = Objects.requireNonNull(cqlType, "cqlType cannot be null"); + this.javaType = Objects.requireNonNull(arrayType, "arrayType cannot be null"); + if (!arrayType.isArray()) { + throw new IllegalArgumentException("Expecting Java array class, got " + arrayType); + } + } + + @NonNull + @Override + public GenericType getJavaType() { + return this.javaType; + } + + @NonNull + @Override + public DataType getCqlType() { + return this.cqlType; + } + + @Nullable + @Override + public ByteBuffer encode(@Nullable ArrayT array, @NonNull ProtocolVersion protocolVersion) { + if (array == null) { + return null; + } + int length = Array.getLength(array); + int totalSize = length * sizeOfComponentType(); + ByteBuffer output = ByteBuffer.allocate(totalSize); + for (int i = 0; i < length; i++) { + serializeElement(output, array, i, protocolVersion); + } + output.flip(); + return output; + } + + @Nullable + @Override + public ArrayT decode(@Nullable ByteBuffer bytes, @NonNull ProtocolVersion protocolVersion) { + if (bytes == null || bytes.remaining() == 0) { + throw new IllegalArgumentException( + "Input ByteBuffer must not be null and must have non-zero remaining bytes"); + } + ByteBuffer input = bytes.duplicate(); + int length = this.cqlType.getDimensions(); + int elementSize = sizeOfComponentType(); + ArrayT array = newInstance(); + for (int i = 0; i < length; i++) { + // Null elements can happen on the decode path, but we cannot tolerate them + if (elementSize < 0) { + throw new NullPointerException("Primitive arrays cannot store null elements"); + } else { + deserializeElement(input, array, i, protocolVersion); + } + } + return array; + } + + /** + * Creates a new array instance with a size matching the specified vector. + * + * @return a new array instance with a size matching the specified vector. + */ + @NonNull + protected abstract ArrayT newInstance(); + + /** + * Return the size in bytes of the array component type. + * + * @return the size in bytes of the array component type. + */ + protected abstract int sizeOfComponentType(); + + /** + * Write the {@code index}th element of {@code array} to {@code output}. + * + * @param output The ByteBuffer to write to. + * @param array The array to read from. + * @param index The element index. + * @param protocolVersion The protocol version to use. + */ + protected abstract void serializeElement( + @NonNull ByteBuffer output, + @NonNull ArrayT array, + int index, + @NonNull ProtocolVersion protocolVersion); + + /** + * Read the {@code index}th element of {@code array} from {@code input}. + * + * @param input The ByteBuffer to read from. + * @param array The array to write to. + * @param index The element index. + * @param protocolVersion The protocol version to use. + */ + protected abstract void deserializeElement( + @NonNull ByteBuffer input, + @NonNull ArrayT array, + int index, + @NonNull ProtocolVersion protocolVersion); +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/vector/FloatVectorToArrayCodec.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/vector/FloatVectorToArrayCodec.java new file mode 100644 index 00000000000..86f31dc4980 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/extras/vector/FloatVectorToArrayCodec.java @@ -0,0 +1,107 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.type.codec.extras.vector; + +import com.datastax.oss.driver.api.core.ProtocolVersion; +import com.datastax.oss.driver.api.core.type.VectorType; +import com.datastax.oss.driver.api.core.type.reflect.GenericType; +import com.datastax.oss.driver.internal.core.type.codec.FloatCodec; +import com.datastax.oss.driver.shaded.guava.common.base.Preconditions; +import com.datastax.oss.driver.shaded.guava.common.base.Splitter; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.Nullable; +import java.nio.ByteBuffer; +import java.util.Arrays; +import java.util.Iterator; +import java.util.Objects; + +/** A codec that maps CQL vectors to the Java type {@code float[]}. */ +public class FloatVectorToArrayCodec extends AbstractVectorToArrayCodec { + + public FloatVectorToArrayCodec(VectorType type) { + super(type, GenericType.of(float[].class)); + } + + @Override + public boolean accepts(@NonNull Class javaClass) { + Objects.requireNonNull(javaClass); + return float[].class.equals(javaClass); + } + + @Override + public boolean accepts(@NonNull Object value) { + Objects.requireNonNull(value); + return value instanceof float[]; + } + + @NonNull + @Override + protected float[] newInstance() { + return new float[cqlType.getDimensions()]; + } + + @Override + protected int sizeOfComponentType() { + return 4; + } + + @Override + protected void serializeElement( + @NonNull ByteBuffer output, + @NonNull float[] array, + int index, + @NonNull ProtocolVersion protocolVersion) { + output.putFloat(array[index]); + } + + @Override + protected void deserializeElement( + @NonNull ByteBuffer input, + @NonNull float[] array, + int index, + @NonNull ProtocolVersion protocolVersion) { + array[index] = input.getFloat(); + } + + @NonNull + @Override + public String format(@Nullable float[] value) { + return value == null ? "NULL" : Arrays.toString(value); + } + + @Nullable + @Override + public float[] parse(@Nullable String str) { + Preconditions.checkArgument(str != null, "Cannot create float array from null string"); + Preconditions.checkArgument(!str.isEmpty(), "Cannot create float array from empty string"); + + FloatCodec codec = new FloatCodec(); + float[] rv = this.newInstance(); + Iterator strIter = + Splitter.on(", ").trimResults().split(str.substring(1, str.length() - 1)).iterator(); + for (int i = 0; i < rv.length; ++i) { + String strVal = strIter.next(); + if (strVal == null) { + throw new IllegalArgumentException("Null element observed in float array string"); + } + Float f = codec.parse(strVal); + rv[i] = f.floatValue(); + } + return rv; + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/registry/CachingCodecRegistry.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/registry/CachingCodecRegistry.java index 35ea21f38c7..3af5a30ba27 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/registry/CachingCodecRegistry.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/registry/CachingCodecRegistry.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,8 +18,10 @@ package com.datastax.oss.driver.internal.core.type.codec.registry; import com.datastax.oss.driver.api.core.data.CqlDuration; +import com.datastax.oss.driver.api.core.data.CqlVector; import com.datastax.oss.driver.api.core.data.TupleValue; import com.datastax.oss.driver.api.core.data.UdtValue; +import com.datastax.oss.driver.api.core.type.ContainerType; import com.datastax.oss.driver.api.core.type.CustomType; import com.datastax.oss.driver.api.core.type.DataType; import com.datastax.oss.driver.api.core.type.DataTypes; @@ -26,6 +30,7 @@ import com.datastax.oss.driver.api.core.type.SetType; import com.datastax.oss.driver.api.core.type.TupleType; import com.datastax.oss.driver.api.core.type.UserDefinedType; +import com.datastax.oss.driver.api.core.type.VectorType; import com.datastax.oss.driver.api.core.type.codec.CodecNotFoundException; import com.datastax.oss.driver.api.core.type.codec.TypeCodec; import com.datastax.oss.driver.api.core.type.codec.TypeCodecs; @@ -340,7 +345,7 @@ protected GenericType inspectType(@NonNull Object value, @Nullable DataType c } GenericType elementType = inspectType( - firstElement, cqlType == null ? null : ((ListType) cqlType).getElementType()); + firstElement, cqlType == null ? null : ((ContainerType) cqlType).getElementType()); return GenericType.listOf(elementType); } } else if (value instanceof Set) { @@ -378,6 +383,22 @@ protected GenericType inspectType(@NonNull Object value, @Nullable DataType c inspectType(firstValue, cqlType == null ? null : ((MapType) cqlType).getValueType()); return GenericType.mapOf(keyType, valueType); } + } else if (value instanceof CqlVector) { + CqlVector vector = (CqlVector) value; + if (vector.isEmpty()) { + return cqlType == null ? JAVA_TYPE_FOR_EMPTY_CQLVECTORS : inferJavaTypeFromCqlType(cqlType); + } else { + Object firstElement = vector.iterator().next(); + if (firstElement == null) { + throw new IllegalArgumentException( + "Can't infer vector codec because the first element is null " + + "(note that CQL does not allow null values in collections)"); + } + GenericType elementType = + inspectType( + firstElement, cqlType == null ? null : ((VectorType) cqlType).getElementType()); + return GenericType.vectorOf(elementType); + } } else { // There's not much more we can do return GenericType.of(value.getClass()); @@ -397,6 +418,10 @@ protected GenericType inferJavaTypeFromCqlType(@NonNull DataType cqlType) { DataType valueType = ((MapType) cqlType).getValueType(); return GenericType.mapOf( inferJavaTypeFromCqlType(keyType), inferJavaTypeFromCqlType(valueType)); + } else if (cqlType instanceof VectorType) { + DataType elementType = ((VectorType) cqlType).getElementType(); + GenericType numberType = inferJavaTypeFromCqlType(elementType); + return GenericType.vectorOf(numberType); } switch (cqlType.getProtocolCode()) { case ProtocolConstants.DataType.CUSTOM: @@ -499,6 +524,22 @@ protected DataType inferCqlTypeFromValue(@NonNull Object value) { return null; } return DataTypes.mapOf(keyType, valueType); + } else if (value instanceof CqlVector) { + CqlVector vector = (CqlVector) value; + if (vector.isEmpty()) { + return CQL_TYPE_FOR_EMPTY_VECTORS; + } + Object firstElement = vector.iterator().next(); + if (firstElement == null) { + throw new IllegalArgumentException( + "Can't infer vector codec because the first element is null " + + "(note that CQL does not allow null values in collections)"); + } + DataType elementType = inferCqlTypeFromValue(firstElement); + if (elementType == null) { + return null; + } + return DataTypes.vectorOf(elementType, vector.size()); } Class javaClass = value.getClass(); if (ByteBuffer.class.isAssignableFrom(javaClass)) { @@ -545,6 +586,26 @@ protected DataType inferCqlTypeFromValue(@NonNull Object value) { return null; } + private TypeCodec getElementCodecForCqlAndJavaType( + ContainerType cqlType, TypeToken token, boolean isJavaCovariant) { + + DataType elementCqlType = cqlType.getElementType(); + if (token.getType() instanceof ParameterizedType) { + Type[] typeArguments = ((ParameterizedType) token.getType()).getActualTypeArguments(); + GenericType elementJavaType = GenericType.of(typeArguments[0]); + return uncheckedCast(codecFor(elementCqlType, elementJavaType, isJavaCovariant)); + } + return codecFor(elementCqlType); + } + + private TypeCodec getElementCodecForJavaType( + ParameterizedType parameterizedType, boolean isJavaCovariant) { + + Type[] typeArguments = parameterizedType.getActualTypeArguments(); + GenericType elementType = GenericType.of(typeArguments[0]); + return codecFor(elementType, isJavaCovariant); + } + // Try to create a codec when we haven't found it in the cache @NonNull protected TypeCodec createCodec( @@ -559,26 +620,12 @@ protected TypeCodec createCodec( } else { // Both non-null TypeToken token = javaType.__getToken(); if (cqlType instanceof ListType && List.class.isAssignableFrom(token.getRawType())) { - DataType elementCqlType = ((ListType) cqlType).getElementType(); - TypeCodec elementCodec; - if (token.getType() instanceof ParameterizedType) { - Type[] typeArguments = ((ParameterizedType) token.getType()).getActualTypeArguments(); - GenericType elementJavaType = GenericType.of(typeArguments[0]); - elementCodec = uncheckedCast(codecFor(elementCqlType, elementJavaType, isJavaCovariant)); - } else { - elementCodec = codecFor(elementCqlType); - } + TypeCodec elementCodec = + getElementCodecForCqlAndJavaType((ContainerType) cqlType, token, isJavaCovariant); return TypeCodecs.listOf(elementCodec); } else if (cqlType instanceof SetType && Set.class.isAssignableFrom(token.getRawType())) { - DataType elementCqlType = ((SetType) cqlType).getElementType(); - TypeCodec elementCodec; - if (token.getType() instanceof ParameterizedType) { - Type[] typeArguments = ((ParameterizedType) token.getType()).getActualTypeArguments(); - GenericType elementJavaType = GenericType.of(typeArguments[0]); - elementCodec = uncheckedCast(codecFor(elementCqlType, elementJavaType, isJavaCovariant)); - } else { - elementCodec = codecFor(elementCqlType); - } + TypeCodec elementCodec = + getElementCodecForCqlAndJavaType((ContainerType) cqlType, token, isJavaCovariant); return TypeCodecs.setOf(elementCodec); } else if (cqlType instanceof MapType && Map.class.isAssignableFrom(token.getRawType())) { DataType keyCqlType = ((MapType) cqlType).getKeyType(); @@ -602,6 +649,15 @@ protected TypeCodec createCodec( } else if (cqlType instanceof UserDefinedType && UdtValue.class.isAssignableFrom(token.getRawType())) { return TypeCodecs.udtOf((UserDefinedType) cqlType); + } else if (cqlType instanceof VectorType + && CqlVector.class.isAssignableFrom(token.getRawType())) { + VectorType vectorType = (VectorType) cqlType; + /* For a vector type we'll always get back an instance of TypeCodec due to the + * type of CqlVector... but getElementCodecForCqlAndJavaType() is a generalized function that can't + * return this more precise type. Thus the cast here. */ + TypeCodec elementCodec = + uncheckedCast(getElementCodecForCqlAndJavaType(vectorType, token, isJavaCovariant)); + return TypeCodecs.vectorOf(vectorType, elementCodec); } else if (cqlType instanceof CustomType && ByteBuffer.class.isAssignableFrom(token.getRawType())) { return TypeCodecs.custom(cqlType); @@ -617,15 +673,13 @@ protected TypeCodec createCodec(@NonNull GenericType javaType, boolean isJ TypeToken token = javaType.__getToken(); if (List.class.isAssignableFrom(token.getRawType()) && token.getType() instanceof ParameterizedType) { - Type[] typeArguments = ((ParameterizedType) token.getType()).getActualTypeArguments(); - GenericType elementType = GenericType.of(typeArguments[0]); - TypeCodec elementCodec = codecFor(elementType, isJavaCovariant); + TypeCodec elementCodec = + getElementCodecForJavaType((ParameterizedType) token.getType(), isJavaCovariant); return TypeCodecs.listOf(elementCodec); } else if (Set.class.isAssignableFrom(token.getRawType()) && token.getType() instanceof ParameterizedType) { - Type[] typeArguments = ((ParameterizedType) token.getType()).getActualTypeArguments(); - GenericType elementType = GenericType.of(typeArguments[0]); - TypeCodec elementCodec = codecFor(elementType, isJavaCovariant); + TypeCodec elementCodec = + getElementCodecForJavaType((ParameterizedType) token.getType(), isJavaCovariant); return TypeCodecs.setOf(elementCodec); } else if (Map.class.isAssignableFrom(token.getRawType()) && token.getType() instanceof ParameterizedType) { @@ -636,6 +690,9 @@ protected TypeCodec createCodec(@NonNull GenericType javaType, boolean isJ TypeCodec valueCodec = codecFor(valueType, isJavaCovariant); return TypeCodecs.mapOf(keyCodec, valueCodec); } + /* Note that this method cannot generate TypeCodec instances for any CqlVector type. VectorCodec needs + * to know the dimensions of the vector it will be operating on and there's no way to determine that from + * the Java type alone. */ throw new CodecNotFoundException(null, javaType); } @@ -657,6 +714,11 @@ protected TypeCodec createCodec(@NonNull DataType cqlType) { TypeCodec keyCodec = codecFor(keyType); TypeCodec valueCodec = codecFor(valueType); return TypeCodecs.mapOf(keyCodec, valueCodec); + } else if (cqlType instanceof VectorType) { + VectorType vectorType = (VectorType) cqlType; + TypeCodec elementCodec = + uncheckedCast(codecFor(vectorType.getElementType())); + return TypeCodecs.vectorOf(vectorType, elementCodec); } else if (cqlType instanceof TupleType) { return TypeCodecs.tupleOf((TupleType) cqlType); } else if (cqlType instanceof UserDefinedType) { @@ -692,8 +754,11 @@ private static TypeCodec uncheckedCast( GenericType.setOf(Boolean.class); private static final GenericType> JAVA_TYPE_FOR_EMPTY_MAPS = GenericType.mapOf(Boolean.class, Boolean.class); + private static final GenericType> JAVA_TYPE_FOR_EMPTY_CQLVECTORS = + GenericType.vectorOf(Number.class); private static final DataType CQL_TYPE_FOR_EMPTY_LISTS = DataTypes.listOf(DataTypes.BOOLEAN); private static final DataType CQL_TYPE_FOR_EMPTY_SETS = DataTypes.setOf(DataTypes.BOOLEAN); private static final DataType CQL_TYPE_FOR_EMPTY_MAPS = DataTypes.mapOf(DataTypes.BOOLEAN, DataTypes.BOOLEAN); + private static final DataType CQL_TYPE_FOR_EMPTY_VECTORS = DataTypes.vectorOf(DataTypes.INT, 0); } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/registry/CodecRegistryConstants.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/registry/CodecRegistryConstants.java index 075b72d6cbf..bbf77bdf5dc 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/registry/CodecRegistryConstants.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/registry/CodecRegistryConstants.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/registry/DefaultCodecRegistry.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/registry/DefaultCodecRegistry.java index 126059c4c7a..cc14740e180 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/registry/DefaultCodecRegistry.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/registry/DefaultCodecRegistry.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -157,7 +159,10 @@ public boolean equals(Object other) { @Override public int hashCode() { - return Objects.hash(cqlType, javaType, isJavaCovariant); + // NOTE: inlined Objects.hash for performance reasons (avoid Object[] allocation + // seen in profiler allocation traces) + return ((31 + Objects.hashCode(cqlType)) * 31 + Objects.hashCode(javaType)) * 31 + + Boolean.hashCode(isJavaCovariant); } } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/type/util/VIntCoding.java b/core/src/main/java/com/datastax/oss/driver/internal/core/type/util/VIntCoding.java index 918949a13fc..552f84f2ae1 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/type/util/VIntCoding.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/type/util/VIntCoding.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -47,6 +49,7 @@ import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; +import java.nio.ByteBuffer; /** * Variable length encoding inspired from Google > 6; } + + public static void writeUnsignedVInt32(int value, ByteBuffer output) { + writeUnsignedVInt((long) value, output); + } + + public static void writeUnsignedVInt(long value, ByteBuffer output) { + int size = VIntCoding.computeUnsignedVIntSize(value); + if (size == 1) { + output.put((byte) value); + return; + } + + output.put(VIntCoding.encodeVInt(value, size), 0, size); + } + + /** + * Read up to a 32-bit integer back, using the unsigned (no zigzag) encoding. + * + *

    Note this method is the same as {@link #readUnsignedVInt(DataInput)}, except that we do + * *not* block if there are not enough bytes in the buffer to reconstruct the value. + * + * @throws VIntOutOfRangeException If the vint doesn't fit into a 32-bit integer + */ + public static int getUnsignedVInt32(ByteBuffer input, int readerIndex) { + return checkedCast(getUnsignedVInt(input, readerIndex)); + } + + public static long getUnsignedVInt(ByteBuffer input, int readerIndex) { + return getUnsignedVInt(input, readerIndex, input.limit()); + } + + public static long getUnsignedVInt(ByteBuffer input, int readerIndex, int readerLimit) { + if (readerIndex < 0) + throw new IllegalArgumentException( + "Reader index should be non-negative, but was " + readerIndex); + + if (readerIndex >= readerLimit) return -1; + + int firstByte = input.get(readerIndex++); + + // Bail out early if this is one byte, necessary or it fails later + if (firstByte >= 0) return firstByte; + + int size = numberOfExtraBytesToRead(firstByte); + if (readerIndex + size > readerLimit) return -1; + + long retval = firstByte & firstByteValueMask(size); + for (int ii = 0; ii < size; ii++) { + byte b = input.get(readerIndex++); + retval <<= 8; + retval |= b & 0xff; + } + + return retval; + } + + public static int checkedCast(long value) { + int result = (int) value; + if ((long) result != value) throw new VIntOutOfRangeException(value); + return result; + } + + /** + * Throw when attempting to decode a vint and the output type doesn't have enough space to fit the + * value that was decoded + */ + public static class VIntOutOfRangeException extends RuntimeException { + public final long value; + + private VIntOutOfRangeException(long value) { + super(value + " is out of range for a 32-bit integer"); + this.value = value; + } + } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/AddressUtils.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/AddressUtils.java new file mode 100644 index 00000000000..8905edb9192 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/util/AddressUtils.java @@ -0,0 +1,59 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.util; + +import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableSet; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.UnknownHostException; +import java.util.HashSet; +import java.util.Set; + +public class AddressUtils { + + public static Set extract(String address, boolean resolve) { + int separator = address.lastIndexOf(':'); + if (separator < 0) { + throw new IllegalArgumentException("expecting format host:port"); + } + + String host = address.substring(0, separator); + String portString = address.substring(separator + 1); + int port; + try { + port = Integer.parseInt(portString); + } catch (NumberFormatException e) { + throw new IllegalArgumentException("expecting port to be a number, got " + portString, e); + } + if (!resolve) { + return ImmutableSet.of(InetSocketAddress.createUnresolved(host, port)); + } else { + InetAddress[] inetAddresses; + try { + inetAddresses = InetAddress.getAllByName(host); + } catch (UnknownHostException e) { + throw new RuntimeException(e); + } + Set result = new HashSet<>(); + for (InetAddress inetAddress : inetAddresses) { + result.add(new InetSocketAddress(inetAddress, port)); + } + return result; + } + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/ArrayUtils.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/ArrayUtils.java index 25597e190c9..490b1dc7d17 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/util/ArrayUtils.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/util/ArrayUtils.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,6 +18,7 @@ package com.datastax.oss.driver.internal.core.util; import edu.umd.cs.findbugs.annotations.NonNull; +import java.util.Random; import java.util.concurrent.ThreadLocalRandom; public class ArrayUtils { @@ -75,7 +78,7 @@ public static void shuffleHead(@NonNull ElementT[] elements, int n) { * Fisher-Yates shuffle */ public static void shuffleHead( - @NonNull ElementT[] elements, int n, @NonNull ThreadLocalRandom random) { + @NonNull ElementT[] elements, int n, @NonNull Random random) { if (n > elements.length) { throw new ArrayIndexOutOfBoundsException( String.format( diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/CollectionsUtils.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/CollectionsUtils.java index 2dcbdf866ba..0dd9a85fcc6 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/util/CollectionsUtils.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/util/CollectionsUtils.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/CountingIterator.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/CountingIterator.java index a65808e7b2a..391996d9369 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/util/CountingIterator.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/util/CountingIterator.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/DefaultDependencyChecker.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/DefaultDependencyChecker.java new file mode 100644 index 00000000000..2e717590569 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/util/DefaultDependencyChecker.java @@ -0,0 +1,61 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.util; + +import java.util.concurrent.ConcurrentHashMap; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A checker for the presence of various {@link Dependency} instances at runtime. Predicate tests + * for Graal substitutions should NOT use this class; see {@link GraalDependencyChecker} for more + * information. + */ +public class DefaultDependencyChecker { + + private static final Logger LOG = LoggerFactory.getLogger(DefaultDependencyChecker.class); + + private static final ConcurrentHashMap CACHE = new ConcurrentHashMap<>(); + + /** + * Return true iff we can find all classes for the dependency on the classpath, false otherwise + * + * @param dependency the dependency to search for + * @return true if the dependency is available, false otherwise + */ + public static boolean isPresent(Dependency dependency) { + try { + return CACHE.computeIfAbsent( + dependency, + (dep) -> { + for (String classNameToTest : dependency.classes()) { + // Always use the driver class loader, assuming that the driver classes and + // the dependency classes are either being loaded by the same class loader, + // or – as in OSGi deployments – by two distinct, but compatible class loaders. + if (Reflection.loadClass(null, classNameToTest) == null) { + return false; + } + } + return true; + }); + } catch (Exception e) { + LOG.warn("Unexpected exception when checking for dependency " + dependency, e); + return false; + } + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/Dependency.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/Dependency.java new file mode 100644 index 00000000000..97cfa25d9af --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/util/Dependency.java @@ -0,0 +1,64 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.util; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +/** + * A set of driver optional dependencies and a common mechanism to test the presence of such + * dependencies on the application's classpath. + * + *

    We use the given fully-qualified names of classes to test the presence of the whole dependency + * on the classpath, including its transitive dependencies if applicable. This assumes that if these + * classes are present, then the entire library is present and functional, and vice versa. + * + *

    Note: some of the libraries declared here may be shaded; in these cases the shade plugin will + * replace the package names listed above with names starting with {@code + * com.datastax.oss.driver.shaded.*}, but the presence check would still work as expected. + */ +public enum Dependency { + SNAPPY("org.xerial.snappy.Snappy"), + LZ4("net.jpountz.lz4.LZ4Compressor"), + ESRI("com.esri.core.geometry.ogc.OGCGeometry"), + TINKERPOP( + // gremlin-core + "org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal", + // tinkergraph-gremlin + "org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV3d0"), + REACTIVE_STREAMS("org.reactivestreams.Publisher"), + JACKSON( + // jackson-core + "com.fasterxml.jackson.core.JsonParser", + // jackson-databind + "com.fasterxml.jackson.databind.ObjectMapper"), + DROPWIZARD("com.codahale.metrics.MetricRegistry"), + ; + + @SuppressWarnings("ImmutableEnumChecker") + private final List clzs; + + Dependency(String... classNames) { + clzs = Collections.unmodifiableList(Arrays.asList(classNames)); + } + + public Iterable classes() { + return this.clzs; + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/DependencyCheck.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/DependencyCheck.java deleted file mode 100644 index 1f3b6ae4480..00000000000 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/util/DependencyCheck.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.datastax.oss.driver.internal.core.util; - -import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableSet; - -/** - * A set of driver optional dependencies and a common mechanism to test the presence of such - * dependencies on the application's classpath. - */ -public enum DependencyCheck { - SNAPPY("org.xerial.snappy.Snappy"), - LZ4("net.jpountz.lz4.LZ4Compressor"), - ESRI("com.esri.core.geometry.ogc.OGCGeometry"), - TINKERPOP( - // gremlin-core - "org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal", - // tinkergraph-gremlin - "org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV3d0"), - REACTIVE_STREAMS("org.reactivestreams.Publisher"), - JACKSON( - // jackson-core - "com.fasterxml.jackson.core.JsonParser", - // jackson-databind - "com.fasterxml.jackson.databind.ObjectMapper"), - ; - - /** - * The fully-qualified name of classes that must exist for the dependency to work properly; we use - * them to test the presence of the whole dependency on the classpath, including its transitive - * dependencies if applicable. This assumes that if these classes are present, then the entire - * library is present and functional, and vice versa. - * - *

    Note: some of the libraries declared here may be shaded; in these cases the shade plugin - * will replace the package names listed above with names starting with {@code - * com.datastax.oss.driver.shaded.*}, but the presence check would still work as expected. - */ - @SuppressWarnings("ImmutableEnumChecker") - private final ImmutableSet fqcns; - - DependencyCheck(String... fqcns) { - this.fqcns = ImmutableSet.copyOf(fqcns); - } - - /** - * Checks if the dependency is present on the application's classpath and is loadable. - * - * @return true if the dependency is present and loadable, false otherwise. - */ - public boolean isPresent() { - for (String fqcn : fqcns) { - // Always use the driver class loader, assuming that the driver classes and - // the dependency classes are either being loaded by the same class loader, - // or – as in OSGi deployments – by two distinct, but compatible class loaders. - if (Reflection.loadClass(null, fqcn) == null) { - return false; - } - } - return true; - } -} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/DirectedGraph.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/DirectedGraph.java index 6f75d759451..b9ab863cb88 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/util/DirectedGraph.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/util/DirectedGraph.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/GraalDependencyChecker.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/GraalDependencyChecker.java new file mode 100644 index 00000000000..c80970eb3b6 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/util/GraalDependencyChecker.java @@ -0,0 +1,62 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.util; + +import java.util.concurrent.ConcurrentHashMap; + +/** + * A dependency checker implementation which should be safe to use for build-time checks when + * building Graal native images. This class is similar to {@link DefaultDependencyChecker} but + * doesn't introduce any external dependencies which might complicate the native image build + * process. Expectation is that this will be most prominently used in the various predicate classes + * which determine whether or not Graal substitutions should be used. + */ +public class GraalDependencyChecker { + + private static final ConcurrentHashMap CACHE = new ConcurrentHashMap<>(); + + /** + * Return true iff we can find all classes for the dependency on the classpath, false otherwise + * + * @param dependency the dependency to search for + * @return true if the dependency is available, false otherwise + */ + public static boolean isPresent(Dependency dependency) { + try { + return CACHE.computeIfAbsent( + dependency, + (dep) -> { + for (String classNameToTest : dependency.classes()) { + // Note that this lands in a pretty similar spot to + // Reflection.loadClass() with a null class loader + // arg. Major difference here is that we avoid the + // more complex exception handling/logging ops in + // that code. + try { + Class.forName(classNameToTest); + } catch (LinkageError | Exception e) { + return false; + } + } + return true; + }); + } catch (Exception e) { + return false; + } + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/Loggers.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/Loggers.java index 0d9d9ab0602..99dca2c60c0 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/util/Loggers.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/util/Loggers.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/NanoTime.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/NanoTime.java index 9f4ec8bc978..0001bc9925c 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/util/NanoTime.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/util/NanoTime.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/ProtocolUtils.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/ProtocolUtils.java index 06b47479eee..f653ea6f5f9 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/util/ProtocolUtils.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/util/ProtocolUtils.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -95,6 +97,10 @@ public static String errorCodeString(int errorCode) { return "FUNCTION_FAILURE"; case ProtocolConstants.ErrorCode.WRITE_FAILURE: return "WRITE_FAILURE"; + case ProtocolConstants.ErrorCode.CDC_WRITE_FAILURE: + return "CDC_WRITE_FAILURE"; + case ProtocolConstants.ErrorCode.CAS_WRITE_UNKNOWN: + return "CAS_WRITE_UNKNOWN"; case ProtocolConstants.ErrorCode.SYNTAX_ERROR: return "SYNTAX_ERROR"; case ProtocolConstants.ErrorCode.UNAUTHORIZED: diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/Reflection.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/Reflection.java index 9526a144536..75a8f5b7380 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/util/Reflection.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/util/Reflection.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -21,6 +23,7 @@ import com.datastax.oss.driver.internal.core.context.InternalDriverContext; import com.datastax.oss.driver.shaded.guava.common.base.Joiner; import com.datastax.oss.driver.shaded.guava.common.base.Preconditions; +import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableList; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap; import com.datastax.oss.driver.shaded.guava.common.collect.ListMultimap; import com.datastax.oss.driver.shaded.guava.common.collect.MultimapBuilder; @@ -29,6 +32,7 @@ import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Collection; +import java.util.List; import java.util.Map; import java.util.Optional; import org.slf4j.Logger; @@ -108,6 +112,36 @@ public static Optional buildFromConfig( return buildFromConfig(context, null, classNameOption, expectedSuperType, defaultPackages); } + /** + * Tries to create a list of instances, given an option defined in the driver configuration. + * + *

    For example: + * + *

    +   * my-policy.classes = [my.package.MyPolicyImpl1,my.package.MyPolicyImpl2]
    +   * 
    + * + * Each class will be instantiated via reflection, and must have a constructor that takes a {@link + * DriverContext} argument. + * + * @param context the driver context. + * @param classNamesOption the option that indicates the class list. It will be looked up in the + * default profile of the configuration stored in the context. + * @param expectedSuperType a super-type that the classes are expected to implement/extend. + * @param defaultPackages the default packages to prepend to the class names if they are not + * qualified. They will be tried in order, the first one that matches an existing class will + * be used. + * @return the list of new instances, or an empty list if {@code classNamesOption} is not defined + * in the configuration. + */ + public static ImmutableList buildFromConfigList( + InternalDriverContext context, + DriverOption classNamesOption, + Class expectedSuperType, + String... defaultPackages) { + return buildFromConfigList(context, null, classNamesOption, expectedSuperType, defaultPackages); + } + /** * Tries to create multiple instances of a class, given options defined in the driver * configuration and possibly overridden in profiles. @@ -199,6 +233,57 @@ public static Optional buildFromConfig( } String className = config.getString(classNameOption); + return Optional.of( + resolveClass( + context, profileName, expectedSuperType, configPath, className, defaultPackages)); + } + + /** + * @param profileName if null, this is a global policy, use the default profile and look for a + * one-arg constructor. If not null, this is a per-profile policy, look for a two-arg + * constructor. + */ + public static ImmutableList buildFromConfigList( + InternalDriverContext context, + String profileName, + DriverOption classNamesOption, + Class expectedSuperType, + String... defaultPackages) { + + DriverExecutionProfile config = + (profileName == null) + ? context.getConfig().getDefaultProfile() + : context.getConfig().getProfile(profileName); + + String configPath = classNamesOption.getPath(); + LOG.debug( + "Creating a list of {} from config option {}", + expectedSuperType.getSimpleName(), + configPath); + + if (!config.isDefined(classNamesOption)) { + LOG.debug("Option is not defined, skipping"); + return ImmutableList.of(); + } + + List classNames = config.getStringList(classNamesOption); + ImmutableList.Builder components = ImmutableList.builder(); + for (String className : classNames) { + components.add( + resolveClass( + context, profileName, expectedSuperType, configPath, className, defaultPackages)); + } + return components.build(); + } + + @NonNull + private static ComponentT resolveClass( + InternalDriverContext context, + String profileName, + Class expectedSuperType, + String configPath, + String className, + String[] defaultPackages) { Class clazz = null; if (className.contains(".")) { LOG.debug("Building from fully-qualified name {}", className); @@ -245,7 +330,7 @@ public static Optional buildFromConfig( (profileName == null) ? constructor.newInstance(context) : constructor.newInstance(context, profileName); - return Optional.of(instance); + return instance; } catch (Exception e) { // ITE just wraps an exception thrown by the constructor, get rid of it: Throwable cause = (e instanceof InvocationTargetException) ? e.getCause() : e; diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/RoutingKey.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/RoutingKey.java index fc1ef249edd..7d8895d228f 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/util/RoutingKey.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/util/RoutingKey.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/Sizes.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/Sizes.java index 6ab1cbe10ac..337895ec107 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/util/Sizes.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/util/Sizes.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/Strings.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/Strings.java index eb95d2cbc18..2e85b451c75 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/util/Strings.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/util/Strings.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -15,7 +17,10 @@ */ package com.datastax.oss.driver.internal.core.util; +import com.datastax.oss.driver.shaded.guava.common.annotations.VisibleForTesting; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableSet; +import java.util.Locale; +import java.util.Objects; public class Strings { @@ -230,8 +235,9 @@ private static String unquote(String text, char quoteChar) { return new String(result); } - private static boolean isReservedCqlKeyword(String id) { - return id != null && RESERVED_KEYWORDS.contains(id.toLowerCase()); + @VisibleForTesting + static boolean isReservedCqlKeyword(String id) { + return id != null && RESERVED_KEYWORDS.contains(id.toLowerCase(Locale.ROOT)); } /** @@ -252,6 +258,21 @@ public static boolean isLongLiteral(String str) { return true; } + /** + * Checks whether the given text is not null and not empty. + * + * @param text The text to check. + * @param name The name of the argument. + * @return The text (for method chaining). + */ + public static String requireNotEmpty(String text, String name) { + Objects.requireNonNull(text, name + " cannot be null"); + if (text.isEmpty()) { + throw new IllegalArgumentException(name + " cannot be empty"); + } + return text; + } + private Strings() {} private static final ImmutableSet RESERVED_KEYWORDS = diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/collection/CompositeQueryPlan.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/collection/CompositeQueryPlan.java new file mode 100644 index 00000000000..10ca8c0c48d --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/util/collection/CompositeQueryPlan.java @@ -0,0 +1,88 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.util.collection; + +import com.datastax.oss.driver.api.core.metadata.Node; +import com.datastax.oss.driver.shaded.guava.common.collect.Iterators; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.Nullable; +import java.util.AbstractQueue; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Queue; +import java.util.concurrent.atomic.AtomicInteger; +import net.jcip.annotations.ThreadSafe; + +/** A query plan that encompasses many child plans, and consumes them one by one. */ +@ThreadSafe +public class CompositeQueryPlan extends AbstractQueue implements QueryPlan { + + private final Queue[] plans; + private final AtomicInteger currentPlan = new AtomicInteger(0); + + @SafeVarargs + public CompositeQueryPlan(@NonNull Queue... plans) { + if (plans.length == 0) { + throw new IllegalArgumentException("at least one child plan must be provided"); + } + for (Queue plan : plans) { + if (plan == null) { + throw new NullPointerException("child plan cannot be null"); + } + } + this.plans = plans; + } + + @Nullable + @Override + public Node poll() { + while (true) { + int current = currentPlan.get(); + Queue plan = plans[current]; + Node n = plan.poll(); + if (n != null) { + return n; + } + int next = current + 1; + if (next == plans.length) { + return null; + } + currentPlan.compareAndSet(current, next); + } + } + + @NonNull + @Override + public Iterator iterator() { + List> its = new ArrayList<>(plans.length); + for (Queue plan : plans) { + its.add(plan.iterator()); + } + return Iterators.concat(its.iterator()); + } + + @Override + public int size() { + int size = 0; + for (Queue plan : plans) { + size += plan.size(); + } + return size; + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/collection/EmptyQueryPlan.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/collection/EmptyQueryPlan.java new file mode 100644 index 00000000000..53177147695 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/util/collection/EmptyQueryPlan.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.util.collection; + +import com.datastax.oss.driver.api.core.metadata.Node; +import edu.umd.cs.findbugs.annotations.NonNull; +import java.util.AbstractQueue; +import java.util.Collections; +import java.util.Iterator; +import net.jcip.annotations.ThreadSafe; + +@ThreadSafe +class EmptyQueryPlan extends AbstractQueue implements QueryPlan { + + @Override + public Node poll() { + return null; + } + + @NonNull + @Override + public Iterator iterator() { + return Collections.emptyIterator(); + } + + @Override + public int size() { + return 0; + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/collection/LazyQueryPlan.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/collection/LazyQueryPlan.java new file mode 100644 index 00000000000..075143c2e8d --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/util/collection/LazyQueryPlan.java @@ -0,0 +1,58 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.util.collection; + +import com.datastax.oss.driver.api.core.metadata.Node; +import net.jcip.annotations.ThreadSafe; + +/** + * A query plan where nodes are computed lazily, when the plan is consumed for the first time. + * + *

    This class can be useful when a query plan computation is heavy but the plan has a low chance + * of ever being consumed, e.g. the last query plan in a {@link CompositeQueryPlan}. + */ +@ThreadSafe +public abstract class LazyQueryPlan extends QueryPlanBase { + + private volatile Object[] nodes; + + /** + * Computes and returns the nodes to use for this query plan. + * + *

    For efficiency, the declared return type is {@code Object[]} but all elements must be + * instances of {@link Node}. See {@link #getNodes()} for details. + * + *

    This method is guaranteed to be invoked only once, at the first call to {@link #poll()}. + * + *

    Implementors must avoid blocking calls in this method as it will be invoked on the driver's + * hot path. + */ + protected abstract Object[] computeNodes(); + + @Override + protected Object[] getNodes() { + if (nodes == null) { + synchronized (this) { + if (nodes == null) { + nodes = computeNodes(); + } + } + } + return nodes; + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/collection/QueryPlan.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/collection/QueryPlan.java index dfe2a45757f..371e100a0e2 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/util/collection/QueryPlan.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/util/collection/QueryPlan.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -15,98 +17,76 @@ */ package com.datastax.oss.driver.internal.core.util.collection; -import com.datastax.oss.driver.api.core.loadbalancing.LoadBalancingPolicy; import com.datastax.oss.driver.api.core.metadata.Node; import com.datastax.oss.driver.api.core.session.Request; import com.datastax.oss.driver.api.core.session.Session; -import com.datastax.oss.driver.internal.core.loadbalancing.DefaultLoadBalancingPolicy; -import com.datastax.oss.driver.shaded.guava.common.collect.Iterators; import edu.umd.cs.findbugs.annotations.NonNull; -import edu.umd.cs.findbugs.annotations.Nullable; -import java.util.AbstractCollection; -import java.util.Arrays; -import java.util.Collections; import java.util.Iterator; import java.util.Queue; -import java.util.concurrent.atomic.AtomicInteger; import net.jcip.annotations.ThreadSafe; /** - * A specialized, thread-safe queue implementation for {@link - * LoadBalancingPolicy#newQueryPlan(Request, Session)}. + * A specialized, thread-safe node queue for use when creating {@linkplain + * com.datastax.oss.driver.api.core.loadbalancing.LoadBalancingPolicy#newQueryPlan(Request, Session) + * query plans}. + * + *

    This interface and its built-in implementations are not general-purpose queues; they are + * tailored for the specific use case of creating query plans in the driver. They make a few + * unconventional API choices for the sake of performance. + * + *

    Furthermore, the driver only consumes query plans through calls to its {@link #poll()} method; + * therefore, this method is the only valid mutation operation for a query plan, other mutating + * methods throw. + * + *

    Both {@link #size()} and {@link #iterator()} are supported and never throw, even if called + * concurrently. These methods are implemented for reporting purposes only, the driver itself does + * not use them. * - *

    All nodes must be provided at construction time. After that, the only valid mutation operation - * is {@link #poll()}, other methods throw. + *

    All built-in {@link QueryPlan} implementations can be safely reused for custom load balancing + * policies; if you plan to do so, study the source code of {@link + * com.datastax.oss.driver.internal.core.loadbalancing.DefaultLoadBalancingPolicy} or {@link + * com.datastax.oss.driver.internal.core.loadbalancing.BasicLoadBalancingPolicy}. * - *

    This class is not a general-purpose implementation, it is tailored for a specific use case in - * the driver. It makes a few unconventional API choices for the sake of performance (see {@link - * #QueryPlan(Object...)}. It can be reused for custom load balancing policies; if you plan to do - * so, study the source code of {@link DefaultLoadBalancingPolicy}. + * @see QueryPlanBase */ @ThreadSafe -public class QueryPlan extends AbstractCollection implements Queue { +public interface QueryPlan extends Queue { - private final Object[] nodes; - private final AtomicInteger nextIndex = new AtomicInteger(); - - /** - * @param nodes the nodes to initially fill the queue with. For efficiency, there is no defensive - * copy, the provided array is used directly. The declared type is {@code Object[]} because of - * implementation details of {@link DefaultLoadBalancingPolicy}, but all elements must be - * instances of {@link Node}, otherwise instance methods will fail later. - */ - public QueryPlan(@NonNull Object... nodes) { - this.nodes = nodes; - } - - @Nullable - @Override - public Node poll() { - // We don't handle overflow. In practice it won't be an issue, since the driver stops polling - // once the query plan is empty. - int i = nextIndex.getAndIncrement(); - return (i >= nodes.length) ? null : (Node) nodes[i]; - } + QueryPlan EMPTY = new EmptyQueryPlan(); /** * {@inheritDoc} * - *

    The returned iterator reflects the state of the queue at the time of the call, and is not - * affected by further modifications. + *

    Implementation note: query plan iterators are snapshots that reflect the contents of the + * queue at the time of the call, and are not affected by further modifications. Successive calls + * to this method will return different objects. */ @NonNull @Override - public Iterator iterator() { - int i = nextIndex.get(); - if (i >= nodes.length) { - return Collections.emptyList().iterator(); - } else { - return Iterators.forArray(Arrays.copyOfRange(nodes, i, nodes.length, Node[].class)); - } - } + Iterator iterator(); @Override - public int size() { - return Math.max(nodes.length - nextIndex.get(), 0); + default boolean offer(Node node) { + throw new UnsupportedOperationException("Not implemented"); } @Override - public boolean offer(Node node) { + default Node peek() { throw new UnsupportedOperationException("Not implemented"); } @Override - public Node remove() { + default boolean add(Node node) { throw new UnsupportedOperationException("Not implemented"); } @Override - public Node element() { + default Node remove() { throw new UnsupportedOperationException("Not implemented"); } @Override - public Node peek() { + default Node element() { throw new UnsupportedOperationException("Not implemented"); } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/collection/QueryPlanBase.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/collection/QueryPlanBase.java new file mode 100644 index 00000000000..43f369f636a --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/util/collection/QueryPlanBase.java @@ -0,0 +1,75 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.util.collection; + +import com.datastax.oss.driver.api.core.metadata.Node; +import com.datastax.oss.driver.shaded.guava.common.collect.Iterators; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.Nullable; +import java.util.AbstractQueue; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.concurrent.atomic.AtomicInteger; +import net.jcip.annotations.ThreadSafe; + +@ThreadSafe +public abstract class QueryPlanBase extends AbstractQueue implements QueryPlan { + + private final AtomicInteger nextIndex = new AtomicInteger(); + + /** + * Returns the nodes in this query plan; the returned array should stay the same across + * invocations. + * + *

    The declared return type is {@code Object[]} because of implementation details of {@link + * com.datastax.oss.driver.internal.core.loadbalancing.DefaultLoadBalancingPolicy + * DefaultLoadBalancingPolicy} and {@link + * com.datastax.oss.driver.internal.core.loadbalancing.BasicLoadBalancingPolicy + * BasicLoadBalancingPolicy}, but all elements must be instances of {@link Node}, otherwise + * instance methods will fail later. + */ + protected abstract Object[] getNodes(); + + @Nullable + @Override + public Node poll() { + // We don't handle overflow. In practice it won't be an issue, since the driver stops polling + // once the query plan is empty. + int i = nextIndex.getAndIncrement(); + Object[] nodes = getNodes(); + return (i >= nodes.length) ? null : (Node) nodes[i]; + } + + @NonNull + @Override + public Iterator iterator() { + int i = nextIndex.get(); + Object[] nodes = getNodes(); + if (i >= nodes.length) { + return Collections.emptyIterator(); + } else { + return Iterators.forArray(Arrays.copyOfRange(nodes, i, nodes.length, Node[].class)); + } + } + + @Override + public int size() { + return Math.max(getNodes().length - nextIndex.get(), 0); + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/collection/SimpleQueryPlan.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/collection/SimpleQueryPlan.java new file mode 100644 index 00000000000..4e0df8d2354 --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/util/collection/SimpleQueryPlan.java @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.util.collection; + +import com.datastax.oss.driver.api.core.metadata.Node; +import edu.umd.cs.findbugs.annotations.NonNull; +import net.jcip.annotations.ThreadSafe; + +/** Query plan where nodes must be provided at construction time. */ +@ThreadSafe +public class SimpleQueryPlan extends QueryPlanBase { + + private final Object[] nodes; + + /** + * Creates a new query plan with the given nodes. + * + *

    For efficiency, there is no defensive copy, the provided array is used directly. The + * declared type is {@code Object[]} but all elements must be instances of {@link Node}. See + * {@link #getNodes()} for details. + * + * @param nodes the nodes to initially fill the queue with. + */ + public SimpleQueryPlan(@NonNull Object... nodes) { + this.nodes = nodes; + } + + @Override + protected Object[] getNodes() { + return nodes; + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/BlockingOperation.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/BlockingOperation.java index 7797594b7b9..3f2d10b62e0 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/BlockingOperation.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/BlockingOperation.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -59,7 +61,7 @@ public Thread newThread(@NonNull Runnable r) { } } - private static class InternalThread extends FastThreadLocalThread { + static class InternalThread extends FastThreadLocalThread { private InternalThread(Runnable runnable) { super(runnable); } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/CompletableFutures.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/CompletableFutures.java index bd3973ddfd9..275b2ddfeef 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/CompletableFutures.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/CompletableFutures.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -98,7 +100,10 @@ public static CompletionStage allSuccessful(List> i } else { Throwable finalError = errors.get(0); for (int i = 1; i < errors.size(); i++) { - finalError.addSuppressed(errors.get(i)); + Throwable suppressedError = errors.get(i); + if (finalError != suppressedError) { + finalError.addSuppressed(suppressedError); + } } result.completeExceptionally(finalError); } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/CycleDetector.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/CycleDetector.java index 25fb3a4f8d8..548ee0bb042 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/CycleDetector.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/CycleDetector.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/Debouncer.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/Debouncer.java index ded770a3d48..6bde155858c 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/Debouncer.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/Debouncer.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -44,6 +46,7 @@ public class Debouncer { private static final Logger LOG = LoggerFactory.getLogger(Debouncer.class); + private final String logPrefix; private final EventExecutor adminExecutor; private final Consumer onFlush; private final Duration window; @@ -69,6 +72,27 @@ public Debouncer( Consumer onFlush, Duration window, long maxEvents) { + this("debouncer", adminExecutor, coalescer, onFlush, window, maxEvents); + } + + /** + * Creates a new instance. + * + * @param logPrefix the log prefix to use in log messages. + * @param adminExecutor the executor that will be used to schedule all tasks. + * @param coalescer how to transform a batch of events into a result. + * @param onFlush what to do with a result. + * @param window the time window. + * @param maxEvents the maximum number of accumulated events before a flush is forced. + */ + public Debouncer( + String logPrefix, + EventExecutor adminExecutor, + Function, CoalescedT> coalescer, + Consumer onFlush, + Duration window, + long maxEvents) { + this.logPrefix = logPrefix; this.coalescer = coalescer; Preconditions.checkArgument(maxEvents >= 1, "maxEvents should be at least 1"); this.adminExecutor = adminExecutor; @@ -85,7 +109,8 @@ public void receive(IncomingT element) { } if (window.isZero() || maxEvents == 1) { LOG.debug( - "Received {}, flushing immediately (window = {}, maxEvents = {})", + "[{}] Received {}, flushing immediately (window = {}, maxEvents = {})", + logPrefix, element, window, maxEvents); @@ -94,12 +119,13 @@ public void receive(IncomingT element) { currentBatch.add(element); if (currentBatch.size() == maxEvents) { LOG.debug( - "Received {}, flushing immediately (because {} accumulated events)", + "[{}] Received {}, flushing immediately (because {} accumulated events)", + logPrefix, element, maxEvents); flushNow(); } else { - LOG.debug("Received {}, scheduling next flush in {}", element, window); + LOG.debug("[{}] Received {}, scheduling next flush in {}", logPrefix, element, window); scheduleFlush(); } } @@ -107,7 +133,7 @@ public void receive(IncomingT element) { public void flushNow() { assert adminExecutor.inEventLoop(); - LOG.debug("Flushing now"); + LOG.debug("[{}] Flushing now", logPrefix); cancelNextFlush(); if (!currentBatch.isEmpty()) { onFlush.accept(coalescer.apply(currentBatch)); @@ -127,7 +153,7 @@ private void cancelNextFlush() { if (nextFlush != null && !nextFlush.isDone()) { boolean cancelled = nextFlush.cancel(true); if (cancelled) { - LOG.debug("Cancelled existing scheduled flush"); + LOG.debug("[{}] Cancelled existing scheduled flush", logPrefix); } } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/DriverBlockHoundIntegration.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/DriverBlockHoundIntegration.java new file mode 100644 index 00000000000..7d90c50028e --- /dev/null +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/DriverBlockHoundIntegration.java @@ -0,0 +1,111 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.util.concurrent; + +import com.datastax.oss.driver.internal.core.util.concurrent.BlockingOperation.InternalThread; +import reactor.blockhound.BlockHound; +import reactor.blockhound.integration.BlockHoundIntegration; + +public final class DriverBlockHoundIntegration implements BlockHoundIntegration { + + @Override + public void applyTo(BlockHound.Builder builder) { + + // disallow blocking operations in driver internal threads by default; + // note that session initialization will happen on one of these threads, which is why + // we need to allow a few blocking calls below. + builder.nonBlockingThreadPredicate(current -> current.or(InternalThread.class::isInstance)); + + // blocking calls in initialization methods + + builder.allowBlockingCallsInside( + "com.datastax.oss.driver.internal.core.context.DefaultNettyOptions", "createTimer"); + builder.allowBlockingCallsInside( + "com.datastax.oss.driver.internal.core.os.Native$LibcLoader", "load"); + builder.allowBlockingCallsInside( + // requires native libraries + "com.datastax.oss.driver.internal.core.time.Clock", "getInstance"); + builder.allowBlockingCallsInside( + "com.datastax.oss.driver.internal.core.util.concurrent.LazyReference", "get"); + builder.allowBlockingCallsInside( + "com.datastax.oss.driver.internal.core.util.concurrent.ReplayingEventFilter", "accept"); + builder.allowBlockingCallsInside( + "com.datastax.oss.driver.internal.core.util.concurrent.ReplayingEventFilter", "markReady"); + builder.allowBlockingCallsInside( + "com.datastax.oss.driver.internal.core.util.concurrent.ReplayingEventFilter", "start"); + + // called upon initialization but also on topology/status events + + builder.allowBlockingCallsInside( + "com.datastax.oss.driver.internal.core.metadata.LoadBalancingPolicyWrapper$SinglePolicyDistanceReporter", + "setDistance"); + builder.allowBlockingCallsInside( + "com.datastax.oss.driver.internal.core.pool.ChannelSet", "add"); + builder.allowBlockingCallsInside( + "com.datastax.oss.driver.internal.core.pool.ChannelSet", "remove"); + + // never called directly by the driver; locks that usually operate with low thread contention + + builder.allowBlockingCallsInside( + "com.datastax.oss.driver.internal.core.type.codec.registry.CachingCodecRegistry", + "register"); + builder.allowBlockingCallsInside( + // requires native libraries, for now because of Uuids.getProcessPiece; if JAVA-1116 gets + // implemented, Uuids.getCurrentTimestamp will also require an exception. Pre-emptively + // protect the whole Uuids.timeBased method. + "com.datastax.oss.driver.api.core.uuid.Uuids", "timeBased"); + + // continuous paging + + builder.allowBlockingCallsInside( + "com.datastax.dse.driver.internal.core.cql.continuous.ContinuousRequestHandlerBase$NodeResponseCallback", + "cancel"); + builder.allowBlockingCallsInside( + "com.datastax.dse.driver.internal.core.cql.continuous.ContinuousRequestHandlerBase$NodeResponseCallback", + "dequeueOrCreatePending"); + builder.allowBlockingCallsInside( + "com.datastax.dse.driver.internal.core.cql.continuous.ContinuousRequestHandlerBase$NodeResponseCallback", + "isLastResponse"); + builder.allowBlockingCallsInside( + "com.datastax.dse.driver.internal.core.cql.continuous.ContinuousRequestHandlerBase$NodeResponseCallback", + "onFailure"); + builder.allowBlockingCallsInside( + "com.datastax.dse.driver.internal.core.cql.continuous.ContinuousRequestHandlerBase$NodeResponseCallback", + "onPageTimeout"); + builder.allowBlockingCallsInside( + "com.datastax.dse.driver.internal.core.cql.continuous.ContinuousRequestHandlerBase$NodeResponseCallback", + "onResponse"); + builder.allowBlockingCallsInside( + "com.datastax.dse.driver.internal.core.cql.continuous.ContinuousRequestHandlerBase$NodeResponseCallback", + "onStreamIdAssigned"); + builder.allowBlockingCallsInside( + "com.datastax.dse.driver.internal.core.cql.continuous.ContinuousRequestHandlerBase$NodeResponseCallback", + "operationComplete"); + + // Netty extra exceptions + + // see https://github.com/netty/netty/pull/10810 + builder.allowBlockingCallsInside("io.netty.util.HashedWheelTimer", "start"); + builder.allowBlockingCallsInside("io.netty.util.HashedWheelTimer", "stop"); + + // see https://github.com/netty/netty/pull/10811 + builder.allowBlockingCallsInside("io.netty.util.concurrent.GlobalEventExecutor", "addTask"); + builder.allowBlockingCallsInside( + "io.netty.util.concurrent.SingleThreadEventExecutor", "addTask"); + } +} diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/LazyReference.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/LazyReference.java index b1d34dda6ea..e04b7647d8e 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/LazyReference.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/LazyReference.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -27,7 +29,7 @@ public class LazyReference { private final Supplier supplier; private final CycleDetector checker; private volatile T value; - private ReentrantLock lock = new ReentrantLock(); + private final ReentrantLock lock = new ReentrantLock(); public LazyReference(String name, Supplier supplier, CycleDetector cycleDetector) { this.name = name; diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/PromiseCombiner.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/PromiseCombiner.java index dd166551631..b854820403d 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/PromiseCombiner.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/PromiseCombiner.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/Reconnection.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/Reconnection.java index d40265bd09a..28aaf596705 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/Reconnection.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/Reconnection.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/ReplayingEventFilter.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/ReplayingEventFilter.java index 5d6fd62918a..27ca1b6ff42 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/ReplayingEventFilter.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/ReplayingEventFilter.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -55,7 +57,7 @@ private enum State { private State state; @GuardedBy("stateLock") - private List recordedEvents; + private final List recordedEvents; public ReplayingEventFilter(Consumer consumer) { this.consumer = consumer; @@ -80,6 +82,7 @@ public void markReady() { consumer.accept(event); } } finally { + recordedEvents.clear(); stateLock.writeLock().unlock(); } } diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/RunOrSchedule.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/RunOrSchedule.java index daf2809b794..addaf1850bf 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/RunOrSchedule.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/RunOrSchedule.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/UncaughtExceptions.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/UncaughtExceptions.java index 1fc9060b710..25bce8773e8 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/UncaughtExceptions.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/UncaughtExceptions.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/core/util/package-info.java b/core/src/main/java/com/datastax/oss/driver/internal/core/util/package-info.java index 17aae22cc7b..bd0e2590b47 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/core/util/package-info.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/core/util/package-info.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/java/com/datastax/oss/driver/internal/package-info.java b/core/src/main/java/com/datastax/oss/driver/internal/package-info.java index 1a4aa15c8bd..486afc446e3 100644 --- a/core/src/main/java/com/datastax/oss/driver/internal/package-info.java +++ b/core/src/main/java/com/datastax/oss/driver/internal/package-info.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/main/resources/META-INF/native-image/com.datastax.oss/java-driver-core/native-image.properties b/core/src/main/resources/META-INF/native-image/com.datastax.oss/java-driver-core/native-image.properties new file mode 100644 index 00000000000..2baa59f3b07 --- /dev/null +++ b/core/src/main/resources/META-INF/native-image/com.datastax.oss/java-driver-core/native-image.properties @@ -0,0 +1,25 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +Args=-H:IncludeResources=reference\\.conf \ + -H:IncludeResources=application\\.conf \ + -H:IncludeResources=application\\.json \ + -H:IncludeResources=application\\.properties \ + -H:IncludeResources=.*Driver\\.properties \ + -H:DynamicProxyConfigurationResources=${.}/proxy.json \ + -H:ReflectionConfigurationResources=${.}/reflection.json \ + --initialize-at-build-time=com.datastax.oss.driver.internal.core.util.Dependency diff --git a/core/src/main/resources/META-INF/native-image/com.datastax.oss/java-driver-core/proxy.json b/core/src/main/resources/META-INF/native-image/com.datastax.oss/java-driver-core/proxy.json new file mode 100644 index 00000000000..37cf6fcf805 --- /dev/null +++ b/core/src/main/resources/META-INF/native-image/com.datastax.oss/java-driver-core/proxy.json @@ -0,0 +1,3 @@ +[ + ["java.lang.reflect.TypeVariable"] +] diff --git a/core/src/main/resources/META-INF/native-image/com.datastax.oss/java-driver-core/reflection.json b/core/src/main/resources/META-INF/native-image/com.datastax.oss/java-driver-core/reflection.json new file mode 100644 index 00000000000..6082b853611 --- /dev/null +++ b/core/src/main/resources/META-INF/native-image/com.datastax.oss/java-driver-core/reflection.json @@ -0,0 +1,154 @@ +[ + { + "name": "com.datastax.oss.driver.internal.core.loadbalancing.DefaultLoadBalancingPolicy", + "methods": [ { "name": "", "parameterTypes": [ "com.datastax.oss.driver.api.core.context.DriverContext", "java.lang.String" ] } ] + }, + { + "name": "com.datastax.oss.driver.internal.core.loadbalancing.DcInferringLoadBalancingPolicy", + "methods": [ { "name": "", "parameterTypes": [ "com.datastax.oss.driver.api.core.context.DriverContext", "java.lang.String" ] } ] + }, + { + "name": "com.datastax.oss.driver.internal.core.loadbalancing.BasicLoadBalancingPolicy", + "methods": [ { "name": "", "parameterTypes": [ "com.datastax.oss.driver.api.core.context.DriverContext", "java.lang.String" ] } ] + }, + { + "name": "com.datastax.oss.driver.internal.core.connection.ExponentialReconnectionPolicy", + "methods": [ { "name": "", "parameterTypes": [ "com.datastax.oss.driver.api.core.context.DriverContext" ] } ] + }, + { + "name": "com.datastax.oss.driver.internal.core.connection.ConstantReconnectionPolicy", + "methods": [ { "name": "", "parameterTypes": [ "com.datastax.oss.driver.api.core.context.DriverContext" ] } ] + }, + { + "name": "com.datastax.oss.driver.internal.core.retry.DefaultRetryPolicy", + "methods": [ { "name": "", "parameterTypes": [ "com.datastax.oss.driver.api.core.context.DriverContext", "java.lang.String" ] } ] + }, + { + "name": "com.datastax.oss.driver.internal.core.retry.ConsistencyDowngradingRetryPolicy", + "methods": [ { "name": "", "parameterTypes": [ "com.datastax.oss.driver.api.core.context.DriverContext", "java.lang.String" ] } ] + }, + { + "name": "com.datastax.oss.driver.internal.core.specex.NoSpeculativeExecutionPolicy", + "methods": [ { "name": "", "parameterTypes": [ "com.datastax.oss.driver.api.core.context.DriverContext", "java.lang.String" ] } ] + }, + { + "name": "com.datastax.oss.driver.internal.core.specex.ConstantSpeculativeExecutionPolicy", + "methods": [ { "name": "", "parameterTypes": [ "com.datastax.oss.driver.api.core.context.DriverContext", "java.lang.String" ] } ] + }, + { + "name": "com.datastax.oss.driver.internal.core.time.AtomicTimestampGenerator", + "methods": [ { "name": "", "parameterTypes": [ "com.datastax.oss.driver.api.core.context.DriverContext" ] } ] + }, + { + "name": "com.datastax.oss.driver.internal.core.time.ThreadLocalTimestampGenerator", + "methods": [ { "name": "", "parameterTypes": [ "com.datastax.oss.driver.api.core.context.DriverContext" ] } ] + }, + { + "name": "com.datastax.oss.driver.internal.core.time.ServerSideTimestampGenerator", + "methods": [ { "name": "", "parameterTypes": [ "com.datastax.oss.driver.api.core.context.DriverContext" ] } ] + }, + { + "name": "com.datastax.oss.driver.internal.core.tracker.NoopRequestTracker", + "methods": [ { "name": "", "parameterTypes": [ "com.datastax.oss.driver.api.core.context.DriverContext" ] } ] + }, + { + "name": "com.datastax.oss.driver.internal.core.tracker.RequestLogger", + "methods": [ { "name": "", "parameterTypes": [ "com.datastax.oss.driver.api.core.context.DriverContext" ] } ] + }, + { + "name": "com.datastax.oss.driver.internal.core.session.throttling.PassThroughRequestThrottler", + "methods": [ { "name": "", "parameterTypes": [ "com.datastax.oss.driver.api.core.context.DriverContext" ] } ] + }, + { + "name": "com.datastax.oss.driver.internal.core.session.throttling.RateLimitingRequestThrottler", + "methods": [ { "name": "", "parameterTypes": [ "com.datastax.oss.driver.api.core.context.DriverContext" ] } ] + }, + { + "name": "com.datastax.oss.driver.internal.core.session.throttling.ConcurrencyLimitingRequestThrottler", + "methods": [ { "name": "", "parameterTypes": [ "com.datastax.oss.driver.api.core.context.DriverContext" ] } ] + }, + { + "name": "com.datastax.oss.driver.internal.core.metadata.NoopNodeStateListener", + "methods": [ { "name": "", "parameterTypes": [ "com.datastax.oss.driver.api.core.context.DriverContext" ] } ] + }, + { + "name": "com.datastax.oss.driver.internal.core.metadata.schema.NoopSchemaChangeListener", + "methods": [ { "name": "", "parameterTypes": [ "com.datastax.oss.driver.api.core.context.DriverContext" ] } ] + }, + { + "name": "com.datastax.oss.driver.internal.core.addresstranslation.PassThroughAddressTranslator", + "methods": [ { "name": "", "parameterTypes": [ "com.datastax.oss.driver.api.core.context.DriverContext" ] } ] + }, + { + "name": "com.datastax.oss.driver.internal.core.addresstranslation.Ec2MultiRegionAddressTranslator", + "methods": [ { "name": "", "parameterTypes": [ "com.datastax.oss.driver.api.core.context.DriverContext" ] } ] + }, + { + "name": "com.datastax.oss.driver.internal.core.auth.PlainTextAuthProvider", + "methods": [ { "name": "", "parameterTypes": [ "com.datastax.oss.driver.api.core.context.DriverContext" ] } ] + }, + { + "name": "com.datastax.dse.driver.internal.core.auth.DseGssApiAuthProvider", + "methods": [ { "name": "", "parameterTypes": [ "com.datastax.oss.driver.api.core.context.DriverContext" ] } ] + }, + { + "name": "com.datastax.oss.driver.internal.core.ssl.DefaultSslEngineFactory", + "methods": [ { "name": "", "parameterTypes": [ "com.datastax.oss.driver.api.core.context.DriverContext" ] } ] + }, + { + "name": "com.datastax.oss.driver.internal.core.metrics.DefaultMetricsFactory", + "methods": [ { "name": "", "parameterTypes": [ "com.datastax.oss.driver.api.core.context.DriverContext" ] } ] + }, + { + "name": "com.datastax.oss.driver.internal.core.metrics.NoopMetricsFactory", + "methods": [ { "name": "", "parameterTypes": [ "com.datastax.oss.driver.api.core.context.DriverContext" ] } ] + }, + { + "name": "com.datastax.oss.driver.internal.core.metrics.DropwizardMetricsFactory", + "methods": [ { "name": "", "parameterTypes": [ "com.datastax.oss.driver.api.core.context.DriverContext" ] } ] + }, + { + "name": "com.datastax.oss.driver.internal.core.metrics.DefaultMetricIdGenerator", + "methods": [ { "name": "", "parameterTypes": [ "com.datastax.oss.driver.api.core.context.DriverContext" ] } ] + }, + { + "name": "com.datastax.oss.driver.internal.core.metrics.TaggingMetricIdGenerator", + "methods": [ { "name": "", "parameterTypes": [ "com.datastax.oss.driver.api.core.context.DriverContext" ] } ] + }, + { + "name": "io.netty.channel.socket.nio.NioSocketChannel", + "methods": [ { "name": "", "parameterTypes": [] } ] + }, + { + "name": "io.netty.buffer.AbstractByteBufAllocator", + "methods": [ { "name": "toLeakAwareBuffer", "parameterTypes": ["io.netty.buffer.ByteBuf" ] } ] + }, + { + "name": "io.netty.util.ReferenceCountUtil", + "methods": [ { "name": "touch", "parameterTypes": ["java.lang.Object", "java.lang.Object" ] } ] + }, + { + "name" : "io.netty.util.internal.shaded.org.jctools.queues.MpscArrayQueueProducerIndexField", + "fields": [ {"name": "producerIndex", "allowUnsafeAccess": true} ] + }, + { + "name" : "io.netty.util.internal.shaded.org.jctools.queues.MpscArrayQueueProducerLimitField", + "fields": [ {"name": "producerLimit", "allowUnsafeAccess": true} ] + }, + { + "name" : "io.netty.util.internal.shaded.org.jctools.queues.MpscArrayQueueConsumerIndexField", + "fields": [ {"name": "consumerIndex", "allowUnsafeAccess": true} ] + }, + { + "name" : "io.netty.util.internal.shaded.org.jctools.queues.BaseMpscLinkedArrayQueueProducerFields", + "fields": [ {"name": "producerIndex", "allowUnsafeAccess": true} ] + }, + { + "name" : "io.netty.util.internal.shaded.org.jctools.queues.BaseMpscLinkedArrayQueueColdProducerFields", + "fields": [ {"name": "producerLimit", "allowUnsafeAccess": true} ] + }, + { + "name" : "io.netty.util.internal.shaded.org.jctools.queues.BaseMpscLinkedArrayQueueConsumerFields", + "fields": [ {"name": "consumerIndex", "allowUnsafeAccess": true} ] + } +] diff --git a/core/src/main/resources/META-INF/services/reactor.blockhound.integration.BlockHoundIntegration b/core/src/main/resources/META-INF/services/reactor.blockhound.integration.BlockHoundIntegration new file mode 100644 index 00000000000..b848ce24855 --- /dev/null +++ b/core/src/main/resources/META-INF/services/reactor.blockhound.integration.BlockHoundIntegration @@ -0,0 +1 @@ +com.datastax.oss.driver.internal.core.util.concurrent.DriverBlockHoundIntegration \ No newline at end of file diff --git a/core/src/main/resources/com/datastax/oss/driver/Driver.properties b/core/src/main/resources/com/datastax/oss/driver/Driver.properties index a62ba0a538a..4706afe2da8 100644 --- a/core/src/main/resources/com/datastax/oss/driver/Driver.properties +++ b/core/src/main/resources/com/datastax/oss/driver/Driver.properties @@ -1,11 +1,13 @@ # -# Copyright DataStax, Inc. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, @@ -23,4 +25,4 @@ driver.version=${project.version} # It would be better to use ${project.parent.name} here, but for some reason the bundle plugin # prevents that from being resolved correctly (unlike the project-level properties above). # The value is not likely to change, so we simply hard-code it: -driver.name=DataStax Java driver for Apache Cassandra(R) +driver.name=Apache Cassandra Java Driver diff --git a/core/src/main/resources/reference.conf b/core/src/main/resources/reference.conf index a025e816d30..4ae83362e29 100644 --- a/core/src/main/resources/reference.conf +++ b/core/src/main/resources/reference.conf @@ -1,4 +1,21 @@ -# Reference configuration for the DataStax Java driver for Apache Cassandra®. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# Reference configuration for the Java Driver for Apache Cassandra®. # # Unless you use a custom mechanism to load your configuration (see # SessionBuilder.withConfigLoader), all the values declared here will be used as defaults. You can @@ -155,7 +172,25 @@ datastax-java-driver { # - com.datastax.oss.driver.internal.core.loadbalancing. # - com.datastax.dse.driver.internal.core.loadbalancing. # - # The driver provides a single implementation out of the box: DefaultLoadBalancingPolicy. + # The driver provides three implementations out of the box: + # + # - `DefaultLoadBalancingPolicy`: should almost always be used; it requires a local datacenter + # to be specified either programmatically when creating the session, or via the configuration + # option: datastax-java-driver.basic.load-balancing-policy.local-datacenter. It can also + # use a highly efficient slow replica avoidance mechanism, which is by default enabled – see + # the option: datastax-java-driver.basic.load-balancing-policy.slow-replica-avoidance. + # - `DcInferringLoadBalancingPolicy`: similar to `DefaultLoadBalancingPolicy`, but does not + # require a local datacenter to be defined, in which case it will attempt to infer the local + # datacenter from the provided contact points, if possible; if that fails, it will throw an + # error during session initialization. This policy is intended mostly for ETL tools and + # should not be used by normal applications. + # - `BasicLoadBalancingPolicy`: similar to `DefaultLoadBalancingPolicy`, but does not have + # the slow replica avoidance mechanism. More importantly, it is the only policy capable of + # operating without local datacenter defined, in which case it will consider nodes in the + # cluster in a datacenter-agnostic way. Beware that this could cause spikes in + # cross-datacenter traffic! This policy is provided mostly as a starting point for users + # wishing to implement their own load balancing policy; it should not be used as is in normal + # applications. # # You can also specify a custom class that implements LoadBalancingPolicy and has a public # constructor with two arguments: the DriverContext and a String representing the profile name. @@ -176,6 +211,27 @@ datastax-java-driver { # are specified, the programmatic value takes precedence. // local-datacenter = datacenter1 + # The class of a custom node distance evaluator. + # + # This option is not required; if present, it must be the fully-qualified name of a class that + # implements `com.datastax.oss.driver.api.core.loadbalancing.NodeDistanceEvaluator`, and has a + # public constructor taking two arguments: the DriverContext and a String representing the + # profile name. + # + # Alternatively, you can pass an instance of your distance evaluator to + # CqlSession.builder().withNodeDistanceEvaluator(). In that case, this option will be ignored. + # + # The evaluator will be invoked each time the policy processes a topology or state change. The + # evaluator's `evaluateDistance` method will be called with the node affected by the change, and + # the local datacenter name (or null if none is defined). If it returns a non-null distance, the + # policy will suggest that distance for the node; if the function returns null, the policy will + # will assign a default distance instead, based on its internal algorithm for computing node + # distances. + // evaluator.class= + + # DEPRECATED. Use evaluator.class instead (see above). If both evaluator.class and filter.class + # are defined, the former wins. + # # A custom filter to include/exclude nodes. # # This option is not required; if present, it must be the fully-qualified name of a class that @@ -202,7 +258,7 @@ datastax-java-driver { slow-replica-avoidance = true } basic.cloud { - # The location of the cloud secure bundle used to connect to Datastax Apache Cassandra as a + # The location of the cloud secure bundle used to connect to DataStax Apache Cassandra as a # service. # This setting must be a valid URL. # If the protocol is not specified, it is implicitly assumed to be the `file://` protocol, @@ -390,25 +446,42 @@ datastax-java-driver { set-keyspace-timeout = ${datastax-java-driver.advanced.connection.init-query-timeout} # The driver maintains a connection pool to each node, according to the distance assigned to it - # by the load balancing policy. If the distance is IGNORED, no connections are maintained. + # by the load balancing policy. + # If the distance is LOCAL, then local.size connections are opened; if the distance is REMOTE, + # then remote.size connections are opened. If the distance is IGNORED, no connections at all + # are maintained. pool { - local { - # The number of connections in the pool. - # - # Each connection can handle many concurrent requests, so 1 is generally a good place to - # start. You should only need higher values in very high performance scenarios, where - # connections might start maxing out their I/O thread (see the driver's online manual for - # more tuning instructions). - # - # Required: yes - # Modifiable at runtime: yes; when the change is detected, all active pools will be notified - # and will adjust their size. - # Overridable in a profile: no - size = 1 - } - remote { - size = 1 - } + # The number of connections in the pool for a node whose distance is LOCAL, that is, a node + # that belongs to the local datacenter, as inferred by the load balancing or defined by the + # option: datastax-java-driver.basic.load-balancing-policy.local-datacenter. + # + # Each connection can handle many concurrent requests, so 1 is generally a good place to + # start. You should only need higher values in very high performance scenarios, where + # connections might start maxing out their I/O thread (see the driver's online manual for + # more tuning instructions). + # + # Required: yes + # Modifiable at runtime: yes; when the change is detected, all active pools will be notified + # and will adjust their size. + # Overridable in a profile: no + local.size = 1 + + # The number of connections in the pool for a node whose distance is REMOTE, that is, a node + # that does not belong to the local datacenter. + # + # Note: by default, the built-in load-balancing policies will never assign the REMOTE distance + # to any node, to avoid cross-datacenter network traffic. If you want to change this behavior + # and understand the consequences, configure your policy to accept nodes in remote + # datacenters by adjusting the following advanced options: + # + # - datastax-java-driver.advanced.load-balancing-policy.dc-failover.max-nodes-per-remote-dc + # - datastax-java-driver.advanced.load-balancing-policy.dc-failover.allow-for-local-consistency-levels + # + # Required: yes + # Modifiable at runtime: yes; when the change is detected, all active pools will be notified + # and will adjust their size. + # Overridable in a profile: no + remote.size = 1 } # The maximum number of requests that can be executed concurrently on a connection. This must be @@ -464,6 +537,53 @@ datastax-java-driver { warn-on-init-error = true } + # Advanced options for the built-in load-balancing policies. + advanced.load-balancing-policy { + # Cross-datacenter failover configuration: configure the load-balancing policies to use nodes + # in remote datacenters. + dc-failover { + # The maximum number of nodes to contact in each remote datacenter. + # + # By default, this number is zero, to avoid cross-datacenter network traffic. When this + # number is greater than zero: + # + # - The load policies will assign the REMOTE distance to that many nodes in each remote + # datacenter. + # - The driver will then attempt to open connections to those nodes. The actual number of + # connections to open to each one of those nodes is configurable via the option: + # datastax-java-driver.advanced.connection.pool.remote.size. + # - The load-balancing policies will include those remote nodes (and only those) in query + # plans, effectively enabling cross-datacenter failover. + # + # Beware that enabling such failover can result in cross-datacenter network traffic spikes, + # if the local datacenter is down or experiencing high latencies! + # + # Required: yes + # Modifiable at runtime: no + # Overridable in a profile: yes + max-nodes-per-remote-dc = 0 + + # Whether cross-datacenter failover should be allowed for requests executed with local + # consistency levels (LOCAL_ONE, LOCAL_QUORUM and LOCAL_SERIAL). + # + # This is disabled by default. Enabling this feature may have unexpected results, since a + # local consistency level may have different semantics depending on the replication factor in + # use in each datacenter. + # + # Required: yes + # Modifiable at runtime: no + # Overridable in a profile: yes + allow-for-local-consistency-levels = false + + # Ordered preference list of remote dc's (in order) optionally supplied for automatic failover. While building a query plan, the driver uses the DC's supplied in order together with max-nodes-per-remote-dc + # Users are not required to specify all DCs, when listing preferences via this config + # Required: no + # Modifiable at runtime: no + # Overridable in a profile: no + preferred-remote-dcs = [""] + } + } + # Whether to schedule reconnection attempts if all contact points are unreachable on the first # initialization attempt. # @@ -516,7 +636,13 @@ datastax-java-driver { # The class of the policy. If it is not qualified, the driver assumes that it resides in the # package com.datastax.oss.driver.internal.core.retry. # - # The driver provides a single implementation out of the box: DefaultRetryPolicy. + # The driver provides two implementations out of the box: + # + # - DefaultRetryPolicy: the default policy, should almost always be the right choice. + # - ConsistencyDowngradingRetryPolicy: an alternative policy that weakens consistency guarantees + # as a trade-off to maximize the chance of success when retrying. Use with caution. + # + # Refer to the manual to understand how these policies work. # # You can also specify a custom class that implements RetryPolicy and has a public constructor # with two arguments: the DriverContext and a String representing the profile name. @@ -581,7 +707,7 @@ datastax-java-driver { # # The driver provides two implementations: # - PlainTextAuthProvider: uses plain-text credentials. It requires the `username` and - # `password` options below. When connecting to Datastax Enterprise, an optional + # `password` options below. When connecting to DataStax Enterprise, an optional # `authorization-id` can also be specified. # For backward compatibility with previous driver versions, you can also use the class name # "DsePlainTextAuthProvider" for this provider. @@ -663,6 +789,12 @@ datastax-java-driver { # name matches the hostname of the server being connected to. If not set, defaults to true. // hostname-validation = true + # Whether or not to allow a DNS reverse-lookup of provided server addresses for SAN addresses, + # if cluster endpoints are specified as literal IPs. + # This is left as true for compatibility, but in most environments a DNS reverse-lookup should + # not be necessary to get an address that matches the server certificate SANs. + // allow-dns-reverse-lookup-san = true + # The locations and passwords used to access truststore and keystore contents. # These properties are optional. If either truststore-path or keystore-path are specified, # the driver builds an SSLContext from these files. If neither option is specified, the @@ -671,6 +803,13 @@ datastax-java-driver { // truststore-password = password123 // keystore-path = /path/to/client.keystore // keystore-password = password123 + + # The duration between attempts to reload the keystore from the contents of the file specified + # by `keystore-path`. This is mainly relevant in environments where certificates have short + # lifetimes and applications are restarted infrequently, since an expired client certificate + # will prevent new connections from being established until the application is restarted. If + # not set, defaults to not reload the keystore. + // keystore-reload-interval = 30 minutes } # The generator that assigns a microsecond timestamp to each request. @@ -716,23 +855,29 @@ datastax-java-driver { force-java-clock = false } - # A session-wide component that tracks the outcome of requests. - # - # Required: yes - # Modifiable at runtime: no (but custom implementations may elect to watch configuration changes - # and allow child options to be changed at runtime). - # Overridable in a profile: no + # Request trackers are session-wide components that get notified of the outcome of requests. advanced.request-tracker { - # The class of the tracker. If it is not qualified, the driver assumes that it resides in the - # package com.datastax.oss.driver.internal.core.tracker. + # The list of trackers to register. # - # The driver provides the following implementations out of the box: - # - NoopRequestTracker: does nothing. + # This must be a list of class names, either fully-qualified or non-qualified; if the latter, + # the driver assumes that the class resides in the package + # com.datastax.oss.driver.internal.core.tracker. + # + # All classes specified here must implement + # com.datastax.oss.driver.api.core.tracker.RequestTracker and have a public constructor with a + # DriverContext argument. + # + # The driver provides the following implementation out of the box: # - RequestLogger: logs requests (see the parameters below). # - # You can also specify a custom class that implements RequestTracker and has a public - # constructor with a DriverContext argument. - class = NoopRequestTracker + # You can also pass instances of your trackers programmatically with + # CqlSession.builder().addRequestTracker(). + # + # Required: no + # Modifiable at runtime: no (but custom implementations may elect to watch configuration changes + # and allow child options to be changed at runtime). + # Overridable in a profile: no + #classes = [RequestLogger,com.example.app.MyTracker] # Parameters for RequestLogger. All of them can be overridden in a profile, and changed at # runtime (the new values will be taken into account for requests logged after the change). @@ -773,6 +918,13 @@ datastax-java-driver { } } + advanced.request-id { + generator { + # The component that generates a unique identifier for each CQL request, and possibly write the id to the custom payload . + // class = W3CContextRequestIdGenerator + } + } + # A session-wide component that controls the rate at which requests are executed. # # Implementations vary, but throttlers generally track a metric that represents the level of @@ -835,39 +987,37 @@ datastax-java-driver { // drain-interval = 10 milliseconds } - # A session-wide component that listens for node state changes. If it is not qualified, the driver - # assumes that it resides in the package com.datastax.oss.driver.internal.core.metadata. - # - # The driver provides a single no-op implementation out of the box: NoopNodeStateListener. + # The list of node state listeners to register. Node state listeners are session-wide + # components that listen for node state changes (e.g., when nodes go down or back up). # - # You can also specify a custom class that implements NodeStateListener and has a public + # This must be a list of fully-qualified class names; classes specified here must implement + # com.datastax.oss.driver.api.core.metadata.NodeStateListener and have a public # constructor with a DriverContext argument. # - # Alternatively, you can pass an instance of your listener programmatically with - # CqlSession.builder().withNodeStateListener(). In that case, this option will be ignored. + # You can also pass instances of your listeners programmatically with + # CqlSession.builder().addNodeStateListener(). # - # Required: unless a listener has been provided programmatically + # Required: no # Modifiable at runtime: no (but custom implementations may elect to watch configuration changes # and allow child options to be changed at runtime). # Overridable in a profile: no - advanced.node-state-listener.class = NoopNodeStateListener + #advanced.node-state-listener.classes = [com.example.app.MyListener1,com.example.app.MyListener2] - # A session-wide component that listens for node state changes. If it is not qualified, the driver - # assumes that it resides in the package com.datastax.oss.driver.internal.core.metadata.schema. - # - # The driver provides a single no-op implementation out of the box: NoopSchemaChangeListener. + # The list of schema change listeners to register. Schema change listeners are session-wide + # components that listen for schema changes (e.g., when tables are created or dropped). # - # You can also specify a custom class that implements SchemaChangeListener and has a public + # This must be a list of fully-qualified class names; classes specified here must implement + # com.datastax.oss.driver.api.core.metadata.schema.SchemaChangeListener and have a public # constructor with a DriverContext argument. # - # Alternatively, you can pass an instance of your listener programmatically with - # CqlSession.builder().withSchemaChangeListener(). In that case, this option will be ignored. + # You can also pass instances of your listeners programmatically with + # CqlSession.builder().addSchemaChangeListener(). # - # Required: unless a listener has been provided programmatically + # Required: no # Modifiable at runtime: no (but custom implementations may elect to watch configuration changes # and allow child options to be changed at runtime). # Overridable in a profile: no - advanced.schema-change-listener.class = NoopSchemaChangeListener + #advanced.schema-change-listener.classes = [com.example.app.MyListener1,com.example.app.MyListener2] # The address translator to use to convert the addresses sent by Cassandra nodes into ones that # the driver uses to connect. @@ -883,7 +1033,9 @@ datastax-java-driver { # the package com.datastax.oss.driver.internal.core.addresstranslation. # # The driver provides the following implementations out of the box: - # - PassThroughAddressTranslator: returns all addresses unchanged + # - PassThroughAddressTranslator: returns all addresses unchanged. + # - FixedHostNameAddressTranslator: translates all addresses to a specific hostname. + # - SubnetAddressTranslator: translates addresses to hostname based on the subnet match. # - Ec2MultiRegionAddressTranslator: suitable for an Amazon multi-region EC2 deployment where # clients are also deployed in EC2. It optimizes network costs by favoring private IPs over # public ones whenever possible. @@ -891,6 +1043,23 @@ datastax-java-driver { # You can also specify a custom class that implements AddressTranslator and has a public # constructor with a DriverContext argument. class = PassThroughAddressTranslator + # + # This property has to be set only in case you use FixedHostNameAddressTranslator. + # advertised-hostname = mycustomhostname + # + # These properties are only applicable in case you use SubnetAddressTranslator. + # subnet-addresses { + # "100.64.0.0/15" = "cassandra.datacenter1.com:9042" + # "100.66.0.0/15" = "cassandra.datacenter2.com:9042" + # # IPv6 example: + # # "::ffff:6440:0/111" = "cassandra.datacenter1.com:9042" + # # "::ffff:6442:0/111" = "cassandra.datacenter2.com:9042" + # } + # Optional. When configured, addresses not matching the configured subnets are translated to this address. + # default-address = "cassandra.datacenter1.com:9042" + # Whether to resolve the addresses once on initialization (if true) or on each node (re-)connection (if false). + # If not configured, defaults to false. + # resolve-addresses = false } # Whether to resolve the addresses passed to `basic.contact-points`. @@ -935,7 +1104,7 @@ datastax-java-driver { # an incompatible node joins the cluster later, connection will fail and the driver will force # it down (i.e. never try to connect to it again). # - # You can check the actual version at runtime with Cluster.getContext().getProtocolVersion(). + # You can check the actual version at runtime with Session.getContext().getProtocolVersion(). # # Required: no # Modifiable at runtime: no @@ -945,7 +1114,7 @@ datastax-java-driver { # The name of the algorithm used to compress protocol frames. # # The possible values are: - # - lz4: requires net.jpountz.lz4:lz4 in the classpath. + # - lz4: requires at.yawk.lz4:lz4-java in the classpath. # - snappy: requires org.xerial.snappy:snappy-java in the classpath. # - the string "none" to indicate no compression (this is functionally equivalent to omitting # the option). @@ -1232,24 +1401,109 @@ datastax-java-driver { factory { # The class for the metrics factory. # - # The driver provides Dropwizard, Micrometer and MicroProfile metrics out of the box. - # To use Dropwizard, this value should be set to "DropwizardMetricsFactory". To use - # Micrometer, set the value to "MicrometerMetricsFactory". To use MicroProfile, set the value - # to "MicroProfileMetricsFactory". + # The driver provides out-of-the-box support for three metrics libraries: Dropwizard, + # Micrometer and MicroProfile Metrics. + # + # Dropwizard is the default metrics library in the driver; to use Dropwizard, this value + # should be left to its default, "DefaultMetricsFactory", or set to + # "DropwizardMetricsFactory". The only difference between the two is that the former will work + # even if Dropwizard is not present on the classpath (in which case it will silently disable + # metrics), while the latter requires its presence. + # + # To select Micrometer, set the value to "MicrometerMetricsFactory", and to select + # MicroProfile Metrics, set the value to "MicroProfileMetricsFactory". For these libraries to + # be used, you will also need to add an additional dependency: + # - Micrometer: org.apache.cassandra:java-driver-metrics-micrometer + # - MicroProfile: org.apache.cassandra:java-driver-metrics-microprofile # - # For Micrometer and MicroProfile, you will also need to add an additional dependency: - # com.datastax.oss:java-driver-metrics-micrometer and - # com.datastax.oss:java-driver-metrics-microprofile respectively. + # If you would like to use another metrics library, set this value to the fully-qualified name + # of a class that implements com.datastax.oss.driver.internal.core.metrics.MetricsFactory. # - # If you would like to use a different metrics framework, change the factory class to the - # fully-qualified name of a class that implements - # com.datastax.oss.driver.internal.core.metrics.MetricsFactory. + # It is also possible to use "NoopMetricsFactory", which forcibly disables metrics completely. + # In fact, "DefaultMetricsFactory" delegates to "DropwizardMetricsFactory" if Dropwizard is + # present on the classpath, or to "NoopMetricsFactory" if it isn't. + # + # Note: specifying a metrics factory is not enough to enable metrics; for the driver to + # actually start collecting metrics, you also need to specify which metrics to collect. See + # the following options for more information: + # - advanced.metrics.session.enabled + # - advanced.metrics.node.enabled + # + # See also the driver online manual for extensive instructions about how to configure metrics. # # Required: yes # Modifiable at runtime: no # Overridable in a profile: no - class = DropwizardMetricsFactory + class = DefaultMetricsFactory + } + + # This section configures how metric ids are generated. A metric id is a unique combination of + # a metric name and metric tags. + id-generator { + + # The class name of a component implementing + # com.datastax.oss.driver.internal.core.metrics.MetricIdGenerator. If it is not qualified, the + # driver assumes that it resides in the package com.datastax.oss.driver.internal.core.metrics. + # + # The driver ships with two built-in implementations: + # + # - DefaultMetricIdGenerator: generates identifiers composed solely of (unique) metric names; + # it does not generate tags. It is mostly suitable for use with metrics libraries that do + # not support tags, like Dropwizard. + # - TaggingMetricIdGenerator: generates identifiers composed of name and tags. It is mostly + # suitable for use with metrics libraries that support tags, like Micrometer or MicroProfile + # Metrics. + # + # For example, here is how each one of them generates identifiers for the session metric + # "bytes-sent", assuming that the session is named "s0": + # - DefaultMetricIdGenerator: name "s0.bytes-sent", tags: {}. + # - TaggingMetricIdGenerator: name "session.bytes-sent", tags: {"session":"s0"} + # + # Here is how each one of them generates identifiers for the node metric "bytes-sent", + # assuming that the session is named "s0", and the node's broadcast address is 10.1.2.3:9042: + # - DefaultMetricIdGenerator: name "s0.nodes.10_1_2_3:9042.bytes-sent", tags: {}. + # - TaggingMetricIdGenerator: name "nodes.bytes-sent", tags: { "session" : "s0", + # "node" : "\10.1.2.3:9042" } + # + # As shown above, both built-in implementations generate names that are path-like structures + # separated by dots. This is indeed the most common expected format by reporting tools. + # + # Required: yes + # Modifiable at runtime: no + # Overridable in a profile: no + class = DefaultMetricIdGenerator + + # An optional prefix to prepend to each generated metric name. + # + # The prefix should not start nor end with a dot or any other path separator; the following + # are two valid examples: "cassandra" or "myapp.prod.cassandra". + # + # For example, if this prefix is set to "cassandra", here is how the session metric + # "bytes-sent" would be named, assuming that the session is named "s0": + # - with DefaultMetricIdGenerator: "cassandra.s0.bytes-sent" + # - with TaggingMetricIdGenerator: "cassandra.session.bytes-sent" + # + # Here is how the node metric "bytes-sent" would be named, assuming that the session is named + # "s0", and the node's broadcast address is 10.1.2.3:9042: + # - with DefaultMetricIdGenerator: "cassandra.s0.nodes.10_1_2_3:9042.bytes-sent" + # - with TaggingMetricIdGenerator: "cassandra.nodes.bytes-sent" + # + # Required: no + # Modifiable at runtime: no + # Overridable in a profile: no + // prefix = "cassandra" + } + + histograms { + # Adds histogram buckets used to generate aggregable percentile approximations in monitoring + # systems that have query facilities to do so (e.g. Prometheus histogram_quantile, Atlas percentiles). + # + # Required: no + # Modifiable at runtime: no + # Overridable in a profile: no + generate-aggregable = true } + # The session-level metrics (all disabled by default). # # Required: yes @@ -1257,10 +1511,12 @@ datastax-java-driver { # Overridable in a profile: no session { enabled = [ - # The number and rate of bytes sent for the entire session (exposed as a Meter). + # The number and rate of bytes sent for the entire session (exposed as a Meter if available, + # otherwise as a Counter). // bytes-sent, - # The number and rate of bytes received for the entire session (exposed as a Meter). + # The number and rate of bytes received for the entire session (exposed as a Meter if + # available, otherwise as a Counter). // bytes-received # The number of nodes to which the driver has at least one active connection (exposed as a @@ -1277,7 +1533,7 @@ datastax-java-driver { # with a DriverTimeoutException (exposed as a Counter). // cql-client-timeouts, - # The size of the driver-side cache of CQL prepared statements. + # The size of the driver-side cache of CQL prepared statements (exposed as a Gauge). # # The cache uses weak values eviction, so this represents the number of PreparedStatement # instances that your application has created, and is still holding a reference to. Note @@ -1336,10 +1592,11 @@ datastax-java-driver { # Extra configuration (for the metrics that need it) - # Required: if the 'cql-requests' metric is enabled + # Required: if the 'cql-requests' metric is enabled, and Dropwizard or Micrometer is used. # Modifiable at runtime: no # Overridable in a profile: no cql-requests { + # The largest latency that we expect to record. # # This should be slightly higher than request.timeout (in theory, readings can't be higher @@ -1347,14 +1604,21 @@ datastax-java-driver { # # This is used to scale internal data structures. If a higher recording is encountered at # runtime, it is discarded and a warning is logged. + # Valid for: Dropwizard, Micrometer. highest-latency = 3 seconds + # The shortest latency that we expect to record. This is used to scale internal data + # structures. + # Valid for: Micrometer. + lowest-latency = 1 millisecond + # The number of significant decimal digits to which internal structures will maintain # value resolution and separation (for example, 3 means that recordings up to 1 second # will be recorded with a resolution of 1 millisecond or better). # - # This must be between 0 and 5. If the value is out of range, it defaults to 3 and a - # warning is logged. + # For Dropwizard, this must be between 0 and 5. If the value is out of range, it defaults to + # 3 and a warning is logged. + # Valid for: Dropwizard, Micrometer. significant-digits = 3 # The interval at which percentile data is refreshed. @@ -1373,94 +1637,58 @@ datastax-java-driver { # # Note that this does not apply to the total count and rates (those are updated in real # time). + # Valid for: Dropwizard. refresh-interval = 5 minutes + + # An optional list of latencies to track as part of the application's service-level + # objectives (SLOs). + # + # If defined, the histogram is guaranteed to contain these boundaries alongside other + # buckets used to generate aggregable percentile approximations. + # Valid for: Micrometer. + // slo = [ 100 milliseconds, 500 milliseconds, 1 second ] + + # An optional list of percentiles to be published by Micrometer. Produces an additional time series for each requested percentile. + # This percentile is computed locally, and so can't be aggregated with percentiles computed across other dimensions (e.g. in a different instance) + # Valid for: Micrometer. + // publish-percentiles = [ 0.75, 0.95, 0.99 ] } - # Required: if the 'throttling.delay' metric is enabled + # Required: if the 'throttling.delay' metric is enabled, and Dropwizard or Micrometer is used. # Modifiable at runtime: no # Overridable in a profile: no throttling.delay { highest-latency = 3 seconds + lowest-latency = 1 millisecond significant-digits = 3 refresh-interval = 5 minutes + // slo = [ 100 milliseconds, 500 milliseconds, 1 second ] + // publish-percentiles = [ 0.75, 0.95, 0.99 ] } - # Required: if the 'continuous-cql-requests' metric is enabled + # Required: if the 'continuous-cql-requests' metric is enabled, and Dropwizard or Micrometer + # is used. # Modifiable at runtime: no # Overridable in a profile: no continuous-cql-requests { - - # The largest latency that we expect to record for a continuous paging request. - # - # This is used to scale internal data structures. If a higher recording is encountered at - # runtime, it is discarded and a warning is logged. highest-latency = 120 seconds - - # The number of significant decimal digits to which internal structures will maintain - # value resolution and separation (for example, 3 means that recordings up to 1 second - # will be recorded with a resolution of 1 millisecond or better). - # - # This must be between 0 and 5. If the value is out of range, it defaults to 3 and a - # warning is logged. + lowest-latency = 10 milliseconds significant-digits = 3 - - # The interval at which percentile data is refreshed. - # - # The driver records latency data in a "live" histogram, and serves results from a cached - # snapshot. Each time the snapshot gets older than the interval, the two are switched. - # Note that this switch happens upon fetching the metrics, so if you never fetch the - # recording interval might grow higher (that shouldn't be an issue in a production - # environment because you would typically have a metrics reporter that exports to a - # monitoring tool at a regular interval). - # - # In practice, this means that if you set this to 5 minutes, you're looking at data from a - # 5-minute interval in the past, that is at most 5 minutes old. If you fetch the metrics - # at a faster pace, you will observe the same data for 5 minutes until the interval - # expires. - # - # Note that this does not apply to the total count and rates (those are updated in real - # time). refresh-interval = 5 minutes + // slo = [ 100 milliseconds, 500 milliseconds, 1 second ] + // publish-percentiles = [ 0.75, 0.95, 0.99 ] } - # Required: if the 'graph-requests' metric is enabled + # Required: if the 'graph-requests' metric is enabled, and Dropwizard or Micrometer is used. # Modifiable at runtime: no # Overridable in a profile: no graph-requests { - # The largest latency that we expect to record. - # - # This should be slightly higher than basic.graph.timeout (in theory, readings can't be higher - # than the timeout, but there might be a small overhead due to internal scheduling). - # - # This is used to scale internal data structures. If a higher recording is encountered at - # runtime, it is discarded and a warning is logged. highest-latency = 12 seconds - - # The number of significant decimal digits to which internal structures will maintain - # value resolution and separation (for example, 3 means that recordings up to 1 second - # will be recorded with a resolution of 1 millisecond or better). - # - # This must be between 0 and 5. If the value is out of range, it defaults to 3 and a - # warning is logged. + lowest-latency = 1 millisecond significant-digits = 3 - - # The interval at which percentile data is refreshed. - # - # The driver records latency data in a "live" histogram, and serves results from a cached - # snapshot. Each time the snapshot gets older than the interval, the two are switched. - # Note that this switch happens upon fetching the metrics, so if you never fetch the - # recording interval might grow higher (that shouldn't be an issue in a production - # environment because you would typically have a metrics reporter that exports to a - # monitoring tool at a regular interval). - # - # In practice, this means that if you set this to 5 minutes, you're looking at data from a - # 5-minute interval in the past, that is at most 5 minutes old. If you fetch the metrics - # at a faster pace, you will observe the same data for 5 minutes until the interval - # expires. - # - # Note that this does not apply to the total count and rates (those are updated in real - # time). refresh-interval = 5 minutes + // slo = [ 100 milliseconds, 500 milliseconds, 1 second ] + // publish-percentiles = [ 0.75, 0.95, 0.99 ] } } # The node-level metrics (all disabled by default). @@ -1496,10 +1724,12 @@ datastax-java-driver { # See the description of the connection.max-orphan-requests option for more details. // pool.orphaned-streams, - # The number and rate of bytes sent to this node (exposed as a Meter). + # The number and rate of bytes sent to this node (exposed as a Meter if available, otherwise + # as a Counter). // bytes-sent, - # The number and rate of bytes received from this node (exposed as a Meter). + # The number and rate of bytes received from this node (exposed as a Meter if available, + # otherwise as a Counter). // bytes-received, # The throughput and latency percentiles of individual CQL messages sent to this node as @@ -1614,32 +1844,37 @@ datastax-java-driver { # See cql-requests in the `session` section # - # Required: if the 'cql-messages' metric is enabled + # Required: if the 'cql-messages' metric is enabled, and Dropwizard or Micrometer is used. # Modifiable at runtime: no # Overridable in a profile: no cql-messages { highest-latency = 3 seconds + lowest-latency = 1 millisecond significant-digits = 3 refresh-interval = 5 minutes + // slo = [ 100 milliseconds, 500 milliseconds, 1 second ] + // publish-percentiles = [ 0.75, 0.95, 0.99 ] } # See graph-requests in the `session` section # - # Required: if the 'graph-messages' metric is enabled + # Required: if the 'graph-messages' metric is enabled, and Dropwizard or Micrometer is used. # Modifiable at runtime: no # Overridable in a profile: no graph-messages { highest-latency = 3 seconds + lowest-latency = 1 millisecond significant-digits = 3 refresh-interval = 5 minutes + // slo = [ 100 milliseconds, 500 milliseconds, 1 second ] + // publish-percentiles = [ 0.75, 0.95, 0.99 ] } # The time after which the node level metrics will be evicted. # # This is used to unregister stale metrics if a node leaves the cluster or gets a new address. - # The eviction will happen only if none of the enabled node-level metrics is updated for a - # given node for a given time. When this interval elapses, all metrics for the idle node are - # removed. + # If the node does not come back up when this interval elapses, all its metrics are removed + # from the registry. # # The lowest allowed value is 5 minutes. If you try to set it lower, the driver will log a # warning and use 5 minutes. @@ -1772,7 +2007,7 @@ datastax-java-driver { max-events = 20 } - # Options relating to schema metadata (Cluster.getMetadata.getKeyspaces). + # Options relating to schema metadata (Session.getMetadata.getKeyspaces). # This metadata is exposed by the driver for informational purposes, and is also necessary for # token-aware routing. schema { @@ -1781,18 +2016,45 @@ datastax-java-driver { # # Required: yes # Modifiable at runtime: yes, the new value will be used for refreshes issued after the - # change. It can also be overridden programmatically via Cluster.setSchemaMetadataEnabled. + # change. It can also be overridden programmatically via Session.setSchemaMetadataEnabled. # Overridable in a profile: no enabled = true - # The list of keyspaces for which schema and token metadata should be maintained. If this - # property is absent or empty, all existing keyspaces are processed. + # The keyspaces for which schema and token metadata should be maintained. # - # Required: no + # Each element can be one of the following: + # 1. An exact name inclusion, for example "Ks1". If the name is case-sensitive, it must appear + # in its exact case. + # 2. An exact name exclusion, for example "!Ks1". + # 3. A regex inclusion, enclosed in slashes, for example "/^Ks.*/". The part between the + # slashes must follow the syntax rules of java.util.regex.Pattern. + # 4. A regex exclusion, for example "!/^Ks.*/". + # + # If the list is empty, or the option is unset, all keyspaces will match. Otherwise: + # + # If a keyspace matches an exact name inclusion, it is always included, regardless of what any + # other rule says. + # Otherwise, if it matches an exact name exclusion, it is always excluded, regardless of what + # any regex rule says. + # Otherwise, if there are regex rules: + # - if they're only inclusions, the keyspace must match at least one of them. + # - if they're only exclusions, the keyspace must match none of them. + # - if they're both, the keyspace must match at least one inclusion and none of the + # exclusions. + # + # If an element is malformed, or if its regex has a syntax error, a warning is logged and that + # single element is ignored. + # + # Try to use only exact name inclusions if possible. This allows the driver to filter on the + # server side with a WHERE IN clause. If you use any other rule, it has to fetch all system + # rows and filter on the client side. + # + # Required: no. The default value excludes all Cassandra and DSE system keyspaces. If the + # option is unset, this is interpreted as "include all keyspaces". # Modifiable at runtime: yes, the new value will be used for refreshes issued after the # change. # Overridable in a profile: no - // refreshed-keyspaces = [ "ks1", "ks2" ] + refreshed-keyspaces = [ "!system", "!/^system_.*/", "!/^dse_.*/", "!solr_admin", "!OpsCenter" ] # The timeout for the requests to the schema tables. # @@ -1833,7 +2095,7 @@ datastax-java-driver { } } - # Whether token metadata (Cluster.getMetadata.getTokenMap) is enabled. + # Whether token metadata (Session.getMetadata.getTokenMap) is enabled. # This metadata is exposed by the driver for informational purposes, and is also necessary for # token-aware routing. # If this is false, it will remain empty, or to the last known value. Note that its computation @@ -1985,6 +2247,18 @@ datastax-java-driver { # Overridable in a profile: no timeout = ${datastax-java-driver.advanced.connection.init-query-timeout} } + + # How to build the cache of prepared statements. + prepared-cache { + # Whether to use weak references for the prepared statements cache values. + # + # If this option is absent, weak references will be used. + # + # Required: no + # Modifiable at runtime: no + # Overridable in a profile: no + // weak-values = true + } } # Options related to the Netty event loop groups used internally by the driver. diff --git a/core/src/test/java/com/datastax/dse/driver/Assertions.java b/core/src/test/java/com/datastax/dse/driver/Assertions.java index 11bf3082d72..09f7b281f84 100644 --- a/core/src/test/java/com/datastax/dse/driver/Assertions.java +++ b/core/src/test/java/com/datastax/dse/driver/Assertions.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/DriverRunListener.java b/core/src/test/java/com/datastax/dse/driver/DriverRunListener.java index ad9f7a42c7a..65e58878dbc 100644 --- a/core/src/test/java/com/datastax/dse/driver/DriverRunListener.java +++ b/core/src/test/java/com/datastax/dse/driver/DriverRunListener.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/DseTestDataProviders.java b/core/src/test/java/com/datastax/dse/driver/DseTestDataProviders.java index 228aaaadf00..7d9aecc28ed 100644 --- a/core/src/test/java/com/datastax/dse/driver/DseTestDataProviders.java +++ b/core/src/test/java/com/datastax/dse/driver/DseTestDataProviders.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/DseTestFixtures.java b/core/src/test/java/com/datastax/dse/driver/DseTestFixtures.java index f6ec4528613..7992dde4fea 100644 --- a/core/src/test/java/com/datastax/dse/driver/DseTestFixtures.java +++ b/core/src/test/java/com/datastax/dse/driver/DseTestFixtures.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/TinkerpopBufferAssert.java b/core/src/test/java/com/datastax/dse/driver/TinkerpopBufferAssert.java index 462867e5d2f..278e5a65070 100644 --- a/core/src/test/java/com/datastax/dse/driver/TinkerpopBufferAssert.java +++ b/core/src/test/java/com/datastax/dse/driver/TinkerpopBufferAssert.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/api/core/data/time/DateRangePrecisionTest.java b/core/src/test/java/com/datastax/dse/driver/api/core/data/time/DateRangePrecisionTest.java index 07b8e468585..4cf8d43b748 100644 --- a/core/src/test/java/com/datastax/dse/driver/api/core/data/time/DateRangePrecisionTest.java +++ b/core/src/test/java/com/datastax/dse/driver/api/core/data/time/DateRangePrecisionTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/api/core/data/time/DateRangeTest.java b/core/src/test/java/com/datastax/dse/driver/api/core/data/time/DateRangeTest.java index e4e071a38f7..b067c12cad0 100644 --- a/core/src/test/java/com/datastax/dse/driver/api/core/data/time/DateRangeTest.java +++ b/core/src/test/java/com/datastax/dse/driver/api/core/data/time/DateRangeTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/api/core/graph/predicates/CqlCollectionTest.java b/core/src/test/java/com/datastax/dse/driver/api/core/graph/predicates/CqlCollectionTest.java index 5c9fdce550c..a890720a3ef 100644 --- a/core/src/test/java/com/datastax/dse/driver/api/core/graph/predicates/CqlCollectionTest.java +++ b/core/src/test/java/com/datastax/dse/driver/api/core/graph/predicates/CqlCollectionTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/api/core/graph/predicates/GeoTest.java b/core/src/test/java/com/datastax/dse/driver/api/core/graph/predicates/GeoTest.java index 2fa006f7082..143aec97b78 100644 --- a/core/src/test/java/com/datastax/dse/driver/api/core/graph/predicates/GeoTest.java +++ b/core/src/test/java/com/datastax/dse/driver/api/core/graph/predicates/GeoTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/api/core/graph/predicates/SearchTest.java b/core/src/test/java/com/datastax/dse/driver/api/core/graph/predicates/SearchTest.java index 8144bedb236..591269e31ad 100644 --- a/core/src/test/java/com/datastax/dse/driver/api/core/graph/predicates/SearchTest.java +++ b/core/src/test/java/com/datastax/dse/driver/api/core/graph/predicates/SearchTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/DependencyCheckTest.java b/core/src/test/java/com/datastax/dse/driver/internal/DependencyCheckTest.java index f12dd8d20f8..d001f791e82 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/DependencyCheckTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/DependencyCheckTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/DependencyCheckTestBase.java b/core/src/test/java/com/datastax/dse/driver/internal/DependencyCheckTestBase.java index b80a6118eed..f2ce5513d65 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/DependencyCheckTestBase.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/DependencyCheckTestBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/context/DseStartupOptionsBuilderTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/context/DseStartupOptionsBuilderTest.java index 0d255488c3d..9e4556e528d 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/context/DseStartupOptionsBuilderTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/context/DseStartupOptionsBuilderTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousCqlRequestHandlerNodeTargetingTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousCqlRequestHandlerNodeTargetingTest.java index 3d560d964b0..1edb7c183bf 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousCqlRequestHandlerNodeTargetingTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousCqlRequestHandlerNodeTargetingTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -25,13 +27,17 @@ import com.datastax.dse.driver.DseTestFixtures; import com.datastax.dse.driver.api.core.DseProtocolVersion; import com.datastax.dse.driver.api.core.cql.continuous.ContinuousAsyncResultSet; -import com.datastax.oss.driver.api.core.NoNodeAvailableException; +import com.datastax.oss.driver.api.core.AllNodesFailedException; +import com.datastax.oss.driver.api.core.NodeUnavailableException; import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; +import com.datastax.oss.driver.api.core.metadata.Node; import com.datastax.oss.driver.api.core.session.Request; import com.datastax.oss.driver.api.core.session.Session; import com.datastax.oss.driver.internal.core.cql.RequestHandlerTestHarness; import com.datastax.oss.driver.internal.core.metadata.LoadBalancingPolicyWrapper; import com.tngtech.java.junit.dataprovider.UseDataProvider; +import java.util.List; +import java.util.Map; import java.util.concurrent.CompletionStage; import org.junit.Test; import org.mockito.InOrder; @@ -67,7 +73,12 @@ public void should_fail_if_targeted_node_not_available(DseProtocolVersion versio assertThatStage(resultSetFuture) .isFailed( error -> { - assertThat(error).isInstanceOf(NoNodeAvailableException.class); + assertThat(error).isInstanceOf(AllNodesFailedException.class); + Map> errors = + ((AllNodesFailedException) error).getAllErrors(); + assertThat(errors).hasSize(1); + List nodeErrors = errors.values().iterator().next(); + assertThat(nodeErrors).singleElement().isInstanceOf(NodeUnavailableException.class); invocations .verify(loadBalancingPolicy, never()) .newQueryPlan(any(Request.class), anyString(), any(Session.class)); diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousCqlRequestHandlerReprepareTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousCqlRequestHandlerReprepareTest.java index 634c6eda5d2..fd8d0ea1f98 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousCqlRequestHandlerReprepareTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousCqlRequestHandlerReprepareTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -18,6 +20,7 @@ import static com.datastax.oss.driver.Assertions.assertThat; import static com.datastax.oss.driver.Assertions.assertThatStage; import static com.datastax.oss.protocol.internal.Frame.NO_PAYLOAD; +import static org.assertj.core.api.Assertions.catchThrowable; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyMap; @@ -91,7 +94,7 @@ public void should_prepare_and_retry_on_same_node(DseProtocolVersion version) { when(harness.getChannel(node1).write(any(Prepare.class), anyBoolean(), anyMap(), any())) .then( invocation -> { - AdminRequestHandler admin = invocation.getArgument(3); + AdminRequestHandler admin = invocation.getArgument(3); admin.onResponse(defaultFrameOf(prepared)); return future; }); @@ -121,7 +124,7 @@ public void should_abort_when_prepare_fails_with_unrecoverable_error(DseProtocol when(harness.getChannel(node1).write(any(Prepare.class), anyBoolean(), anyMap(), any())) .then( invocation -> { - AdminRequestHandler admin = invocation.getArgument(3); + AdminRequestHandler admin = invocation.getArgument(3); admin.onResponse(defaultFrameOf(unrecoverable)); return future; }); @@ -135,10 +138,9 @@ public void should_abort_when_prepare_fails_with_unrecoverable_error(DseProtocol verify(harness.getChannel(node1)).write(any(Prepare.class), anyBoolean(), anyMap(), any()); assertThat(handler.getState()).isEqualTo(-2); - assertThat(page1Future) - .hasFailedWithThrowableThat() - .isInstanceOf(SyntaxError.class) - .hasMessageContaining("bad query"); + assertThat(page1Future).isCompletedExceptionally(); + Throwable t = catchThrowable(() -> page1Future.toCompletableFuture().get()); + assertThat(t).hasRootCauseInstanceOf(SyntaxError.class).hasMessageContaining("bad query"); } } @@ -158,7 +160,7 @@ public void should_try_next_node_when_prepare_fails_with_recoverable_error( when(harness.getChannel(node1).write(any(Prepare.class), anyBoolean(), anyMap(), any())) .then( invocation -> { - AdminRequestHandler admin = invocation.getArgument(3); + AdminRequestHandler admin = invocation.getArgument(3); admin.onResponse(defaultFrameOf(recoverable)); return future; }); diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousCqlRequestHandlerRetryTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousCqlRequestHandlerRetryTest.java index 4241c091515..97fe82985de 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousCqlRequestHandlerRetryTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousCqlRequestHandlerRetryTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -24,6 +26,7 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.atMost; +import static org.mockito.Mockito.when; import com.datastax.dse.driver.DseTestFixtures; import com.datastax.dse.driver.api.core.DseProtocolVersion; @@ -38,8 +41,8 @@ import com.datastax.oss.driver.api.core.cql.Statement; import com.datastax.oss.driver.api.core.metadata.Node; import com.datastax.oss.driver.api.core.metrics.DefaultNodeMetric; -import com.datastax.oss.driver.api.core.retry.RetryDecision; import com.datastax.oss.driver.api.core.retry.RetryPolicy; +import com.datastax.oss.driver.api.core.retry.RetryVerdict; import com.datastax.oss.driver.api.core.servererrors.BootstrappingException; import com.datastax.oss.driver.api.core.servererrors.DefaultWriteType; import com.datastax.oss.driver.api.core.servererrors.InvalidQueryException; @@ -170,8 +173,8 @@ public void should_try_next_node_if_idempotent_and_retry_policy_decides_so( harnessBuilder.withResponse(node2, defaultFrameOf(DseTestFixtures.singleDseRow())); try (RequestHandlerTestHarness harness = harnessBuilder.build()) { - failureScenario.mockRetryPolicyDecision( - harness.getContext().getRetryPolicy(anyString()), RetryDecision.RETRY_NEXT); + failureScenario.mockRetryPolicyVerdict( + harness.getContext().getRetryPolicy(anyString()), RetryVerdict.RETRY_NEXT); ContinuousCqlRequestHandler handler = new ContinuousCqlRequestHandler( @@ -225,8 +228,8 @@ public void should_try_same_node_if_idempotent_and_retry_policy_decides_so( harnessBuilder.withResponse(node1, defaultFrameOf(DseTestFixtures.singleDseRow())); try (RequestHandlerTestHarness harness = harnessBuilder.build()) { - failureScenario.mockRetryPolicyDecision( - harness.getContext().getRetryPolicy(anyString()), RetryDecision.RETRY_SAME); + failureScenario.mockRetryPolicyVerdict( + harness.getContext().getRetryPolicy(anyString()), RetryVerdict.RETRY_SAME); ContinuousCqlRequestHandler handler = new ContinuousCqlRequestHandler( @@ -279,8 +282,8 @@ public void should_ignore_error_if_idempotent_and_retry_policy_decides_so( failureScenario.mockRequestError(harnessBuilder, node1); try (RequestHandlerTestHarness harness = harnessBuilder.build()) { - failureScenario.mockRetryPolicyDecision( - harness.getContext().getRetryPolicy(anyString()), RetryDecision.IGNORE); + failureScenario.mockRetryPolicyVerdict( + harness.getContext().getRetryPolicy(anyString()), RetryVerdict.IGNORE); ContinuousCqlRequestHandler handler = new ContinuousCqlRequestHandler( @@ -332,8 +335,8 @@ public void should_rethrow_error_if_idempotent_and_retry_policy_decides_so( try (RequestHandlerTestHarness harness = harnessBuilder.build()) { - failureScenario.mockRetryPolicyDecision( - harness.getContext().getRetryPolicy(anyString()), RetryDecision.RETHROW); + failureScenario.mockRetryPolicyVerdict( + harness.getContext().getRetryPolicy(anyString()), RetryVerdict.RETHROW); ContinuousCqlRequestHandler handler = new ContinuousCqlRequestHandler( @@ -384,8 +387,8 @@ public void should_rethrow_error_if_not_idempotent_and_error_unsafe_or_policy_re try (RequestHandlerTestHarness harness = harnessBuilder.build()) { if (shouldCallRetryPolicy) { - failureScenario.mockRetryPolicyDecision( - harness.getContext().getRetryPolicy(anyString()), RetryDecision.RETHROW); + failureScenario.mockRetryPolicyVerdict( + harness.getContext().getRetryPolicy(anyString()), RetryVerdict.RETHROW); } ContinuousCqlRequestHandler handler = @@ -441,7 +444,7 @@ private abstract static class FailureScenario { abstract void mockRequestError(RequestHandlerTestHarness.Builder builder, Node node); - abstract void mockRetryPolicyDecision(RetryPolicy policy, RetryDecision decision); + abstract void mockRetryPolicyVerdict(RetryPolicy policy, RetryVerdict verdict); } @DataProvider @@ -462,16 +465,15 @@ public void mockRequestError(RequestHandlerTestHarness.Builder builder, Node nod } @Override - public void mockRetryPolicyDecision(RetryPolicy policy, RetryDecision decision) { - Mockito.when( - policy.onReadTimeout( - any(SimpleStatement.class), - eq(DefaultConsistencyLevel.LOCAL_ONE), - eq(2), - eq(1), - eq(true), - eq(0))) - .thenReturn(decision); + public void mockRetryPolicyVerdict(RetryPolicy policy, RetryVerdict verdict) { + when(policy.onReadTimeoutVerdict( + any(SimpleStatement.class), + eq(DefaultConsistencyLevel.LOCAL_ONE), + eq(2), + eq(1), + eq(true), + eq(0))) + .thenReturn(verdict); } }, new FailureScenario( @@ -493,16 +495,15 @@ public void mockRequestError(RequestHandlerTestHarness.Builder builder, Node nod } @Override - public void mockRetryPolicyDecision(RetryPolicy policy, RetryDecision decision) { - Mockito.when( - policy.onWriteTimeout( - any(SimpleStatement.class), - eq(DefaultConsistencyLevel.LOCAL_ONE), - eq(DefaultWriteType.SIMPLE), - eq(2), - eq(1), - eq(0))) - .thenReturn(decision); + public void mockRetryPolicyVerdict(RetryPolicy policy, RetryVerdict verdict) { + when(policy.onWriteTimeoutVerdict( + any(SimpleStatement.class), + eq(DefaultConsistencyLevel.LOCAL_ONE), + eq(DefaultWriteType.SIMPLE), + eq(2), + eq(1), + eq(0))) + .thenReturn(verdict); } }, new FailureScenario( @@ -520,15 +521,14 @@ public void mockRequestError(RequestHandlerTestHarness.Builder builder, Node nod } @Override - public void mockRetryPolicyDecision(RetryPolicy policy, RetryDecision decision) { - Mockito.when( - policy.onUnavailable( - any(SimpleStatement.class), - eq(DefaultConsistencyLevel.LOCAL_ONE), - eq(2), - eq(1), - eq(0))) - .thenReturn(decision); + public void mockRetryPolicyVerdict(RetryPolicy policy, RetryVerdict verdict) { + when(policy.onUnavailableVerdict( + any(SimpleStatement.class), + eq(DefaultConsistencyLevel.LOCAL_ONE), + eq(2), + eq(1), + eq(0))) + .thenReturn(verdict); } }, new FailureScenario( @@ -545,11 +545,10 @@ public void mockRequestError(RequestHandlerTestHarness.Builder builder, Node nod } @Override - public void mockRetryPolicyDecision(RetryPolicy policy, RetryDecision decision) { - Mockito.when( - policy.onErrorResponse( - any(SimpleStatement.class), any(ServerError.class), eq(0))) - .thenReturn(decision); + public void mockRetryPolicyVerdict(RetryPolicy policy, RetryVerdict verdict) { + when(policy.onErrorResponseVerdict( + any(SimpleStatement.class), any(ServerError.class), eq(0))) + .thenReturn(verdict); } }, new FailureScenario( @@ -563,11 +562,10 @@ public void mockRequestError(RequestHandlerTestHarness.Builder builder, Node nod } @Override - public void mockRetryPolicyDecision(RetryPolicy policy, RetryDecision decision) { - Mockito.when( - policy.onRequestAborted( - any(SimpleStatement.class), any(HeartbeatException.class), eq(0))) - .thenReturn(decision); + public void mockRetryPolicyVerdict(RetryPolicy policy, RetryVerdict verdict) { + when(policy.onRequestAbortedVerdict( + any(SimpleStatement.class), any(HeartbeatException.class), eq(0))) + .thenReturn(verdict); } }); } diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousCqlRequestHandlerTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousCqlRequestHandlerTest.java index 6b1d8919630..a816183e9ee 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousCqlRequestHandlerTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousCqlRequestHandlerTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousCqlRequestHandlerTestBase.java b/core/src/test/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousCqlRequestHandlerTestBase.java index 2336d247521..04195f5faf0 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousCqlRequestHandlerTestBase.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/cql/continuous/ContinuousCqlRequestHandlerTestBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/cql/continuous/DefaultContinuousAsyncResultSetTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/cql/continuous/DefaultContinuousAsyncResultSetTest.java index 9756a50c643..1e59559013f 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/cql/continuous/DefaultContinuousAsyncResultSetTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/cql/continuous/DefaultContinuousAsyncResultSetTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/cql/continuous/DefaultContinuousResultSetTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/cql/continuous/DefaultContinuousResultSetTest.java index 03cb9b58c7a..2bfb4768e49 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/cql/continuous/DefaultContinuousResultSetTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/cql/continuous/DefaultContinuousResultSetTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/cql/continuous/reactive/ContinuousCqlRequestReactiveProcessorTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/cql/continuous/reactive/ContinuousCqlRequestReactiveProcessorTest.java index ddd956ab84e..0bfb00695d3 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/cql/continuous/reactive/ContinuousCqlRequestReactiveProcessorTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/cql/continuous/reactive/ContinuousCqlRequestReactiveProcessorTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/cql/reactive/CqlRequestReactiveProcessorTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/cql/reactive/CqlRequestReactiveProcessorTest.java index 4655ae04607..a7a6bced9e8 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/cql/reactive/CqlRequestReactiveProcessorTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/cql/reactive/CqlRequestReactiveProcessorTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/cql/reactive/DefaultReactiveResultSetTckTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/cql/reactive/DefaultReactiveResultSetTckTest.java index d1b97d20901..a9ff5222460 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/cql/reactive/DefaultReactiveResultSetTckTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/cql/reactive/DefaultReactiveResultSetTckTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/cql/reactive/MockAsyncResultSet.java b/core/src/test/java/com/datastax/dse/driver/internal/core/cql/reactive/MockAsyncResultSet.java index 0e215f22c78..3783a2c6922 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/cql/reactive/MockAsyncResultSet.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/cql/reactive/MockAsyncResultSet.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/cql/reactive/MockRow.java b/core/src/test/java/com/datastax/dse/driver/internal/core/cql/reactive/MockRow.java index d629380a1ff..792bfb432f6 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/cql/reactive/MockRow.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/cql/reactive/MockRow.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/cql/reactive/ReactiveResultSetSubscriptionTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/cql/reactive/ReactiveResultSetSubscriptionTest.java index 9a57f9e03fb..6a1a5d644e3 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/cql/reactive/ReactiveResultSetSubscriptionTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/cql/reactive/ReactiveResultSetSubscriptionTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -145,4 +147,34 @@ public void should_report_error_on_intermediary_page() { assertThat(wasAppliedSubscriber.getElements()).hasSize(1).containsExactly(true); assertThat(wasAppliedSubscriber.getError()).isNull(); } + + @Test + public void should_handle_empty_non_final_pages() { + CompletableFuture future1 = new CompletableFuture<>(); + CompletableFuture future2 = new CompletableFuture<>(); + CompletableFuture future3 = new CompletableFuture<>(); + MockAsyncResultSet page1 = new MockAsyncResultSet(10, future2); + MockAsyncResultSet page2 = new MockAsyncResultSet(0, future3); + MockAsyncResultSet page3 = new MockAsyncResultSet(10, null); + TestSubscriber mainSubscriber = new TestSubscriber<>(1); + TestSubscriber colDefsSubscriber = new TestSubscriber<>(); + TestSubscriber execInfosSubscriber = new TestSubscriber<>(); + TestSubscriber wasAppliedSubscriber = new TestSubscriber<>(); + ReactiveResultSetSubscription subscription = + new ReactiveResultSetSubscription<>( + mainSubscriber, colDefsSubscriber, execInfosSubscriber, wasAppliedSubscriber); + mainSubscriber.onSubscribe(subscription); + subscription.start(() -> future1); + future1.complete(page1); + future2.complete(page2); + // emulate backpressure + subscription.request(1); + future3.complete(page3); + subscription.request(Long.MAX_VALUE); + mainSubscriber.awaitTermination(); + assertThat(mainSubscriber.getError()).isNull(); + List expected = new ArrayList<>(page1.currentPage()); + expected.addAll(page3.currentPage()); + assertThat(mainSubscriber.getElements()).hasSize(20).extracting("row").isEqualTo(expected); + } } diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/cql/reactive/SimpleUnicastProcessorTckTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/cql/reactive/SimpleUnicastProcessorTckTest.java index b92f98c5b2e..3bdd138beef 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/cql/reactive/SimpleUnicastProcessorTckTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/cql/reactive/SimpleUnicastProcessorTckTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/cql/reactive/SimpleUnicastProcessorTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/cql/reactive/SimpleUnicastProcessorTest.java index 211df9aa28c..3ad2173946b 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/cql/reactive/SimpleUnicastProcessorTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/cql/reactive/SimpleUnicastProcessorTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/cql/reactive/TestSubscriber.java b/core/src/test/java/com/datastax/dse/driver/internal/core/cql/reactive/TestSubscriber.java index 607bf57aac5..652155e5309 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/cql/reactive/TestSubscriber.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/cql/reactive/TestSubscriber.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -31,16 +33,25 @@ public class TestSubscriber implements Subscriber { private final List elements = new ArrayList<>(); private final CountDownLatch latch = new CountDownLatch(1); + private final long demand; private Subscription subscription; private Throwable error; + public TestSubscriber() { + this.demand = Long.MAX_VALUE; + } + + public TestSubscriber(long demand) { + this.demand = demand; + } + @Override public void onSubscribe(Subscription s) { if (subscription != null) { fail("already subscribed"); } subscription = s; - s.request(Long.MAX_VALUE); + subscription.request(demand); } @Override @@ -70,6 +81,8 @@ public List getElements() { } public void awaitTermination() { - Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.MINUTES); + if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.MINUTES)) { + fail("subscriber not terminated"); + } } } diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/data/geometry/DefaultLineStringTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/data/geometry/DefaultLineStringTest.java index b362394a528..38dc84549c4 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/data/geometry/DefaultLineStringTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/data/geometry/DefaultLineStringTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/data/geometry/DefaultPointTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/data/geometry/DefaultPointTest.java index 526d8de7329..1e3a7366741 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/data/geometry/DefaultPointTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/data/geometry/DefaultPointTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/data/geometry/DefaultPolygonTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/data/geometry/DefaultPolygonTest.java index b5bc53da030..d86e9cdc269 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/data/geometry/DefaultPolygonTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/data/geometry/DefaultPolygonTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/data/geometry/DistanceTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/data/geometry/DistanceTest.java index 52b1e21ec6e..ba158288891 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/data/geometry/DistanceTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/data/geometry/DistanceTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/data/geometry/SerializationUtils.java b/core/src/test/java/com/datastax/dse/driver/internal/core/data/geometry/SerializationUtils.java index db751d532bb..84bd1dab343 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/data/geometry/SerializationUtils.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/data/geometry/SerializationUtils.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/graph/ContinuousGraphRequestHandlerSpeculativeExecutionTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/graph/ContinuousGraphRequestHandlerSpeculativeExecutionTest.java index 203b49a7ffb..c67be162181 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/graph/ContinuousGraphRequestHandlerSpeculativeExecutionTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/graph/ContinuousGraphRequestHandlerSpeculativeExecutionTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/graph/ContinuousGraphRequestHandlerTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/graph/ContinuousGraphRequestHandlerTest.java index 63935dc7afb..b374539f12e 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/graph/ContinuousGraphRequestHandlerTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/graph/ContinuousGraphRequestHandlerTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -20,6 +22,7 @@ import static com.datastax.dse.driver.internal.core.graph.GraphTestUtils.tenGraphRows; import static com.datastax.oss.driver.Assertions.assertThat; import static com.datastax.oss.driver.Assertions.assertThatStage; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.times; @@ -85,7 +88,7 @@ public void should_return_paged_results(GraphProtocol graphProtocol) throws IOEx try (RequestHandlerTestHarness harness = builder.build()) { - GraphStatement graphStatement = + GraphStatement graphStatement = ScriptGraphStatement.newInstance("mockQuery").setExecutionProfileName(profileName); ContinuousGraphRequestHandler handler = @@ -158,7 +161,7 @@ public void should_honor_default_timeout() throws Exception { when(profile.getString(DseDriverOption.GRAPH_SUB_PROTOCOL)) .thenReturn(GraphProtocol.GRAPH_BINARY_1_0.toInternalCode()); - GraphStatement graphStatement = ScriptGraphStatement.newInstance("mockQuery"); + GraphStatement graphStatement = ScriptGraphStatement.newInstance("mockQuery"); // when ContinuousGraphRequestHandler handler = @@ -182,9 +185,10 @@ public void should_honor_default_timeout() throws Exception { // will trigger the global timeout and complete it exceptionally globalTimeout.task().run(globalTimeout); - assertThat(page1Future.toCompletableFuture()) - .hasFailedWithThrowableThat() - .isInstanceOf(DriverTimeoutException.class) + assertThat(page1Future.toCompletableFuture()).isCompletedExceptionally(); + + assertThatThrownBy(() -> page1Future.toCompletableFuture().get()) + .hasRootCauseExactlyInstanceOf(DriverTimeoutException.class) .hasMessageContaining("Query timed out after " + defaultTimeout); } } @@ -207,7 +211,7 @@ public void should_honor_statement_timeout() throws Exception { when(profile.getString(DseDriverOption.GRAPH_SUB_PROTOCOL)) .thenReturn(GraphProtocol.GRAPH_BINARY_1_0.toInternalCode()); - GraphStatement graphStatement = + GraphStatement graphStatement = ScriptGraphStatement.newInstance("mockQuery").setTimeout(statementTimeout); // when @@ -233,9 +237,10 @@ public void should_honor_statement_timeout() throws Exception { // will trigger the global timeout and complete it exceptionally globalTimeout.task().run(globalTimeout); - assertThat(page1Future.toCompletableFuture()) - .hasFailedWithThrowableThat() - .isInstanceOf(DriverTimeoutException.class) + assertThat(page1Future.toCompletableFuture()).isCompletedExceptionally(); + + assertThatThrownBy(() -> page1Future.toCompletableFuture().get()) + .hasRootCauseExactlyInstanceOf(DriverTimeoutException.class) .hasMessageContaining("Query timed out after " + statementTimeout); } } @@ -249,10 +254,7 @@ private void validateMetrics(String profileName, RequestHandlerTestHarness harne verify(harness.getSession().getMetricUpdater()) .updateTimer( - eq(DseSessionMetric.GRAPH_REQUESTS), - eq(profileName), - anyLong(), - eq(TimeUnit.NANOSECONDS)); + eq(DseSessionMetric.GRAPH_REQUESTS), eq(null), anyLong(), eq(TimeUnit.NANOSECONDS)); verifyNoMoreInteractions(harness.getSession().getMetricUpdater()); } } diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphExecutionInfoConverterTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphExecutionInfoConverterTest.java index 467972523e5..1814b12aa4e 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphExecutionInfoConverterTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphExecutionInfoConverterTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphNodeTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphNodeTest.java index e6e92214292..d7ded441e70 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphNodeTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphNodeTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphRequestHandlerTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphRequestHandlerTest.java index aed0eb4ade4..9f325003610 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphRequestHandlerTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphRequestHandlerTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -137,7 +139,7 @@ public void should_create_query_message_from_fluent_statement(GraphProtocol grap throws IOException { // initialization GraphRequestHandlerTestHarness harness = GraphRequestHandlerTestHarness.builder().build(); - GraphTraversal traversalTest = + GraphTraversal traversalTest = DseGraph.g.V().has("person", "name", "marko").has("p1", 1L).has("p2", Uuids.random()); GraphStatement graphStatement = FluentGraphStatement.newInstance(traversalTest); @@ -171,6 +173,7 @@ public void should_create_query_message_from_batch_statement(GraphProtocol graph throws IOException { // initialization GraphRequestHandlerTestHarness harness = GraphRequestHandlerTestHarness.builder().build(); + @SuppressWarnings("rawtypes") List traversalsTest = ImmutableList.of( // randomly testing some complex data types. Complete suite of data types test is in @@ -424,7 +427,7 @@ public void should_return_results_for_statements(GraphProtocol graphProtocol, Ve Mockito.spy(new GraphRequestAsyncProcessor(harness.getContext(), graphSupportChecker)); when(p.getGraphBinaryModule()).thenReturn(module); - GraphStatement graphStatement = + GraphStatement graphStatement = ScriptGraphStatement.newInstance("mockQuery").setExecutionProfileName("test-graph"); GraphResultSet grs = new GraphRequestSyncProcessor(p) @@ -487,7 +490,7 @@ public void should_invoke_request_tracker_and_update_metrics( RequestTracker requestTracker = mock(RequestTracker.class); when(harness.getContext().getRequestTracker()).thenReturn(requestTracker); - GraphStatement graphStatement = ScriptGraphStatement.newInstance("mockQuery"); + GraphStatement graphStatement = ScriptGraphStatement.newInstance("mockQuery"); node1Behavior.setResponseSuccess(defaultDseFrameOf(singleGraphRow(graphProtocol, module))); @@ -549,6 +552,31 @@ public void should_invoke_request_tracker_and_update_metrics( verifyNoMoreInteractions(harness.getSession().getMetricUpdater()); } + @Test + public void should_honor_statement_consistency_level() { + // initialization + GraphRequestHandlerTestHarness harness = GraphRequestHandlerTestHarness.builder().build(); + ScriptGraphStatement graphStatement = + ScriptGraphStatement.builder("mockScript") + .setConsistencyLevel(DefaultConsistencyLevel.THREE) + .build(); + + GraphBinaryModule module = createGraphBinaryModule(harness.getContext()); + + // when + DriverExecutionProfile executionProfile = + Conversions.resolveExecutionProfile(graphStatement, harness.getContext()); + + Message m = + GraphConversions.createMessageFromGraphStatement( + graphStatement, GRAPH_BINARY_1_0, executionProfile, harness.getContext(), module); + + // checks + assertThat(m).isInstanceOf(Query.class); + Query q = ((Query) m); + assertThat(q.options.consistency).isEqualTo(DefaultConsistencyLevel.THREE.getProtocolCode()); + } + @DataProvider public static Object[][] dseVersionsWithDefaultGraphProtocol() { // Default GraphSON sub protocol version differs based on DSE version, so test with a version diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphRequestHandlerTestHarness.java b/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphRequestHandlerTestHarness.java index e903d9ce1d2..7e46b09bd59 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphRequestHandlerTestHarness.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphRequestHandlerTestHarness.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphResultSetTestBase.java b/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphResultSetTestBase.java index 6d14e80339b..aed248675ae 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphResultSetTestBase.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphResultSetTestBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphResultSetsTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphResultSetsTest.java index bdcb526fba8..fd5cffd2530 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphResultSetsTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphResultSetsTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphStatementBuilderBaseTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphStatementBuilderBaseTest.java index 97212882358..4799437e617 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphStatementBuilderBaseTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphStatementBuilderBaseTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphSupportCheckerTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphSupportCheckerTest.java index da541adf19f..ec31bd4b12d 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphSupportCheckerTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphSupportCheckerTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphTestUtils.java b/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphTestUtils.java index 13b66f2502e..f58fc54d8c7 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphTestUtils.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/graph/GraphTestUtils.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/graph/binary/GraphDataTypesTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/graph/binary/GraphDataTypesTest.java index d814e36cbac..e36f7e97e5a 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/graph/binary/GraphDataTypesTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/graph/binary/GraphDataTypesTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/graph/reactive/ReactiveGraphRequestProcessorTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/graph/reactive/ReactiveGraphRequestProcessorTest.java index 8658f044d9c..324c4ff4672 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/graph/reactive/ReactiveGraphRequestProcessorTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/graph/reactive/ReactiveGraphRequestProcessorTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/graph/schema/refresh/GraphSchemaRefreshTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/graph/schema/refresh/GraphSchemaRefreshTest.java index 5047032e95e..0d05f129520 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/graph/schema/refresh/GraphSchemaRefreshTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/graph/schema/refresh/GraphSchemaRefreshTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/insights/AddressFormatterTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/insights/AddressFormatterTest.java index ec65f4e156d..85af9b5691b 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/insights/AddressFormatterTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/insights/AddressFormatterTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/insights/ConfigAntiPatternsFinderTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/insights/ConfigAntiPatternsFinderTest.java index 22ffa73c0c7..d5466b23dbc 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/insights/ConfigAntiPatternsFinderTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/insights/ConfigAntiPatternsFinderTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/insights/DataCentersFinderTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/insights/DataCentersFinderTest.java index c11b9144220..dde6db6059e 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/insights/DataCentersFinderTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/insights/DataCentersFinderTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/insights/ExecutionProfileMockUtil.java b/core/src/test/java/com/datastax/dse/driver/internal/core/insights/ExecutionProfileMockUtil.java index de8a4693d5e..de0f3a9d60b 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/insights/ExecutionProfileMockUtil.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/insights/ExecutionProfileMockUtil.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -20,7 +22,7 @@ import static com.datastax.oss.driver.api.core.config.DefaultDriverOption.CONNECTION_POOL_LOCAL_SIZE; import static com.datastax.oss.driver.api.core.config.DefaultDriverOption.CONNECTION_POOL_REMOTE_SIZE; import static com.datastax.oss.driver.api.core.config.DefaultDriverOption.HEARTBEAT_INTERVAL; -import static com.datastax.oss.driver.api.core.config.DefaultDriverOption.LOAD_BALANCING_FILTER_CLASS; +import static com.datastax.oss.driver.api.core.config.DefaultDriverOption.LOAD_BALANCING_DISTANCE_EVALUATOR_CLASS; import static com.datastax.oss.driver.api.core.config.DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER; import static com.datastax.oss.driver.api.core.config.DefaultDriverOption.LOAD_BALANCING_POLICY_CLASS; import static com.datastax.oss.driver.api.core.config.DefaultDriverOption.PROTOCOL_COMPRESSION; @@ -50,7 +52,7 @@ static DriverExecutionProfile mockDefaultExecutionProfile() { when(profile.getDuration(REQUEST_TIMEOUT)).thenReturn(Duration.ofMillis(100)); when(profile.getString(LOAD_BALANCING_POLICY_CLASS)).thenReturn("LoadBalancingPolicyImpl"); - when(profile.isDefined(LOAD_BALANCING_FILTER_CLASS)).thenReturn(true); + when(profile.isDefined(LOAD_BALANCING_DISTANCE_EVALUATOR_CLASS)).thenReturn(true); when(profile.isDefined(LOAD_BALANCING_LOCAL_DATACENTER)).thenReturn(true); when(profile.getString(LOAD_BALANCING_LOCAL_DATACENTER)).thenReturn(DEFAULT_LOCAL_DC); when(profile.isDefined(SPECULATIVE_EXECUTION_MAX)).thenReturn(true); diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/insights/ExecutionProfilesInfoFinderTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/insights/ExecutionProfilesInfoFinderTest.java index d119ea5b655..fc92ab20521 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/insights/ExecutionProfilesInfoFinderTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/insights/ExecutionProfilesInfoFinderTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/insights/InsightsClientTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/insights/InsightsClientTest.java index da5ce66c8b6..74869893b72 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/insights/InsightsClientTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/insights/InsightsClientTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/insights/InsightsSupportVerifierTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/insights/InsightsSupportVerifierTest.java index ccd3f94212a..9edd4494bdd 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/insights/InsightsSupportVerifierTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/insights/InsightsSupportVerifierTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/insights/PackageUtilTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/insights/PackageUtilTest.java index 352ef690165..336f19184d3 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/insights/PackageUtilTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/insights/PackageUtilTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/insights/PlatformInfoFinderTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/insights/PlatformInfoFinderTest.java index 2f243915881..2a098363d46 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/insights/PlatformInfoFinderTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/insights/PlatformInfoFinderTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -75,7 +77,7 @@ public void should_find_dependencies_from_file() { "com.fasterxml.jackson.core:jackson-annotations", withUnverifiedRuntimeVersion("2.8.11")); expected.put("com.fasterxml.jackson.core:jackson-core", withUnverifiedRuntimeVersion("2.8.11")); expected.put("io.netty:netty-handler", withUnverifiedRuntimeVersion("4.0.56.Final")); - expected.put("org.lz4:lz4-java", withUnverifiedRuntimeVersionOptional("1.4.1")); + expected.put("at.yawk.lz4:lz4-java", withUnverifiedRuntimeVersionOptional("1.10.1")); expected.put("org.hdrhistogram:HdrHistogram", withUnverifiedRuntimeVersionOptional("2.1.10")); expected.put("com.github.jnr:jffi", withUnverifiedRuntimeVersion("1.2.16")); expected.put("io.netty:netty-buffer", withUnverifiedRuntimeVersion("4.0.56.Final")); diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/insights/ReconnectionPolicyInfoFinderTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/insights/ReconnectionPolicyInfoFinderTest.java index 5952e05f30e..a076ca38b1c 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/insights/ReconnectionPolicyInfoFinderTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/insights/ReconnectionPolicyInfoFinderTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/protocol/TinkerpopBufferPrimitiveCodecTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/protocol/TinkerpopBufferPrimitiveCodecTest.java index 7dd240baf99..3ef89c78714 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/protocol/TinkerpopBufferPrimitiveCodecTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/protocol/TinkerpopBufferPrimitiveCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,6 +18,7 @@ package com.datastax.dse.driver.internal.core.protocol; import static com.datastax.dse.driver.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.datastax.dse.driver.Assertions; import com.datastax.dse.driver.internal.core.graph.binary.buffer.DseNettyBufferFactory; @@ -29,9 +32,7 @@ import java.nio.ByteBuffer; import java.util.function.Supplier; import org.apache.tinkerpop.gremlin.structure.io.Buffer; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; /** @@ -45,8 +46,6 @@ public class TinkerpopBufferPrimitiveCodecTest { private static final DseNettyBufferFactory factory = new DseNettyBufferFactory(); private final TinkerpopBufferPrimitiveCodec codec = new TinkerpopBufferPrimitiveCodec(factory); - @Rule public ExpectedException expectedException = ExpectedException.none(); - @Test public void should_concatenate() { Buffer left = factory.withBytes(0xca, 0xfe); @@ -93,8 +92,6 @@ public void should_read_inet_v6() { @Test public void should_fail_to_read_inet_if_length_invalid() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Invalid address length: 3 ([127, 0, 1])"); Buffer source = factory.withBytes( // length (as a byte) @@ -108,7 +105,9 @@ public void should_fail_to_read_inet_if_length_invalid() { 0x00, 0x23, 0x52); - codec.readInet(source); + assertThatThrownBy(() -> codec.readInet(source)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid address length: 3 ([127, 0, 1])"); } @Test @@ -138,9 +137,6 @@ public void should_read_inetaddr_v6() { @Test public void should_fail_to_read_inetaddr_if_length_invalid() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Invalid address length: 3 ([127, 0, 1])"); - Buffer source = factory.withBytes( // length (as a byte) @@ -149,7 +145,9 @@ public void should_fail_to_read_inetaddr_if_length_invalid() { 0x7f, 0x00, 0x01); - codec.readInetAddr(source); + assertThatThrownBy(() -> codec.readInetAddr(source)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid address length: 3 ([127, 0, 1])"); } @Test @@ -220,14 +218,12 @@ public void should_read_string(Supplier supplier) { @Test public void should_fail_to_read_string_if_not_enough_characters() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage( - "Not enough bytes to read an UTF-8 serialized string of size 4"); - Buffer source = factory.heap(); source.writeShort(4); - codec.readString(source); + assertThatThrownBy(() -> codec.readString(source)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Not enough bytes to read an UTF-8 serialized string of size 4"); } @Test @@ -250,13 +246,12 @@ public void should_read_long_string() { @Test public void should_fail_to_read_long_string_if_not_enough_characters() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage( - "Not enough bytes to read an UTF-8 serialized string of size 4"); Buffer source = factory.heap(4, 4); source.writeInt(4); - codec.readLongString(source); + assertThatThrownBy(() -> codec.readLongString(source)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Not enough bytes to read an UTF-8 serialized string of size 4"); } @Test diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/type/codec/geometry/GeometryCodecTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/type/codec/geometry/GeometryCodecTest.java index 3dff7dc704a..9e4d019660c 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/type/codec/geometry/GeometryCodecTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/type/codec/geometry/GeometryCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/type/codec/geometry/LineStringCodecTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/type/codec/geometry/LineStringCodecTest.java index 5f8f0c11a64..ba71026ac2c 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/type/codec/geometry/LineStringCodecTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/type/codec/geometry/LineStringCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/type/codec/geometry/PointCodecTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/type/codec/geometry/PointCodecTest.java index cec225df130..7948f4d758a 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/type/codec/geometry/PointCodecTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/type/codec/geometry/PointCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/type/codec/geometry/PolygonCodecTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/type/codec/geometry/PolygonCodecTest.java index e4c65a37189..290dabe7519 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/type/codec/geometry/PolygonCodecTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/type/codec/geometry/PolygonCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/type/codec/time/DateRangeCodecTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/type/codec/time/DateRangeCodecTest.java index affbb32dea2..b9b618b8dd3 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/type/codec/time/DateRangeCodecTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/type/codec/time/DateRangeCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/dse/driver/internal/core/util/concurrent/BoundedConcurrentQueueTest.java b/core/src/test/java/com/datastax/dse/driver/internal/core/util/concurrent/BoundedConcurrentQueueTest.java index 0509994282f..5cf8a67f84b 100644 --- a/core/src/test/java/com/datastax/dse/driver/internal/core/util/concurrent/BoundedConcurrentQueueTest.java +++ b/core/src/test/java/com/datastax/dse/driver/internal/core/util/concurrent/BoundedConcurrentQueueTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/Assertions.java b/core/src/test/java/com/datastax/oss/driver/Assertions.java index 6137414a5db..8478053e6d8 100644 --- a/core/src/test/java/com/datastax/oss/driver/Assertions.java +++ b/core/src/test/java/com/datastax/oss/driver/Assertions.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/ByteBufAssert.java b/core/src/test/java/com/datastax/oss/driver/ByteBufAssert.java index 917d572e721..4cd9c3ed358 100644 --- a/core/src/test/java/com/datastax/oss/driver/ByteBufAssert.java +++ b/core/src/test/java/com/datastax/oss/driver/ByteBufAssert.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/DriverRunListener.java b/core/src/test/java/com/datastax/oss/driver/DriverRunListener.java index 67c22c56eeb..085134b28f2 100644 --- a/core/src/test/java/com/datastax/oss/driver/DriverRunListener.java +++ b/core/src/test/java/com/datastax/oss/driver/DriverRunListener.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/TestDataProviders.java b/core/src/test/java/com/datastax/oss/driver/TestDataProviders.java index 866a4bc9f75..a0448c4b769 100644 --- a/core/src/test/java/com/datastax/oss/driver/TestDataProviders.java +++ b/core/src/test/java/com/datastax/oss/driver/TestDataProviders.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -17,6 +19,7 @@ import com.tngtech.java.junit.dataprovider.DataProvider; import java.util.Arrays; +import java.util.Locale; public class TestDataProviders { @@ -83,4 +86,24 @@ public static Object[][] combine(Object[][]... providers) { public static Object[][] booleans() { return fromList(true, false); } + + /** An arbitrary set of locales to use when testing locale-sensitive operations. */ + @DataProvider + public static Object[][] locales() { + return new Object[][] { + new Object[] {Locale.US}, + // non-latin alphabets + new Object[] {Locale.CHINA}, + new Object[] {Locale.JAPAN}, + new Object[] {Locale.KOREA}, + new Object[] {new Locale("gr") /* greek */}, + new Object[] {new Locale("ar") /* arabic */}, + // latin-based alphabets with extended character sets + new Object[] {new Locale("vi") /* vietnamese */}, + // JAVA-2883: Turkish is the most problematic locale as String.toLowerCase("TITLE") + // wouldn't return "title" but rather "tıtle", where 'ı' is the 'LATIN SMALL LETTER + // DOTLESS I' character specific to the Turkish language. + new Object[] {new Locale("tr") /* turkish*/}, + }; + } } diff --git a/core/src/test/java/com/datastax/oss/driver/api/core/AllNodesFailedExceptionTest.java b/core/src/test/java/com/datastax/oss/driver/api/core/AllNodesFailedExceptionTest.java index 5c5ad335ef6..4cd4c0fcd74 100644 --- a/core/src/test/java/com/datastax/oss/driver/api/core/AllNodesFailedExceptionTest.java +++ b/core/src/test/java/com/datastax/oss/driver/api/core/AllNodesFailedExceptionTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/api/core/CqlIdentifierTest.java b/core/src/test/java/com/datastax/oss/driver/api/core/CqlIdentifierTest.java index db440007e92..5c7203b8f8d 100644 --- a/core/src/test/java/com/datastax/oss/driver/api/core/CqlIdentifierTest.java +++ b/core/src/test/java/com/datastax/oss/driver/api/core/CqlIdentifierTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -17,9 +19,16 @@ import static org.assertj.core.api.Assertions.assertThat; +import com.datastax.oss.driver.TestDataProviders; +import com.tngtech.java.junit.dataprovider.DataProviderRunner; +import com.tngtech.java.junit.dataprovider.UseDataProvider; +import java.util.Locale; import org.junit.Test; +import org.junit.runner.RunWith; +@RunWith(DataProviderRunner.class) public class CqlIdentifierTest { + @Test public void should_build_from_internal() { assertThat(CqlIdentifier.fromInternal("foo").asInternal()).isEqualTo("foo"); @@ -30,13 +39,22 @@ public void should_build_from_internal() { } @Test - public void should_build_from_valid_cql() { - assertThat(CqlIdentifier.fromCql("foo").asInternal()).isEqualTo("foo"); - assertThat(CqlIdentifier.fromCql("Foo").asInternal()).isEqualTo("foo"); - assertThat(CqlIdentifier.fromCql("\"Foo\"").asInternal()).isEqualTo("Foo"); - assertThat(CqlIdentifier.fromCql("\"foo bar\"").asInternal()).isEqualTo("foo bar"); - assertThat(CqlIdentifier.fromCql("\"foo\"\"bar\"").asInternal()).isEqualTo("foo\"bar"); - assertThat(CqlIdentifier.fromCql("\"create\"").asInternal()).isEqualTo("create"); + @UseDataProvider(location = TestDataProviders.class, value = "locales") + public void should_build_from_valid_cql(Locale locale) { + Locale def = Locale.getDefault(); + try { + Locale.setDefault(locale); + assertThat(CqlIdentifier.fromCql("foo").asInternal()).isEqualTo("foo"); + assertThat(CqlIdentifier.fromCql("Foo").asInternal()).isEqualTo("foo"); + assertThat(CqlIdentifier.fromCql("\"Foo\"").asInternal()).isEqualTo("Foo"); + assertThat(CqlIdentifier.fromCql("\"foo bar\"").asInternal()).isEqualTo("foo bar"); + assertThat(CqlIdentifier.fromCql("\"foo\"\"bar\"").asInternal()).isEqualTo("foo\"bar"); + assertThat(CqlIdentifier.fromCql("\"create\"").asInternal()).isEqualTo("create"); + // JAVA-2883: this would fail under turkish locale if it was used internally + assertThat(CqlIdentifier.fromCql("TITLE").asInternal()).isEqualTo("title"); + } finally { + Locale.setDefault(def); + } } @Test(expected = IllegalArgumentException.class) diff --git a/core/src/test/java/com/datastax/oss/driver/api/core/VersionAssert.java b/core/src/test/java/com/datastax/oss/driver/api/core/VersionAssert.java index 1525d95b1da..61beb5cea51 100644 --- a/core/src/test/java/com/datastax/oss/driver/api/core/VersionAssert.java +++ b/core/src/test/java/com/datastax/oss/driver/api/core/VersionAssert.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/api/core/VersionTest.java b/core/src/test/java/com/datastax/oss/driver/api/core/VersionTest.java index 4a61e246827..bce30816f9c 100644 --- a/core/src/test/java/com/datastax/oss/driver/api/core/VersionTest.java +++ b/core/src/test/java/com/datastax/oss/driver/api/core/VersionTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/api/core/auth/ProgrammaticPlainTextAuthProviderTest.java b/core/src/test/java/com/datastax/oss/driver/api/core/auth/ProgrammaticPlainTextAuthProviderTest.java new file mode 100644 index 00000000000..44d2acfbb2e --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/api/core/auth/ProgrammaticPlainTextAuthProviderTest.java @@ -0,0 +1,101 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.api.core.auth; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.datastax.oss.driver.api.core.auth.PlainTextAuthProviderBase.Credentials; +import com.datastax.oss.driver.api.core.metadata.EndPoint; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.Strict.class) +public class ProgrammaticPlainTextAuthProviderTest { + + @Mock private EndPoint endpoint; + + @Test + public void should_return_correct_credentials_without_authorization_id() { + // given + ProgrammaticPlainTextAuthProvider provider = + new ProgrammaticPlainTextAuthProvider("user", "pass"); + // when + Credentials credentials = provider.getCredentials(endpoint, "irrelevant"); + // then + assertThat(credentials.getUsername()).isEqualTo("user".toCharArray()); + assertThat(credentials.getPassword()).isEqualTo("pass".toCharArray()); + assertThat(credentials.getAuthorizationId()).isEqualTo(new char[0]); + } + + @Test + public void should_return_correct_credentials_with_authorization_id() { + // given + ProgrammaticPlainTextAuthProvider provider = + new ProgrammaticPlainTextAuthProvider("user", "pass", "proxy"); + // when + Credentials credentials = provider.getCredentials(endpoint, "irrelevant"); + // then + assertThat(credentials.getUsername()).isEqualTo("user".toCharArray()); + assertThat(credentials.getPassword()).isEqualTo("pass".toCharArray()); + assertThat(credentials.getAuthorizationId()).isEqualTo("proxy".toCharArray()); + } + + @Test + public void should_change_username() { + // given + ProgrammaticPlainTextAuthProvider provider = + new ProgrammaticPlainTextAuthProvider("user", "pass"); + // when + provider.setUsername("user2"); + Credentials credentials = provider.getCredentials(endpoint, "irrelevant"); + // then + assertThat(credentials.getUsername()).isEqualTo("user2".toCharArray()); + assertThat(credentials.getPassword()).isEqualTo("pass".toCharArray()); + assertThat(credentials.getAuthorizationId()).isEqualTo(new char[0]); + } + + @Test + public void should_change_password() { + // given + ProgrammaticPlainTextAuthProvider provider = + new ProgrammaticPlainTextAuthProvider("user", "pass"); + // when + provider.setPassword("pass2"); + Credentials credentials = provider.getCredentials(endpoint, "irrelevant"); + // then + assertThat(credentials.getUsername()).isEqualTo("user".toCharArray()); + assertThat(credentials.getPassword()).isEqualTo("pass2".toCharArray()); + assertThat(credentials.getAuthorizationId()).isEqualTo(new char[0]); + } + + @Test + public void should_change_authorization_id() { + // given + ProgrammaticPlainTextAuthProvider provider = + new ProgrammaticPlainTextAuthProvider("user", "pass", "proxy"); + // when + provider.setAuthorizationId("proxy2"); + Credentials credentials = provider.getCredentials(endpoint, "irrelevant"); + // then + assertThat(credentials.getUsername()).isEqualTo("user".toCharArray()); + assertThat(credentials.getPassword()).isEqualTo("pass".toCharArray()); + assertThat(credentials.getAuthorizationId()).isEqualTo("proxy2".toCharArray()); + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/api/core/config/OptionsMapTest.java b/core/src/test/java/com/datastax/oss/driver/api/core/config/OptionsMapTest.java index f47fb872b16..ec0410ed868 100644 --- a/core/src/test/java/com/datastax/oss/driver/api/core/config/OptionsMapTest.java +++ b/core/src/test/java/com/datastax/oss/driver/api/core/config/OptionsMapTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/api/core/config/TypedDriverOptionTest.java b/core/src/test/java/com/datastax/oss/driver/api/core/config/TypedDriverOptionTest.java index 9c63250d87d..eee4000a459 100644 --- a/core/src/test/java/com/datastax/oss/driver/api/core/config/TypedDriverOptionTest.java +++ b/core/src/test/java/com/datastax/oss/driver/api/core/config/TypedDriverOptionTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/api/core/cql/StatementBuilderTest.java b/core/src/test/java/com/datastax/oss/driver/api/core/cql/StatementBuilderTest.java index fd5830cfd38..9904b1e27d7 100644 --- a/core/src/test/java/com/datastax/oss/driver/api/core/cql/StatementBuilderTest.java +++ b/core/src/test/java/com/datastax/oss/driver/api/core/cql/StatementBuilderTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/api/core/cql/StatementProfileTest.java b/core/src/test/java/com/datastax/oss/driver/api/core/cql/StatementProfileTest.java index 7606979f3a7..af2dccd0432 100644 --- a/core/src/test/java/com/datastax/oss/driver/api/core/cql/StatementProfileTest.java +++ b/core/src/test/java/com/datastax/oss/driver/api/core/cql/StatementProfileTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/api/core/data/CqlDurationTest.java b/core/src/test/java/com/datastax/oss/driver/api/core/data/CqlDurationTest.java index a880f4a8579..f55453b3eba 100644 --- a/core/src/test/java/com/datastax/oss/driver/api/core/data/CqlDurationTest.java +++ b/core/src/test/java/com/datastax/oss/driver/api/core/data/CqlDurationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -19,92 +21,120 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; +import com.datastax.oss.driver.TestDataProviders; +import com.datastax.oss.driver.internal.SerializationHelper; +import com.tngtech.java.junit.dataprovider.DataProviderRunner; +import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.time.ZonedDateTime; import java.time.temporal.ChronoUnit; import java.time.temporal.UnsupportedTemporalTypeException; +import java.util.Locale; import org.junit.Test; +import org.junit.runner.RunWith; +@RunWith(DataProviderRunner.class) public class CqlDurationTest { @Test - public void should_parse_from_string_with_standard_pattern() { - assertThat(CqlDuration.from("1y2mo")).isEqualTo(CqlDuration.newInstance(14, 0, 0)); - assertThat(CqlDuration.from("-1y2mo")).isEqualTo(CqlDuration.newInstance(-14, 0, 0)); - assertThat(CqlDuration.from("1Y2MO")).isEqualTo(CqlDuration.newInstance(14, 0, 0)); - assertThat(CqlDuration.from("2w")).isEqualTo(CqlDuration.newInstance(0, 14, 0)); - assertThat(CqlDuration.from("2d10h")) - .isEqualTo(CqlDuration.newInstance(0, 2, 10 * CqlDuration.NANOS_PER_HOUR)); - assertThat(CqlDuration.from("2d")).isEqualTo(CqlDuration.newInstance(0, 2, 0)); - assertThat(CqlDuration.from("30h")) - .isEqualTo(CqlDuration.newInstance(0, 0, 30 * CqlDuration.NANOS_PER_HOUR)); - assertThat(CqlDuration.from("30h20m")) - .isEqualTo( - CqlDuration.newInstance( - 0, 0, 30 * CqlDuration.NANOS_PER_HOUR + 20 * CqlDuration.NANOS_PER_MINUTE)); - assertThat(CqlDuration.from("20m")) - .isEqualTo(CqlDuration.newInstance(0, 0, 20 * CqlDuration.NANOS_PER_MINUTE)); - assertThat(CqlDuration.from("56s")) - .isEqualTo(CqlDuration.newInstance(0, 0, 56 * CqlDuration.NANOS_PER_SECOND)); - assertThat(CqlDuration.from("567ms")) - .isEqualTo(CqlDuration.newInstance(0, 0, 567 * CqlDuration.NANOS_PER_MILLI)); - assertThat(CqlDuration.from("1950us")) - .isEqualTo(CqlDuration.newInstance(0, 0, 1950 * CqlDuration.NANOS_PER_MICRO)); - assertThat(CqlDuration.from("1950µs")) - .isEqualTo(CqlDuration.newInstance(0, 0, 1950 * CqlDuration.NANOS_PER_MICRO)); - assertThat(CqlDuration.from("1950000ns")).isEqualTo(CqlDuration.newInstance(0, 0, 1950000)); - assertThat(CqlDuration.from("1950000NS")).isEqualTo(CqlDuration.newInstance(0, 0, 1950000)); - assertThat(CqlDuration.from("-1950000ns")).isEqualTo(CqlDuration.newInstance(0, 0, -1950000)); - assertThat(CqlDuration.from("1y3mo2h10m")) - .isEqualTo(CqlDuration.newInstance(15, 0, 130 * CqlDuration.NANOS_PER_MINUTE)); + @UseDataProvider(location = TestDataProviders.class, value = "locales") + public void should_parse_from_string_with_standard_pattern(Locale locale) { + Locale def = Locale.getDefault(); + try { + Locale.setDefault(locale); + assertThat(CqlDuration.from("1y2mo")).isEqualTo(CqlDuration.newInstance(14, 0, 0)); + assertThat(CqlDuration.from("-1y2mo")).isEqualTo(CqlDuration.newInstance(-14, 0, 0)); + assertThat(CqlDuration.from("1Y2MO")).isEqualTo(CqlDuration.newInstance(14, 0, 0)); + assertThat(CqlDuration.from("2w")).isEqualTo(CqlDuration.newInstance(0, 14, 0)); + assertThat(CqlDuration.from("2d10h")) + .isEqualTo(CqlDuration.newInstance(0, 2, 10 * CqlDuration.NANOS_PER_HOUR)); + assertThat(CqlDuration.from("2d")).isEqualTo(CqlDuration.newInstance(0, 2, 0)); + assertThat(CqlDuration.from("30h")) + .isEqualTo(CqlDuration.newInstance(0, 0, 30 * CqlDuration.NANOS_PER_HOUR)); + assertThat(CqlDuration.from("30h20m")) + .isEqualTo( + CqlDuration.newInstance( + 0, 0, 30 * CqlDuration.NANOS_PER_HOUR + 20 * CqlDuration.NANOS_PER_MINUTE)); + assertThat(CqlDuration.from("20m")) + .isEqualTo(CqlDuration.newInstance(0, 0, 20 * CqlDuration.NANOS_PER_MINUTE)); + assertThat(CqlDuration.from("56s")) + .isEqualTo(CqlDuration.newInstance(0, 0, 56 * CqlDuration.NANOS_PER_SECOND)); + assertThat(CqlDuration.from("567ms")) + .isEqualTo(CqlDuration.newInstance(0, 0, 567 * CqlDuration.NANOS_PER_MILLI)); + assertThat(CqlDuration.from("1950us")) + .isEqualTo(CqlDuration.newInstance(0, 0, 1950 * CqlDuration.NANOS_PER_MICRO)); + assertThat(CqlDuration.from("1950µs")) + .isEqualTo(CqlDuration.newInstance(0, 0, 1950 * CqlDuration.NANOS_PER_MICRO)); + assertThat(CqlDuration.from("1950000ns")).isEqualTo(CqlDuration.newInstance(0, 0, 1950000)); + assertThat(CqlDuration.from("1950000NS")).isEqualTo(CqlDuration.newInstance(0, 0, 1950000)); + assertThat(CqlDuration.from("-1950000ns")).isEqualTo(CqlDuration.newInstance(0, 0, -1950000)); + assertThat(CqlDuration.from("1y3mo2h10m")) + .isEqualTo(CqlDuration.newInstance(15, 0, 130 * CqlDuration.NANOS_PER_MINUTE)); + } finally { + Locale.setDefault(def); + } } @Test - public void should_parse_from_string_with_iso8601_pattern() { - assertThat(CqlDuration.from("P1Y2D")).isEqualTo(CqlDuration.newInstance(12, 2, 0)); - assertThat(CqlDuration.from("P1Y2M")).isEqualTo(CqlDuration.newInstance(14, 0, 0)); - assertThat(CqlDuration.from("P2W")).isEqualTo(CqlDuration.newInstance(0, 14, 0)); - assertThat(CqlDuration.from("P1YT2H")) - .isEqualTo(CqlDuration.newInstance(12, 0, 2 * CqlDuration.NANOS_PER_HOUR)); - assertThat(CqlDuration.from("-P1Y2M")).isEqualTo(CqlDuration.newInstance(-14, 0, 0)); - assertThat(CqlDuration.from("P2D")).isEqualTo(CqlDuration.newInstance(0, 2, 0)); - assertThat(CqlDuration.from("PT30H")) - .isEqualTo(CqlDuration.newInstance(0, 0, 30 * CqlDuration.NANOS_PER_HOUR)); - assertThat(CqlDuration.from("PT30H20M")) - .isEqualTo( - CqlDuration.newInstance( - 0, 0, 30 * CqlDuration.NANOS_PER_HOUR + 20 * CqlDuration.NANOS_PER_MINUTE)); - assertThat(CqlDuration.from("PT20M")) - .isEqualTo(CqlDuration.newInstance(0, 0, 20 * CqlDuration.NANOS_PER_MINUTE)); - assertThat(CqlDuration.from("PT56S")) - .isEqualTo(CqlDuration.newInstance(0, 0, 56 * CqlDuration.NANOS_PER_SECOND)); - assertThat(CqlDuration.from("P1Y3MT2H10M")) - .isEqualTo(CqlDuration.newInstance(15, 0, 130 * CqlDuration.NANOS_PER_MINUTE)); + @UseDataProvider(location = TestDataProviders.class, value = "locales") + public void should_parse_from_string_with_iso8601_pattern(Locale locale) { + Locale def = Locale.getDefault(); + try { + Locale.setDefault(locale); + assertThat(CqlDuration.from("P1Y2D")).isEqualTo(CqlDuration.newInstance(12, 2, 0)); + assertThat(CqlDuration.from("P1Y2M")).isEqualTo(CqlDuration.newInstance(14, 0, 0)); + assertThat(CqlDuration.from("P2W")).isEqualTo(CqlDuration.newInstance(0, 14, 0)); + assertThat(CqlDuration.from("P1YT2H")) + .isEqualTo(CqlDuration.newInstance(12, 0, 2 * CqlDuration.NANOS_PER_HOUR)); + assertThat(CqlDuration.from("-P1Y2M")).isEqualTo(CqlDuration.newInstance(-14, 0, 0)); + assertThat(CqlDuration.from("P2D")).isEqualTo(CqlDuration.newInstance(0, 2, 0)); + assertThat(CqlDuration.from("PT30H")) + .isEqualTo(CqlDuration.newInstance(0, 0, 30 * CqlDuration.NANOS_PER_HOUR)); + assertThat(CqlDuration.from("PT30H20M")) + .isEqualTo( + CqlDuration.newInstance( + 0, 0, 30 * CqlDuration.NANOS_PER_HOUR + 20 * CqlDuration.NANOS_PER_MINUTE)); + assertThat(CqlDuration.from("PT20M")) + .isEqualTo(CqlDuration.newInstance(0, 0, 20 * CqlDuration.NANOS_PER_MINUTE)); + assertThat(CqlDuration.from("PT56S")) + .isEqualTo(CqlDuration.newInstance(0, 0, 56 * CqlDuration.NANOS_PER_SECOND)); + assertThat(CqlDuration.from("P1Y3MT2H10M")) + .isEqualTo(CqlDuration.newInstance(15, 0, 130 * CqlDuration.NANOS_PER_MINUTE)); + } finally { + Locale.setDefault(def); + } } @Test - public void should_parse_from_string_with_iso8601_alternative_pattern() { - assertThat(CqlDuration.from("P0001-00-02T00:00:00")) - .isEqualTo(CqlDuration.newInstance(12, 2, 0)); - assertThat(CqlDuration.from("P0001-02-00T00:00:00")) - .isEqualTo(CqlDuration.newInstance(14, 0, 0)); - assertThat(CqlDuration.from("P0001-00-00T02:00:00")) - .isEqualTo(CqlDuration.newInstance(12, 0, 2 * CqlDuration.NANOS_PER_HOUR)); - assertThat(CqlDuration.from("-P0001-02-00T00:00:00")) - .isEqualTo(CqlDuration.newInstance(-14, 0, 0)); - assertThat(CqlDuration.from("P0000-00-02T00:00:00")) - .isEqualTo(CqlDuration.newInstance(0, 2, 0)); - assertThat(CqlDuration.from("P0000-00-00T30:00:00")) - .isEqualTo(CqlDuration.newInstance(0, 0, 30 * CqlDuration.NANOS_PER_HOUR)); - assertThat(CqlDuration.from("P0000-00-00T30:20:00")) - .isEqualTo( - CqlDuration.newInstance( - 0, 0, 30 * CqlDuration.NANOS_PER_HOUR + 20 * CqlDuration.NANOS_PER_MINUTE)); - assertThat(CqlDuration.from("P0000-00-00T00:20:00")) - .isEqualTo(CqlDuration.newInstance(0, 0, 20 * CqlDuration.NANOS_PER_MINUTE)); - assertThat(CqlDuration.from("P0000-00-00T00:00:56")) - .isEqualTo(CqlDuration.newInstance(0, 0, 56 * CqlDuration.NANOS_PER_SECOND)); - assertThat(CqlDuration.from("P0001-03-00T02:10:00")) - .isEqualTo(CqlDuration.newInstance(15, 0, 130 * CqlDuration.NANOS_PER_MINUTE)); + @UseDataProvider(location = TestDataProviders.class, value = "locales") + public void should_parse_from_string_with_iso8601_alternative_pattern(Locale locale) { + Locale def = Locale.getDefault(); + try { + Locale.setDefault(locale); + assertThat(CqlDuration.from("P0001-00-02T00:00:00")) + .isEqualTo(CqlDuration.newInstance(12, 2, 0)); + assertThat(CqlDuration.from("P0001-02-00T00:00:00")) + .isEqualTo(CqlDuration.newInstance(14, 0, 0)); + assertThat(CqlDuration.from("P0001-00-00T02:00:00")) + .isEqualTo(CqlDuration.newInstance(12, 0, 2 * CqlDuration.NANOS_PER_HOUR)); + assertThat(CqlDuration.from("-P0001-02-00T00:00:00")) + .isEqualTo(CqlDuration.newInstance(-14, 0, 0)); + assertThat(CqlDuration.from("P0000-00-02T00:00:00")) + .isEqualTo(CqlDuration.newInstance(0, 2, 0)); + assertThat(CqlDuration.from("P0000-00-00T30:00:00")) + .isEqualTo(CqlDuration.newInstance(0, 0, 30 * CqlDuration.NANOS_PER_HOUR)); + assertThat(CqlDuration.from("P0000-00-00T30:20:00")) + .isEqualTo( + CqlDuration.newInstance( + 0, 0, 30 * CqlDuration.NANOS_PER_HOUR + 20 * CqlDuration.NANOS_PER_MINUTE)); + assertThat(CqlDuration.from("P0000-00-00T00:20:00")) + .isEqualTo(CqlDuration.newInstance(0, 0, 20 * CqlDuration.NANOS_PER_MINUTE)); + assertThat(CqlDuration.from("P0000-00-00T00:00:56")) + .isEqualTo(CqlDuration.newInstance(0, 0, 56 * CqlDuration.NANOS_PER_SECOND)); + assertThat(CqlDuration.from("P0001-03-00T02:10:00")) + .isEqualTo(CqlDuration.newInstance(15, 0, 130 * CqlDuration.NANOS_PER_MINUTE)); + } finally { + Locale.setDefault(def); + } } @Test @@ -163,4 +193,18 @@ public void should_subtract_from_temporal() { assertThat(dateTime.minus(CqlDuration.from("1h15s15ns"))) .isEqualTo("2018-10-03T22:59:44.999999985-07:00[America/Los_Angeles]"); } + + @Test + public void should_serialize_and_deserialize() throws Exception { + CqlDuration initial = CqlDuration.from("3mo2d15s"); + CqlDuration deserialized = SerializationHelper.serializeAndDeserialize(initial); + assertThat(deserialized).isEqualTo(initial); + } + + @Test + public void should_serialize_and_deserialize_negative() throws Exception { + CqlDuration initial = CqlDuration.from("-2d15m"); + CqlDuration deserialized = SerializationHelper.serializeAndDeserialize(initial); + assertThat(deserialized).isEqualTo(initial); + } } diff --git a/core/src/test/java/com/datastax/oss/driver/api/core/data/CqlVectorTest.java b/core/src/test/java/com/datastax/oss/driver/api/core/data/CqlVectorTest.java new file mode 100644 index 00000000000..3e0872cb946 --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/api/core/data/CqlVectorTest.java @@ -0,0 +1,259 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.api.core.data; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.fail; + +import com.datastax.oss.driver.api.core.type.codec.TypeCodecs; +import com.datastax.oss.driver.internal.SerializationHelper; +import com.tngtech.java.junit.dataprovider.DataProvider; +import com.tngtech.java.junit.dataprovider.DataProviderRunner; +import com.tngtech.java.junit.dataprovider.UseDataProvider; +import java.io.ByteArrayInputStream; +import java.io.ObjectInputStream; +import java.io.ObjectStreamException; +import java.time.LocalTime; +import java.util.AbstractList; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.stream.Collectors; +import org.apache.commons.codec.DecoderException; +import org.apache.commons.codec.binary.Hex; +import org.assertj.core.util.Lists; +import org.junit.Test; +import org.junit.runner.RunWith; + +@RunWith(DataProviderRunner.class) +public class CqlVectorTest { + + @DataProvider + public static Object[][] dataProvider() { + return new Object[][] { + {new Float[] {1.0f, 2.5f}}, + {new LocalTime[] {LocalTime.of(1, 2), LocalTime.of(3, 4)}}, + {new List[] {Arrays.asList(1, 2), Arrays.asList(3, 4)}}, + {new CqlVector[] {CqlVector.newInstance("a", "bc"), CqlVector.newInstance("d", "ef")}} + }; + } + + private void validate_built_vector(CqlVector vec, Object[] expectedVals) { + assertThat(vec.size()).isEqualTo(2); + assertThat(vec.isEmpty()).isFalse(); + assertThat(vec.get(0)).isEqualTo(expectedVals[0]); + assertThat(vec.get(1)).isEqualTo(expectedVals[1]); + } + + @UseDataProvider("dataProvider") + @Test + public void should_build_vector_from_elements(Object[] vals) { + validate_built_vector(CqlVector.newInstance(vals), vals); + } + + @Test + @UseDataProvider("dataProvider") + public void should_build_vector_from_list(Object[] vals) { + validate_built_vector(CqlVector.newInstance(Lists.newArrayList(vals)), vals); + } + + @Test + public void should_throw_from_null_string() { + assertThatThrownBy( + () -> { + CqlVector.from(null, TypeCodecs.FLOAT); + }) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + public void should_throw_from_empty_string() { + + assertThatThrownBy( + () -> { + CqlVector.from("", TypeCodecs.FLOAT); + }) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + public void should_throw_when_building_with_nulls() { + + assertThatThrownBy( + () -> { + CqlVector.newInstance(1.1f, null, 2.2f); + }) + .isInstanceOf(IllegalArgumentException.class); + + Float[] theArray = new Float[] {1.1f, null, 2.2f}; + assertThatThrownBy( + () -> { + CqlVector.newInstance(theArray); + }) + .isInstanceOf(IllegalArgumentException.class); + + List theList = Lists.newArrayList(1.1f, null, 2.2f); + assertThatThrownBy( + () -> { + CqlVector.newInstance(theList); + }) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + public void should_build_empty_vector() { + CqlVector vector = CqlVector.newInstance(); + assertThat(vector.isEmpty()).isTrue(); + assertThat(vector.size()).isEqualTo(0); + } + + @Test + @UseDataProvider("dataProvider") + public void should_behave_mostly_like_a_list(T[] vals) { + T[] theArray = Arrays.copyOf(vals, vals.length); + CqlVector vector = CqlVector.newInstance(theArray); + assertThat(vector.get(0)).isEqualTo(theArray[0]); + vector.set(0, theArray[1]); + assertThat(vector.get(0)).isEqualTo(theArray[1]); + assertThat(vector.isEmpty()).isFalse(); + assertThat(vector.size()).isEqualTo(2); + Iterator iterator = vector.iterator(); + assertThat(iterator.next()).isEqualTo(theArray[1]); + assertThat(iterator.next()).isEqualTo(theArray[1]); + } + + @Test + @UseDataProvider("dataProvider") + public void should_play_nicely_with_streams(T[] vals) { + CqlVector vector = CqlVector.newInstance(vals); + List results = + vector.stream() + .map(Object::toString) + .collect(Collectors.toCollection(() -> new ArrayList())); + for (int i = 0; i < vector.size(); ++i) { + assertThat(results.get(i)).isEqualTo(vector.get(i).toString()); + } + } + + @Test + @UseDataProvider("dataProvider") + public void should_reflect_changes_to_mutable_list(T[] vals) { + List theList = Lists.newArrayList(vals); + CqlVector vector = CqlVector.newInstance(theList); + assertThat(vector.size()).isEqualTo(2); + assertThat(vector.get(1)).isEqualTo(vals[1]); + + T newVal = vals[0]; + theList.set(1, newVal); + assertThat(vector.size()).isEqualTo(2); + assertThat(vector.get(1)).isEqualTo(newVal); + } + + @Test + @UseDataProvider("dataProvider") + public void should_reflect_changes_to_array(T[] vals) { + T[] theArray = Arrays.copyOf(vals, vals.length); + CqlVector vector = CqlVector.newInstance(theArray); + assertThat(vector.size()).isEqualTo(2); + assertThat(vector.get(1)).isEqualTo(theArray[1]); + + T newVal = theArray[0]; + theArray[1] = newVal; + assertThat(vector.size()).isEqualTo(2); + assertThat(vector.get(1)).isEqualTo(newVal); + } + + @Test + @UseDataProvider("dataProvider") + public void should_correctly_compare_vectors(T[] vals) { + CqlVector vector1 = CqlVector.newInstance(vals); + CqlVector vector2 = CqlVector.newInstance(vals); + CqlVector vector3 = CqlVector.newInstance(Lists.newArrayList(vals)); + assertThat(vector1).isNotSameAs(vector2); + assertThat(vector1).isEqualTo(vector2); + assertThat(vector1).isNotSameAs(vector3); + assertThat(vector1).isEqualTo(vector3); + + T[] differentArgs = Arrays.copyOf(vals, vals.length); + T newVal = differentArgs[1]; + differentArgs[0] = newVal; + CqlVector vector4 = CqlVector.newInstance(differentArgs); + assertThat(vector1).isNotSameAs(vector4); + assertThat(vector1).isNotEqualTo(vector4); + + T[] biggerArgs = Arrays.copyOf(vals, vals.length + 1); + biggerArgs[biggerArgs.length - 1] = newVal; + CqlVector vector5 = CqlVector.newInstance(biggerArgs); + assertThat(vector1).isNotSameAs(vector5); + assertThat(vector1).isNotEqualTo(vector5); + } + + @Test + @UseDataProvider("dataProvider") + public void should_serialize_and_deserialize(T[] vals) throws Exception { + CqlVector initial = CqlVector.newInstance(vals); + CqlVector deserialized = SerializationHelper.serializeAndDeserialize(initial); + assertThat(deserialized).isEqualTo(initial); + } + + @Test + public void should_serialize_and_deserialize_empty_vector() throws Exception { + CqlVector initial = CqlVector.newInstance(Collections.emptyList()); + CqlVector deserialized = SerializationHelper.serializeAndDeserialize(initial); + assertThat(deserialized).isEqualTo(initial); + } + + @Test + @UseDataProvider("dataProvider") + public void should_serialize_and_deserialize_unserializable_list(T[] vals) throws Exception { + CqlVector initial = + CqlVector.newInstance( + new AbstractList() { + @Override + public T get(int index) { + return vals[index]; + } + + @Override + public int size() { + return vals.length; + } + }); + CqlVector deserialized = SerializationHelper.serializeAndDeserialize(initial); + assertThat(deserialized).isEqualTo(initial); + } + + @Test + public void should_not_use_preallocate_serialized_size() throws DecoderException { + // serialized CqlVector(1.0f, 2.5f, 3.0f) with size field adjusted to Integer.MAX_VALUE + byte[] suspiciousBytes = + Hex.decodeHex( + "aced000573720042636f6d2e64617461737461782e6f73732e6472697665722e6170692e636f72652e646174612e43716c566563746f722453657269616c697a6174696f6e50726f78790000000000000001030000787077047fffffff7372000f6a6176612e6c616e672e466c6f6174daedc9a2db3cf0ec02000146000576616c7565787200106a6176612e6c616e672e4e756d62657286ac951d0b94e08b02000078703f8000007371007e0002402000007371007e00024040000078" + .toCharArray()); + try { + new ObjectInputStream(new ByteArrayInputStream(suspiciousBytes)).readObject(); + fail("Should not be able to deserialize bytes with incorrect size field"); + } catch (Exception e) { + // check we fail to deserialize, rather than OOM + assertThat(e).isInstanceOf(ObjectStreamException.class); + } + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/api/core/metadata/SafeInitNodeStateListenerTest.java b/core/src/test/java/com/datastax/oss/driver/api/core/metadata/SafeInitNodeStateListenerTest.java index b9e6db630c0..a5b9b447e6a 100644 --- a/core/src/test/java/com/datastax/oss/driver/api/core/metadata/SafeInitNodeStateListenerTest.java +++ b/core/src/test/java/com/datastax/oss/driver/api/core/metadata/SafeInitNodeStateListenerTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/api/core/paging/OffsetPagerAsyncTest.java b/core/src/test/java/com/datastax/oss/driver/api/core/paging/OffsetPagerAsyncTest.java index 82ceeb4c940..3963bf6de84 100644 --- a/core/src/test/java/com/datastax/oss/driver/api/core/paging/OffsetPagerAsyncTest.java +++ b/core/src/test/java/com/datastax/oss/driver/api/core/paging/OffsetPagerAsyncTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/api/core/paging/OffsetPagerSyncTest.java b/core/src/test/java/com/datastax/oss/driver/api/core/paging/OffsetPagerSyncTest.java index 4787658cb9b..0d8b380dd49 100644 --- a/core/src/test/java/com/datastax/oss/driver/api/core/paging/OffsetPagerSyncTest.java +++ b/core/src/test/java/com/datastax/oss/driver/api/core/paging/OffsetPagerSyncTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/api/core/paging/OffsetPagerTestBase.java b/core/src/test/java/com/datastax/oss/driver/api/core/paging/OffsetPagerTestBase.java index 458f12e496d..7f9ca2ddaa2 100644 --- a/core/src/test/java/com/datastax/oss/driver/api/core/paging/OffsetPagerTestBase.java +++ b/core/src/test/java/com/datastax/oss/driver/api/core/paging/OffsetPagerTestBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/api/core/paging/OffsetPagerTestFixture.java b/core/src/test/java/com/datastax/oss/driver/api/core/paging/OffsetPagerTestFixture.java index 471566c0158..91079722aa2 100644 --- a/core/src/test/java/com/datastax/oss/driver/api/core/paging/OffsetPagerTestFixture.java +++ b/core/src/test/java/com/datastax/oss/driver/api/core/paging/OffsetPagerTestFixture.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/api/core/retry/ConsistencyDowngradingRetryPolicyTest.java b/core/src/test/java/com/datastax/oss/driver/api/core/retry/ConsistencyDowngradingRetryPolicyTest.java new file mode 100644 index 00000000000..e4463d833bf --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/api/core/retry/ConsistencyDowngradingRetryPolicyTest.java @@ -0,0 +1,148 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.api.core.retry; + +import static com.datastax.oss.driver.api.core.ConsistencyLevel.EACH_QUORUM; +import static com.datastax.oss.driver.api.core.ConsistencyLevel.ONE; +import static com.datastax.oss.driver.api.core.ConsistencyLevel.QUORUM; +import static com.datastax.oss.driver.api.core.ConsistencyLevel.SERIAL; +import static com.datastax.oss.driver.api.core.ConsistencyLevel.THREE; +import static com.datastax.oss.driver.api.core.ConsistencyLevel.TWO; +import static com.datastax.oss.driver.api.core.retry.RetryDecision.IGNORE; +import static com.datastax.oss.driver.api.core.retry.RetryDecision.RETHROW; +import static com.datastax.oss.driver.api.core.retry.RetryDecision.RETRY_NEXT; +import static com.datastax.oss.driver.api.core.retry.RetryDecision.RETRY_SAME; +import static com.datastax.oss.driver.api.core.servererrors.WriteType.BATCH; +import static com.datastax.oss.driver.api.core.servererrors.WriteType.BATCH_LOG; +import static com.datastax.oss.driver.api.core.servererrors.WriteType.CAS; +import static com.datastax.oss.driver.api.core.servererrors.WriteType.CDC; +import static com.datastax.oss.driver.api.core.servererrors.WriteType.COUNTER; +import static com.datastax.oss.driver.api.core.servererrors.WriteType.SIMPLE; +import static com.datastax.oss.driver.api.core.servererrors.WriteType.UNLOGGED_BATCH; +import static com.datastax.oss.driver.api.core.servererrors.WriteType.VIEW; + +import com.datastax.oss.driver.api.core.connection.ClosedConnectionException; +import com.datastax.oss.driver.api.core.connection.HeartbeatException; +import com.datastax.oss.driver.api.core.servererrors.OverloadedException; +import com.datastax.oss.driver.api.core.servererrors.ReadFailureException; +import com.datastax.oss.driver.api.core.servererrors.ServerError; +import com.datastax.oss.driver.api.core.servererrors.TruncateException; +import com.datastax.oss.driver.api.core.servererrors.WriteFailureException; +import com.datastax.oss.driver.internal.core.retry.ConsistencyDowngradingRetryPolicy; +import org.junit.Test; + +public class ConsistencyDowngradingRetryPolicyTest extends RetryPolicyTestBase { + + public ConsistencyDowngradingRetryPolicyTest() { + super(new ConsistencyDowngradingRetryPolicy("test")); + } + + @Test + public void should_process_read_timeouts() { + // retry count != 0 + assertOnReadTimeout(QUORUM, 2, 2, false, 1).hasDecision(RETHROW); + // serial CL + assertOnReadTimeout(SERIAL, 2, 2, false, 0).hasDecision(RETHROW); + // received < blockFor + assertOnReadTimeout(QUORUM, 4, 3, true, 0).hasDecision(RETRY_SAME).hasConsistency(THREE); + assertOnReadTimeout(QUORUM, 4, 3, false, 0).hasDecision(RETRY_SAME).hasConsistency(THREE); + assertOnReadTimeout(QUORUM, 3, 2, true, 0).hasDecision(RETRY_SAME).hasConsistency(TWO); + assertOnReadTimeout(QUORUM, 3, 2, false, 0).hasDecision(RETRY_SAME).hasConsistency(TWO); + assertOnReadTimeout(QUORUM, 2, 1, true, 0).hasDecision(RETRY_SAME).hasConsistency(ONE); + assertOnReadTimeout(QUORUM, 2, 1, false, 0).hasDecision(RETRY_SAME).hasConsistency(ONE); + assertOnReadTimeout(EACH_QUORUM, 2, 0, true, 0).hasDecision(RETRY_SAME).hasConsistency(ONE); + assertOnReadTimeout(EACH_QUORUM, 2, 0, false, 0).hasDecision(RETRY_SAME).hasConsistency(ONE); + assertOnReadTimeout(QUORUM, 2, 0, true, 0).hasDecision(RETHROW); + assertOnReadTimeout(QUORUM, 2, 0, false, 0).hasDecision(RETHROW); + // data present + assertOnReadTimeout(QUORUM, 2, 2, false, 0).hasDecision(RETRY_SAME); + assertOnReadTimeout(QUORUM, 2, 2, true, 0).hasDecision(RETHROW); + } + + @Test + public void should_process_write_timeouts() { + // retry count != 0 + assertOnWriteTimeout(QUORUM, BATCH_LOG, 2, 0, 1).hasDecision(RETHROW); + // SIMPLE + assertOnWriteTimeout(QUORUM, SIMPLE, 2, 1, 0).hasDecision(IGNORE); + assertOnWriteTimeout(QUORUM, SIMPLE, 2, 0, 0).hasDecision(RETHROW); + // BATCH + assertOnWriteTimeout(QUORUM, BATCH, 2, 1, 0).hasDecision(IGNORE); + assertOnWriteTimeout(QUORUM, BATCH, 2, 0, 0).hasDecision(RETHROW); + // UNLOGGED_BATCH + assertOnWriteTimeout(QUORUM, UNLOGGED_BATCH, 4, 3, 0) + .hasDecision(RETRY_SAME) + .hasConsistency(THREE); + assertOnWriteTimeout(QUORUM, UNLOGGED_BATCH, 3, 2, 0) + .hasDecision(RETRY_SAME) + .hasConsistency(TWO); + assertOnWriteTimeout(QUORUM, UNLOGGED_BATCH, 2, 1, 0) + .hasDecision(RETRY_SAME) + .hasConsistency(ONE); + assertOnWriteTimeout(EACH_QUORUM, UNLOGGED_BATCH, 2, 0, 0) + .hasDecision(RETRY_SAME) + .hasConsistency(ONE); + assertOnWriteTimeout(QUORUM, UNLOGGED_BATCH, 2, 0, 0).hasDecision(RETHROW); + // BATCH_LOG + assertOnWriteTimeout(QUORUM, BATCH_LOG, 2, 1, 0).hasDecision(RETRY_SAME); + // others + assertOnWriteTimeout(QUORUM, COUNTER, 2, 1, 0).hasDecision(RETHROW); + assertOnWriteTimeout(QUORUM, CAS, 2, 1, 0).hasDecision(RETHROW); + assertOnWriteTimeout(QUORUM, VIEW, 2, 1, 0).hasDecision(RETHROW); + assertOnWriteTimeout(QUORUM, CDC, 2, 1, 0).hasDecision(RETHROW); + } + + @Test + public void should_process_unavailable() { + // retry count != 0 + assertOnUnavailable(QUORUM, 2, 1, 1).hasDecision(RETHROW); + // SERIAL + assertOnUnavailable(SERIAL, 2, 1, 0).hasDecision(RETRY_NEXT); + // downgrade + assertOnUnavailable(QUORUM, 4, 3, 0).hasDecision(RETRY_SAME).hasConsistency(THREE); + assertOnUnavailable(QUORUM, 3, 2, 0).hasDecision(RETRY_SAME).hasConsistency(TWO); + assertOnUnavailable(QUORUM, 2, 1, 0).hasDecision(RETRY_SAME).hasConsistency(ONE); + assertOnUnavailable(EACH_QUORUM, 2, 0, 0).hasDecision(RETRY_SAME).hasConsistency(ONE); + assertOnUnavailable(QUORUM, 2, 0, 0).hasDecision(RETHROW); + } + + @Test + public void should_process_aborted_request() { + assertOnRequestAborted(ClosedConnectionException.class, 0).hasDecision(RETRY_NEXT); + assertOnRequestAborted(ClosedConnectionException.class, 1).hasDecision(RETRY_NEXT); + assertOnRequestAborted(HeartbeatException.class, 0).hasDecision(RETRY_NEXT); + assertOnRequestAborted(HeartbeatException.class, 1).hasDecision(RETRY_NEXT); + assertOnRequestAborted(Throwable.class, 0).hasDecision(RETHROW); + } + + @Test + public void should_process_error_response() { + assertOnErrorResponse(ReadFailureException.class, 0).hasDecision(RETHROW); + assertOnErrorResponse(ReadFailureException.class, 1).hasDecision(RETHROW); + assertOnErrorResponse(WriteFailureException.class, 0).hasDecision(RETHROW); + assertOnErrorResponse(WriteFailureException.class, 1).hasDecision(RETHROW); + assertOnErrorResponse(WriteFailureException.class, 1).hasDecision(RETHROW); + + assertOnErrorResponse(OverloadedException.class, 0).hasDecision(RETRY_NEXT); + assertOnErrorResponse(OverloadedException.class, 1).hasDecision(RETRY_NEXT); + assertOnErrorResponse(ServerError.class, 0).hasDecision(RETRY_NEXT); + assertOnErrorResponse(ServerError.class, 1).hasDecision(RETRY_NEXT); + assertOnErrorResponse(TruncateException.class, 0).hasDecision(RETRY_NEXT); + assertOnErrorResponse(TruncateException.class, 1).hasDecision(RETRY_NEXT); + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/api/core/retry/DefaultRetryPolicyTest.java b/core/src/test/java/com/datastax/oss/driver/api/core/retry/DefaultRetryPolicyTest.java index dac4dcafe20..e36ccff2b91 100644 --- a/core/src/test/java/com/datastax/oss/driver/api/core/retry/DefaultRetryPolicyTest.java +++ b/core/src/test/java/com/datastax/oss/driver/api/core/retry/DefaultRetryPolicyTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -40,48 +42,48 @@ public DefaultRetryPolicyTest() { @Test public void should_process_read_timeouts() { - assertOnReadTimeout(QUORUM, 2, 2, false, 0).isEqualTo(RETRY_SAME); - assertOnReadTimeout(QUORUM, 2, 2, false, 1).isEqualTo(RETHROW); - assertOnReadTimeout(QUORUM, 2, 2, true, 0).isEqualTo(RETHROW); - assertOnReadTimeout(QUORUM, 2, 1, true, 0).isEqualTo(RETHROW); - assertOnReadTimeout(QUORUM, 2, 1, false, 0).isEqualTo(RETHROW); + assertOnReadTimeout(QUORUM, 2, 2, false, 0).hasDecision(RETRY_SAME); + assertOnReadTimeout(QUORUM, 2, 2, false, 1).hasDecision(RETHROW); + assertOnReadTimeout(QUORUM, 2, 2, true, 0).hasDecision(RETHROW); + assertOnReadTimeout(QUORUM, 2, 1, true, 0).hasDecision(RETHROW); + assertOnReadTimeout(QUORUM, 2, 1, false, 0).hasDecision(RETHROW); } @Test public void should_process_write_timeouts() { - assertOnWriteTimeout(QUORUM, BATCH_LOG, 2, 0, 0).isEqualTo(RETRY_SAME); - assertOnWriteTimeout(QUORUM, BATCH_LOG, 2, 0, 1).isEqualTo(RETHROW); - assertOnWriteTimeout(QUORUM, SIMPLE, 2, 0, 0).isEqualTo(RETHROW); + assertOnWriteTimeout(QUORUM, BATCH_LOG, 2, 0, 0).hasDecision(RETRY_SAME); + assertOnWriteTimeout(QUORUM, BATCH_LOG, 2, 0, 1).hasDecision(RETHROW); + assertOnWriteTimeout(QUORUM, SIMPLE, 2, 0, 0).hasDecision(RETHROW); } @Test public void should_process_unavailable() { - assertOnUnavailable(QUORUM, 2, 1, 0).isEqualTo(RETRY_NEXT); - assertOnUnavailable(QUORUM, 2, 1, 1).isEqualTo(RETHROW); + assertOnUnavailable(QUORUM, 2, 1, 0).hasDecision(RETRY_NEXT); + assertOnUnavailable(QUORUM, 2, 1, 1).hasDecision(RETHROW); } @Test public void should_process_aborted_request() { - assertOnRequestAborted(ClosedConnectionException.class, 0).isEqualTo(RETRY_NEXT); - assertOnRequestAborted(ClosedConnectionException.class, 1).isEqualTo(RETRY_NEXT); - assertOnRequestAborted(HeartbeatException.class, 0).isEqualTo(RETRY_NEXT); - assertOnRequestAborted(HeartbeatException.class, 1).isEqualTo(RETRY_NEXT); - assertOnRequestAborted(Throwable.class, 0).isEqualTo(RETHROW); + assertOnRequestAborted(ClosedConnectionException.class, 0).hasDecision(RETRY_NEXT); + assertOnRequestAborted(ClosedConnectionException.class, 1).hasDecision(RETRY_NEXT); + assertOnRequestAborted(HeartbeatException.class, 0).hasDecision(RETRY_NEXT); + assertOnRequestAborted(HeartbeatException.class, 1).hasDecision(RETRY_NEXT); + assertOnRequestAborted(Throwable.class, 0).hasDecision(RETHROW); } @Test public void should_process_error_response() { - assertOnErrorResponse(ReadFailureException.class, 0).isEqualTo(RETHROW); - assertOnErrorResponse(ReadFailureException.class, 1).isEqualTo(RETHROW); - assertOnErrorResponse(WriteFailureException.class, 0).isEqualTo(RETHROW); - assertOnErrorResponse(WriteFailureException.class, 1).isEqualTo(RETHROW); - assertOnErrorResponse(WriteFailureException.class, 1).isEqualTo(RETHROW); + assertOnErrorResponse(ReadFailureException.class, 0).hasDecision(RETHROW); + assertOnErrorResponse(ReadFailureException.class, 1).hasDecision(RETHROW); + assertOnErrorResponse(WriteFailureException.class, 0).hasDecision(RETHROW); + assertOnErrorResponse(WriteFailureException.class, 1).hasDecision(RETHROW); + assertOnErrorResponse(WriteFailureException.class, 1).hasDecision(RETHROW); - assertOnErrorResponse(OverloadedException.class, 0).isEqualTo(RETRY_NEXT); - assertOnErrorResponse(OverloadedException.class, 1).isEqualTo(RETRY_NEXT); - assertOnErrorResponse(ServerError.class, 0).isEqualTo(RETRY_NEXT); - assertOnErrorResponse(ServerError.class, 1).isEqualTo(RETRY_NEXT); - assertOnErrorResponse(TruncateException.class, 0).isEqualTo(RETRY_NEXT); - assertOnErrorResponse(TruncateException.class, 1).isEqualTo(RETRY_NEXT); + assertOnErrorResponse(OverloadedException.class, 0).hasDecision(RETRY_NEXT); + assertOnErrorResponse(OverloadedException.class, 1).hasDecision(RETRY_NEXT); + assertOnErrorResponse(ServerError.class, 0).hasDecision(RETRY_NEXT); + assertOnErrorResponse(ServerError.class, 1).hasDecision(RETRY_NEXT); + assertOnErrorResponse(TruncateException.class, 0).hasDecision(RETRY_NEXT); + assertOnErrorResponse(TruncateException.class, 1).hasDecision(RETRY_NEXT); } } diff --git a/core/src/test/java/com/datastax/oss/driver/api/core/retry/RetryPolicyTestBase.java b/core/src/test/java/com/datastax/oss/driver/api/core/retry/RetryPolicyTestBase.java index 78c227816e9..a57f4ab352f 100644 --- a/core/src/test/java/com/datastax/oss/driver/api/core/retry/RetryPolicyTestBase.java +++ b/core/src/test/java/com/datastax/oss/driver/api/core/retry/RetryPolicyTestBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -22,7 +24,8 @@ import com.datastax.oss.driver.api.core.servererrors.CoordinatorException; import com.datastax.oss.driver.api.core.servererrors.WriteType; import com.datastax.oss.driver.api.core.session.Request; -import org.assertj.core.api.Assert; +import com.datastax.oss.driver.internal.core.retry.ConsistencyDowngradingRetryVerdict; +import org.assertj.core.api.AbstractAssert; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; @@ -37,30 +40,52 @@ protected RetryPolicyTestBase(RetryPolicy policy) { this.policy = policy; } - protected Assert assertOnReadTimeout( + protected RetryVerdictAssert assertOnReadTimeout( ConsistencyLevel cl, int blockFor, int received, boolean dataPresent, int retryCount) { - return assertThat( - policy.onReadTimeout(request, cl, blockFor, received, dataPresent, retryCount)); + return new RetryVerdictAssert( + policy.onReadTimeoutVerdict(request, cl, blockFor, received, dataPresent, retryCount)); } - protected Assert assertOnWriteTimeout( + protected RetryVerdictAssert assertOnWriteTimeout( ConsistencyLevel cl, WriteType writeType, int blockFor, int received, int retryCount) { - return assertThat( - policy.onWriteTimeout(request, cl, writeType, blockFor, received, retryCount)); + return new RetryVerdictAssert( + policy.onWriteTimeoutVerdict(request, cl, writeType, blockFor, received, retryCount)); } - protected Assert assertOnUnavailable( + protected RetryVerdictAssert assertOnUnavailable( ConsistencyLevel cl, int required, int alive, int retryCount) { - return assertThat(policy.onUnavailable(request, cl, required, alive, retryCount)); + return new RetryVerdictAssert( + policy.onUnavailableVerdict(request, cl, required, alive, retryCount)); } - protected Assert assertOnRequestAborted( + protected RetryVerdictAssert assertOnRequestAborted( Class errorClass, int retryCount) { - return assertThat(policy.onRequestAborted(request, mock(errorClass), retryCount)); + return new RetryVerdictAssert( + policy.onRequestAbortedVerdict(request, mock(errorClass), retryCount)); } - protected Assert assertOnErrorResponse( + protected RetryVerdictAssert assertOnErrorResponse( Class errorClass, int retryCount) { - return assertThat(policy.onErrorResponse(request, mock(errorClass), retryCount)); + return new RetryVerdictAssert( + policy.onErrorResponseVerdict(request, mock(errorClass), retryCount)); + } + + public static class RetryVerdictAssert extends AbstractAssert { + RetryVerdictAssert(RetryVerdict actual) { + super(actual, RetryVerdictAssert.class); + } + + public RetryVerdictAssert hasDecision(RetryDecision decision) { + assertThat(actual.getRetryDecision()).isEqualTo(decision); + return this; + } + + public RetryVerdictAssert hasConsistency(ConsistencyLevel cl) { + assertThat(actual) + .isInstanceOf(ConsistencyDowngradingRetryVerdict.class) + .extracting("consistencyLevel") + .isEqualTo(cl); + return this; + } } } diff --git a/core/src/test/java/com/datastax/oss/driver/api/core/specex/ConstantSpeculativeExecutionPolicyTest.java b/core/src/test/java/com/datastax/oss/driver/api/core/specex/ConstantSpeculativeExecutionPolicyTest.java index 7a279dfd99d..efd804fa66e 100644 --- a/core/src/test/java/com/datastax/oss/driver/api/core/specex/ConstantSpeculativeExecutionPolicyTest.java +++ b/core/src/test/java/com/datastax/oss/driver/api/core/specex/ConstantSpeculativeExecutionPolicyTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/api/core/type/UserDefinedTypeTest.java b/core/src/test/java/com/datastax/oss/driver/api/core/type/UserDefinedTypeTest.java index 05416857057..9db93b37c91 100644 --- a/core/src/test/java/com/datastax/oss/driver/api/core/type/UserDefinedTypeTest.java +++ b/core/src/test/java/com/datastax/oss/driver/api/core/type/UserDefinedTypeTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/api/core/type/reflect/GenericTypeTest.java b/core/src/test/java/com/datastax/oss/driver/api/core/type/reflect/GenericTypeTest.java index ac66cfca01a..bddb8f92773 100644 --- a/core/src/test/java/com/datastax/oss/driver/api/core/type/reflect/GenericTypeTest.java +++ b/core/src/test/java/com/datastax/oss/driver/api/core/type/reflect/GenericTypeTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/api/core/uuid/UuidsTest.java b/core/src/test/java/com/datastax/oss/driver/api/core/uuid/UuidsTest.java index 848aebc7f7a..c547f95e67c 100644 --- a/core/src/test/java/com/datastax/oss/driver/api/core/uuid/UuidsTest.java +++ b/core/src/test/java/com/datastax/oss/driver/api/core/uuid/UuidsTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -27,18 +29,122 @@ import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; import java.util.Arrays; import java.util.HashSet; import java.util.Random; import java.util.Set; +import java.util.SplittableRandom; import java.util.UUID; import java.util.concurrent.ConcurrentSkipListSet; +import java.util.concurrent.ThreadLocalRandom; +import java.util.function.Supplier; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(DataProviderRunner.class) public class UuidsTest { + @Test + public void should_generate_unique_random_uuids_Random() { + Set generated = serialGeneration(1_000_000, Uuids::random); + assertThat(generated).hasSize(1_000_000); + } + + @Test + public void should_generate_unique_random_uuids_shared_Random2() { + Random random = new Random(); + Set generated = serialGeneration(1_000_000, () -> Uuids.random(random)); + assertThat(generated).hasSize(1_000_000); + } + + @Test + public void should_generate_unique_random_uuids_across_threads_shared_Random() throws Exception { + Random random = new Random(); + Set generated = parallelGeneration(10, 10_000, () -> () -> Uuids.random(random)); + assertThat(generated).hasSize(10 * 10_000); + } + + @Test + public void should_generate_unique_random_uuids_shared_SecureRandom() { + SecureRandom random = new SecureRandom(); + Set generated = serialGeneration(1_000_000, () -> Uuids.random(random)); + assertThat(generated).hasSize(1_000_000); + } + + @Test + public void should_generate_unique_random_uuids_across_threads_shared_SecureRandom() + throws Exception { + SecureRandom random = new SecureRandom(); + Set generated = parallelGeneration(10, 10_000, () -> () -> Uuids.random(random)); + assertThat(generated).hasSize(10 * 10_000); + } + + @Test + public void should_generate_unique_random_uuids_ThreadLocalRandom() { + ThreadLocalRandom random = ThreadLocalRandom.current(); + Set generated = serialGeneration(1_000_000, () -> Uuids.random(random)); + assertThat(generated).hasSize(1_000_000); + } + + @Test + public void should_generate_unique_random_uuids_across_threads_ThreadLocalRandom() + throws Exception { + Set generated = + parallelGeneration( + 10, + 10_000, + () -> { + ThreadLocalRandom random = ThreadLocalRandom.current(); + return () -> Uuids.random(random); + }); + assertThat(generated).hasSize(10 * 10_000); + } + + @Test + public void should_generate_unique_random_uuids_Netty_ThreadLocalRandom() { + io.netty.util.internal.ThreadLocalRandom random = + io.netty.util.internal.ThreadLocalRandom.current(); + Set generated = serialGeneration(1_000_000, () -> Uuids.random(random)); + assertThat(generated).hasSize(1_000_000); + } + + @Test + public void should_generate_unique_random_uuids_across_threads_Netty_ThreadLocalRandom() + throws Exception { + Set generated = + parallelGeneration( + 10, + 10_000, + () -> { + io.netty.util.internal.ThreadLocalRandom random = + io.netty.util.internal.ThreadLocalRandom.current(); + return () -> Uuids.random(random); + }); + assertThat(generated).hasSize(10 * 10_000); + } + + @Test + public void should_generate_unique_random_uuids_SplittableRandom() { + SplittableRandom random = new SplittableRandom(); + Set generated = serialGeneration(1_000_000, () -> Uuids.random(random)); + assertThat(generated).hasSize(1_000_000); + } + + @Test + public void should_generate_unique_random_uuids_across_threads_SplittableRandom() + throws Exception { + Set generated = + parallelGeneration( + 10, + 10_000, + () -> { + SplittableRandom random = new SplittableRandom(); + return () -> Uuids.random(random); + }); + assertThat(generated).hasSize(10 * 10_000); + } + @Test @UseDataProvider("byteArrayNames") public void should_generate_name_based_uuid_from_namespace_and_byte_array( @@ -186,7 +292,7 @@ public void should_generate_timestamp_within_10_ms() { // The Uuids class does some computation at class initialization, which may screw up our // assumption below that Uuids.timeBased() takes less than 10ms, so force class loading now. - Uuids.random(); + Uuids.timeBased(); long start = System.currentTimeMillis(); UUID uuid = Uuids.timeBased(); @@ -203,34 +309,14 @@ public void should_generate_timestamp_within_10_ms() { @Test public void should_generate_unique_time_based_uuids() { - int count = 1_000_000; - Set generated = new HashSet<>(count); - - for (int i = 0; i < count; ++i) { - generated.add(Uuids.timeBased()); - } - - assertThat(generated).hasSize(count); + Set generated = serialGeneration(1_000_000, Uuids::timeBased); + assertThat(generated).hasSize(1_000_000); } @Test public void should_generate_unique_time_based_uuids_across_threads() throws Exception { - int threadCount = 10; - int uuidsPerThread = 10_000; - Set generated = new ConcurrentSkipListSet<>(); - - UUIDGenerator[] generators = new UUIDGenerator[threadCount]; - for (int i = 0; i < threadCount; i++) { - generators[i] = new UUIDGenerator(uuidsPerThread, generated); - } - for (int i = 0; i < threadCount; i++) { - generators[i].start(); - } - for (int i = 0; i < threadCount; i++) { - generators[i].join(); - } - - assertThat(generated).hasSize(threadCount * uuidsPerThread); + Set generated = parallelGeneration(10, 10_000, () -> Uuids::timeBased); + assertThat(generated).hasSize(10 * 10_000); } @Test @@ -362,20 +448,48 @@ private static byte[] longToBytes(long x) { return ByteBuffer.allocate(Long.BYTES).putLong(x).array(); } - private static class UUIDGenerator extends Thread { + private Set serialGeneration(int count, Supplier uuidSupplier) { + Set generated = new HashSet<>(count); + for (int i = 0; i < count; ++i) { + generated.add(uuidSupplier.get()); + } + return generated; + } + + public Set parallelGeneration( + int threadCount, int uuidsPerThread, Supplier> uuidSupplier) + throws InterruptedException { + Set generated = new ConcurrentSkipListSet<>(); + UuidGenerator[] generators = new UuidGenerator[threadCount]; + for (int i = 0; i < threadCount; i++) { + generators[i] = new UuidGenerator(uuidsPerThread, uuidSupplier, generated); + } + for (int i = 0; i < threadCount; i++) { + generators[i].start(); + } + for (int i = 0; i < threadCount; i++) { + generators[i].join(); + } + return generated; + } + + private static class UuidGenerator extends Thread { private final int toGenerate; private final Set generated; + private final Supplier> uuidSupplier; - UUIDGenerator(int toGenerate, Set generated) { + UuidGenerator(int toGenerate, Supplier> uuidSupplier, Set generated) { this.toGenerate = toGenerate; this.generated = generated; + this.uuidSupplier = uuidSupplier; } @Override public void run() { + Supplier uuidSupplier = this.uuidSupplier.get(); for (int i = 0; i < toGenerate; ++i) { - generated.add(Uuids.timeBased()); + generated.add(uuidSupplier.get()); } } } diff --git a/core/src/test/java/com/datastax/oss/driver/internal/SerializationHelper.java b/core/src/test/java/com/datastax/oss/driver/internal/SerializationHelper.java index 0494aeaf539..4daf7e28eb6 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/SerializationHelper.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/SerializationHelper.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/AsyncPagingIterableWrapperTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/AsyncPagingIterableWrapperTest.java index 7513a18d1f7..dff9877b62d 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/AsyncPagingIterableWrapperTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/AsyncPagingIterableWrapperTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/CompletionStageAssert.java b/core/src/test/java/com/datastax/oss/driver/internal/core/CompletionStageAssert.java index 0484386cd8f..6c0d78d62dd 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/CompletionStageAssert.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/CompletionStageAssert.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/ContactPointsTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/ContactPointsTest.java index 96b396d9e40..72b875b8602 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/ContactPointsTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/ContactPointsTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -119,7 +121,7 @@ public void should_ignore_malformed_host_and_port_and_warn() { ContactPoints.merge(Collections.emptySet(), ImmutableList.of("foobar"), true); assertThat(endPoints).isEmpty(); - assertLog(Level.WARN, "Ignoring invalid contact point foobar (expecting host:port)"); + assertLog(Level.WARN, "Ignoring invalid contact point foobar (expecting format host:port)"); } @Test @@ -130,7 +132,7 @@ public void should_ignore_malformed_port_and_warn() { assertThat(endPoints).isEmpty(); assertLog( Level.WARN, - "Ignoring invalid contact point 127.0.0.1:foobar (expecting a number, got foobar)"); + "Ignoring invalid contact point 127.0.0.1:foobar (expecting port to be a number, got foobar)"); } @Test diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/DefaultProtocolVersionRegistryTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/DefaultProtocolVersionRegistryTest.java index c86d7c824c5..1d7cc65d1f2 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/DefaultProtocolVersionRegistryTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/DefaultProtocolVersionRegistryTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -20,9 +22,11 @@ import static com.datastax.oss.driver.api.core.ProtocolVersion.V3; import static com.datastax.oss.driver.api.core.ProtocolVersion.V4; import static com.datastax.oss.driver.api.core.ProtocolVersion.V5; +import static com.datastax.oss.driver.api.core.ProtocolVersion.V6; import static com.datastax.oss.driver.internal.core.DefaultProtocolFeature.DATE_TYPE; import static com.datastax.oss.driver.internal.core.DefaultProtocolFeature.SMALLINT_AND_TINYINT_TYPES; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.datastax.dse.driver.api.core.DseProtocolVersion; import com.datastax.dse.driver.api.core.metadata.DseNodeProperties; @@ -50,6 +54,17 @@ public void should_find_version_by_name() { assertThat(registry.fromName("DSE_V1")).isEqualTo(DseProtocolVersion.DSE_V1); } + @Test + public void should_fail_to_find_version_by_name_different_case() { + assertThatThrownBy(() -> registry.fromName("v4")).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> registry.fromName("dse_v1")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> registry.fromName("dDSE_v1")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> registry.fromName("dse_v1")) + .isInstanceOf(IllegalArgumentException.class); + } + @Test public void should_downgrade_if_lower_version_available() { Optional downgraded = registry.downgrade(V4); @@ -64,7 +79,13 @@ public void should_not_downgrade_if_no_lower_version() { @Test public void should_downgrade_from_dse_to_oss() { - assertThat(registry.downgrade(DseProtocolVersion.DSE_V1).get()).isEqualTo(ProtocolVersion.V4); + assertThat(registry.downgrade(DseProtocolVersion.DSE_V1).get()).isEqualTo(ProtocolVersion.V5); + } + + @Test + public void should_pick_dse_v2_as_highest_common_when_all_nodes_are_dse_7() { + assertThat(registry.highestCommon(ImmutableList.of(mockDseNode("7.0"), mockDseNode("7.1")))) + .isEqualTo(DseProtocolVersion.DSE_V2); } @Test @@ -124,6 +145,7 @@ public void should_support_date_type_on_oss_v4_and_later() { assertThat(registry.supports(V3, DATE_TYPE)).isFalse(); assertThat(registry.supports(V4, DATE_TYPE)).isTrue(); assertThat(registry.supports(V5, DATE_TYPE)).isTrue(); + assertThat(registry.supports(V6, DATE_TYPE)).isTrue(); assertThat(registry.supports(DSE_V1, DATE_TYPE)).isTrue(); assertThat(registry.supports(DSE_V2, DATE_TYPE)).isTrue(); } @@ -133,6 +155,7 @@ public void should_support_smallint_and_tinyint_types_on_oss_v4_and_later() { assertThat(registry.supports(V3, SMALLINT_AND_TINYINT_TYPES)).isFalse(); assertThat(registry.supports(V4, SMALLINT_AND_TINYINT_TYPES)).isTrue(); assertThat(registry.supports(V5, SMALLINT_AND_TINYINT_TYPES)).isTrue(); + assertThat(registry.supports(V6, SMALLINT_AND_TINYINT_TYPES)).isTrue(); assertThat(registry.supports(DSE_V1, SMALLINT_AND_TINYINT_TYPES)).isTrue(); assertThat(registry.supports(DSE_V2, SMALLINT_AND_TINYINT_TYPES)).isTrue(); } @@ -152,7 +175,9 @@ private Node mockDseNode(String rawDseVersion) { .thenReturn(ImmutableMap.of(DseNodeProperties.DSE_VERSION, dseVersion)); Version cassandraVersion; - if (dseVersion.compareTo(DefaultProtocolVersionRegistry.DSE_6_0_0) >= 0) { + if (dseVersion.compareTo(DefaultProtocolVersionRegistry.DSE_7_0_0) >= 0) { + cassandraVersion = Version.parse("5.0"); + } else if (dseVersion.compareTo(DefaultProtocolVersionRegistry.DSE_6_0_0) >= 0) { cassandraVersion = Version.parse("4.0"); } else if (dseVersion.compareTo(DefaultProtocolVersionRegistry.DSE_5_1_0) >= 0) { cassandraVersion = Version.parse("3.11"); diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/DriverConfigAssert.java b/core/src/test/java/com/datastax/oss/driver/internal/core/DriverConfigAssert.java index 8da0b24ecb2..adbe26159db 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/DriverConfigAssert.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/DriverConfigAssert.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/MockAsyncPagingIterable.java b/core/src/test/java/com/datastax/oss/driver/internal/core/MockAsyncPagingIterable.java index b58d290782a..731c558a81f 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/MockAsyncPagingIterable.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/MockAsyncPagingIterable.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/MockPagingIterable.java b/core/src/test/java/com/datastax/oss/driver/internal/core/MockPagingIterable.java index 51afa93013b..885983ee98e 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/MockPagingIterable.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/MockPagingIterable.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/NettyFutureAssert.java b/core/src/test/java/com/datastax/oss/driver/internal/core/NettyFutureAssert.java index 0e572b89f93..15af3c61bff 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/NettyFutureAssert.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/NettyFutureAssert.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/PagingIterableWrapperTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/PagingIterableWrapperTest.java index 85718052928..1e7cc62f8ac 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/PagingIterableWrapperTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/PagingIterableWrapperTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/TestResponses.java b/core/src/test/java/com/datastax/oss/driver/internal/core/TestResponses.java index 0b22b1aa067..ce028e66dbd 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/TestResponses.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/TestResponses.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/addresstranslation/Ec2MultiRegionAddressTranslatorTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/addresstranslation/Ec2MultiRegionAddressTranslatorTest.java index 2b2f7cf5eb8..2b871b3e0cc 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/addresstranslation/Ec2MultiRegionAddressTranslatorTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/addresstranslation/Ec2MultiRegionAddressTranslatorTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/addresstranslation/FixedHostNameAddressTranslatorTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/addresstranslation/FixedHostNameAddressTranslatorTest.java new file mode 100644 index 00000000000..3bb9c4bc291 --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/addresstranslation/FixedHostNameAddressTranslatorTest.java @@ -0,0 +1,46 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.addresstranslation; + +import static com.datastax.oss.driver.api.core.config.DefaultDriverOption.ADDRESS_TRANSLATOR_ADVERTISED_HOSTNAME; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; +import com.datastax.oss.driver.internal.core.context.DefaultDriverContext; +import com.datastax.oss.driver.internal.core.context.MockedDriverContextFactory; +import java.net.InetSocketAddress; +import org.junit.Test; + +public class FixedHostNameAddressTranslatorTest { + + @Test + public void should_translate_address() { + DriverExecutionProfile defaultProfile = mock(DriverExecutionProfile.class); + when(defaultProfile.getString(ADDRESS_TRANSLATOR_ADVERTISED_HOSTNAME)).thenReturn("myaddress"); + DefaultDriverContext defaultDriverContext = + MockedDriverContextFactory.defaultDriverContext(defaultProfile); + + FixedHostNameAddressTranslator translator = + new FixedHostNameAddressTranslator(defaultDriverContext); + InetSocketAddress address = new InetSocketAddress("192.0.2.5", 6061); + + assertThat(translator.translate(address)).isEqualTo(new InetSocketAddress("myaddress", 6061)); + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/addresstranslation/SubnetAddressTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/addresstranslation/SubnetAddressTest.java new file mode 100644 index 00000000000..bd505f5dd44 --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/addresstranslation/SubnetAddressTest.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.addresstranslation; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +import java.net.InetSocketAddress; +import org.junit.Test; + +public class SubnetAddressTest { + @Test + public void should_return_return_true_on_overlapping_with_another_subnet_address() { + SubnetAddress subnetAddress1 = + new SubnetAddress("100.64.0.0/15", mock(InetSocketAddress.class)); + SubnetAddress subnetAddress2 = + new SubnetAddress("100.65.0.0/16", mock(InetSocketAddress.class)); + assertThat(subnetAddress1.isOverlapping(subnetAddress2)).isTrue(); + } + + @Test + public void should_return_return_false_on_not_overlapping_with_another_subnet_address() { + SubnetAddress subnetAddress1 = + new SubnetAddress("100.64.0.0/15", mock(InetSocketAddress.class)); + SubnetAddress subnetAddress2 = + new SubnetAddress("100.66.0.0/15", mock(InetSocketAddress.class)); + assertThat(subnetAddress1.isOverlapping(subnetAddress2)).isFalse(); + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/addresstranslation/SubnetAddressTranslatorTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/addresstranslation/SubnetAddressTranslatorTest.java new file mode 100644 index 00000000000..420170654dc --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/addresstranslation/SubnetAddressTranslatorTest.java @@ -0,0 +1,152 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.addresstranslation; + +import static com.datastax.oss.driver.api.core.config.DefaultDriverOption.ADDRESS_TRANSLATOR_DEFAULT_ADDRESS; +import static com.datastax.oss.driver.api.core.config.DefaultDriverOption.ADDRESS_TRANSLATOR_SUBNET_ADDRESSES; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; +import com.datastax.oss.driver.internal.core.context.DefaultDriverContext; +import com.datastax.oss.driver.internal.core.context.MockedDriverContextFactory; +import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap; +import java.net.InetSocketAddress; +import java.util.Map; +import org.junit.Test; + +@SuppressWarnings("resource") +public class SubnetAddressTranslatorTest { + + @Test + public void should_translate_to_correct_subnet_address_ipv4() { + Map subnetAddresses = + ImmutableMap.of( + "\"100.64.0.0/15\"", "cassandra.datacenter1.com:19042", + "100.66.0.\"0/15\"", "cassandra.datacenter2.com:19042"); + DefaultDriverContext context = context(subnetAddresses); + SubnetAddressTranslator translator = new SubnetAddressTranslator(context); + InetSocketAddress address = new InetSocketAddress("100.64.0.1", 9042); + assertThat(translator.translate(address)) + .isEqualTo(InetSocketAddress.createUnresolved("cassandra.datacenter1.com", 19042)); + } + + @Test + public void should_translate_to_correct_subnet_address_ipv6() { + Map subnetAddresses = + ImmutableMap.of( + "\"::ffff:6440:0/111\"", "cassandra.datacenter1.com:19042", + "\"::ffff:6442:0/111\"", "cassandra.datacenter2.com:19042"); + DefaultDriverContext context = context(subnetAddresses); + SubnetAddressTranslator translator = new SubnetAddressTranslator(context); + InetSocketAddress address = new InetSocketAddress("::ffff:6440:1", 9042); + assertThat(translator.translate(address)) + .isEqualTo(InetSocketAddress.createUnresolved("cassandra.datacenter1.com", 19042)); + } + + @Test + public void should_translate_to_default_address() { + DefaultDriverContext context = context(ImmutableMap.of()); + when(context + .getConfig() + .getDefaultProfile() + .getString(ADDRESS_TRANSLATOR_DEFAULT_ADDRESS, null)) + .thenReturn("cassandra.com:19042"); + SubnetAddressTranslator translator = new SubnetAddressTranslator(context); + InetSocketAddress address = new InetSocketAddress("100.68.0.1", 9042); + assertThat(translator.translate(address)) + .isEqualTo(InetSocketAddress.createUnresolved("cassandra.com", 19042)); + } + + @Test + public void should_pass_through_not_matched_address() { + DefaultDriverContext context = context(ImmutableMap.of()); + SubnetAddressTranslator translator = new SubnetAddressTranslator(context); + InetSocketAddress address = new InetSocketAddress("100.68.0.1", 9042); + assertThat(translator.translate(address)).isEqualTo(address); + } + + @Test + public void should_fail_on_intersecting_subnets_ipv4() { + Map subnetAddresses = + ImmutableMap.of( + "\"100.64.0.0/15\"", "cassandra.datacenter1.com:19042", + "100.65.0.\"0/16\"", "cassandra.datacenter2.com:19042"); + DefaultDriverContext context = context(subnetAddresses); + assertThatIllegalArgumentException() + .isThrownBy(() -> new SubnetAddressTranslator(context)) + .withMessage( + "Configured subnets are overlapping: " + + String.format( + "SubnetAddress[subnet=[100, 64, 0, 0], address=%s], ", + InetSocketAddress.createUnresolved("cassandra.datacenter1.com", 19042)) + + String.format( + "SubnetAddress[subnet=[100, 65, 0, 0], address=%s]", + InetSocketAddress.createUnresolved("cassandra.datacenter2.com", 19042))); + } + + @Test + public void should_fail_on_intersecting_subnets_ipv6() { + Map subnetAddresses = + ImmutableMap.of( + "\"::ffff:6440:0/111\"", "cassandra.datacenter1.com:19042", + "\"::ffff:6441:0/112\"", "cassandra.datacenter2.com:19042"); + DefaultDriverContext context = context(subnetAddresses); + assertThatIllegalArgumentException() + .isThrownBy(() -> new SubnetAddressTranslator(context)) + .withMessage( + "Configured subnets are overlapping: " + + String.format( + "SubnetAddress[subnet=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 100, 64, 0, 0], address=%s], ", + InetSocketAddress.createUnresolved("cassandra.datacenter1.com", 19042)) + + String.format( + "SubnetAddress[subnet=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 100, 65, 0, 0], address=%s]", + InetSocketAddress.createUnresolved("cassandra.datacenter2.com", 19042))); + } + + @Test + public void should_fail_on_subnet_address_without_port() { + Map subnetAddresses = + ImmutableMap.of("\"100.64.0.0/15\"", "cassandra.datacenter1.com"); + DefaultDriverContext context = context(subnetAddresses); + assertThatIllegalArgumentException() + .isThrownBy(() -> new SubnetAddressTranslator(context)) + .withMessage("Invalid address cassandra.datacenter1.com (expecting format host:port)"); + } + + @Test + public void should_fail_on_default_address_without_port() { + DefaultDriverContext context = context(ImmutableMap.of()); + when(context + .getConfig() + .getDefaultProfile() + .getString(ADDRESS_TRANSLATOR_DEFAULT_ADDRESS, null)) + .thenReturn("cassandra.com"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new SubnetAddressTranslator(context)) + .withMessage("Invalid address cassandra.com (expecting format host:port)"); + } + + private static DefaultDriverContext context(Map subnetAddresses) { + DriverExecutionProfile profile = mock(DriverExecutionProfile.class); + when(profile.getStringMap(ADDRESS_TRANSLATOR_SUBNET_ADDRESSES)).thenReturn(subnetAddresses); + return MockedDriverContextFactory.defaultDriverContext(profile); + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/addresstranslation/SubnetTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/addresstranslation/SubnetTest.java new file mode 100644 index 00000000000..f8ba8929e9e --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/addresstranslation/SubnetTest.java @@ -0,0 +1,118 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.addresstranslation; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatNoException; + +import java.net.UnknownHostException; +import org.junit.Test; + +public class SubnetTest { + @Test + public void should_parse_to_correct_ipv4_subnet() throws UnknownHostException { + Subnet subnet = Subnet.parse("100.64.0.0/15"); + assertThat(subnet.getSubnet()).containsExactly(100, 64, 0, 0); + assertThat(subnet.getNetworkMask()).containsExactly(255, 254, 0, 0); + assertThat(subnet.getUpper()).containsExactly(100, 65, 255, 255); + assertThat(subnet.getLower()).containsExactly(100, 64, 0, 0); + } + + @Test + public void should_parse_to_correct_ipv6_subnet() throws UnknownHostException { + Subnet subnet = Subnet.parse("2001:db8:85a3::8a2e:370:0/111"); + assertThat(subnet.getSubnet()) + .containsExactly(32, 1, 13, 184, 133, 163, 0, 0, 0, 0, 138, 46, 3, 112, 0, 0); + assertThat(subnet.getNetworkMask()) + .containsExactly( + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 0, 0); + assertThat(subnet.getUpper()) + .containsExactly(32, 1, 13, 184, 133, 163, 0, 0, 0, 0, 138, 46, 3, 113, 255, 255); + assertThat(subnet.getLower()) + .containsExactly(32, 1, 13, 184, 133, 163, 0, 0, 0, 0, 138, 46, 3, 112, 0, 0); + } + + @Test + public void should_parse_to_correct_ipv6_subnet_ipv4_convertible() throws UnknownHostException { + Subnet subnet = Subnet.parse("::ffff:6440:0/111"); + assertThat(subnet.getSubnet()) + .containsExactly(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 100, 64, 0, 0); + assertThat(subnet.getNetworkMask()) + .containsExactly( + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 0, 0); + assertThat(subnet.getUpper()) + .containsExactly(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 100, 65, 255, 255); + assertThat(subnet.getLower()) + .containsExactly(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 100, 64, 0, 0); + } + + @Test + public void should_fail_on_invalid_cidr_format() { + assertThatIllegalArgumentException() + .isThrownBy(() -> Subnet.parse("invalid")) + .withMessage("Invalid subnet: invalid"); + } + + @Test + public void should_parse_bounding_prefix_lengths_correctly() { + assertThatNoException().isThrownBy(() -> Subnet.parse("0.0.0.0/0")); + assertThatNoException().isThrownBy(() -> Subnet.parse("100.64.0.0/32")); + } + + @Test + public void should_fail_on_invalid_prefix_length() { + assertThatIllegalArgumentException() + .isThrownBy(() -> Subnet.parse("100.64.0.0/-1")) + .withMessage("Prefix length -1 must be within [0; 32]"); + assertThatIllegalArgumentException() + .isThrownBy(() -> Subnet.parse("100.64.0.0/33")) + .withMessage("Prefix length 33 must be within [0; 32]"); + } + + @Test + public void should_fail_on_not_prefix_block_subnet_ipv4() { + assertThatIllegalArgumentException() + .isThrownBy(() -> Subnet.parse("100.65.0.0/15")) + .withMessage("Subnet 100.65.0.0/15 must be represented as a network prefix block"); + } + + @Test + public void should_fail_on_not_prefix_block_subnet_ipv6() { + assertThatIllegalArgumentException() + .isThrownBy(() -> Subnet.parse("::ffff:6441:0/111")) + .withMessage("Subnet ::ffff:6441:0/111 must be represented as a network prefix block"); + } + + @Test + public void should_return_true_on_containing_address() throws UnknownHostException { + Subnet subnet = Subnet.parse("100.64.0.0/15"); + assertThat(subnet.contains(new byte[] {100, 64, 0, 0})).isTrue(); + assertThat(subnet.contains(new byte[] {100, 65, (byte) 255, (byte) 255})).isTrue(); + assertThat(subnet.contains(new byte[] {100, 65, 100, 100})).isTrue(); + } + + @Test + public void should_return_false_on_not_containing_address() throws UnknownHostException { + Subnet subnet = Subnet.parse("100.64.0.0/15"); + assertThat(subnet.contains(new byte[] {100, 63, (byte) 255, (byte) 255})).isFalse(); + assertThat(subnet.contains(new byte[] {100, 66, 0, 0})).isFalse(); + // IPv6 cannot be contained by IPv4 subnet. + assertThat(subnet.contains(new byte[16])).isFalse(); + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/channel/ChannelFactoryAvailableIdsTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/channel/ChannelFactoryAvailableIdsTest.java index 95d4ff119eb..a1eab41b998 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/channel/ChannelFactoryAvailableIdsTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/channel/ChannelFactoryAvailableIdsTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/channel/ChannelFactoryClusterNameTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/channel/ChannelFactoryClusterNameTest.java index 5a3cf93edeb..d9793247c9c 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/channel/ChannelFactoryClusterNameTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/channel/ChannelFactoryClusterNameTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/channel/ChannelFactoryProtocolNegotiationTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/channel/ChannelFactoryProtocolNegotiationTest.java index 189561c161b..b9738a140c0 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/channel/ChannelFactoryProtocolNegotiationTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/channel/ChannelFactoryProtocolNegotiationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -94,6 +96,44 @@ public void should_fail_if_version_specified_and_not_supported_by_server(int err }); } + @Test + public void should_fail_if_version_specified_and_considered_beta_by_server() { + // Given + when(defaultProfile.isDefined(DefaultDriverOption.PROTOCOL_VERSION)).thenReturn(true); + when(defaultProfile.getString(DefaultDriverOption.PROTOCOL_VERSION)).thenReturn("V5"); + when(protocolVersionRegistry.fromName("V5")).thenReturn(DefaultProtocolVersion.V5); + ChannelFactory factory = newChannelFactory(); + + // When + CompletionStage channelFuture = + factory.connect( + SERVER_ADDRESS, DriverChannelOptions.DEFAULT, NoopNodeMetricUpdater.INSTANCE); + + Frame requestFrame = readOutboundFrame(); + assertThat(requestFrame.message).isInstanceOf(Options.class); + writeInboundFrame(requestFrame, TestResponses.supportedResponse("mock_key", "mock_value")); + + requestFrame = readOutboundFrame(); + assertThat(requestFrame.protocolVersion).isEqualTo(DefaultProtocolVersion.V5.getCode()); + // Server considers v5 beta, e.g. C* 3.10 or 3.11 + writeInboundFrame( + requestFrame, + new Error( + ProtocolConstants.ErrorCode.PROTOCOL_ERROR, + "Beta version of the protocol used (5/v5-beta), but USE_BETA flag is unset")); + + // Then + assertThatStage(channelFuture) + .isFailed( + e -> { + assertThat(e) + .isInstanceOf(UnsupportedProtocolVersionException.class) + .hasMessageContaining("Host does not support protocol version V5"); + assertThat(((UnsupportedProtocolVersionException) e).getAttemptedVersions()) + .containsExactly(DefaultProtocolVersion.V5); + }); + } + @Test public void should_succeed_if_version_not_specified_and_server_supports_latest_supported() { // Given diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/channel/ChannelFactorySupportedOptionsTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/channel/ChannelFactorySupportedOptionsTest.java index 81246d782a1..559e11e0bc2 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/channel/ChannelFactorySupportedOptionsTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/channel/ChannelFactorySupportedOptionsTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/channel/ChannelFactoryTestBase.java b/core/src/test/java/com/datastax/oss/driver/internal/core/channel/ChannelFactoryTestBase.java index d28e10d0d9d..b25a1e9ad71 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/channel/ChannelFactoryTestBase.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/channel/ChannelFactoryTestBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/channel/ChannelHandlerTestBase.java b/core/src/test/java/com/datastax/oss/driver/internal/core/channel/ChannelHandlerTestBase.java index d0da5377c5f..5feb85a457b 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/channel/ChannelHandlerTestBase.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/channel/ChannelHandlerTestBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/channel/ConnectInitHandlerTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/channel/ConnectInitHandlerTest.java index ba5fd28aeb5..6024ed26a5c 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/channel/ConnectInitHandlerTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/channel/ConnectInitHandlerTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/channel/DriverChannelTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/channel/DriverChannelTest.java index d543c83fe53..e0660b9609e 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/channel/DriverChannelTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/channel/DriverChannelTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/channel/EmbeddedEndPoint.java b/core/src/test/java/com/datastax/oss/driver/internal/core/channel/EmbeddedEndPoint.java index d844bc35fb4..5e463299a66 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/channel/EmbeddedEndPoint.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/channel/EmbeddedEndPoint.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/channel/InFlightHandlerTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/channel/InFlightHandlerTest.java index 2fca9366104..35049e99af1 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/channel/InFlightHandlerTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/channel/InFlightHandlerTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -37,7 +39,9 @@ import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelPromise; import java.net.InetSocketAddress; +import java.util.ArrayList; import java.util.Collections; +import java.util.List; import java.util.concurrent.TimeUnit; import org.junit.Before; import org.junit.Test; @@ -254,7 +258,7 @@ public void should_refuse_new_writes_during_graceful_close() { } @Test - public void should_close_gracefully_if_orphan_ids_above_max_and_pending_requests() { + public void should_close_gracefully_if_orphan_ids_above_max_and_pending_request() { // Given addToPipeline(); // Generate n orphan ids by writing and cancelling the requests: @@ -309,6 +313,65 @@ public void should_close_gracefully_if_orphan_ids_above_max_and_pending_requests assertThat(channel.closeFuture()).isSuccess(); } + @Test + public void should_close_gracefully_if_orphan_ids_above_max_and_multiple_pending_requests() { + // Given + addToPipeline(); + // Generate n orphan ids by writing and cancelling the requests. + for (int i = 0; i < MAX_ORPHAN_IDS; i++) { + when(streamIds.acquire()).thenReturn(i); + MockResponseCallback responseCallback = new MockResponseCallback(); + channel + .writeAndFlush( + new DriverChannel.RequestMessage(QUERY, false, Frame.NO_PAYLOAD, responseCallback)) + .awaitUninterruptibly(); + channel.writeAndFlush(responseCallback).awaitUninterruptibly(); + } + // Generate 3 additional requests that are pending and not cancelled. + List pendingResponseCallbacks = new ArrayList<>(); + for (int i = 0; i < 3; i++) { + when(streamIds.acquire()).thenReturn(MAX_ORPHAN_IDS + i); + MockResponseCallback responseCallback = new MockResponseCallback(); + channel + .writeAndFlush( + new DriverChannel.RequestMessage(QUERY, false, Frame.NO_PAYLOAD, responseCallback)) + .awaitUninterruptibly(); + pendingResponseCallbacks.add(responseCallback); + } + + // When + // Generate the n+1th orphan id that makes us go above the threshold by canceling one if the + // pending requests. + channel.writeAndFlush(pendingResponseCallbacks.remove(0)).awaitUninterruptibly(); + + // Then + // Channel should be closing gracefully but there's no way to observe that from the outside + // besides writing another request and check that it's rejected. + assertThat(channel.closeFuture()).isNotDone(); + ChannelFuture otherWriteFuture = + channel.writeAndFlush( + new DriverChannel.RequestMessage( + QUERY, false, Frame.NO_PAYLOAD, new MockResponseCallback())); + assertThat(otherWriteFuture).isFailed(); + assertThat(otherWriteFuture.cause()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Channel is closing"); + + // When + // Cancel the remaining pending requests causing the n+ith orphan ids above the threshold. + for (MockResponseCallback pendingResponseCallback : pendingResponseCallbacks) { + ChannelFuture future = channel.writeAndFlush(pendingResponseCallback).awaitUninterruptibly(); + + // Then + // The future should succeed even though the channel has started closing gracefully. + assertThat(future).isSuccess(); + } + + // Then + // The graceful shutdown completes. + assertThat(channel.closeFuture()).isSuccess(); + } + @Test public void should_close_immediately_if_orphan_ids_above_max_and_no_pending_requests() { // Given diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/channel/LocalEndPoint.java b/core/src/test/java/com/datastax/oss/driver/internal/core/channel/LocalEndPoint.java index a82ddf1115a..c90731eece9 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/channel/LocalEndPoint.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/channel/LocalEndPoint.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/channel/MockAuthenticator.java b/core/src/test/java/com/datastax/oss/driver/internal/core/channel/MockAuthenticator.java index 26db7c768b4..6015203ed38 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/channel/MockAuthenticator.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/channel/MockAuthenticator.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/channel/MockChannelFactoryHelper.java b/core/src/test/java/com/datastax/oss/driver/internal/core/channel/MockChannelFactoryHelper.java index 8379585ddf4..43768131108 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/channel/MockChannelFactoryHelper.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/channel/MockChannelFactoryHelper.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/channel/MockResponseCallback.java b/core/src/test/java/com/datastax/oss/driver/internal/core/channel/MockResponseCallback.java index d8f5604ac72..8774ee3e298 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/channel/MockResponseCallback.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/channel/MockResponseCallback.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/channel/ProtocolInitHandlerTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/channel/ProtocolInitHandlerTest.java index 127b4ef6ec4..2fd12fc9f94 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/channel/ProtocolInitHandlerTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/channel/ProtocolInitHandlerTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/channel/StreamIdGeneratorTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/channel/StreamIdGeneratorTest.java index 53917f78ec4..83802884c45 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/channel/StreamIdGeneratorTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/channel/StreamIdGeneratorTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/config/MockOptions.java b/core/src/test/java/com/datastax/oss/driver/internal/core/config/MockOptions.java index 357097a5c8a..cee57abbfdf 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/config/MockOptions.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/config/MockOptions.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -22,6 +24,7 @@ public enum MockOptions implements DriverOption { INT1("int1"), INT2("int2"), AUTH_PROVIDER("auth_provider"), + SUBNET_ADDRESSES("subnet_addresses"), ; private final String path; diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/config/MockTypedOptions.java b/core/src/test/java/com/datastax/oss/driver/internal/core/config/MockTypedOptions.java index de6345cc0e2..ecad298aa37 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/config/MockTypedOptions.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/config/MockTypedOptions.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/config/cloud/CloudConfigFactoryTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/config/cloud/CloudConfigFactoryTest.java index 6f54413b601..a0db82d298e 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/config/cloud/CloudConfigFactoryTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/config/cloud/CloudConfigFactoryTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/config/composite/CompositeDriverConfigReloadTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/config/composite/CompositeDriverConfigReloadTest.java index 761ecf9cc60..1d327a08101 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/config/composite/CompositeDriverConfigReloadTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/config/composite/CompositeDriverConfigReloadTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,6 +18,7 @@ package com.datastax.oss.driver.internal.core.config.composite; import static com.datastax.oss.driver.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -83,9 +86,9 @@ public void should_delegate_reloading_to_reloadable_children( if (compositeShouldBeReloadable) { assertThat(reloadFuture).isCompletedWithValue(true); } else { - assertThat(reloadFuture) - .hasFailedWithThrowableThat() - .isInstanceOf(UnsupportedOperationException.class); + assertThat(reloadFuture).isCompletedExceptionally(); + Throwable t = catchThrowable(() -> reloadFuture.toCompletableFuture().get()); + assertThat(t).hasRootCauseInstanceOf(UnsupportedOperationException.class); } verify(primaryLoader, primaryIsReloadable ? times(1) : never()).reload(); verify(fallbackLoader, fallbackIsReloadable ? times(1) : never()).reload(); diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/config/composite/CompositeDriverConfigTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/config/composite/CompositeDriverConfigTest.java index 1c6121b1121..e5d5ffcdf83 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/config/composite/CompositeDriverConfigTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/config/composite/CompositeDriverConfigTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,7 +18,9 @@ package com.datastax.oss.driver.internal.core.config.composite; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.entry; +import com.datastax.dse.driver.api.core.config.DseDriverOption; import com.datastax.oss.driver.api.core.config.DefaultDriverOption; import com.datastax.oss.driver.api.core.config.DriverConfig; import com.datastax.oss.driver.api.core.config.DriverConfigLoader; @@ -59,6 +63,10 @@ public void should_use_value_from_primary_config() { .isTrue(); assertThat(compositeDefaultProfile.getInt(DefaultDriverOption.CONNECTION_POOL_LOCAL_SIZE)) .isEqualTo(1); + assertThat(compositeDefaultProfile.entrySet()) + .containsExactly( + entry(DefaultDriverOption.CONNECTION_POOL_LOCAL_SIZE.getPath(), 1), + entry(DseDriverOption.CONTINUOUS_PAGING_MAX_PAGES.getPath(), 1)); } @Test @@ -70,6 +78,10 @@ public void should_ignore_value_from_fallback_config_if_defined_in_both() { .isTrue(); assertThat(compositeDefaultProfile.getInt(DefaultDriverOption.CONNECTION_POOL_LOCAL_SIZE)) .isEqualTo(1); + assertThat(compositeDefaultProfile.entrySet()) + .containsExactly( + entry(DefaultDriverOption.CONNECTION_POOL_LOCAL_SIZE.getPath(), 1), + entry(DseDriverOption.CONTINUOUS_PAGING_MAX_PAGES.getPath(), 1)); } @Test @@ -80,6 +92,10 @@ public void should_use_value_from_fallback_config_if_not_defined_in_primary() { .isTrue(); assertThat(compositeDefaultProfile.getInt(DefaultDriverOption.CONNECTION_POOL_LOCAL_SIZE)) .isEqualTo(1); + assertThat(compositeDefaultProfile.entrySet()) + .containsExactly( + entry(DefaultDriverOption.CONNECTION_POOL_LOCAL_SIZE.getPath(), 1), + entry(DseDriverOption.CONTINUOUS_PAGING_MAX_PAGES.getPath(), 1)); } @Test @@ -112,5 +128,20 @@ public void should_merge_profiles() { .getProfile("onlyInFallback") .getInt(DefaultDriverOption.CONNECTION_POOL_LOCAL_SIZE)) .isEqualTo(4); + + assertThat(compositeConfig.getProfile("onlyInPrimary").entrySet()) + .containsExactly( + entry(DefaultDriverOption.CONNECTION_POOL_LOCAL_SIZE.getPath(), 1), + entry(DseDriverOption.CONTINUOUS_PAGING_MAX_PAGES.getPath(), 1)); + + assertThat(compositeConfig.getProfile("inBoth").entrySet()) + .containsExactly( + entry(DefaultDriverOption.CONNECTION_POOL_LOCAL_SIZE.getPath(), 2), + entry(DseDriverOption.CONTINUOUS_PAGING_MAX_PAGES.getPath(), 1)); + + assertThat(compositeConfig.getProfile("onlyInFallback").entrySet()) + .containsExactly( + entry(DefaultDriverOption.CONNECTION_POOL_LOCAL_SIZE.getPath(), 4), + entry(DseDriverOption.CONTINUOUS_PAGING_MAX_PAGES.getPath(), 1)); } } diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/config/map/MapBasedDriverConfigLoaderTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/config/map/MapBasedDriverConfigLoaderTest.java index 0b4cd07458e..93f6b274826 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/config/map/MapBasedDriverConfigLoaderTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/config/map/MapBasedDriverConfigLoaderTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/config/map/MapBasedDriverConfigTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/config/map/MapBasedDriverConfigTest.java index f21803c5688..1ebd5fb48ba 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/config/map/MapBasedDriverConfigTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/config/map/MapBasedDriverConfigTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/config/typesafe/DefaultDriverConfigLoaderTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/config/typesafe/DefaultDriverConfigLoaderTest.java index aa4ff4a2287..16b8f0b3aa6 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/config/typesafe/DefaultDriverConfigLoaderTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/config/typesafe/DefaultDriverConfigLoaderTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/config/typesafe/DefaultProgrammaticDriverConfigLoaderBuilderTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/config/typesafe/DefaultProgrammaticDriverConfigLoaderBuilderTest.java index 7e2b6041ff8..4f2edf98246 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/config/typesafe/DefaultProgrammaticDriverConfigLoaderBuilderTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/config/typesafe/DefaultProgrammaticDriverConfigLoaderBuilderTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -29,6 +31,22 @@ public class DefaultProgrammaticDriverConfigLoaderBuilderTest { private static final String FALLBACK_CONFIG = "int1 = 1\nint2 = 2\nprofiles.profile1 { int1 = 11 }"; + @Test + public void should_override_option() { + DriverConfigLoader loader = + new DefaultProgrammaticDriverConfigLoaderBuilder( + () -> ConfigFactory.parseString(FALLBACK_CONFIG), "") + .withInt(MockOptions.INT1, 2) + .withInt(MockOptions.INT1, 3) + .withInt(MockOptions.INT1, 4) + .withInt(MockOptions.INT2, 3) + .withInt(MockOptions.INT2, 4) + .build(); + DriverConfig config = loader.getInitialConfig(); + assertThat(config.getDefaultProfile().getInt(MockOptions.INT1)).isEqualTo(4); + assertThat(config.getDefaultProfile().getInt(MockOptions.INT2)).isEqualTo(4); + } + @Test public void should_override_option_in_default_profile() { DriverConfigLoader loader = diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/config/typesafe/TypeSafeDriverConfigOverrideDefaultsTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/config/typesafe/TypeSafeDriverConfigOverrideDefaultsTest.java index 9541bae4bf7..2f2f0a9b3c1 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/config/typesafe/TypeSafeDriverConfigOverrideDefaultsTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/config/typesafe/TypeSafeDriverConfigOverrideDefaultsTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/config/typesafe/TypesafeDriverConfigTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/config/typesafe/TypesafeDriverConfigTest.java index b268df322de..4a78c3ccb03 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/config/typesafe/TypesafeDriverConfigTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/config/typesafe/TypesafeDriverConfigTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -24,14 +26,10 @@ import com.typesafe.config.ConfigFactory; import java.util.HashMap; import java.util.Map; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; public class TypesafeDriverConfigTest { - @Rule public ExpectedException expectedException = ExpectedException.none(); - @Test public void should_load_minimal_config_with_no_profiles() { TypesafeDriverConfig config = parse("int1 = 42"); @@ -103,7 +101,6 @@ public void should_fetch_string_map() { parse( "int1 = 42 \n auth_provider { auth_thing_one= one \n auth_thing_two = two \n auth_thing_three = three}"); DriverExecutionProfile base = config.getDefaultProfile(); - base.getStringMap(MockOptions.AUTH_PROVIDER); Map map = base.getStringMap(MockOptions.AUTH_PROVIDER); assertThat(map.entrySet().size()).isEqualTo(3); assertThat(map.get("auth_thing_one")).isEqualTo("one"); @@ -111,6 +108,19 @@ public void should_fetch_string_map() { assertThat(map.get("auth_thing_three")).isEqualTo("three"); } + @Test + public void should_fetch_string_map_with_forward_slash_in_keys() { + TypesafeDriverConfig config = + parse( + "subnet_addresses { 100.64.0.0/15 = \"cassandra.datacenter1.com:9042\" \n \"100.66.0.0/15\" = \"cassandra.datacenter2.com\" \n \"::ffff:6440:0/111\" = \"cassandra.datacenter3.com:19042\" }"); + DriverExecutionProfile base = config.getDefaultProfile(); + Map map = base.getStringMap(MockOptions.SUBNET_ADDRESSES); + assertThat(map.entrySet().size()).isEqualTo(3); + assertThat(map.get("100.64.0.\"0/15\"")).isEqualTo("cassandra.datacenter1.com:9042"); + assertThat(map.get("\"100.66.0.0/15\"")).isEqualTo("cassandra.datacenter2.com"); + assertThat(map.get("\"::ffff:6440:0/111\"")).isEqualTo("cassandra.datacenter3.com:19042"); + } + @Test public void should_create_derived_profile_with_string_map() { TypesafeDriverConfig config = parse("int1 = 42"); @@ -175,6 +185,14 @@ public void should_enumerate_options() { entry("int1", 45)); } + @Test + public void should_update_default_profile_on_reload() { + TypesafeDriverConfig config = parse("int1 = 42\n profiles { profile1 { int1 = 43 } }"); + assertThat(config.getDefaultProfile().getInt(MockOptions.INT1)).isEqualTo(42); + config.reload(ConfigFactory.parseString("int1 = 44\n profiles { profile1 { int1 = 45 } }")); + assertThat(config.getDefaultProfile().getInt(MockOptions.INT1)).isEqualTo(44); + } + private TypesafeDriverConfig parse(String configString) { Config config = ConfigFactory.parseString(configString); return new TypesafeDriverConfig(config); diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/connection/ExponentialReconnectionPolicyTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/connection/ExponentialReconnectionPolicyTest.java index 3f1a7c12bb5..9a973c1b0e4 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/connection/ExponentialReconnectionPolicyTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/connection/ExponentialReconnectionPolicyTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/context/DefaultDriverContextTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/context/DefaultDriverContextTest.java index c87263871be..6d4585cb4d7 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/context/DefaultDriverContextTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/context/DefaultDriverContextTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -40,7 +42,7 @@ private DefaultDriverContext buildMockedContext(Optional compressionOpti DriverExecutionProfile defaultProfile = mock(DriverExecutionProfile.class); when(defaultProfile.getString(DefaultDriverOption.PROTOCOL_COMPRESSION, "none")) .thenReturn(compressionOption.orElse("none")); - return MockedDriverContextFactory.defaultDriverContext(Optional.of(defaultProfile)); + return MockedDriverContextFactory.defaultDriverContext(defaultProfile); } private void doCreateCompressorTest(Optional configVal, Class expectedClz) { diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/context/MockedDriverContextFactory.java b/core/src/test/java/com/datastax/oss/driver/internal/core/context/MockedDriverContextFactory.java index 15d6d296fc4..a8b25193f54 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/context/MockedDriverContextFactory.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/context/MockedDriverContextFactory.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -22,44 +24,45 @@ import com.datastax.oss.driver.api.core.config.DriverConfig; import com.datastax.oss.driver.api.core.config.DriverConfigLoader; import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; +import com.datastax.oss.driver.api.core.loadbalancing.LoadBalancingPolicy; +import com.datastax.oss.driver.api.core.loadbalancing.NodeDistanceEvaluator; +import com.datastax.oss.driver.api.core.metadata.Node; import com.datastax.oss.driver.api.core.metadata.NodeStateListener; import com.datastax.oss.driver.api.core.metadata.schema.SchemaChangeListener; import com.datastax.oss.driver.api.core.session.ProgrammaticArguments; import com.datastax.oss.driver.api.core.tracker.RequestTracker; +import com.datastax.oss.driver.internal.core.ConsistencyLevelRegistry; +import com.datastax.oss.driver.internal.core.loadbalancing.DefaultLoadBalancingPolicy; +import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap; import com.datastax.oss.driver.shaded.guava.common.collect.Maps; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.Nullable; import java.time.Duration; +import java.util.Collections; +import java.util.List; +import java.util.Map; import java.util.Optional; +import java.util.UUID; public class MockedDriverContextFactory { public static DefaultDriverContext defaultDriverContext() { - return defaultDriverContext(Optional.empty()); + return defaultDriverContext(MockedDriverContextFactory.defaultProfile("datacenter1")); } public static DefaultDriverContext defaultDriverContext( - Optional profileOption) { - - /* If the caller provided a profile use that, otherwise make a new one */ - final DriverExecutionProfile profile = - profileOption.orElseGet( - () -> { - DriverExecutionProfile blankProfile = mock(DriverExecutionProfile.class); - when(blankProfile.getString(DefaultDriverOption.PROTOCOL_COMPRESSION, "none")) - .thenReturn("none"); - when(blankProfile.getDuration(DefaultDriverOption.METRICS_NODE_EXPIRE_AFTER)) - .thenReturn(Duration.ofMinutes(5)); - when(blankProfile.isDefined(DefaultDriverOption.METRICS_FACTORY_CLASS)) - .thenReturn(true); - when(blankProfile.getString(DefaultDriverOption.METRICS_FACTORY_CLASS)) - .thenReturn("DropwizardMetricsFactory"); - return blankProfile; - }); + DriverExecutionProfile defaultProfile, DriverExecutionProfile... profiles) { /* Setup machinery to connect the input DriverExecutionProfile to the config loader */ final DriverConfig driverConfig = mock(DriverConfig.class); final DriverConfigLoader configLoader = mock(DriverConfigLoader.class); when(configLoader.getInitialConfig()).thenReturn(driverConfig); - when(driverConfig.getDefaultProfile()).thenReturn(profile); + when(driverConfig.getDefaultProfile()).thenReturn(defaultProfile); + when(driverConfig.getProfile(defaultProfile.getName())).thenReturn(defaultProfile); + + for (DriverExecutionProfile profile : profiles) { + when(driverConfig.getProfile(profile.getName())).thenReturn(profile); + } ProgrammaticArguments args = ProgrammaticArguments.builder() @@ -67,8 +70,91 @@ public static DefaultDriverContext defaultDriverContext( .withSchemaChangeListener(mock(SchemaChangeListener.class)) .withRequestTracker(mock(RequestTracker.class)) .withLocalDatacenters(Maps.newHashMap()) - .withNodeFilters(Maps.newHashMap()) + .withNodeDistanceEvaluators(Maps.newHashMap()) .build(); - return new DefaultDriverContext(configLoader, args); + + return new DefaultDriverContext(configLoader, args) { + @NonNull + @Override + public Map getLoadBalancingPolicies() { + ImmutableMap.Builder map = ImmutableMap.builder(); + map.put( + defaultProfile.getName(), + mockLoadBalancingPolicy( + this, + defaultProfile.getName(), + defaultProfile.getString(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER))); + for (DriverExecutionProfile profile : profiles) { + map.put( + profile.getName(), + mockLoadBalancingPolicy( + this, + profile.getName(), + profile.getString(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER))); + } + return map.build(); + } + + @NonNull + @Override + public ConsistencyLevelRegistry getConsistencyLevelRegistry() { + return mock(ConsistencyLevelRegistry.class); + } + }; + } + + public static DriverExecutionProfile defaultProfile(String localDc) { + return createProfile(DriverExecutionProfile.DEFAULT_NAME, localDc); + } + + public static DriverExecutionProfile createProfile(String name, String localDc) { + DriverExecutionProfile defaultProfile = mock(DriverExecutionProfile.class); + when(defaultProfile.getName()).thenReturn(name); + when(defaultProfile.getString(DefaultDriverOption.PROTOCOL_COMPRESSION, "none")) + .thenReturn("none"); + when(defaultProfile.getDuration(DefaultDriverOption.METRICS_NODE_EXPIRE_AFTER)) + .thenReturn(Duration.ofMinutes(5)); + when(defaultProfile.isDefined(DefaultDriverOption.METRICS_FACTORY_CLASS)).thenReturn(true); + when(defaultProfile.getString(DefaultDriverOption.METRICS_FACTORY_CLASS)) + .thenReturn("DefaultMetricsFactory"); + when(defaultProfile.getString(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER)) + .thenReturn(localDc); + return defaultProfile; + } + + public static void allowRemoteDcConnectivity( + DriverExecutionProfile profile, + int maxNodesPerRemoteDc, + boolean allowRemoteSatisfyLocalDc, + List preferredRemoteDcs) { + when(profile.getInt(DefaultDriverOption.LOAD_BALANCING_DC_FAILOVER_MAX_NODES_PER_REMOTE_DC)) + .thenReturn(maxNodesPerRemoteDc); + when(profile.getBoolean( + DefaultDriverOption.LOAD_BALANCING_DC_FAILOVER_ALLOW_FOR_LOCAL_CONSISTENCY_LEVELS)) + .thenReturn(allowRemoteSatisfyLocalDc); + when(profile.getStringList(DefaultDriverOption.LOAD_BALANCING_DC_FAILOVER_PREFERRED_REMOTE_DCS)) + .thenReturn(preferredRemoteDcs); + } + + private static LoadBalancingPolicy mockLoadBalancingPolicy( + DefaultDriverContext driverContext, String profile, String localDc) { + LoadBalancingPolicy loadBalancingPolicy = + new DefaultLoadBalancingPolicy(driverContext, profile) { + @NonNull + @Override + protected Optional discoverLocalDc(@NonNull Map nodes) { + return Optional.ofNullable(localDc); + } + + @NonNull + @Override + protected NodeDistanceEvaluator createNodeDistanceEvaluator( + @Nullable String localDc, @NonNull Map nodes) { + return mock(NodeDistanceEvaluator.class); + } + }; + loadBalancingPolicy.init( + Collections.emptyMap(), mock(LoadBalancingPolicy.DistanceReporter.class)); + return loadBalancingPolicy; } } diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/context/StartupOptionsBuilderTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/context/StartupOptionsBuilderTest.java index c9f1952d83f..d12e50b7e8e 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/context/StartupOptionsBuilderTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/context/StartupOptionsBuilderTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -24,10 +26,10 @@ import com.datastax.oss.driver.api.core.config.DefaultDriverOption; import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; import com.datastax.oss.driver.api.core.session.Session; +import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableList; import com.datastax.oss.protocol.internal.request.Startup; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; -import java.util.Optional; import org.junit.Test; import org.junit.runner.RunWith; @@ -39,7 +41,8 @@ private DefaultDriverContext buildMockedContext(String compression) { DriverExecutionProfile defaultProfile = mock(DriverExecutionProfile.class); when(defaultProfile.getString(DefaultDriverOption.PROTOCOL_COMPRESSION, "none")) .thenReturn(compression); - return MockedDriverContextFactory.defaultDriverContext(Optional.of(defaultProfile)); + when(defaultProfile.getName()).thenReturn(DriverExecutionProfile.DEFAULT_NAME); + return MockedDriverContextFactory.defaultDriverContext(defaultProfile); } private void assertDefaultStartupOptions(Startup startup) { @@ -92,4 +95,44 @@ public void should_fail_to_build_startup_options_with_invalid_compression() { new Startup(ctx.getStartupOptions()); }); } + + @Test + public void should_include_all_local_dcs_in_startup_message() { + + DefaultDriverContext ctx = + MockedDriverContextFactory.defaultDriverContext( + MockedDriverContextFactory.defaultProfile("us-west-2"), + MockedDriverContextFactory.createProfile("oltp", "us-east-2"), + MockedDriverContextFactory.createProfile("olap", "eu-central-1")); + Startup startup = new Startup(ctx.getStartupOptions()); + assertThat(startup.options) + .containsEntry( + StartupOptionsBuilder.DRIVER_BAGGAGE, + "{\"default\":{\"DefaultLoadBalancingPolicy\":{\"localDc\":\"us-west-2\"}}," + + "\"oltp\":{\"DefaultLoadBalancingPolicy\":{\"localDc\":\"us-east-2\"}}," + + "\"olap\":{\"DefaultLoadBalancingPolicy\":{\"localDc\":\"eu-central-1\"}}}"); + } + + @Test + public void should_include_all_lbp_details_in_startup_message() { + + DriverExecutionProfile defaultProfile = MockedDriverContextFactory.defaultProfile("dc1"); + DriverExecutionProfile oltpProfile = MockedDriverContextFactory.createProfile("oltp", "dc1"); + MockedDriverContextFactory.allowRemoteDcConnectivity( + oltpProfile, 2, true, ImmutableList.of("dc2", "dc3")); + DefaultDriverContext ctx = + MockedDriverContextFactory.defaultDriverContext(defaultProfile, oltpProfile); + + Startup startup = new Startup(ctx.getStartupOptions()); + + assertThat(startup.options) + .containsEntry( + StartupOptionsBuilder.DRIVER_BAGGAGE, + "{\"default\":{\"DefaultLoadBalancingPolicy\":{\"localDc\":\"dc1\"}}," + + "\"oltp\":{\"DefaultLoadBalancingPolicy\":{" + + "\"localDc\":\"dc1\"," + + "\"preferredRemoteDcs\":[\"dc2\",\"dc3\"]," + + "\"allowDcFailoverForLocalCl\":true," + + "\"maxNodesPerRemoteDc\":2}}}"); + } } diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/context/bus/EventBusTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/context/bus/EventBusTest.java index 1bf71a7ce6c..61533a8e8e9 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/context/bus/EventBusTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/context/bus/EventBusTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/control/ControlConnectionEventsTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/control/ControlConnectionEventsTest.java index c92cf14de41..cb83b523ebe 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/control/ControlConnectionEventsTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/control/ControlConnectionEventsTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/control/ControlConnectionTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/control/ControlConnectionTest.java index edaa9e90060..526efefa2fe 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/control/ControlConnectionTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/control/ControlConnectionTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/control/ControlConnectionTestBase.java b/core/src/test/java/com/datastax/oss/driver/internal/core/control/ControlConnectionTestBase.java index ca349d135a1..c52199465a8 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/control/ControlConnectionTestBase.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/control/ControlConnectionTestBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -58,7 +60,6 @@ abstract class ControlConnectionTestBase { protected static final InetSocketAddress ADDRESS1 = new InetSocketAddress("127.0.0.1", 9042); - protected static final InetSocketAddress ADDRESS2 = new InetSocketAddress("127.0.0.2", 9042); /** How long we wait when verifying mocks for async invocations */ protected static final VerificationWithTimeout VERIFY_TIMEOUT = timeout(500); diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/cql/ConversionsTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/cql/ConversionsTest.java index 4d52ab2323a..954cf0e14a0 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/cql/ConversionsTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/cql/ConversionsTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/cql/CqlPrepareHandlerTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/cql/CqlPrepareHandlerTest.java index 3e0503bb1e0..1924ef5a9af 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/cql/CqlPrepareHandlerTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/cql/CqlPrepareHandlerTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -25,14 +27,16 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import com.datastax.oss.driver.api.core.AllNodesFailedException; +import com.datastax.oss.driver.api.core.NodeUnavailableException; import com.datastax.oss.driver.api.core.config.DefaultDriverOption; import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; import com.datastax.oss.driver.api.core.cql.ColumnDefinitions; import com.datastax.oss.driver.api.core.cql.PreparedStatement; import com.datastax.oss.driver.api.core.cql.SimpleStatement; import com.datastax.oss.driver.api.core.metadata.Node; -import com.datastax.oss.driver.api.core.retry.RetryDecision; import com.datastax.oss.driver.api.core.retry.RetryPolicy; +import com.datastax.oss.driver.api.core.retry.RetryVerdict; import com.datastax.oss.driver.api.core.servererrors.OverloadedException; import com.datastax.oss.driver.internal.core.channel.ResponseCallback; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableList; @@ -47,6 +51,7 @@ import com.datastax.oss.protocol.internal.response.result.RowsMetadata; import com.datastax.oss.protocol.internal.util.Bytes; import java.nio.ByteBuffer; +import java.util.List; import java.util.Map; import java.util.concurrent.CompletionStage; import org.junit.Before; @@ -177,8 +182,8 @@ public void should_retry_initial_prepare_if_recoverable_error() { when(harness .getContext() .getRetryPolicy(anyString()) - .onErrorResponse(eq(PREPARE_REQUEST), any(OverloadedException.class), eq(0))) - .thenReturn(RetryDecision.RETRY_NEXT); + .onErrorResponseVerdict(eq(PREPARE_REQUEST), any(OverloadedException.class), eq(0))) + .thenReturn(RetryVerdict.RETRY_NEXT); CompletionStage prepareFuture = new CqlPrepareHandler(PREPARE_REQUEST, harness.getSession(), harness.getContext(), "test") @@ -210,8 +215,8 @@ public void should_not_retry_initial_prepare_if_unrecoverable_error() { when(harness .getContext() .getRetryPolicy(anyString()) - .onErrorResponse(eq(PREPARE_REQUEST), any(OverloadedException.class), eq(0))) - .thenReturn(RetryDecision.RETHROW); + .onErrorResponseVerdict(eq(PREPARE_REQUEST), any(OverloadedException.class), eq(0))) + .thenReturn(RetryVerdict.RETHROW); CompletionStage prepareFuture = new CqlPrepareHandler(PREPARE_REQUEST, harness.getSession(), harness.getContext(), "test") @@ -228,6 +233,39 @@ public void should_not_retry_initial_prepare_if_unrecoverable_error() { } } + @Test + public void should_fail_if_nodes_unavailable() { + RequestHandlerTestHarness.Builder harnessBuilder = RequestHandlerTestHarness.builder(); + try (RequestHandlerTestHarness harness = + harnessBuilder.withEmptyPool(node1).withEmptyPool(node2).build()) { + CompletionStage prepareFuture = + new CqlPrepareHandler(PREPARE_REQUEST, harness.getSession(), harness.getContext(), "test") + .handle(); + assertThatStage(prepareFuture) + .isFailed( + error -> { + assertThat(error).isInstanceOf(AllNodesFailedException.class); + Map> allErrors = + ((AllNodesFailedException) error).getAllErrors(); + assertThat(allErrors).hasSize(2); + assertThat(allErrors) + .hasEntrySatisfying( + node1, + nodeErrors -> + assertThat(nodeErrors) + .singleElement() + .isInstanceOf(NodeUnavailableException.class)); + assertThat(allErrors) + .hasEntrySatisfying( + node2, + nodeErrors -> + assertThat(nodeErrors) + .singleElement() + .isInstanceOf(NodeUnavailableException.class)); + }); + } + } + @Test public void should_fail_if_retry_policy_ignores_error() { RequestHandlerTestHarness.Builder harnessBuilder = @@ -243,9 +281,9 @@ public void should_fail_if_retry_policy_ignores_error() { // Make node1's error unrecoverable, will rethrow RetryPolicy mockRetryPolicy = harness.getContext().getRetryPolicy(DriverExecutionProfile.DEFAULT_NAME); - when(mockRetryPolicy.onErrorResponse( + when(mockRetryPolicy.onErrorResponseVerdict( eq(PREPARE_REQUEST), any(OverloadedException.class), eq(0))) - .thenReturn(RetryDecision.IGNORE); + .thenReturn(RetryVerdict.IGNORE); CompletionStage prepareFuture = new CqlPrepareHandler(PREPARE_REQUEST, harness.getSession(), harness.getContext(), "test") diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/cql/CqlRequestHandlerRetryTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/cql/CqlRequestHandlerRetryTest.java index ef04f814e94..ccac873c616 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/cql/CqlRequestHandlerRetryTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/cql/CqlRequestHandlerRetryTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -37,8 +39,8 @@ import com.datastax.oss.driver.api.core.cql.Statement; import com.datastax.oss.driver.api.core.metadata.Node; import com.datastax.oss.driver.api.core.metrics.DefaultNodeMetric; -import com.datastax.oss.driver.api.core.retry.RetryDecision; import com.datastax.oss.driver.api.core.retry.RetryPolicy; +import com.datastax.oss.driver.api.core.retry.RetryVerdict; import com.datastax.oss.driver.api.core.servererrors.BootstrappingException; import com.datastax.oss.driver.api.core.servererrors.DefaultWriteType; import com.datastax.oss.driver.api.core.servererrors.InvalidQueryException; @@ -46,6 +48,8 @@ import com.datastax.oss.driver.api.core.servererrors.ServerError; import com.datastax.oss.driver.api.core.servererrors.UnavailableException; import com.datastax.oss.driver.api.core.servererrors.WriteTimeoutException; +import com.datastax.oss.driver.api.core.session.Request; +import com.datastax.oss.driver.api.core.tracker.RequestIdGenerator; import com.datastax.oss.protocol.internal.ProtocolConstants; import com.datastax.oss.protocol.internal.response.Error; import com.datastax.oss.protocol.internal.response.error.ReadTimeout; @@ -53,9 +57,13 @@ import com.datastax.oss.protocol.internal.response.error.WriteTimeout; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.UseDataProvider; +import edu.umd.cs.findbugs.annotations.NonNull; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; import java.util.Iterator; import java.util.concurrent.CompletionStage; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; public class CqlRequestHandlerRetryTest extends CqlRequestHandlerTestBase { @@ -152,8 +160,8 @@ public void should_try_next_node_if_idempotent_and_retry_policy_decides_so( harnessBuilder.withResponse(node2, defaultFrameOf(singleRow())); try (RequestHandlerTestHarness harness = harnessBuilder.build()) { - failureScenario.mockRetryPolicyDecision( - harness.getContext().getRetryPolicy(anyString()), RetryDecision.RETRY_NEXT); + failureScenario.mockRetryPolicyVerdict( + harness.getContext().getRetryPolicy(anyString()), RetryVerdict.RETRY_NEXT); CompletionStage resultSetFuture = new CqlRequestHandler(statement, harness.getSession(), harness.getContext(), "test") @@ -203,8 +211,8 @@ public void should_try_same_node_if_idempotent_and_retry_policy_decides_so( harnessBuilder.withResponse(node1, defaultFrameOf(singleRow())); try (RequestHandlerTestHarness harness = harnessBuilder.build()) { - failureScenario.mockRetryPolicyDecision( - harness.getContext().getRetryPolicy(anyString()), RetryDecision.RETRY_SAME); + failureScenario.mockRetryPolicyVerdict( + harness.getContext().getRetryPolicy(anyString()), RetryVerdict.RETRY_SAME); CompletionStage resultSetFuture = new CqlRequestHandler(statement, harness.getSession(), harness.getContext(), "test") @@ -253,8 +261,8 @@ public void should_ignore_error_if_idempotent_and_retry_policy_decides_so( failureScenario.mockRequestError(harnessBuilder, node1); try (RequestHandlerTestHarness harness = harnessBuilder.build()) { - failureScenario.mockRetryPolicyDecision( - harness.getContext().getRetryPolicy(anyString()), RetryDecision.IGNORE); + failureScenario.mockRetryPolicyVerdict( + harness.getContext().getRetryPolicy(anyString()), RetryVerdict.IGNORE); CompletionStage resultSetFuture = new CqlRequestHandler(statement, harness.getSession(), harness.getContext(), "test") @@ -302,8 +310,8 @@ public void should_rethrow_error_if_idempotent_and_retry_policy_decides_so( try (RequestHandlerTestHarness harness = harnessBuilder.build()) { - failureScenario.mockRetryPolicyDecision( - harness.getContext().getRetryPolicy(anyString()), RetryDecision.RETHROW); + failureScenario.mockRetryPolicyVerdict( + harness.getContext().getRetryPolicy(anyString()), RetryVerdict.RETHROW); CompletionStage resultSetFuture = new CqlRequestHandler(statement, harness.getSession(), harness.getContext(), "test") @@ -349,8 +357,8 @@ public void should_rethrow_error_if_not_idempotent_and_error_unsafe_or_policy_re try (RequestHandlerTestHarness harness = harnessBuilder.build()) { if (shouldCallRetryPolicy) { - failureScenario.mockRetryPolicyDecision( - harness.getContext().getRetryPolicy(anyString()), RetryDecision.RETHROW); + failureScenario.mockRetryPolicyVerdict( + harness.getContext().getRetryPolicy(anyString()), RetryVerdict.RETHROW); } CompletionStage resultSetFuture = @@ -382,6 +390,63 @@ public void should_rethrow_error_if_not_idempotent_and_error_unsafe_or_policy_re } } + @Test + @UseDataProvider("failureAndIdempotent") + public void should_not_fail_with_duplicate_key_when_retrying_with_request_id_generator( + FailureScenario failureScenario, boolean defaultIdempotence, Statement statement) { + + // Create a RequestIdGenerator that uses the same key as the statement's custom payload + RequestIdGenerator requestIdGenerator = + new RequestIdGenerator() { + private AtomicInteger counter = new AtomicInteger(0); + + @Override + public String getSessionRequestId() { + return "session-123"; + } + + @Override + public String getNodeRequestId(@NonNull Request request, @NonNull String parentId) { + return parentId + "-" + counter.getAndIncrement(); + } + }; + + RequestHandlerTestHarness.Builder harnessBuilder = + RequestHandlerTestHarness.builder() + .withDefaultIdempotence(defaultIdempotence) + .withRequestIdGenerator(requestIdGenerator); + failureScenario.mockRequestError(harnessBuilder, node1); + harnessBuilder.withResponse(node2, defaultFrameOf(singleRow())); + + try (RequestHandlerTestHarness harness = harnessBuilder.build()) { + failureScenario.mockRetryPolicyVerdict( + harness.getContext().getRetryPolicy(anyString()), RetryVerdict.RETRY_NEXT); + + CompletionStage resultSetFuture = + new CqlRequestHandler(statement, harness.getSession(), harness.getContext(), "test") + .handle(); + + // The test should succeed without throwing a duplicate key exception + assertThatStage(resultSetFuture) + .isSuccess( + resultSet -> { + Iterator rows = resultSet.currentPage().iterator(); + assertThat(rows.hasNext()).isTrue(); + assertThat(rows.next().getString("message")).isEqualTo("hello, world"); + + ExecutionInfo executionInfo = resultSet.getExecutionInfo(); + assertThat(executionInfo.getCoordinator()).isEqualTo(node2); + assertThat(executionInfo.getErrors()).hasSize(1); + assertThat(executionInfo.getErrors().get(0).getKey()).isEqualTo(node1); + + // Verify that the custom payload still contains the request ID key + // (either the original value or the generated one, depending on implementation) + assertThat(executionInfo.getRequest().getCustomPayload().get("request-id")) + .isEqualTo(ByteBuffer.wrap("session-123-1".getBytes(StandardCharsets.UTF_8))); + }); + } + } + /** * Sets up the mocks to simulate an error from a node, and make the retry policy return a given * decision for that error. @@ -405,7 +470,7 @@ protected FailureScenario( abstract void mockRequestError(RequestHandlerTestHarness.Builder builder, Node node); - abstract void mockRetryPolicyDecision(RetryPolicy policy, RetryDecision decision); + abstract void mockRetryPolicyVerdict(RetryPolicy policy, RetryVerdict verdict); } @DataProvider @@ -426,15 +491,15 @@ public void mockRequestError(RequestHandlerTestHarness.Builder builder, Node nod } @Override - public void mockRetryPolicyDecision(RetryPolicy policy, RetryDecision decision) { - when(policy.onReadTimeout( + public void mockRetryPolicyVerdict(RetryPolicy policy, RetryVerdict verdict) { + when(policy.onReadTimeoutVerdict( any(Statement.class), eq(DefaultConsistencyLevel.LOCAL_ONE), eq(2), eq(1), eq(true), eq(0))) - .thenReturn(decision); + .thenReturn(verdict); } }, new FailureScenario( @@ -456,15 +521,15 @@ public void mockRequestError(RequestHandlerTestHarness.Builder builder, Node nod } @Override - public void mockRetryPolicyDecision(RetryPolicy policy, RetryDecision decision) { - when(policy.onWriteTimeout( + public void mockRetryPolicyVerdict(RetryPolicy policy, RetryVerdict verdict) { + when(policy.onWriteTimeoutVerdict( any(Statement.class), eq(DefaultConsistencyLevel.LOCAL_ONE), eq(DefaultWriteType.SIMPLE), eq(2), eq(1), eq(0))) - .thenReturn(decision); + .thenReturn(verdict); } }, new FailureScenario( @@ -482,14 +547,14 @@ public void mockRequestError(RequestHandlerTestHarness.Builder builder, Node nod } @Override - public void mockRetryPolicyDecision(RetryPolicy policy, RetryDecision decision) { - when(policy.onUnavailable( + public void mockRetryPolicyVerdict(RetryPolicy policy, RetryVerdict verdict) { + when(policy.onUnavailableVerdict( any(Statement.class), eq(DefaultConsistencyLevel.LOCAL_ONE), eq(2), eq(1), eq(0))) - .thenReturn(decision); + .thenReturn(verdict); } }, new FailureScenario( @@ -506,9 +571,9 @@ public void mockRequestError(RequestHandlerTestHarness.Builder builder, Node nod } @Override - public void mockRetryPolicyDecision(RetryPolicy policy, RetryDecision decision) { - when(policy.onErrorResponse(any(Statement.class), any(ServerError.class), eq(0))) - .thenReturn(decision); + public void mockRetryPolicyVerdict(RetryPolicy policy, RetryVerdict verdict) { + when(policy.onErrorResponseVerdict(any(Statement.class), any(ServerError.class), eq(0))) + .thenReturn(verdict); } }, new FailureScenario( @@ -522,10 +587,10 @@ public void mockRequestError(RequestHandlerTestHarness.Builder builder, Node nod } @Override - public void mockRetryPolicyDecision(RetryPolicy policy, RetryDecision decision) { - when(policy.onRequestAborted( + public void mockRetryPolicyVerdict(RetryPolicy policy, RetryVerdict verdict) { + when(policy.onRequestAbortedVerdict( any(Statement.class), any(HeartbeatException.class), eq(0))) - .thenReturn(decision); + .thenReturn(verdict); } }); } diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/cql/CqlRequestHandlerSpeculativeExecutionTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/cql/CqlRequestHandlerSpeculativeExecutionTest.java index eb70e79b0d5..a09a9eb3d5a 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/cql/CqlRequestHandlerSpeculativeExecutionTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/cql/CqlRequestHandlerSpeculativeExecutionTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/cql/CqlRequestHandlerTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/cql/CqlRequestHandlerTest.java index 5f41fc42f62..c1a2765eef0 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/cql/CqlRequestHandlerTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/cql/CqlRequestHandlerTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -21,9 +23,11 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import com.datastax.oss.driver.api.core.AllNodesFailedException; import com.datastax.oss.driver.api.core.CqlIdentifier; import com.datastax.oss.driver.api.core.DriverTimeoutException; import com.datastax.oss.driver.api.core.NoNodeAvailableException; +import com.datastax.oss.driver.api.core.NodeUnavailableException; import com.datastax.oss.driver.api.core.config.DefaultDriverOption; import com.datastax.oss.driver.api.core.cql.AsyncResultSet; import com.datastax.oss.driver.api.core.cql.BoundStatement; @@ -32,6 +36,7 @@ import com.datastax.oss.driver.api.core.cql.PreparedStatement; import com.datastax.oss.driver.api.core.cql.Row; import com.datastax.oss.driver.api.core.cql.Statement; +import com.datastax.oss.driver.api.core.metadata.Node; import com.datastax.oss.driver.internal.core.session.RepreparePayload; import com.datastax.oss.driver.internal.core.util.concurrent.CapturingTimer.CapturedTimeout; import com.datastax.oss.protocol.internal.request.Prepare; @@ -43,6 +48,8 @@ import java.time.Duration; import java.util.Collections; import java.util.Iterator; +import java.util.List; +import java.util.Map; import java.util.concurrent.CompletionStage; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; @@ -105,6 +112,43 @@ public void should_fail_if_no_node_available() { } } + @Test + public void should_fail_if_nodes_unavailable() { + RequestHandlerTestHarness.Builder harnessBuilder = RequestHandlerTestHarness.builder(); + try (RequestHandlerTestHarness harness = + harnessBuilder.withEmptyPool(node1).withEmptyPool(node2).build()) { + CompletionStage resultSetFuture = + new CqlRequestHandler( + UNDEFINED_IDEMPOTENCE_STATEMENT, + harness.getSession(), + harness.getContext(), + "test") + .handle(); + assertThatStage(resultSetFuture) + .isFailed( + error -> { + assertThat(error).isInstanceOf(AllNodesFailedException.class); + Map> allErrors = + ((AllNodesFailedException) error).getAllErrors(); + assertThat(allErrors).hasSize(2); + assertThat(allErrors) + .hasEntrySatisfying( + node1, + nodeErrors -> + assertThat(nodeErrors) + .singleElement() + .isInstanceOf(NodeUnavailableException.class)); + assertThat(allErrors) + .hasEntrySatisfying( + node2, + nodeErrors -> + assertThat(nodeErrors) + .singleElement() + .isInstanceOf(NodeUnavailableException.class)); + }); + } + } + @Test public void should_time_out_if_first_node_takes_too_long_to_respond() throws Exception { RequestHandlerTestHarness.Builder harnessBuilder = RequestHandlerTestHarness.builder(); diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/cql/CqlRequestHandlerTestBase.java b/core/src/test/java/com/datastax/oss/driver/internal/core/cql/CqlRequestHandlerTestBase.java index 3f81d458d8e..9bd3b6fa28c 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/cql/CqlRequestHandlerTestBase.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/cql/CqlRequestHandlerTestBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/cql/CqlRequestHandlerTrackerTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/cql/CqlRequestHandlerTrackerTest.java index a6b4ebca2a2..ecc087fb8ac 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/cql/CqlRequestHandlerTrackerTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/cql/CqlRequestHandlerTrackerTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/cql/DefaultAsyncResultSetTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/cql/DefaultAsyncResultSetTest.java index 31a13eeb3d8..8ed509caeb7 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/cql/DefaultAsyncResultSetTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/cql/DefaultAsyncResultSetTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/cql/PagingIterableSpliteratorTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/cql/PagingIterableSpliteratorTest.java index 8cce0492571..d6787cc018e 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/cql/PagingIterableSpliteratorTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/cql/PagingIterableSpliteratorTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/cql/PoolBehavior.java b/core/src/test/java/com/datastax/oss/driver/internal/core/cql/PoolBehavior.java index 50694b50b72..9b018f17531 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/cql/PoolBehavior.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/cql/PoolBehavior.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/cql/QueryTraceFetcherTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/cql/QueryTraceFetcherTest.java index 3030d41f008..dc238775bc1 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/cql/QueryTraceFetcherTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/cql/QueryTraceFetcherTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -77,7 +79,7 @@ public class QueryTraceFetcherTest { @Mock private NettyOptions nettyOptions; @Mock private EventExecutorGroup adminEventExecutorGroup; @Mock private EventExecutor eventExecutor; - @Mock private InetAddress address; + private InetAddress address = InetAddress.getLoopbackAddress(); @Captor private ArgumentCaptor statementCaptor; diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/cql/RequestHandlerTestHarness.java b/core/src/test/java/com/datastax/oss/driver/internal/core/cql/RequestHandlerTestHarness.java index 53d8623de8f..6a7657d5809 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/cql/RequestHandlerTestHarness.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/cql/RequestHandlerTestHarness.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -35,6 +37,7 @@ import com.datastax.oss.driver.api.core.session.Session; import com.datastax.oss.driver.api.core.specex.SpeculativeExecutionPolicy; import com.datastax.oss.driver.api.core.time.TimestampGenerator; +import com.datastax.oss.driver.api.core.tracker.RequestIdGenerator; import com.datastax.oss.driver.api.core.type.codec.registry.CodecRegistry; import com.datastax.oss.driver.internal.core.DefaultConsistencyLevelRegistry; import com.datastax.oss.driver.internal.core.ProtocolFeature; @@ -59,6 +62,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Queue; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; @@ -166,6 +170,9 @@ protected RequestHandlerTestHarness(Builder builder) { when(context.getRequestThrottler()).thenReturn(new PassThroughRequestThrottler(context)); when(context.getRequestTracker()).thenReturn(new NoopRequestTracker(context)); + + when(context.getRequestIdGenerator()) + .thenReturn(Optional.ofNullable(builder.requestIdGenerator)); } public DefaultSession getSession() { @@ -198,6 +205,7 @@ public static class Builder { private final List poolBehaviors = new ArrayList<>(); private boolean defaultIdempotence; private ProtocolVersion protocolVersion; + private RequestIdGenerator requestIdGenerator; /** * Sets the given node as the next one in the query plan; an empty pool will be simulated when @@ -253,6 +261,11 @@ public Builder withProtocolVersion(ProtocolVersion protocolVersion) { return this; } + public Builder withRequestIdGenerator(RequestIdGenerator requestIdGenerator) { + this.requestIdGenerator = requestIdGenerator; + return this; + } + /** * Sets the given node as the next one in the query plan; the test code is responsible of * calling the methods on the returned object to complete the write and the query. diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/cql/ResultSetTestBase.java b/core/src/test/java/com/datastax/oss/driver/internal/core/cql/ResultSetTestBase.java index 5ac3c8531d5..54b215458fe 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/cql/ResultSetTestBase.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/cql/ResultSetTestBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/cql/ResultSetsTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/cql/ResultSetsTest.java index 3d52fc3d22e..0b5860f7e95 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/cql/ResultSetsTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/cql/ResultSetsTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/cql/StatementSizeTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/cql/StatementSizeTest.java index 64cc76b0e79..dc3ab0702f7 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/cql/StatementSizeTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/cql/StatementSizeTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/data/AccessibleByIdTestBase.java b/core/src/test/java/com/datastax/oss/driver/internal/core/data/AccessibleByIdTestBase.java index 9a480a5e21f..c27b55e3f25 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/data/AccessibleByIdTestBase.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/data/AccessibleByIdTestBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/data/AccessibleByIndexTestBase.java b/core/src/test/java/com/datastax/oss/driver/internal/core/data/AccessibleByIndexTestBase.java index 3239a655ece..94da926f2bc 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/data/AccessibleByIndexTestBase.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/data/AccessibleByIndexTestBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/data/DefaultTupleValueTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/data/DefaultTupleValueTest.java index 07c1dc42a89..aed357cb1cd 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/data/DefaultTupleValueTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/data/DefaultTupleValueTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/data/DefaultUdtValueTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/data/DefaultUdtValueTest.java index 0bec3c152b3..6a9f2886783 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/data/DefaultUdtValueTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/data/DefaultUdtValueTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/data/IdentifierIndexTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/data/IdentifierIndexTest.java index 183e4c17fab..697a32fb029 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/data/IdentifierIndexTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/data/IdentifierIndexTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -17,10 +19,16 @@ import static org.assertj.core.api.Assertions.assertThat; +import com.datastax.oss.driver.TestDataProviders; import com.datastax.oss.driver.api.core.CqlIdentifier; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableList; +import com.tngtech.java.junit.dataprovider.DataProviderRunner; +import com.tngtech.java.junit.dataprovider.UseDataProvider; +import java.util.Locale; import org.junit.Test; +import org.junit.runner.RunWith; +@RunWith(DataProviderRunner.class) public class IdentifierIndexTest { private static final CqlIdentifier Foo = CqlIdentifier.fromInternal("Foo"); private static final CqlIdentifier foo = CqlIdentifier.fromInternal("foo"); @@ -41,13 +49,31 @@ public void should_not_find_index_of_nonexistent_identifier() { } @Test - public void should_find_first_index_of_case_insensitive_name() { - assertThat(index.firstIndexOf("foo")).isEqualTo(0); + @UseDataProvider(location = TestDataProviders.class, value = "locales") + public void should_find_first_index_of_case_insensitive_name(Locale locale) { + Locale def = Locale.getDefault(); + try { + Locale.setDefault(locale); + assertThat(index.firstIndexOf("foo")).isEqualTo(0); + assertThat(index.firstIndexOf("FOO")).isEqualTo(0); + assertThat(index.firstIndexOf("fOO")).isEqualTo(0); + } finally { + Locale.setDefault(def); + } } @Test - public void should_not_find_first_index_of_nonexistent_case_insensitive_name() { - assertThat(index.firstIndexOf("bar")).isEqualTo(-1); + @UseDataProvider(location = TestDataProviders.class, value = "locales") + public void should_not_find_first_index_of_nonexistent_case_insensitive_name(Locale locale) { + Locale def = Locale.getDefault(); + try { + Locale.setDefault(locale); + assertThat(index.firstIndexOf("bar")).isEqualTo(-1); + assertThat(index.firstIndexOf("BAR")).isEqualTo(-1); + assertThat(index.firstIndexOf("bAR")).isEqualTo(-1); + } finally { + Locale.setDefault(def); + } } @Test @@ -75,13 +101,31 @@ public void should_not_find_indices_of_nonexistent_identifier() { } @Test - public void should_all_indices_of_case_insensitive_name() { - assertThat(index.allIndicesOf("foo")).containsExactly(0, 1, 2, 3, 4, 5); + @UseDataProvider(location = TestDataProviders.class, value = "locales") + public void should_find_all_indices_of_case_insensitive_name(Locale locale) { + Locale def = Locale.getDefault(); + try { + Locale.setDefault(locale); + assertThat(index.allIndicesOf("foo")).containsExactly(0, 1, 2, 3, 4, 5); + assertThat(index.allIndicesOf("FOO")).containsExactly(0, 1, 2, 3, 4, 5); + assertThat(index.allIndicesOf("fOO")).containsExactly(0, 1, 2, 3, 4, 5); + } finally { + Locale.setDefault(def); + } } @Test - public void should_not_find_indices_of_nonexistent_case_insensitive_name() { - assertThat(index.allIndicesOf("bar")).isEmpty(); + @UseDataProvider(location = TestDataProviders.class, value = "locales") + public void should_not_find_indices_of_nonexistent_case_insensitive_name(Locale locale) { + Locale def = Locale.getDefault(); + try { + Locale.setDefault(locale); + assertThat(index.allIndicesOf("bar")).isEmpty(); + assertThat(index.allIndicesOf("BAR")).isEmpty(); + assertThat(index.allIndicesOf("bAR")).isEmpty(); + } finally { + Locale.setDefault(def); + } } @Test diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/BasicLoadBalancingPolicyDcAgnosticTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/BasicLoadBalancingPolicyDcAgnosticTest.java new file mode 100644 index 00000000000..3c832812662 --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/BasicLoadBalancingPolicyDcAgnosticTest.java @@ -0,0 +1,58 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.loadbalancing; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +import com.datastax.oss.driver.api.core.config.DefaultDriverOption; +import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableSet; +import java.util.Optional; +import org.junit.Before; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; + +// TODO fix unnecessary stubbing of config option in parent class (and stop using "silent" runner) +@RunWith(MockitoJUnitRunner.Silent.class) +public class BasicLoadBalancingPolicyDcAgnosticTest extends BasicLoadBalancingPolicyQueryPlanTest { + + @Before + @Override + public void setup() { + super.setup(); + when(defaultProfile.isDefined(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER)) + .thenReturn(false); + when(metadataManager.getContactPoints()).thenReturn(ImmutableSet.of(node1)); + when(metadataManager.getMetadata()).thenReturn(metadata); + when(metadata.getTokenMap()).thenAnswer(invocation -> Optional.of(this.tokenMap)); + + // since there is no local datacenter defined, the policy should behave with DC awareness + // disabled and pick nodes regardless of their datacenters; we therefore expect all tests of + // BasicLoadBalancingPolicyQueryPlanTest to pass even with the below DC distribution. + when(node1.getDatacenter()).thenReturn("dc1"); + when(node2.getDatacenter()).thenReturn("dc2"); + when(node3.getDatacenter()).thenReturn("dc3"); + when(node4.getDatacenter()).thenReturn("dc4"); + when(node5.getDatacenter()).thenReturn(null); + + policy = createAndInitPolicy(); + + assertThat(policy.getLiveNodes().dc(null)).containsExactly(node1, node2, node3, node4, node5); + assertThat(policy.getLiveNodes().dcs()).isEmpty(); + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/BasicLoadBalancingPolicyDcFailoverTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/BasicLoadBalancingPolicyDcFailoverTest.java new file mode 100644 index 00000000000..dc955c6e5de --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/BasicLoadBalancingPolicyDcFailoverTest.java @@ -0,0 +1,155 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.loadbalancing; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.datastax.oss.driver.api.core.config.DefaultDriverOption; +import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; +import com.datastax.oss.driver.api.core.metadata.Node; +import com.datastax.oss.driver.internal.core.metadata.DefaultNode; +import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap; +import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableSet; +import java.util.Map; +import java.util.UUID; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +// TODO fix unnecessary stubbing of config option in parent class (and stop using "silent" runner) +@RunWith(MockitoJUnitRunner.Silent.class) +public class BasicLoadBalancingPolicyDcFailoverTest extends BasicLoadBalancingPolicyQueryPlanTest { + + @Mock protected DefaultNode node6; + @Mock protected DefaultNode node7; + @Mock protected DefaultNode node8; + @Mock protected DefaultNode node9; + + @Test + @Override + public void should_prioritize_single_replica() { + when(request.getRoutingKeyspace()).thenReturn(KEYSPACE); + when(request.getRoutingKey()).thenReturn(ROUTING_KEY); + when(tokenMap.getReplicas(KEYSPACE, ROUTING_KEY)).thenReturn(ImmutableSet.of(node3)); + + // node3 always first, round-robin on the rest, then remote nodes + assertThat(policy.newQueryPlan(request, session)) + .containsExactly(node3, node1, node2, node4, node5, node7, node8); + assertThat(policy.newQueryPlan(request, session)) + .containsExactly(node3, node2, node1, node4, node5, node7, node8); + assertThat(policy.newQueryPlan(request, session)) + .containsExactly(node3, node1, node2, node4, node5, node7, node8); + + // Should not shuffle replicas since there is only one + verify(policy, never()).shuffleHead(any(), eq(1)); + // But should shuffle remote nodes + verify(policy, times(3)).shuffleHead(any(), eq(4)); + } + + @Test + @Override + public void should_prioritize_and_shuffle_replicas() { + when(request.getRoutingKeyspace()).thenReturn(KEYSPACE); + when(request.getRoutingKey()).thenReturn(ROUTING_KEY); + when(tokenMap.getReplicas(KEYSPACE, ROUTING_KEY)) + .thenReturn(ImmutableSet.of(node2, node3, node5, node8)); + + // node 5 and 8 being in a remote DC, they don't get a boost for being a replica + assertThat(policy.newQueryPlan(request, session)) + .containsExactly(node2, node3, node1, node4, node5, node7, node8); + assertThat(policy.newQueryPlan(request, session)) + .containsExactly(node2, node3, node1, node4, node5, node7, node8); + assertThat(policy.newQueryPlan(request, session)) + .containsExactly(node2, node3, node1, node4, node5, node7, node8); + + // should shuffle replicas + verify(policy, times(3)).shuffleHead(any(), eq(2)); + // should shuffle remote nodes + verify(policy, times(3)).shuffleHead(any(), eq(4)); + // No power of two choices with only two replicas + verify(session, never()).getPools(); + } + + @Override + protected void assertRoundRobinQueryPlans() { + // nodes 4 to 9 being in a remote DC, they always appear after nodes 1, 2, 3 + for (int i = 0; i < 3; i++) { + assertThat(policy.newQueryPlan(request, session)) + .containsExactly(node1, node2, node3, node4, node5, node7, node8); + assertThat(policy.newQueryPlan(request, session)) + .containsExactly(node2, node3, node1, node4, node5, node7, node8); + assertThat(policy.newQueryPlan(request, session)) + .containsExactly(node3, node1, node2, node4, node5, node7, node8); + } + // should shuffle remote nodes + verify(policy, atLeast(1)).shuffleHead(any(), eq(4)); + } + + @Override + protected BasicLoadBalancingPolicy createAndInitPolicy() { + when(node4.getDatacenter()).thenReturn("dc2"); + when(node5.getDatacenter()).thenReturn("dc2"); + when(node6.getDatacenter()).thenReturn("dc2"); + when(node7.getDatacenter()).thenReturn("dc3"); + when(node8.getDatacenter()).thenReturn("dc3"); + when(node9.getDatacenter()).thenReturn("dc3"); + // Accept 2 nodes per remote DC + when(defaultProfile.getInt( + DefaultDriverOption.LOAD_BALANCING_DC_FAILOVER_MAX_NODES_PER_REMOTE_DC)) + .thenReturn(2); + when(defaultProfile.getBoolean( + DefaultDriverOption.LOAD_BALANCING_DC_FAILOVER_ALLOW_FOR_LOCAL_CONSISTENCY_LEVELS)) + .thenReturn(false); + // Use a subclass to disable shuffling, we just spy to make sure that the shuffling method was + // called (makes tests easier) + BasicLoadBalancingPolicy policy = + spy( + new BasicLoadBalancingPolicy(context, DriverExecutionProfile.DEFAULT_NAME) { + @Override + protected void shuffleHead(Object[] currentNodes, int headLength) { + // nothing (keep in same order) + } + }); + Map nodes = + ImmutableMap.builder() + .put(UUID.randomUUID(), node1) + .put(UUID.randomUUID(), node2) + .put(UUID.randomUUID(), node3) + .put(UUID.randomUUID(), node4) + .put(UUID.randomUUID(), node5) + .put(UUID.randomUUID(), node6) + .put(UUID.randomUUID(), node7) + .put(UUID.randomUUID(), node8) + .put(UUID.randomUUID(), node9) + .build(); + policy.init(nodes, distanceReporter); + assertThat(policy.getLiveNodes().dc("dc1")).containsExactly(node1, node2, node3); + assertThat(policy.getLiveNodes().dc("dc2")).containsExactly(node4, node5); // only 2 allowed + assertThat(policy.getLiveNodes().dc("dc3")).containsExactly(node7, node8); // only 2 allowed + return policy; + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/BasicLoadBalancingPolicyDistanceTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/BasicLoadBalancingPolicyDistanceTest.java new file mode 100644 index 00000000000..5b2b6bf864d --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/BasicLoadBalancingPolicyDistanceTest.java @@ -0,0 +1,224 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.loadbalancing; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.datastax.oss.driver.api.core.config.DefaultDriverOption; +import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; +import com.datastax.oss.driver.api.core.loadbalancing.NodeDistance; +import com.datastax.oss.driver.api.core.loadbalancing.NodeDistanceEvaluator; +import com.datastax.oss.driver.api.core.metadata.Node; +import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap; +import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableSet; +import edu.umd.cs.findbugs.annotations.NonNull; +import java.util.UUID; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +// TODO fix unnecessary stubbing of config option in parent class (and stop using "silent" runner) +@RunWith(MockitoJUnitRunner.Silent.class) +public class BasicLoadBalancingPolicyDistanceTest extends LoadBalancingPolicyTestBase { + + @Mock private NodeDistanceEvaluator nodeDistanceEvaluator; + + private ImmutableMap nodes; + + @Before + @Override + public void setup() { + super.setup(); + when(context.getNodeDistanceEvaluator(DriverExecutionProfile.DEFAULT_NAME)) + .thenReturn(nodeDistanceEvaluator); + when(metadataManager.getContactPoints()).thenReturn(ImmutableSet.of(node1, node2, node3)); + nodes = + ImmutableMap.of( + UUID.randomUUID(), node1, UUID.randomUUID(), node2, UUID.randomUUID(), node3); + } + + @Test + public void should_report_distance_reported_by_user_distance_reporter() { + // Given + given(node2.getDatacenter()).willReturn("dc2"); + given(nodeDistanceEvaluator.evaluateDistance(node1, "dc1")).willReturn(NodeDistance.LOCAL); + given(nodeDistanceEvaluator.evaluateDistance(node2, "dc1")).willReturn(NodeDistance.REMOTE); + given(nodeDistanceEvaluator.evaluateDistance(node3, "dc1")).willReturn(NodeDistance.IGNORED); + BasicLoadBalancingPolicy policy = createPolicy(); + // When + policy.init(nodes, distanceReporter); + // Then + verify(distanceReporter).setDistance(node1, NodeDistance.LOCAL); + verify(distanceReporter).setDistance(node2, NodeDistance.REMOTE); + verify(distanceReporter).setDistance(node3, NodeDistance.IGNORED); + assertThat(policy.getLiveNodes().dc("dc1")).containsExactly(node1); + } + + @Test + public void should_report_LOCAL_when_dc_agnostic() { + // Given + given(defaultProfile.isDefined(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER)) + .willReturn(false); + given(node1.getDatacenter()).willReturn(null); + given(node2.getDatacenter()).willReturn("dc1"); + given(node3.getDatacenter()).willReturn("dc2"); + BasicLoadBalancingPolicy policy = createPolicy(); + // When + policy.init(nodes, distanceReporter); + // Then + verify(distanceReporter).setDistance(node1, NodeDistance.LOCAL); + verify(distanceReporter).setDistance(node2, NodeDistance.LOCAL); + verify(distanceReporter).setDistance(node3, NodeDistance.LOCAL); + assertThat(policy.getLiveNodes().dc(null)).containsExactly(node1, node2, node3); + } + + @Test + public void should_report_LOCAL_when_node_in_local_dc() { + // Given + BasicLoadBalancingPolicy policy = createPolicy(); + // When + policy.init(nodes, distanceReporter); + // Then + verify(distanceReporter).setDistance(node1, NodeDistance.LOCAL); + verify(distanceReporter).setDistance(node2, NodeDistance.LOCAL); + verify(distanceReporter).setDistance(node3, NodeDistance.LOCAL); + assertThat(policy.getLiveNodes().dc("dc1")).containsExactly(node1, node2, node3); + } + + @Test + public void should_report_IGNORED_when_node_not_in_local_dc() { + // Given + given(node1.getDatacenter()).willReturn(null); + given(node2.getDatacenter()).willReturn("dc2"); + given(node3.getDatacenter()).willReturn("dc3"); + BasicLoadBalancingPolicy policy = createPolicy(); + // When + policy.init(nodes, distanceReporter); + // Then + // Note: driver 3 would have reported LOCAL for node1 since its datacenter is null + verify(distanceReporter).setDistance(node1, NodeDistance.IGNORED); + verify(distanceReporter).setDistance(node2, NodeDistance.IGNORED); + verify(distanceReporter).setDistance(node3, NodeDistance.IGNORED); + assertThat(policy.getLiveNodes().dc(null)).isEmpty(); + assertThat(policy.getLiveNodes().dc("dc1")).isEmpty(); + assertThat(policy.getLiveNodes().dc("dc2")).isEmpty(); + assertThat(policy.getLiveNodes().dc("dc3")).isEmpty(); + } + + @Test + public void should_report_REMOTE_when_node_not_in_local_dc_and_dc_failover_enabled() { + // Given + given(node1.getDatacenter()).willReturn("dc2"); + given(node2.getDatacenter()).willReturn("dc3"); + given(node3.getDatacenter()).willReturn("dc4"); + given( + defaultProfile.getInt( + DefaultDriverOption.LOAD_BALANCING_DC_FAILOVER_MAX_NODES_PER_REMOTE_DC)) + .willReturn(1); + BasicLoadBalancingPolicy policy = createPolicy(); + // When + policy.init(nodes, distanceReporter); + // Then + verify(distanceReporter).setDistance(node1, NodeDistance.REMOTE); + verify(distanceReporter).setDistance(node2, NodeDistance.REMOTE); + verify(distanceReporter).setDistance(node3, NodeDistance.REMOTE); + assertThat(policy.getLiveNodes().dc("dc1")).isEmpty(); + assertThat(policy.getLiveNodes().dc("dc2")).containsExactly(node1); + assertThat(policy.getLiveNodes().dc("dc3")).containsExactly(node2); + assertThat(policy.getLiveNodes().dc("dc4")).containsExactly(node3); + } + + @Test + public void should_report_IGNORED_when_node_not_in_local_dc_and_too_many_nodes_for_dc_failover() { + // Given + given(node1.getDatacenter()).willReturn("dc2"); + given(node2.getDatacenter()).willReturn("dc2"); + given(node3.getDatacenter()).willReturn("dc2"); + given( + defaultProfile.getInt( + DefaultDriverOption.LOAD_BALANCING_DC_FAILOVER_MAX_NODES_PER_REMOTE_DC)) + .willReturn(2); + BasicLoadBalancingPolicy policy = createPolicy(); + // When + policy.init(nodes, distanceReporter); + // Then + verify(distanceReporter).setDistance(node1, NodeDistance.REMOTE); + verify(distanceReporter).setDistance(node2, NodeDistance.REMOTE); + verify(distanceReporter).setDistance(node3, NodeDistance.IGNORED); + assertThat(policy.getLiveNodes().dc("dc1")).isEmpty(); + assertThat(policy.getLiveNodes().dc("dc2")).containsExactly(node1, node2); + } + + @Test + public void should_report_REMOTE_when_remote_node_up_and_dc_failover() { + // Given + given(node1.getDatacenter()).willReturn("dc2"); + given(node2.getDatacenter()).willReturn("dc2"); + given(node3.getDatacenter()).willReturn("dc2"); + given(node4.getDatacenter()).willReturn("dc2"); + given( + defaultProfile.getInt( + DefaultDriverOption.LOAD_BALANCING_DC_FAILOVER_MAX_NODES_PER_REMOTE_DC)) + .willReturn(4); + BasicLoadBalancingPolicy policy = createPolicy(); + // When + policy.init(nodes, distanceReporter); + policy.onUp(node4); + // Then + verify(distanceReporter).setDistance(node1, NodeDistance.REMOTE); + verify(distanceReporter).setDistance(node2, NodeDistance.REMOTE); + verify(distanceReporter).setDistance(node3, NodeDistance.REMOTE); + verify(distanceReporter).setDistance(node4, NodeDistance.REMOTE); + assertThat(policy.getLiveNodes().dc("dc1")).isEmpty(); + assertThat(policy.getLiveNodes().dc("dc2")).containsExactly(node1, node2, node3, node4); + } + + @Test + public void should_report_IGNORED_when_remote_node_up_and_too_many_nodes_for_dc_failover() { + // Given + given(node1.getDatacenter()).willReturn("dc2"); + given(node2.getDatacenter()).willReturn("dc2"); + given(node3.getDatacenter()).willReturn("dc2"); + given(node4.getDatacenter()).willReturn("dc2"); + given( + defaultProfile.getInt( + DefaultDriverOption.LOAD_BALANCING_DC_FAILOVER_MAX_NODES_PER_REMOTE_DC)) + .willReturn(3); + BasicLoadBalancingPolicy policy = createPolicy(); + // When + policy.init(nodes, distanceReporter); + policy.onUp(node4); + // Then + verify(distanceReporter).setDistance(node1, NodeDistance.REMOTE); + verify(distanceReporter).setDistance(node2, NodeDistance.REMOTE); + verify(distanceReporter).setDistance(node3, NodeDistance.REMOTE); + verify(distanceReporter).setDistance(node4, NodeDistance.IGNORED); + assertThat(policy.getLiveNodes().dc("dc1")).isEmpty(); + assertThat(policy.getLiveNodes().dc("dc2")).containsExactly(node1, node2, node3); + } + + @NonNull + protected BasicLoadBalancingPolicy createPolicy() { + return new BasicLoadBalancingPolicy(context, DriverExecutionProfile.DEFAULT_NAME); + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/BasicLoadBalancingPolicyEventsTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/BasicLoadBalancingPolicyEventsTest.java index f8dee137d64..9959ddbd1bc 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/BasicLoadBalancingPolicyEventsTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/BasicLoadBalancingPolicyEventsTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -25,12 +27,11 @@ import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; import com.datastax.oss.driver.api.core.loadbalancing.NodeDistance; -import com.datastax.oss.driver.api.core.metadata.Node; +import com.datastax.oss.driver.api.core.loadbalancing.NodeDistanceEvaluator; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableSet; import edu.umd.cs.findbugs.annotations.NonNull; import java.util.UUID; -import java.util.function.Predicate; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -39,9 +40,9 @@ // TODO fix unnecessary stubbing of config option in parent class (and stop using "silent" runner) @RunWith(MockitoJUnitRunner.Silent.class) -public class BasicLoadBalancingPolicyEventsTest extends DefaultLoadBalancingPolicyTestBase { +public class BasicLoadBalancingPolicyEventsTest extends LoadBalancingPolicyTestBase { - @Mock private Predicate filter; + @Mock private NodeDistanceEvaluator nodeDistanceEvaluator; private BasicLoadBalancingPolicy policy; @@ -49,8 +50,8 @@ public class BasicLoadBalancingPolicyEventsTest extends DefaultLoadBalancingPoli @Override public void setup() { super.setup(); - when(filter.test(any(Node.class))).thenReturn(true); - when(context.getNodeFilter(DriverExecutionProfile.DEFAULT_NAME)).thenReturn(filter); + when(context.getNodeDistanceEvaluator(DriverExecutionProfile.DEFAULT_NAME)) + .thenReturn(nodeDistanceEvaluator); when(metadataManager.getContactPoints()).thenReturn(ImmutableSet.of(node1)); policy = createAndInitPolicy(); reset(distanceReporter); @@ -62,10 +63,10 @@ public void should_remove_down_node_from_live_set() { policy.onDown(node2); // Then - assertThat(policy.getLiveNodes()).containsExactlyInAnyOrder(node1); + assertThat(policy.getLiveNodes().dc("dc1")).containsExactly(node1); verify(distanceReporter, never()).setDistance(eq(node2), any(NodeDistance.class)); // should have been called only once, during initialization, but not during onDown - verify(filter).test(node2); + verify(nodeDistanceEvaluator).evaluateDistance(node2, "dc1"); } @Test @@ -74,10 +75,10 @@ public void should_remove_removed_node_from_live_set() { policy.onRemove(node2); // Then - assertThat(policy.getLiveNodes()).containsExactlyInAnyOrder(node1); + assertThat(policy.getLiveNodes().dc("dc1")).containsExactly(node1); verify(distanceReporter, never()).setDistance(eq(node2), any(NodeDistance.class)); // should have been called only once, during initialization, but not during onRemove - verify(filter).test(node2); + verify(nodeDistanceEvaluator).evaluateDistance(node2, "dc1"); } @Test @@ -87,22 +88,22 @@ public void should_set_added_node_to_local() { // Then verify(distanceReporter).setDistance(node3, NodeDistance.LOCAL); - verify(filter).test(node3); + verify(nodeDistanceEvaluator).evaluateDistance(node3, "dc1"); // Not added to the live set yet, we're waiting for the pool to open - assertThat(policy.getLiveNodes()).containsExactlyInAnyOrder(node1, node2); + assertThat(policy.getLiveNodes().dc("dc1")).containsExactly(node1, node2); } @Test public void should_ignore_added_node_when_filtered() { // Given - when(filter.test(node3)).thenReturn(false); + when(nodeDistanceEvaluator.evaluateDistance(node3, "dc1")).thenReturn(NodeDistance.IGNORED); // When policy.onAdd(node3); // Then verify(distanceReporter).setDistance(node3, NodeDistance.IGNORED); - assertThat(policy.getLiveNodes()).containsExactlyInAnyOrder(node1, node2); + assertThat(policy.getLiveNodes().dc("dc1")).containsExactly(node1, node2); } @Test @@ -115,7 +116,8 @@ public void should_ignore_added_node_when_remote_dc() { // Then verify(distanceReporter).setDistance(node3, NodeDistance.IGNORED); - assertThat(policy.getLiveNodes()).containsExactlyInAnyOrder(node1, node2); + assertThat(policy.getLiveNodes().dc("dc1")).containsExactly(node1, node2); + assertThat(policy.getLiveNodes().dc("dc2")).isEmpty(); } @Test @@ -125,22 +127,22 @@ public void should_add_up_node_to_live_set() { // Then verify(distanceReporter).setDistance(node3, NodeDistance.LOCAL); - verify(filter).test(node3); - assertThat(policy.getLiveNodes()).containsExactlyInAnyOrder(node1, node2, node3); + verify(nodeDistanceEvaluator).evaluateDistance(node3, "dc1"); + assertThat(policy.getLiveNodes().dc("dc1")).containsExactly(node1, node2, node3); } @Test public void should_ignore_up_node_when_filtered() { // Given - when(filter.test(node3)).thenReturn(false); + when(nodeDistanceEvaluator.evaluateDistance(node3, "dc1")).thenReturn(NodeDistance.IGNORED); // When policy.onUp(node3); // Then verify(distanceReporter).setDistance(node3, NodeDistance.IGNORED); - verify(filter).test(node3); - assertThat(policy.getLiveNodes()).containsExactlyInAnyOrder(node1, node2); + verify(nodeDistanceEvaluator).evaluateDistance(node3, "dc1"); + assertThat(policy.getLiveNodes().dc("dc1")).containsExactly(node1, node2); } @Test @@ -153,7 +155,8 @@ public void should_ignore_up_node_when_remote_dc() { // Then verify(distanceReporter).setDistance(node3, NodeDistance.IGNORED); - assertThat(policy.getLiveNodes()).containsExactlyInAnyOrder(node1, node2); + assertThat(policy.getLiveNodes().dc("dc1")).containsExactly(node1, node2); + assertThat(policy.getLiveNodes().dc("dc2")).isEmpty(); } @NonNull @@ -162,7 +165,7 @@ protected BasicLoadBalancingPolicy createAndInitPolicy() { new BasicLoadBalancingPolicy(context, DriverExecutionProfile.DEFAULT_NAME); policy.init( ImmutableMap.of(UUID.randomUUID(), node1, UUID.randomUUID(), node2), distanceReporter); - assertThat(policy.liveNodes).containsExactlyInAnyOrder(node1, node2); + assertThat(policy.getLiveNodes().dc("dc1")).containsExactly(node1, node2); return policy; } } diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/BasicLoadBalancingPolicyInitTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/BasicLoadBalancingPolicyInitTest.java index b4bca1638a6..1863e7357e1 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/BasicLoadBalancingPolicyInitTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/BasicLoadBalancingPolicyInitTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -19,7 +21,6 @@ import static org.assertj.core.api.Assertions.filter; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.never; -import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -39,14 +40,7 @@ // TODO fix unnecessary stubbing of config option in parent class (and stop using "silent" runner) @RunWith(MockitoJUnitRunner.Silent.class) -public class BasicLoadBalancingPolicyInitTest extends DefaultLoadBalancingPolicyTestBase { - - @Override - public void setup() { - super.setup(); - reset(defaultProfile); - when(defaultProfile.getName()).thenReturn(DriverExecutionProfile.DEFAULT_NAME); - } +public class BasicLoadBalancingPolicyInitTest extends LoadBalancingPolicyTestBase { @Test public void should_use_local_dc_if_provided_via_config() { @@ -63,7 +57,7 @@ public void should_use_local_dc_if_provided_via_config() { policy.init(ImmutableMap.of(UUID.randomUUID(), node1), distanceReporter); // Then - assertThat(policy.getLocalDatacenter()).contains("dc1"); + assertThat(policy.getLocalDatacenter()).isEqualTo("dc1"); } @Test @@ -79,7 +73,7 @@ public void should_use_local_dc_if_provided_via_context() { policy.init(ImmutableMap.of(UUID.randomUUID(), node1), distanceReporter); // Then - assertThat(policy.getLocalDatacenter()).contains("dc1"); + assertThat(policy.getLocalDatacenter()).isEqualTo("dc1"); verify(defaultProfile, never()) .getString(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER, null); } @@ -89,15 +83,22 @@ public void should_not_infer_local_dc_if_not_provided() { // Given when(defaultProfile.isDefined(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER)) .thenReturn(false); + when(node1.getDatacenter()).thenReturn("dc1"); + when(node2.getDatacenter()).thenReturn("dc2"); + when(node3.getDatacenter()).thenReturn("dc3"); BasicLoadBalancingPolicy policy = new BasicLoadBalancingPolicy(context, DriverExecutionProfile.DEFAULT_NAME) {}; // When policy.init( - ImmutableMap.of(UUID.randomUUID(), node1, UUID.randomUUID(), node2), distanceReporter); + ImmutableMap.of( + UUID.randomUUID(), node1, UUID.randomUUID(), node2, UUID.randomUUID(), node3), + distanceReporter); // Then - assertThat(policy.getLocalDatacenter()).isEmpty(); + assertThat(policy.getLocalDatacenter()).isNull(); + // should not warn about contact points not being in the same DC + verify(appender, never()).doAppend(loggingEventCaptor.capture()); } @Test @@ -148,13 +149,12 @@ public void should_include_nodes_from_local_dc_if_local_dc_set() { verify(distanceReporter).setDistance(node2, NodeDistance.LOCAL); verify(distanceReporter).setDistance(node3, NodeDistance.LOCAL); // But only include UP or UNKNOWN nodes in the live set - assertThat(policy.getLiveNodes()).containsExactlyInAnyOrder(node1, node3); + assertThat(policy.getLiveNodes().dc("dc1")).containsExactly(node1, node3); } @Test public void should_ignore_nodes_from_remote_dcs_if_local_dc_set() { // Given - when(context.getLocalDatacenter(DriverExecutionProfile.DEFAULT_NAME)).thenReturn("dc1"); when(node2.getDatacenter()).thenReturn("dc2"); when(node3.getDatacenter()).thenReturn("dc3"); when(metadataManager.getContactPoints()).thenReturn(ImmutableSet.of(node1, node2)); @@ -170,12 +170,17 @@ public void should_ignore_nodes_from_remote_dcs_if_local_dc_set() { verify(distanceReporter).setDistance(node1, NodeDistance.LOCAL); verify(distanceReporter).setDistance(node2, NodeDistance.IGNORED); verify(distanceReporter).setDistance(node3, NodeDistance.IGNORED); - assertThat(policy.getLiveNodes()).containsExactlyInAnyOrder(node1); + assertThat(policy.getLiveNodes().dc("dc1")).containsExactly(node1); } @Test public void should_not_ignore_nodes_from_remote_dcs_if_local_dc_not_set() { // Given + when(defaultProfile.isDefined(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER)) + .thenReturn(false); + when(node2.getDatacenter()).thenReturn("dc2"); + when(node3.getDatacenter()).thenReturn("dc3"); + when(metadataManager.getContactPoints()).thenReturn(ImmutableSet.of(node1, node2)); BasicLoadBalancingPolicy policy = createPolicy(); // When @@ -188,14 +193,15 @@ public void should_not_ignore_nodes_from_remote_dcs_if_local_dc_not_set() { verify(distanceReporter).setDistance(node1, NodeDistance.LOCAL); verify(distanceReporter).setDistance(node2, NodeDistance.LOCAL); verify(distanceReporter).setDistance(node3, NodeDistance.LOCAL); - assertThat(policy.getLiveNodes()).containsExactlyInAnyOrder(node1, node2, node3); + assertThat(policy.getLiveNodes().dc("dc1")).containsExactly(node1, node2, node3); } @Test - public void should_ignore_nodes_excluded_by_filter() { + public void should_ignore_nodes_excluded_by_distance_reporter() { // Given - when(context.getNodeFilter(DriverExecutionProfile.DEFAULT_NAME)) - .thenReturn(node -> node.equals(node1)); + when(metadataManager.getContactPoints()).thenReturn(ImmutableSet.of(node1, node2)); + when(context.getNodeDistanceEvaluator(DriverExecutionProfile.DEFAULT_NAME)) + .thenReturn((node, dc) -> node.equals(node1) ? NodeDistance.IGNORED : null); BasicLoadBalancingPolicy policy = createPolicy(); @@ -206,10 +212,10 @@ public void should_ignore_nodes_excluded_by_filter() { distanceReporter); // Then - verify(distanceReporter).setDistance(node1, NodeDistance.LOCAL); - verify(distanceReporter).setDistance(node2, NodeDistance.IGNORED); - verify(distanceReporter).setDistance(node3, NodeDistance.IGNORED); - assertThat(policy.getLiveNodes()).containsExactlyInAnyOrder(node1); + verify(distanceReporter).setDistance(node1, NodeDistance.IGNORED); + verify(distanceReporter).setDistance(node2, NodeDistance.LOCAL); + verify(distanceReporter).setDistance(node3, NodeDistance.LOCAL); + assertThat(policy.getLiveNodes().dc("dc1")).containsExactly(node2, node3); } @NonNull diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/BasicLoadBalancingPolicyPreferredRemoteDcsTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/BasicLoadBalancingPolicyPreferredRemoteDcsTest.java new file mode 100644 index 00000000000..cefdfd31189 --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/BasicLoadBalancingPolicyPreferredRemoteDcsTest.java @@ -0,0 +1,184 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.loadbalancing; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.datastax.oss.driver.api.core.config.DefaultDriverOption; +import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; +import com.datastax.oss.driver.api.core.metadata.Node; +import com.datastax.oss.driver.internal.core.metadata.DefaultNode; +import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableList; +import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap; +import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableSet; +import java.util.Map; +import java.util.UUID; +import org.junit.Test; +import org.mockito.Mock; + +public class BasicLoadBalancingPolicyPreferredRemoteDcsTest + extends BasicLoadBalancingPolicyDcFailoverTest { + @Mock protected DefaultNode node10; + @Mock protected DefaultNode node11; + @Mock protected DefaultNode node12; + @Mock protected DefaultNode node13; + @Mock protected DefaultNode node14; + + @Override + @Test + public void should_prioritize_single_replica() { + when(request.getRoutingKeyspace()).thenReturn(KEYSPACE); + when(request.getRoutingKey()).thenReturn(ROUTING_KEY); + when(tokenMap.getReplicas(KEYSPACE, ROUTING_KEY)).thenReturn(ImmutableSet.of(node3)); + + // node3 always first, round-robin on the rest + assertThat(policy.newQueryPlan(request, session)) + .containsExactly( + node3, node1, node2, node4, node5, node9, node10, node6, node7, node12, node13); + assertThat(policy.newQueryPlan(request, session)) + .containsExactly( + node3, node2, node4, node5, node1, node9, node10, node6, node7, node12, node13); + assertThat(policy.newQueryPlan(request, session)) + .containsExactly( + node3, node4, node5, node1, node2, node9, node10, node6, node7, node12, node13); + assertThat(policy.newQueryPlan(request, session)) + .containsExactly( + node3, node5, node1, node2, node4, node9, node10, node6, node7, node12, node13); + + // Should not shuffle replicas since there is only one + verify(policy, never()).shuffleHead(any(), eq(1)); + // But should shuffle remote nodes + verify(policy, times(12)).shuffleHead(any(), eq(2)); + } + + @Override + @Test + public void should_prioritize_and_shuffle_replicas() { + when(request.getRoutingKeyspace()).thenReturn(KEYSPACE); + when(request.getRoutingKey()).thenReturn(ROUTING_KEY); + when(tokenMap.getReplicas(KEYSPACE, ROUTING_KEY)) + .thenReturn(ImmutableSet.of(node1, node2, node3, node6, node9)); + + // node 6 and 9 being in a remote DC, they don't get a boost for being a replica + assertThat(policy.newQueryPlan(request, session)) + .containsExactly( + node1, node2, node3, node4, node5, node9, node10, node6, node7, node12, node13); + assertThat(policy.newQueryPlan(request, session)) + .containsExactly( + node1, node2, node3, node5, node4, node9, node10, node6, node7, node12, node13); + + // should shuffle replicas + verify(policy, times(2)).shuffleHead(any(), eq(3)); + // should shuffle remote nodes + verify(policy, times(6)).shuffleHead(any(), eq(2)); + // No power of two choices with only two replicas + verify(session, never()).getPools(); + } + + @Override + protected void assertRoundRobinQueryPlans() { + for (int i = 0; i < 3; i++) { + assertThat(policy.newQueryPlan(request, session)) + .containsExactly( + node1, node2, node3, node4, node5, node9, node10, node6, node7, node12, node13); + assertThat(policy.newQueryPlan(request, session)) + .containsExactly( + node2, node3, node4, node5, node1, node9, node10, node6, node7, node12, node13); + assertThat(policy.newQueryPlan(request, session)) + .containsExactly( + node3, node4, node5, node1, node2, node9, node10, node6, node7, node12, node13); + assertThat(policy.newQueryPlan(request, session)) + .containsExactly( + node4, node5, node1, node2, node3, node9, node10, node6, node7, node12, node13); + assertThat(policy.newQueryPlan(request, session)) + .containsExactly( + node5, node1, node2, node3, node4, node9, node10, node6, node7, node12, node13); + } + + verify(policy, atLeast(15)).shuffleHead(any(), eq(2)); + } + + @Override + protected BasicLoadBalancingPolicy createAndInitPolicy() { + when(node4.getDatacenter()).thenReturn("dc1"); + when(node5.getDatacenter()).thenReturn("dc1"); + when(node6.getDatacenter()).thenReturn("dc2"); + when(node7.getDatacenter()).thenReturn("dc2"); + when(node8.getDatacenter()).thenReturn("dc2"); + when(node9.getDatacenter()).thenReturn("dc3"); + when(node10.getDatacenter()).thenReturn("dc3"); + when(node11.getDatacenter()).thenReturn("dc3"); + when(node12.getDatacenter()).thenReturn("dc4"); + when(node13.getDatacenter()).thenReturn("dc4"); + when(node14.getDatacenter()).thenReturn("dc4"); + + // Accept 2 nodes per remote DC + when(defaultProfile.getInt( + DefaultDriverOption.LOAD_BALANCING_DC_FAILOVER_MAX_NODES_PER_REMOTE_DC)) + .thenReturn(2); + when(defaultProfile.getBoolean( + DefaultDriverOption.LOAD_BALANCING_DC_FAILOVER_ALLOW_FOR_LOCAL_CONSISTENCY_LEVELS)) + .thenReturn(false); + + when(defaultProfile.getStringList( + DefaultDriverOption.LOAD_BALANCING_DC_FAILOVER_PREFERRED_REMOTE_DCS)) + .thenReturn(ImmutableList.of("dc3", "dc2")); + + // Use a subclass to disable shuffling, we just spy to make sure that the shuffling method was + // called (makes tests easier) + BasicLoadBalancingPolicy policy = + spy( + new BasicLoadBalancingPolicy(context, DriverExecutionProfile.DEFAULT_NAME) { + @Override + protected void shuffleHead(Object[] currentNodes, int headLength) { + // nothing (keep in same order) + } + }); + Map nodes = + ImmutableMap.builder() + .put(UUID.randomUUID(), node1) + .put(UUID.randomUUID(), node2) + .put(UUID.randomUUID(), node3) + .put(UUID.randomUUID(), node4) + .put(UUID.randomUUID(), node5) + .put(UUID.randomUUID(), node6) + .put(UUID.randomUUID(), node7) + .put(UUID.randomUUID(), node8) + .put(UUID.randomUUID(), node9) + .put(UUID.randomUUID(), node10) + .put(UUID.randomUUID(), node11) + .put(UUID.randomUUID(), node12) + .put(UUID.randomUUID(), node13) + .put(UUID.randomUUID(), node14) + .build(); + policy.init(nodes, distanceReporter); + assertThat(policy.getLiveNodes().dc("dc1")).containsExactly(node1, node2, node3, node4, node5); + assertThat(policy.getLiveNodes().dc("dc2")).containsExactly(node6, node7); // only 2 allowed + assertThat(policy.getLiveNodes().dc("dc3")).containsExactly(node9, node10); // only 2 allowed + assertThat(policy.getLiveNodes().dc("dc4")).containsExactly(node12, node13); // only 2 allowed + return policy; + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/BasicLoadBalancingPolicyQueryPlanTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/BasicLoadBalancingPolicyQueryPlanTest.java index f5c68e79c2b..50670ab317a 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/BasicLoadBalancingPolicyQueryPlanTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/BasicLoadBalancingPolicyQueryPlanTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -31,7 +33,6 @@ import com.datastax.oss.driver.api.core.CqlIdentifier; import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; -import com.datastax.oss.driver.api.core.context.DriverContext; import com.datastax.oss.driver.api.core.metadata.Metadata; import com.datastax.oss.driver.api.core.metadata.TokenMap; import com.datastax.oss.driver.api.core.metadata.token.Token; @@ -52,7 +53,7 @@ // TODO fix unnecessary stubbing of config option in parent class (and stop using "silent" runner) @RunWith(MockitoJUnitRunner.Silent.class) -public class BasicLoadBalancingPolicyQueryPlanTest extends DefaultLoadBalancingPolicyTestBase { +public class BasicLoadBalancingPolicyQueryPlanTest extends LoadBalancingPolicyTestBase { protected static final CqlIdentifier KEYSPACE = CqlIdentifier.fromInternal("ks"); protected static final ByteBuffer ROUTING_KEY = Bytes.fromHexString("0xdeadbeef"); @@ -74,10 +75,6 @@ public void setup() { when(metadata.getTokenMap()).thenAnswer(invocation -> Optional.of(this.tokenMap)); policy = createAndInitPolicy(); - - // Note: this test relies on the fact that the policy uses a CopyOnWriteArraySet which preserves - // insertion order. - assertThat(policy.liveNodes).containsExactly(node1, node2, node3, node4, node5); } @Test @@ -186,7 +183,7 @@ public void should_use_round_robin_when_token_map_absent() { } @Test - public void should_round_robin_and_log_error_when_request_throws() { + public void should_use_round_robin_and_log_error_when_request_throws() { // Given given(request.getKeyspace()).willThrow(new NullPointerException()); // When @@ -197,7 +194,7 @@ public void should_round_robin_and_log_error_when_request_throws() { .contains("Unexpected error while trying to compute query plan"); } - private void assertRoundRobinQueryPlans() { + protected void assertRoundRobinQueryPlans() { for (int i = 0; i < 3; i++) { assertThat(policy.newQueryPlan(request, session)) .containsExactly(node1, node2, node3, node4, node5); @@ -253,8 +250,14 @@ public void should_prioritize_and_shuffle_replicas() { protected BasicLoadBalancingPolicy createAndInitPolicy() { // Use a subclass to disable shuffling, we just spy to make sure that the shuffling method was // called (makes tests easier) - NonShufflingBasicLoadBalancingPolicy policy = - spy(new NonShufflingBasicLoadBalancingPolicy(context, DriverExecutionProfile.DEFAULT_NAME)); + BasicLoadBalancingPolicy policy = + spy( + new BasicLoadBalancingPolicy(context, DriverExecutionProfile.DEFAULT_NAME) { + @Override + protected void shuffleHead(Object[] currentNodes, int headLength) { + // nothing (keep in same order) + } + }); policy.init( ImmutableMap.of( UUID.randomUUID(), node1, @@ -263,17 +266,7 @@ protected BasicLoadBalancingPolicy createAndInitPolicy() { UUID.randomUUID(), node4, UUID.randomUUID(), node5), distanceReporter); + assertThat(policy.getLiveNodes().dc("dc1")).containsExactly(node1, node2, node3, node4, node5); return policy; } - - static class NonShufflingBasicLoadBalancingPolicy extends BasicLoadBalancingPolicy { - NonShufflingBasicLoadBalancingPolicy(DriverContext context, String profileName) { - super(context, profileName); - } - - @Override - protected void shuffleHead(Object[] currentNodes, int replicaCount) { - // nothing (keep in same order) - } - } } diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DcInferringLoadBalancingPolicyDcFailoverTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DcInferringLoadBalancingPolicyDcFailoverTest.java new file mode 100644 index 00000000000..dd9b74158f1 --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DcInferringLoadBalancingPolicyDcFailoverTest.java @@ -0,0 +1,79 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.loadbalancing; + +import static com.datastax.oss.driver.api.core.config.DriverExecutionProfile.DEFAULT_NAME; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +import com.datastax.oss.driver.api.core.config.DefaultDriverOption; +import com.datastax.oss.driver.api.core.metadata.Node; +import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap; +import java.util.Map; +import java.util.UUID; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; + +// TODO fix unnecessary stubbing of config option in parent class (and stop using "silent" runner) +@RunWith(MockitoJUnitRunner.Silent.class) +public class DcInferringLoadBalancingPolicyDcFailoverTest + extends BasicLoadBalancingPolicyDcFailoverTest { + + @Override + protected DcInferringLoadBalancingPolicy createAndInitPolicy() { + when(node4.getDatacenter()).thenReturn("dc2"); + when(node5.getDatacenter()).thenReturn("dc2"); + when(node6.getDatacenter()).thenReturn("dc2"); + when(node7.getDatacenter()).thenReturn("dc3"); + when(node8.getDatacenter()).thenReturn("dc3"); + when(node9.getDatacenter()).thenReturn("dc3"); + // Accept 2 nodes per remote DC + when(defaultProfile.getInt( + DefaultDriverOption.LOAD_BALANCING_DC_FAILOVER_MAX_NODES_PER_REMOTE_DC)) + .thenReturn(2); + when(defaultProfile.getBoolean( + DefaultDriverOption.LOAD_BALANCING_DC_FAILOVER_ALLOW_FOR_LOCAL_CONSISTENCY_LEVELS)) + .thenReturn(false); + // Use a subclass to disable shuffling, we just spy to make sure that the shuffling method was + // called (makes tests easier) + DcInferringLoadBalancingPolicy policy = + spy( + new DcInferringLoadBalancingPolicy(context, DEFAULT_NAME) { + @Override + protected void shuffleHead(Object[] array, int n) {} + }); + Map nodes = + ImmutableMap.builder() + .put(UUID.randomUUID(), node1) + .put(UUID.randomUUID(), node2) + .put(UUID.randomUUID(), node3) + .put(UUID.randomUUID(), node4) + .put(UUID.randomUUID(), node5) + .put(UUID.randomUUID(), node6) + .put(UUID.randomUUID(), node7) + .put(UUID.randomUUID(), node8) + .put(UUID.randomUUID(), node9) + .build(); + policy.init(nodes, distanceReporter); + assertThat(policy.getLiveNodes().dc("dc1")).containsExactly(node1, node2, node3); + assertThat(policy.getLiveNodes().dc("dc2")).containsExactly(node4, node5); // only 2 allowed + assertThat(policy.getLiveNodes().dc("dc3")).containsExactly(node7, node8); // only 2 allowed + return policy; + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DcInferringLoadBalancingPolicyDistanceTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DcInferringLoadBalancingPolicyDistanceTest.java new file mode 100644 index 00000000000..80c414aa8f2 --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DcInferringLoadBalancingPolicyDistanceTest.java @@ -0,0 +1,54 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.loadbalancing; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; +import edu.umd.cs.findbugs.annotations.NonNull; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; + +// TODO fix unnecessary stubbing of config option in parent class (and stop using "silent" runner) +@RunWith(MockitoJUnitRunner.Silent.class) +public class DcInferringLoadBalancingPolicyDistanceTest + extends BasicLoadBalancingPolicyDistanceTest { + + @Override + public void should_report_LOCAL_when_dc_agnostic() { + // This policy cannot operate when contact points are from different DCs + Throwable error = catchThrowable(super::should_report_LOCAL_when_dc_agnostic); + assertThat(error) + .isInstanceOfSatisfying( + IllegalStateException.class, + ise -> + assertThat(ise) + .hasMessageContaining( + "No local DC was provided, but the contact points are from different DCs") + .hasMessageContaining("node1=null") + .hasMessageContaining("node2=dc1") + .hasMessageContaining("node3=dc2")); + } + + @NonNull + @Override + protected BasicLoadBalancingPolicy createPolicy() { + return new DcInferringLoadBalancingPolicy(context, DriverExecutionProfile.DEFAULT_NAME); + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DcInferringLoadBalancingPolicyEventsTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DcInferringLoadBalancingPolicyEventsTest.java index 7535e8c8fce..218d6338df9 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DcInferringLoadBalancingPolicyEventsTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DcInferringLoadBalancingPolicyEventsTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -17,24 +19,14 @@ import static com.datastax.oss.driver.Assertions.assertThat; import static com.datastax.oss.driver.api.core.config.DriverExecutionProfile.DEFAULT_NAME; -import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.reset; -import com.datastax.dse.driver.internal.core.tracker.MultiplexingRequestTracker; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap; import edu.umd.cs.findbugs.annotations.NonNull; import java.util.UUID; -import org.junit.Before; public class DcInferringLoadBalancingPolicyEventsTest extends BasicLoadBalancingPolicyEventsTest { - @Override - @Before - public void setup() { - given(context.getRequestTracker()).willReturn(new MultiplexingRequestTracker()); - super.setup(); - } - @Override @NonNull protected BasicLoadBalancingPolicy createAndInitPolicy() { @@ -42,7 +34,7 @@ protected BasicLoadBalancingPolicy createAndInitPolicy() { new DcInferringLoadBalancingPolicy(context, DEFAULT_NAME); policy.init( ImmutableMap.of(UUID.randomUUID(), node1, UUID.randomUUID(), node2), distanceReporter); - assertThat(policy.getLiveNodes()).containsOnly(node1, node2); + assertThat(policy.getLiveNodes().dc("dc1")).containsOnly(node1, node2); reset(distanceReporter); return policy; } diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DcInferringLoadBalancingPolicyInitTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DcInferringLoadBalancingPolicyInitTest.java index 71d1ef154c8..20de3afe9c3 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DcInferringLoadBalancingPolicyInitTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DcInferringLoadBalancingPolicyInitTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,8 +18,8 @@ package com.datastax.oss.driver.internal.core.loadbalancing; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; import static org.assertj.core.api.Assertions.filter; -import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -25,7 +27,6 @@ import ch.qos.logback.classic.Level; import ch.qos.logback.classic.spi.ILoggingEvent; -import com.datastax.dse.driver.internal.core.tracker.MultiplexingRequestTracker; import com.datastax.oss.driver.api.core.config.DefaultDriverOption; import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; import com.datastax.oss.driver.api.core.loadbalancing.NodeDistance; @@ -34,17 +35,9 @@ import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableSet; import edu.umd.cs.findbugs.annotations.NonNull; import java.util.UUID; -import org.junit.Before; import org.junit.Test; -public class DcInferringLoadBalancingPolicyInitTest extends DefaultLoadBalancingPolicyTestBase { - - @Override - @Before - public void setup() { - given(context.getRequestTracker()).willReturn(new MultiplexingRequestTracker()); - super.setup(); - } +public class DcInferringLoadBalancingPolicyInitTest extends LoadBalancingPolicyTestBase { @Test public void should_use_local_dc_if_provided_via_config() { @@ -57,7 +50,7 @@ public void should_use_local_dc_if_provided_via_config() { policy.init(ImmutableMap.of(UUID.randomUUID(), node1), distanceReporter); // Then - assertThat(policy.getLocalDatacenter()).contains("dc1"); + assertThat(policy.getLocalDatacenter()).isEqualTo("dc1"); } @Test @@ -73,7 +66,7 @@ public void should_use_local_dc_if_provided_via_context() { policy.init(ImmutableMap.of(UUID.randomUUID(), node1), distanceReporter); // Then - assertThat(policy.getLocalDatacenter()).contains("dc1"); + assertThat(policy.getLocalDatacenter()).isEqualTo("dc1"); verify(defaultProfile, never()) .getString(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER, null); } @@ -90,7 +83,7 @@ public void should_infer_local_dc_from_contact_points() { policy.init(ImmutableMap.of(UUID.randomUUID(), node1), distanceReporter); // Then - assertThat(policy.getLocalDatacenter()).contains("dc1"); + assertThat(policy.getLocalDatacenter()).isEqualTo("dc1"); } @Test @@ -102,13 +95,19 @@ public void should_require_local_dc_if_contact_points_from_different_dcs() { when(node2.getDatacenter()).thenReturn("dc2"); BasicLoadBalancingPolicy policy = createPolicy(); - thrown.expect(IllegalStateException.class); - thrown.expectMessage( - "No local DC was provided, but the contact points are from different DCs: node1=dc1, node2=dc2"); - // When - policy.init( - ImmutableMap.of(UUID.randomUUID(), node1, UUID.randomUUID(), node2), distanceReporter); + Throwable t = + catchThrowable( + () -> + policy.init( + ImmutableMap.of(UUID.randomUUID(), node1, UUID.randomUUID(), node2), + distanceReporter)); + + // Then + assertThat(t) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining( + "No local DC was provided, but the contact points are from different DCs: node1=dc1, node2=dc2"); } @Test @@ -121,13 +120,19 @@ public void should_require_local_dc_if_contact_points_have_null_dcs() { when(node2.getDatacenter()).thenReturn(null); BasicLoadBalancingPolicy policy = createPolicy(); - thrown.expect(IllegalStateException.class); - thrown.expectMessage( - "The local DC could not be inferred from contact points, please set it explicitly"); - // When - policy.init( - ImmutableMap.of(UUID.randomUUID(), node1, UUID.randomUUID(), node2), distanceReporter); + Throwable t = + catchThrowable( + () -> + policy.init( + ImmutableMap.of(UUID.randomUUID(), node1, UUID.randomUUID(), node2), + distanceReporter)); + + // Then + assertThat(t) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining( + "The local DC could not be inferred from contact points, please set it explicitly"); } @Test @@ -177,7 +182,7 @@ public void should_include_nodes_from_local_dc() { verify(distanceReporter).setDistance(node2, NodeDistance.LOCAL); verify(distanceReporter).setDistance(node3, NodeDistance.LOCAL); // But only include UP or UNKNOWN nodes in the live set - assertThat(policy.getLiveNodes()).containsExactlyInAnyOrder(node1, node3); + assertThat(policy.getLiveNodes().dc("dc1")).containsExactly(node1, node3); } @Test @@ -198,15 +203,15 @@ public void should_ignore_nodes_from_remote_dcs() { verify(distanceReporter).setDistance(node1, NodeDistance.LOCAL); verify(distanceReporter).setDistance(node2, NodeDistance.IGNORED); verify(distanceReporter).setDistance(node3, NodeDistance.IGNORED); - assertThat(policy.getLiveNodes()).containsExactlyInAnyOrder(node1); + assertThat(policy.getLiveNodes().dc("dc1")).containsExactly(node1); } @Test - public void should_ignore_nodes_excluded_by_filter() { + public void should_ignore_nodes_excluded_by_distance_reporter() { // Given when(metadataManager.getContactPoints()).thenReturn(ImmutableSet.of(node1, node2)); - when(context.getNodeFilter(DriverExecutionProfile.DEFAULT_NAME)) - .thenReturn(node -> node.equals(node1)); + when(context.getNodeDistanceEvaluator(DriverExecutionProfile.DEFAULT_NAME)) + .thenReturn((node, dc) -> node.equals(node1) ? NodeDistance.IGNORED : null); BasicLoadBalancingPolicy policy = createPolicy(); @@ -217,10 +222,10 @@ public void should_ignore_nodes_excluded_by_filter() { distanceReporter); // Then - verify(distanceReporter).setDistance(node1, NodeDistance.LOCAL); - verify(distanceReporter).setDistance(node2, NodeDistance.IGNORED); - verify(distanceReporter).setDistance(node3, NodeDistance.IGNORED); - assertThat(policy.getLiveNodes()).containsExactlyInAnyOrder(node1); + verify(distanceReporter).setDistance(node1, NodeDistance.IGNORED); + verify(distanceReporter).setDistance(node2, NodeDistance.LOCAL); + verify(distanceReporter).setDistance(node3, NodeDistance.LOCAL); + assertThat(policy.getLiveNodes().dc("dc1")).containsExactly(node2, node3); } @NonNull diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DcInferringLoadBalancingPolicyQueryPlanTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DcInferringLoadBalancingPolicyQueryPlanTest.java index 1c2b8f09e67..23d4636a615 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DcInferringLoadBalancingPolicyQueryPlanTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DcInferringLoadBalancingPolicyQueryPlanTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -25,7 +27,7 @@ public class DcInferringLoadBalancingPolicyQueryPlanTest extends DefaultLoadBalancingPolicyQueryPlanTest { @Override - protected DefaultLoadBalancingPolicy createAndInitPolicy() { + protected DcInferringLoadBalancingPolicy createAndInitPolicy() { DcInferringLoadBalancingPolicy policy = spy( new DcInferringLoadBalancingPolicy(context, DEFAULT_NAME) { diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DefaultLoadBalancingPolicyDcFailoverTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DefaultLoadBalancingPolicyDcFailoverTest.java new file mode 100644 index 00000000000..f2e741fd756 --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DefaultLoadBalancingPolicyDcFailoverTest.java @@ -0,0 +1,79 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.loadbalancing; + +import static com.datastax.oss.driver.api.core.config.DriverExecutionProfile.DEFAULT_NAME; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +import com.datastax.oss.driver.api.core.config.DefaultDriverOption; +import com.datastax.oss.driver.api.core.metadata.Node; +import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap; +import java.util.Map; +import java.util.UUID; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; + +// TODO fix unnecessary stubbing of config option in parent class (and stop using "silent" runner) +@RunWith(MockitoJUnitRunner.Silent.class) +public class DefaultLoadBalancingPolicyDcFailoverTest + extends BasicLoadBalancingPolicyDcFailoverTest { + + @Override + protected DefaultLoadBalancingPolicy createAndInitPolicy() { + when(node4.getDatacenter()).thenReturn("dc2"); + when(node5.getDatacenter()).thenReturn("dc2"); + when(node6.getDatacenter()).thenReturn("dc2"); + when(node7.getDatacenter()).thenReturn("dc3"); + when(node8.getDatacenter()).thenReturn("dc3"); + when(node9.getDatacenter()).thenReturn("dc3"); + // Accept 2 nodes per remote DC + when(defaultProfile.getInt( + DefaultDriverOption.LOAD_BALANCING_DC_FAILOVER_MAX_NODES_PER_REMOTE_DC)) + .thenReturn(2); + when(defaultProfile.getBoolean( + DefaultDriverOption.LOAD_BALANCING_DC_FAILOVER_ALLOW_FOR_LOCAL_CONSISTENCY_LEVELS)) + .thenReturn(false); + // Use a subclass to disable shuffling, we just spy to make sure that the shuffling method was + // called (makes tests easier) + DefaultLoadBalancingPolicy policy = + spy( + new DefaultLoadBalancingPolicy(context, DEFAULT_NAME) { + @Override + protected void shuffleHead(Object[] array, int n) {} + }); + Map nodes = + ImmutableMap.builder() + .put(UUID.randomUUID(), node1) + .put(UUID.randomUUID(), node2) + .put(UUID.randomUUID(), node3) + .put(UUID.randomUUID(), node4) + .put(UUID.randomUUID(), node5) + .put(UUID.randomUUID(), node6) + .put(UUID.randomUUID(), node7) + .put(UUID.randomUUID(), node8) + .put(UUID.randomUUID(), node9) + .build(); + policy.init(nodes, distanceReporter); + assertThat(policy.getLiveNodes().dc("dc1")).containsExactly(node1, node2, node3); + assertThat(policy.getLiveNodes().dc("dc2")).containsExactly(node4, node5); // only 2 allowed + assertThat(policy.getLiveNodes().dc("dc3")).containsExactly(node7, node8); // only 2 allowed + return policy; + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DefaultLoadBalancingPolicyDistanceTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DefaultLoadBalancingPolicyDistanceTest.java new file mode 100644 index 00000000000..9cf30e048e9 --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DefaultLoadBalancingPolicyDistanceTest.java @@ -0,0 +1,53 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.loadbalancing; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; +import edu.umd.cs.findbugs.annotations.NonNull; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; + +// TODO fix unnecessary stubbing of config option in parent class (and stop using "silent" runner) +@RunWith(MockitoJUnitRunner.Silent.class) +public class DefaultLoadBalancingPolicyDistanceTest extends BasicLoadBalancingPolicyDistanceTest { + + @Override + public void should_report_LOCAL_when_dc_agnostic() { + // This policy cannot operate in dc-agnostic mode + Throwable error = catchThrowable(super::should_report_LOCAL_when_dc_agnostic); + assertThat(error) + .isInstanceOfSatisfying( + IllegalStateException.class, + ise -> + assertThat(ise) + .hasMessageContaining("the local DC must be explicitly set") + .hasMessageContaining("node1=null") + .hasMessageContaining("node2=dc1") + .hasMessageContaining("node3=dc2") + .hasMessageContaining("Current DCs in this cluster are: dc1, dc2")); + } + + @NonNull + @Override + protected BasicLoadBalancingPolicy createPolicy() { + return new DefaultLoadBalancingPolicy(context, DriverExecutionProfile.DEFAULT_NAME); + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DefaultLoadBalancingPolicyEventsTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DefaultLoadBalancingPolicyEventsTest.java index 5c0f1b8c581..17e926a29e0 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DefaultLoadBalancingPolicyEventsTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DefaultLoadBalancingPolicyEventsTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -17,31 +19,21 @@ import static com.datastax.oss.driver.Assertions.assertThat; import static com.datastax.oss.driver.api.core.config.DriverExecutionProfile.DEFAULT_NAME; -import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.reset; -import com.datastax.dse.driver.internal.core.tracker.MultiplexingRequestTracker; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap; import edu.umd.cs.findbugs.annotations.NonNull; import java.util.UUID; -import org.junit.Before; public class DefaultLoadBalancingPolicyEventsTest extends BasicLoadBalancingPolicyEventsTest { - @Override - @Before - public void setup() { - given(context.getRequestTracker()).willReturn(new MultiplexingRequestTracker()); - super.setup(); - } - @Override @NonNull protected DefaultLoadBalancingPolicy createAndInitPolicy() { DefaultLoadBalancingPolicy policy = new DefaultLoadBalancingPolicy(context, DEFAULT_NAME); policy.init( ImmutableMap.of(UUID.randomUUID(), node1, UUID.randomUUID(), node2), distanceReporter); - assertThat(policy.getLiveNodes()).containsOnly(node1, node2); + assertThat(policy.getLiveNodes().dc("dc1")).containsOnly(node1, node2); reset(distanceReporter); return policy; } diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DefaultLoadBalancingPolicyInitTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DefaultLoadBalancingPolicyInitTest.java index 2372e3de92d..7b875209743 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DefaultLoadBalancingPolicyInitTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DefaultLoadBalancingPolicyInitTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,8 +18,8 @@ package com.datastax.oss.driver.internal.core.loadbalancing; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.filter; -import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -25,7 +27,6 @@ import ch.qos.logback.classic.Level; import ch.qos.logback.classic.spi.ILoggingEvent; -import com.datastax.dse.driver.internal.core.tracker.MultiplexingRequestTracker; import com.datastax.oss.driver.api.core.config.DefaultDriverOption; import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; import com.datastax.oss.driver.api.core.loadbalancing.NodeDistance; @@ -34,17 +35,9 @@ import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableSet; import edu.umd.cs.findbugs.annotations.NonNull; import java.util.UUID; -import org.junit.Before; import org.junit.Test; -public class DefaultLoadBalancingPolicyInitTest extends DefaultLoadBalancingPolicyTestBase { - - @Override - @Before - public void setup() { - given(context.getRequestTracker()).willReturn(new MultiplexingRequestTracker()); - super.setup(); - } +public class DefaultLoadBalancingPolicyInitTest extends LoadBalancingPolicyTestBase { @Test public void should_use_local_dc_if_provided_via_config() { @@ -57,7 +50,7 @@ public void should_use_local_dc_if_provided_via_config() { policy.init(ImmutableMap.of(UUID.randomUUID(), node1), distanceReporter); // Then - assertThat(policy.getLocalDatacenter()).contains("dc1"); + assertThat(policy.getLocalDatacenter()).isEqualTo("dc1"); } @Test @@ -73,7 +66,7 @@ public void should_use_local_dc_if_provided_via_context() { policy.init(ImmutableMap.of(UUID.randomUUID(), node1), distanceReporter); // Then - assertThat(policy.getLocalDatacenter()).contains("dc1"); + assertThat(policy.getLocalDatacenter()).isEqualTo("dc1"); verify(defaultProfile, never()) .getString(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER, null); } @@ -91,7 +84,7 @@ public void should_infer_local_dc_if_no_explicit_contact_points() { policy.init(ImmutableMap.of(UUID.randomUUID(), node1), distanceReporter); // Then - assertThat(policy.getLocalDatacenter()).contains("dc1"); + assertThat(policy.getLocalDatacenter()).isEqualTo("dc1"); } @Test @@ -102,12 +95,12 @@ public void should_require_local_dc_if_explicit_contact_points() { when(metadataManager.wasImplicitContactPoint()).thenReturn(false); DefaultLoadBalancingPolicy policy = createPolicy(); - thrown.expect(IllegalStateException.class); - thrown.expectMessage( - "Since you provided explicit contact points, the local DC must be explicitly set"); - // When - policy.init(ImmutableMap.of(UUID.randomUUID(), node2), distanceReporter); + assertThatThrownBy( + () -> policy.init(ImmutableMap.of(UUID.randomUUID(), node2), distanceReporter)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining( + "Since you provided explicit contact points, the local DC must be explicitly set"); } @Test @@ -157,7 +150,7 @@ public void should_include_nodes_from_local_dc() { verify(distanceReporter).setDistance(node2, NodeDistance.LOCAL); verify(distanceReporter).setDistance(node3, NodeDistance.LOCAL); // But only include UP or UNKNOWN nodes in the live set - assertThat(policy.getLiveNodes()).containsExactlyInAnyOrder(node1, node3); + assertThat(policy.getLiveNodes().dc("dc1")).containsExactly(node1, node3); } @Test @@ -178,17 +171,19 @@ public void should_ignore_nodes_from_remote_dcs() { verify(distanceReporter).setDistance(node1, NodeDistance.LOCAL); verify(distanceReporter).setDistance(node2, NodeDistance.IGNORED); verify(distanceReporter).setDistance(node3, NodeDistance.IGNORED); - assertThat(policy.getLiveNodes()).containsExactlyInAnyOrder(node1); + assertThat(policy.getLiveNodes().dc("dc1")).containsExactly(node1); + assertThat(policy.getLiveNodes().dc("dc2")).isEmpty(); + assertThat(policy.getLiveNodes().dc("dc3")).isEmpty(); } @Test - public void should_ignore_nodes_excluded_by_filter() { + public void should_ignore_nodes_excluded_by_distance_reporter() { // Given when(metadataManager.getContactPoints()).thenReturn(ImmutableSet.of(node1, node2)); - when(context.getNodeFilter(DriverExecutionProfile.DEFAULT_NAME)) - .thenReturn(node -> node.equals(node1)); + when(context.getNodeDistanceEvaluator(DriverExecutionProfile.DEFAULT_NAME)) + .thenReturn((node, dc) -> node.equals(node1) ? NodeDistance.IGNORED : null); - DefaultLoadBalancingPolicy policy = createPolicy(); + BasicLoadBalancingPolicy policy = createPolicy(); // When policy.init( @@ -197,10 +192,10 @@ public void should_ignore_nodes_excluded_by_filter() { distanceReporter); // Then - verify(distanceReporter).setDistance(node1, NodeDistance.LOCAL); - verify(distanceReporter).setDistance(node2, NodeDistance.IGNORED); - verify(distanceReporter).setDistance(node3, NodeDistance.IGNORED); - assertThat(policy.getLiveNodes()).containsExactlyInAnyOrder(node1); + verify(distanceReporter).setDistance(node1, NodeDistance.IGNORED); + verify(distanceReporter).setDistance(node2, NodeDistance.LOCAL); + verify(distanceReporter).setDistance(node3, NodeDistance.LOCAL); + assertThat(policy.getLiveNodes().dc("dc1")).containsExactly(node2, node3); } @NonNull diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DefaultLoadBalancingPolicyQueryPlanTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DefaultLoadBalancingPolicyQueryPlanTest.java index b3e65fdd4f2..fff86a1b750 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DefaultLoadBalancingPolicyQueryPlanTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DefaultLoadBalancingPolicyQueryPlanTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -25,7 +27,6 @@ import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; -import com.datastax.dse.driver.internal.core.tracker.MultiplexingRequestTracker; import com.datastax.oss.driver.api.core.metadata.Node; import com.datastax.oss.driver.internal.core.pool.ChannelPool; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap; @@ -59,7 +60,6 @@ public class DefaultLoadBalancingPolicyQueryPlanTest extends BasicLoadBalancingP @Before @Override public void setup() { - given(context.getRequestTracker()).willReturn(new MultiplexingRequestTracker()); nanoTime = T1; diceRoll = 4; given(node4.getDatacenter()).willReturn("dc1"); @@ -78,9 +78,10 @@ public void setup() { given(metadata.getTokenMap()).willAnswer(invocation -> Optional.of(tokenMap)); super.setup(); dsePolicy = (DefaultLoadBalancingPolicy) policy; - // Note: tests in this class rely on the fact that the policy uses a CopyOnWriteArraySet which - // preserves insertion order, which is why we can use containsExactly() throughout this class. - assertThat(dsePolicy.getLiveNodes()).containsExactly(node1, node2, node3, node4, node5); + // Note: this assertion relies on the fact that policy.getLiveNodes() implementation preserves + // insertion order. + assertThat(dsePolicy.getLiveNodes().dc("dc1")) + .containsExactly(node1, node2, node3, node4, node5); } @Test @@ -202,7 +203,10 @@ public void should_prioritize_and_shuffle_3_or_more_replicas_when_first_unhealth given(pool3.getInFlight()).willReturn(0); given(pool5.getInFlight()).willReturn(0); - dsePolicy.responseTimes.put(node1, new AtomicLongArray(new long[] {T0, T0})); // unhealthy + dsePolicy.responseTimes.put( + node1, + dsePolicy + .new NodeResponseRateSample(new AtomicLongArray(new long[] {T0, T0}))); // unhealthy // When Queue plan1 = dsePolicy.newQueryPlan(request, session); @@ -231,7 +235,9 @@ public void should_prioritize_and_shuffle_3_or_more_replicas_when_first_unhealth given(pool3.getInFlight()).willReturn(0); given(pool5.getInFlight()).willReturn(0); - dsePolicy.responseTimes.put(node1, new AtomicLongArray(new long[] {T1, T1})); // healthy + dsePolicy.responseTimes.put( + node1, + dsePolicy.new NodeResponseRateSample(new AtomicLongArray(new long[] {T1, T1}))); // healthy // When Queue plan1 = dsePolicy.newQueryPlan(request, session); diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DefaultLoadBalancingPolicyRequestTrackerTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DefaultLoadBalancingPolicyRequestTrackerTest.java index 76517fc2c0c..757af43ef67 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DefaultLoadBalancingPolicyRequestTrackerTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DefaultLoadBalancingPolicyRequestTrackerTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -19,7 +21,6 @@ import static com.datastax.oss.driver.api.core.config.DriverExecutionProfile.DEFAULT_NAME; import static org.mockito.BDDMockito.given; -import com.datastax.dse.driver.internal.core.tracker.MultiplexingRequestTracker; import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; import com.datastax.oss.driver.api.core.session.Request; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap; @@ -29,8 +30,7 @@ import org.junit.Test; import org.mockito.Mock; -public class DefaultLoadBalancingPolicyRequestTrackerTest - extends DefaultLoadBalancingPolicyTestBase { +public class DefaultLoadBalancingPolicyRequestTrackerTest extends LoadBalancingPolicyTestBase { @Mock Request request; @Mock DriverExecutionProfile profile; @@ -42,7 +42,6 @@ public class DefaultLoadBalancingPolicyRequestTrackerTest @Before @Override public void setup() { - given(context.getRequestTracker()).willReturn(new MultiplexingRequestTracker()); super.setup(); given(metadataManager.getContactPoints()).willReturn(ImmutableSet.of(node1)); policy = @@ -70,11 +69,11 @@ public void should_record_first_response_time_on_node_success() { // Then assertThat(policy.responseTimes) - .hasEntrySatisfying(node1, value -> assertThat(value.get(0)).isEqualTo(123L)) + .hasEntrySatisfying(node1, value -> assertThat(value.oldest).isEqualTo(123L)) .doesNotContainKeys(node2, node3); - assertThat(policy.isResponseRateInsufficient(node1, nextNanoTime)).isTrue(); - assertThat(policy.isResponseRateInsufficient(node2, nextNanoTime)).isTrue(); - assertThat(policy.isResponseRateInsufficient(node3, nextNanoTime)).isTrue(); + assertThat(policy.isResponseRateInsufficient(node1, nextNanoTime)).isFalse(); + assertThat(policy.isResponseRateInsufficient(node2, nextNanoTime)).isFalse(); + assertThat(policy.isResponseRateInsufficient(node3, nextNanoTime)).isFalse(); } @Test @@ -92,13 +91,13 @@ public void should_record_second_response_time_on_node_success() { node1, value -> { // oldest value first - assertThat(value.get(0)).isEqualTo(123); - assertThat(value.get(1)).isEqualTo(456); + assertThat(value.oldest).isEqualTo(123); + assertThat(value.newest.getAsLong()).isEqualTo(456); }) .doesNotContainKeys(node2, node3); assertThat(policy.isResponseRateInsufficient(node1, nextNanoTime)).isFalse(); - assertThat(policy.isResponseRateInsufficient(node2, nextNanoTime)).isTrue(); - assertThat(policy.isResponseRateInsufficient(node3, nextNanoTime)).isTrue(); + assertThat(policy.isResponseRateInsufficient(node2, nextNanoTime)).isFalse(); + assertThat(policy.isResponseRateInsufficient(node3, nextNanoTime)).isFalse(); } @Test @@ -117,14 +116,14 @@ public void should_record_further_response_times_on_node_success() { node1, value -> { // values should rotate left (bubble up) - assertThat(value.get(0)).isEqualTo(456); - assertThat(value.get(1)).isEqualTo(789); + assertThat(value.oldest).isEqualTo(456); + assertThat(value.newest.getAsLong()).isEqualTo(789); }) - .hasEntrySatisfying(node2, value -> assertThat(value.get(0)).isEqualTo(789)) + .hasEntrySatisfying(node2, value -> assertThat(value.oldest).isEqualTo(789)) .doesNotContainKey(node3); assertThat(policy.isResponseRateInsufficient(node1, nextNanoTime)).isFalse(); - assertThat(policy.isResponseRateInsufficient(node2, nextNanoTime)).isTrue(); - assertThat(policy.isResponseRateInsufficient(node3, nextNanoTime)).isTrue(); + assertThat(policy.isResponseRateInsufficient(node2, nextNanoTime)).isFalse(); + assertThat(policy.isResponseRateInsufficient(node3, nextNanoTime)).isFalse(); } @Test @@ -138,11 +137,11 @@ public void should_record_first_response_time_on_node_error() { // Then assertThat(policy.responseTimes) - .hasEntrySatisfying(node1, value -> assertThat(value.get(0)).isEqualTo(123L)) + .hasEntrySatisfying(node1, value -> assertThat(value.oldest).isEqualTo(123L)) .doesNotContainKeys(node2, node3); - assertThat(policy.isResponseRateInsufficient(node1, nextNanoTime)).isTrue(); - assertThat(policy.isResponseRateInsufficient(node2, nextNanoTime)).isTrue(); - assertThat(policy.isResponseRateInsufficient(node3, nextNanoTime)).isTrue(); + assertThat(policy.isResponseRateInsufficient(node1, nextNanoTime)).isFalse(); + assertThat(policy.isResponseRateInsufficient(node2, nextNanoTime)).isFalse(); + assertThat(policy.isResponseRateInsufficient(node3, nextNanoTime)).isFalse(); } @Test @@ -161,13 +160,13 @@ public void should_record_second_response_time_on_node_error() { node1, value -> { // oldest value first - assertThat(value.get(0)).isEqualTo(123); - assertThat(value.get(1)).isEqualTo(456); + assertThat(value.oldest).isEqualTo(123); + assertThat(value.newest.getAsLong()).isEqualTo(456); }) .doesNotContainKeys(node2, node3); assertThat(policy.isResponseRateInsufficient(node1, nextNanoTime)).isFalse(); - assertThat(policy.isResponseRateInsufficient(node2, nextNanoTime)).isTrue(); - assertThat(policy.isResponseRateInsufficient(node3, nextNanoTime)).isTrue(); + assertThat(policy.isResponseRateInsufficient(node2, nextNanoTime)).isFalse(); + assertThat(policy.isResponseRateInsufficient(node3, nextNanoTime)).isFalse(); } @Test @@ -187,13 +186,13 @@ public void should_record_further_response_times_on_node_error() { node1, value -> { // values should rotate left (bubble up) - assertThat(value.get(0)).isEqualTo(456); - assertThat(value.get(1)).isEqualTo(789); + assertThat(value.oldest).isEqualTo(456); + assertThat(value.newest.getAsLong()).isEqualTo(789); }) - .hasEntrySatisfying(node2, value -> assertThat(value.get(0)).isEqualTo(789)) + .hasEntrySatisfying(node2, value -> assertThat(value.oldest).isEqualTo(789)) .doesNotContainKey(node3); assertThat(policy.isResponseRateInsufficient(node1, nextNanoTime)).isFalse(); - assertThat(policy.isResponseRateInsufficient(node2, nextNanoTime)).isTrue(); - assertThat(policy.isResponseRateInsufficient(node3, nextNanoTime)).isTrue(); + assertThat(policy.isResponseRateInsufficient(node2, nextNanoTime)).isFalse(); + assertThat(policy.isResponseRateInsufficient(node3, nextNanoTime)).isFalse(); } } diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DefaultLoadBalancingPolicyTestBase.java b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/LoadBalancingPolicyTestBase.java similarity index 74% rename from core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DefaultLoadBalancingPolicyTestBase.java rename to core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/LoadBalancingPolicyTestBase.java index f5ac866e4ef..c9149efa69f 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/DefaultLoadBalancingPolicyTestBase.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/LoadBalancingPolicyTestBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -26,14 +28,13 @@ import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; import com.datastax.oss.driver.api.core.loadbalancing.LoadBalancingPolicy; import com.datastax.oss.driver.api.core.metadata.Node; +import com.datastax.oss.driver.internal.core.DefaultConsistencyLevelRegistry; import com.datastax.oss.driver.internal.core.context.InternalDriverContext; import com.datastax.oss.driver.internal.core.metadata.DefaultNode; import com.datastax.oss.driver.internal.core.metadata.MetadataManager; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableList; import org.junit.After; import org.junit.Before; -import org.junit.Rule; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; @@ -42,9 +43,7 @@ import org.slf4j.LoggerFactory; @RunWith(MockitoJUnitRunner.class) -public abstract class DefaultLoadBalancingPolicyTestBase { - - @Rule public ExpectedException thrown = ExpectedException.none(); +public abstract class LoadBalancingPolicyTestBase { @Mock protected DefaultNode node1; @Mock protected DefaultNode node2; @@ -75,6 +74,13 @@ public void setup() { .thenReturn("dc1"); when(defaultProfile.getBoolean(DefaultDriverOption.LOAD_BALANCING_POLICY_SLOW_AVOIDANCE, true)) .thenReturn(true); + when(defaultProfile.getInt( + DefaultDriverOption.LOAD_BALANCING_DC_FAILOVER_MAX_NODES_PER_REMOTE_DC)) + .thenReturn(0); + when(defaultProfile.getBoolean( + DefaultDriverOption.LOAD_BALANCING_DC_FAILOVER_ALLOW_FOR_LOCAL_CONSISTENCY_LEVELS)) + .thenReturn(false); + when(defaultProfile.getString(DefaultDriverOption.REQUEST_CONSISTENCY)).thenReturn("ONE"); when(context.getMetadataManager()).thenReturn(metadataManager); @@ -87,6 +93,7 @@ public void setup() { } when(context.getLocalDatacenter(anyString())).thenReturn(null); + when(context.getConsistencyLevelRegistry()).thenReturn(new DefaultConsistencyLevelRegistry()); } @After diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/nodeset/DcAgnosticNodeSetTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/nodeset/DcAgnosticNodeSetTest.java new file mode 100644 index 00000000000..0730bcd346c --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/nodeset/DcAgnosticNodeSetTest.java @@ -0,0 +1,61 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.loadbalancing.nodeset; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +import com.datastax.oss.driver.api.core.metadata.Node; +import org.junit.Test; + +public class DcAgnosticNodeSetTest { + + @Test + public void should_add_node() { + DcAgnosticNodeSet set = new DcAgnosticNodeSet(); + Node node = mock(Node.class); + assertThat(set.add(node)).isTrue(); + assertThat(set.add(node)).isFalse(); + } + + @Test + public void should_remove_node() { + DcAgnosticNodeSet set = new DcAgnosticNodeSet(); + Node node = mock(Node.class); + set.add(node); + assertThat(set.remove(node)).isTrue(); + assertThat(set.remove(node)).isFalse(); + } + + @Test + public void should_return_all_nodes() { + DcAgnosticNodeSet set = new DcAgnosticNodeSet(); + Node node1 = mock(Node.class); + set.add(node1); + Node node2 = mock(Node.class); + set.add(node2); + assertThat(set.dc(null)).contains(node1, node2); + assertThat(set.dc("irrelevant")).contains(node1, node2); + } + + @Test + public void should_return_empty_dcs() { + DcAgnosticNodeSet set = new DcAgnosticNodeSet(); + assertThat(set.dcs()).isEmpty(); + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/nodeset/MultiDcNodeSetTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/nodeset/MultiDcNodeSetTest.java new file mode 100644 index 00000000000..21c58cbb829 --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/nodeset/MultiDcNodeSetTest.java @@ -0,0 +1,83 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.loadbalancing.nodeset; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.datastax.oss.driver.api.core.metadata.Node; +import org.junit.Test; + +public class MultiDcNodeSetTest { + + @Test + public void should_add_node() { + MultiDcNodeSet set = new MultiDcNodeSet(); + Node node1 = mockNode("dc1"); + assertThat(set.add(node1)).isTrue(); + assertThat(set.add(node1)).isFalse(); + Node node2 = mockNode("dc2"); + assertThat(set.add(node2)).isTrue(); + assertThat(set.add(node2)).isFalse(); + } + + @Test + public void should_remove_node() { + MultiDcNodeSet set = new MultiDcNodeSet(); + Node node1 = mockNode("dc1"); + set.add(node1); + assertThat(set.remove(node1)).isTrue(); + assertThat(set.remove(node1)).isFalse(); + Node node2 = mockNode("dc2"); + set.add(node2); + assertThat(set.remove(node2)).isTrue(); + assertThat(set.remove(node2)).isFalse(); + } + + @Test + public void should_return_all_nodes_in_dc() { + MultiDcNodeSet set = new MultiDcNodeSet(); + Node node1 = mockNode("dc1"); + set.add(node1); + Node node2 = mockNode("dc1"); + set.add(node2); + Node node3 = mockNode("dc2"); + set.add(node3); + assertThat(set.dc("dc1")).contains(node1, node2); + assertThat(set.dc("dc2")).contains(node3); + assertThat(set.dc("dc3")).isEmpty(); + assertThat(set.dc(null)).isEmpty(); + } + + @Test + public void should_return_all_dcs() { + MultiDcNodeSet set = new MultiDcNodeSet(); + Node node1 = mockNode("dc1"); + set.add(node1); + Node node2 = mockNode("dc2"); + set.add(node2); + assertThat(set.dcs()).contains("dc1", "dc2"); + } + + private Node mockNode(String dc) { + Node node = mock(Node.class); + when(node.getDatacenter()).thenReturn(dc); + return node; + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/nodeset/SingleDcNodeSetTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/nodeset/SingleDcNodeSetTest.java new file mode 100644 index 00000000000..063c13c9386 --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/loadbalancing/nodeset/SingleDcNodeSetTest.java @@ -0,0 +1,73 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.loadbalancing.nodeset; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.datastax.oss.driver.api.core.metadata.Node; +import org.junit.Test; + +public class SingleDcNodeSetTest { + + @Test + public void should_add_node() { + SingleDcNodeSet set = new SingleDcNodeSet("dc1"); + Node node1 = mockNode("dc1"); + assertThat(set.add(node1)).isTrue(); + assertThat(set.add(node1)).isFalse(); + Node node2 = mockNode("dc2"); + assertThat(set.add(node2)).isFalse(); + } + + @Test + public void should_remove_node() { + SingleDcNodeSet set = new SingleDcNodeSet("dc1"); + Node node = mockNode("dc1"); + set.add(node); + assertThat(set.remove(node)).isTrue(); + assertThat(set.remove(node)).isFalse(); + } + + @Test + public void should_return_all_nodes_if_local_dc() { + SingleDcNodeSet set = new SingleDcNodeSet("dc1"); + Node node1 = mockNode("dc1"); + set.add(node1); + Node node2 = mockNode("dc1"); + set.add(node2); + Node node3 = mockNode("dc2"); + set.add(node3); + assertThat(set.dc("dc1")).contains(node1, node2); + assertThat(set.dc("dc2")).isEmpty(); + assertThat(set.dc(null)).isEmpty(); + } + + @Test + public void should_return_only_local_dc() { + SingleDcNodeSet set = new SingleDcNodeSet("dc1"); + assertThat(set.dcs()).contains("dc1"); + } + + private Node mockNode(String dc) { + Node node = mock(Node.class); + when(node.getDatacenter()).thenReturn(dc); + return node; + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/AddNodeRefreshTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/AddNodeRefreshTest.java index 67b3cc36c8e..8d337bcc7e3 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/AddNodeRefreshTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/AddNodeRefreshTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/DefaultEndPointTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/DefaultEndPointTest.java index 5c3689920c1..7da8fb39415 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/DefaultEndPointTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/DefaultEndPointTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,16 +18,13 @@ package com.datastax.oss.driver.internal.core.metadata; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.net.InetSocketAddress; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; public class DefaultEndPointTest { - @Rule public ExpectedException thrown = ExpectedException.none(); - @Test public void should_create_from_host_name() { DefaultEndPoint endPoint = new DefaultEndPoint(new InetSocketAddress("localhost", 9042)); @@ -54,9 +53,8 @@ public void should_create_from_unresolved_address() { @Test public void should_reject_null_address() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("address can't be null"); - - new DefaultEndPoint(null); + assertThatThrownBy(() -> new DefaultEndPoint(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("address can't be null"); } } diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/DefaultMetadataTokenMapTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/DefaultMetadataTokenMapTest.java index db8f9cd2eda..b463f9caa7b 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/DefaultMetadataTokenMapTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/DefaultMetadataTokenMapTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/DefaultNodeTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/DefaultNodeTest.java index bc9a1b86e2f..6a53fe3e433 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/DefaultNodeTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/DefaultNodeTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/DefaultTopologyMonitorTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/DefaultTopologyMonitorTest.java index f989ea14de5..dd40f233518 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/DefaultTopologyMonitorTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/DefaultTopologyMonitorTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -36,6 +38,7 @@ import com.datastax.oss.driver.api.core.config.DefaultDriverOption; import com.datastax.oss.driver.api.core.config.DriverConfig; import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; +import com.datastax.oss.driver.api.core.ssl.SslEngineFactory; import com.datastax.oss.driver.internal.core.addresstranslation.PassThroughAddressTranslator; import com.datastax.oss.driver.internal.core.adminrequest.AdminResult; import com.datastax.oss.driver.internal.core.adminrequest.AdminRow; @@ -48,9 +51,11 @@ import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableSet; import com.datastax.oss.driver.shaded.guava.common.collect.Iterators; +import com.datastax.oss.driver.shaded.guava.common.collect.Maps; import com.datastax.oss.protocol.internal.Message; import com.datastax.oss.protocol.internal.ProtocolConstants; import com.datastax.oss.protocol.internal.response.Error; +import com.google.common.collect.Streams; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; @@ -93,6 +98,8 @@ public class DefaultTopologyMonitorTest { @Mock private Appender appender; @Captor private ArgumentCaptor loggingEventCaptor; + @Mock private SslEngineFactory sslEngineFactory; + private DefaultNode node1; private DefaultNode node2; @@ -412,18 +419,6 @@ public void should_skip_invalid_peers_row_v2(String columnToCheck) { + "This is likely a gossip or snitch issue, this node will be ignored."); } - @DataProvider - public static Object[][] columnsToCheckV1() { - return new Object[][] {{"rpc_address"}, {"host_id"}, {"data_center"}, {"rack"}, {"tokens"}}; - } - - @DataProvider - public static Object[][] columnsToCheckV2() { - return new Object[][] { - {"native_address"}, {"native_port"}, {"host_id"}, {"data_center"}, {"rack"}, {"tokens"} - }; - } - @Test public void should_stop_executing_queries_once_closed() { // Given @@ -441,9 +436,9 @@ public void should_stop_executing_queries_once_closed() { public void should_warn_when_control_host_found_in_system_peers() { // Given AdminRow local = mockLocalRow(1, node1.getHostId()); - AdminRow peer3 = mockPeersRow(3, UUID.randomUUID()); - AdminRow peer2 = mockPeersRow(2, node2.getHostId()); AdminRow peer1 = mockPeersRow(1, node2.getHostId()); // invalid + AdminRow peer2 = mockPeersRow(2, node2.getHostId()); + AdminRow peer3 = mockPeersRow(3, UUID.randomUUID()); topologyMonitor.stubQueries( new StubbedQuery("SELECT * FROM system.local", mockResult(local)), new StubbedQuery("SELECT * FROM system.peers_v2", Collections.emptyMap(), null, true), @@ -460,7 +455,7 @@ public void should_warn_when_control_host_found_in_system_peers() { .hasSize(3) .extractingResultOf("getEndPoint") .containsOnlyOnce(node1.getEndPoint())); - assertLog( + assertLogContains( Level.WARN, "[null] Control node /127.0.0.1:9042 has an entry for itself in system.peers: " + "this entry will be ignored. This is likely due to a misconfiguration; " @@ -490,7 +485,7 @@ public void should_warn_when_control_host_found_in_system_peers_v2() { .hasSize(3) .extractingResultOf("getEndPoint") .containsOnlyOnce(node1.getEndPoint())); - assertLog( + assertLogContains( Level.WARN, "[null] Control node /127.0.0.1:9042 has an entry for itself in system.peers_v2: " + "this entry will be ignored. This is likely due to a misconfiguration; " @@ -498,6 +493,116 @@ public void should_warn_when_control_host_found_in_system_peers_v2() { + "all nodes in your cluster."); } + // Confirm the base case of extracting peer info from peers_v2, no SSL involved + @Test + public void should_get_peer_address_info_peers_v2() { + // Given + AdminRow local = mockLocalRow(1, node1.getHostId()); + AdminRow peer2 = mockPeersV2Row(3, node2.getHostId()); + AdminRow peer1 = mockPeersV2Row(2, node1.getHostId()); + topologyMonitor.isSchemaV2 = true; + topologyMonitor.stubQueries( + new StubbedQuery("SELECT * FROM system.local", mockResult(local)), + new StubbedQuery("SELECT * FROM system.peers_v2", mockResult(peer2, peer1))); + when(context.getSslEngineFactory()).thenReturn(Optional.empty()); + + // When + CompletionStage> futureInfos = topologyMonitor.refreshNodeList(); + + // Then + assertThatStage(futureInfos) + .isSuccess( + infos -> { + Iterator iterator = infos.iterator(); + // First NodeInfo is for local, skip past that + iterator.next(); + NodeInfo peer2nodeInfo = iterator.next(); + assertThat(peer2nodeInfo.getEndPoint().resolve()) + .isEqualTo(new InetSocketAddress("127.0.0.3", 9042)); + NodeInfo peer1nodeInfo = iterator.next(); + assertThat(peer1nodeInfo.getEndPoint().resolve()) + .isEqualTo(new InetSocketAddress("127.0.0.2", 9042)); + }); + } + + // Confirm the base case of extracting peer info from DSE peers table, no SSL involved + @Test + public void should_get_peer_address_info_peers_dse() { + // Given + AdminRow local = mockLocalRow(1, node1.getHostId()); + AdminRow peer2 = mockPeersRowDse(3, node2.getHostId()); + AdminRow peer1 = mockPeersRowDse(2, node1.getHostId()); + topologyMonitor.isSchemaV2 = true; + topologyMonitor.stubQueries( + new StubbedQuery("SELECT * FROM system.local", mockResult(local)), + new StubbedQuery("SELECT * FROM system.peers_v2", Maps.newHashMap(), null, true), + new StubbedQuery("SELECT * FROM system.peers", mockResult(peer2, peer1))); + when(context.getSslEngineFactory()).thenReturn(Optional.empty()); + + // When + CompletionStage> futureInfos = topologyMonitor.refreshNodeList(); + + // Then + assertThatStage(futureInfos) + .isSuccess( + infos -> { + Iterator iterator = infos.iterator(); + // First NodeInfo is for local, skip past that + iterator.next(); + NodeInfo peer2nodeInfo = iterator.next(); + assertThat(peer2nodeInfo.getEndPoint().resolve()) + .isEqualTo(new InetSocketAddress("127.0.0.3", 9042)); + NodeInfo peer1nodeInfo = iterator.next(); + assertThat(peer1nodeInfo.getEndPoint().resolve()) + .isEqualTo(new InetSocketAddress("127.0.0.2", 9042)); + }); + } + + // Confirm the base case of extracting peer info from DSE peers table, this time with SSL + @Test + public void should_get_peer_address_info_peers_dse_with_ssl() { + // Given + AdminRow local = mockLocalRow(1, node1.getHostId()); + AdminRow peer2 = mockPeersRowDseWithSsl(3, node2.getHostId()); + AdminRow peer1 = mockPeersRowDseWithSsl(2, node1.getHostId()); + topologyMonitor.isSchemaV2 = true; + topologyMonitor.stubQueries( + new StubbedQuery("SELECT * FROM system.local", mockResult(local)), + new StubbedQuery("SELECT * FROM system.peers_v2", Maps.newHashMap(), null, true), + new StubbedQuery("SELECT * FROM system.peers", mockResult(peer2, peer1))); + when(context.getSslEngineFactory()).thenReturn(Optional.of(sslEngineFactory)); + + // When + CompletionStage> futureInfos = topologyMonitor.refreshNodeList(); + + // Then + assertThatStage(futureInfos) + .isSuccess( + infos -> { + Iterator iterator = infos.iterator(); + // First NodeInfo is for local, skip past that + iterator.next(); + NodeInfo peer2nodeInfo = iterator.next(); + assertThat(peer2nodeInfo.getEndPoint().resolve()) + .isEqualTo(new InetSocketAddress("127.0.0.3", 9043)); + NodeInfo peer1nodeInfo = iterator.next(); + assertThat(peer1nodeInfo.getEndPoint().resolve()) + .isEqualTo(new InetSocketAddress("127.0.0.2", 9043)); + }); + } + + @DataProvider + public static Object[][] columnsToCheckV1() { + return new Object[][] {{"rpc_address"}, {"host_id"}, {"data_center"}, {"rack"}, {"tokens"}}; + } + + @DataProvider + public static Object[][] columnsToCheckV2() { + return new Object[][] { + {"native_address"}, {"native_port"}, {"host_id"}, {"data_center"}, {"rack"}, {"tokens"} + }; + } + /** Mocks the query execution logic. */ private static class TestTopologyMonitor extends DefaultTopologyMonitor { @@ -639,6 +744,43 @@ private AdminRow mockPeersV2Row(int i, UUID hostId) { } } + // Mock row for DSE ~6.8 + private AdminRow mockPeersRowDse(int i, UUID hostId) { + try { + AdminRow row = mock(AdminRow.class); + when(row.contains("peer")).thenReturn(true); + when(row.isNull("data_center")).thenReturn(false); + when(row.getString("data_center")).thenReturn("dc" + i); + when(row.getString("dse_version")).thenReturn("6.8.30"); + when(row.contains("graph")).thenReturn(true); + when(row.isNull("host_id")).thenReturn(hostId == null); + when(row.getUuid("host_id")).thenReturn(hostId); + when(row.getInetAddress("peer")).thenReturn(InetAddress.getByName("127.0.0." + i)); + when(row.isNull("rack")).thenReturn(false); + when(row.getString("rack")).thenReturn("rack" + i); + when(row.isNull("native_transport_address")).thenReturn(false); + when(row.getInetAddress("native_transport_address")) + .thenReturn(InetAddress.getByName("127.0.0." + i)); + when(row.isNull("native_transport_port")).thenReturn(false); + when(row.getInteger("native_transport_port")).thenReturn(9042); + when(row.isNull("tokens")).thenReturn(false); + when(row.getSetOfString("tokens")).thenReturn(ImmutableSet.of("token" + i)); + when(row.isNull("rpc_address")).thenReturn(false); + + return row; + } catch (UnknownHostException e) { + fail("unexpected", e); + return null; + } + } + + private AdminRow mockPeersRowDseWithSsl(int i, UUID hostId) { + AdminRow row = mockPeersRowDse(i, hostId); + when(row.isNull("native_transport_port_ssl")).thenReturn(false); + when(row.getInteger("native_transport_port_ssl")).thenReturn(9043); + return row; + } + private AdminResult mockResult(AdminRow... rows) { AdminResult result = mock(AdminResult.class); when(result.iterator()).thenReturn(Iterators.forArray(rows)); @@ -652,4 +794,12 @@ private void assertLog(Level level, String message) { assertThat(logs).hasSize(1); assertThat(logs.iterator().next().getFormattedMessage()).contains(message); } + + private void assertLogContains(Level level, String message) { + verify(appender, atLeast(1)).doAppend(loggingEventCaptor.capture()); + Iterable logs = + filter(loggingEventCaptor.getAllValues()).with("level", level).get(); + assertThat( + Streams.stream(logs).map(ILoggingEvent::getFormattedMessage).anyMatch(message::contains)); + } } diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/FullNodeListRefreshTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/FullNodeListRefreshTest.java index 1c0185f3882..679ec1be037 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/FullNodeListRefreshTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/FullNodeListRefreshTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/InitialNodeListRefreshTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/InitialNodeListRefreshTest.java index 85c29fc3bc1..3787bf8fe10 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/InitialNodeListRefreshTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/InitialNodeListRefreshTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -46,6 +48,8 @@ public class InitialNodeListRefreshTest { private UUID hostId1; private UUID hostId2; private UUID hostId3; + private UUID hostId4; + private UUID hostId5; @Before public void setup() { @@ -59,10 +63,12 @@ public void setup() { hostId1 = UUID.randomUUID(); hostId2 = UUID.randomUUID(); hostId3 = UUID.randomUUID(); + hostId4 = UUID.randomUUID(); + hostId5 = UUID.randomUUID(); } @Test - public void should_copy_contact_points() { + public void should_copy_contact_points_on_first_endpoint_match_only() { // Given Iterable newInfos = ImmutableList.of( @@ -74,6 +80,17 @@ public void should_copy_contact_points() { DefaultNodeInfo.builder() .withEndPoint(contactPoint2.getEndPoint()) .withHostId(hostId2) + .build(), + DefaultNodeInfo.builder().withEndPoint(endPoint3).withHostId(hostId3).build(), + DefaultNodeInfo.builder() + // address translator can translate node addresses to the same endpoints + .withEndPoint(contactPoint2.getEndPoint()) + .withHostId(hostId4) + .build(), + DefaultNodeInfo.builder() + // address translator can translate node addresses to the same endpoints + .withEndPoint(endPoint3) + .withHostId(hostId5) .build()); InitialNodeListRefresh refresh = new InitialNodeListRefresh(newInfos, ImmutableSet.of(contactPoint1, contactPoint2)); @@ -84,11 +101,26 @@ public void should_copy_contact_points() { // Then // contact points have been copied to the metadata, and completed with missing information Map newNodes = result.newMetadata.getNodes(); - assertThat(newNodes).containsOnlyKeys(hostId1, hostId2); + assertThat(newNodes).containsOnlyKeys(hostId1, hostId2, hostId3, hostId4, hostId5); assertThat(newNodes.get(hostId1)).isEqualTo(contactPoint1); assertThat(contactPoint1.getHostId()).isEqualTo(hostId1); assertThat(newNodes.get(hostId2)).isEqualTo(contactPoint2); assertThat(contactPoint2.getHostId()).isEqualTo(hostId2); + // And + // node has been added for the new endpoint + assertThat(newNodes.get(hostId3).getEndPoint()).isEqualTo(endPoint3); + assertThat(newNodes.get(hostId3).getHostId()).isEqualTo(hostId3); + // And + // nodes have been added for duplicated endpoints + assertThat(newNodes.get(hostId4).getEndPoint()).isEqualTo(contactPoint2.getEndPoint()); + assertThat(newNodes.get(hostId4).getHostId()).isEqualTo(hostId4); + assertThat(newNodes.get(hostId5).getEndPoint()).isEqualTo(endPoint3); + assertThat(newNodes.get(hostId5).getHostId()).isEqualTo(hostId5); + assertThat(result.events) + .containsExactlyInAnyOrder( + NodeStateEvent.added((DefaultNode) newNodes.get(hostId3)), + NodeStateEvent.added((DefaultNode) newNodes.get(hostId4)), + NodeStateEvent.added((DefaultNode) newNodes.get(hostId5))); } @Test diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/LoadBalancingPolicyWrapperTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/LoadBalancingPolicyWrapperTest.java index d7be8e96b0b..1a0292e3947 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/LoadBalancingPolicyWrapperTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/LoadBalancingPolicyWrapperTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -18,7 +20,6 @@ import static com.datastax.oss.driver.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyMap; -import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; @@ -41,6 +42,7 @@ import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableSet; import com.datastax.oss.driver.shaded.guava.common.collect.Lists; import java.util.Map; +import java.util.Objects; import java.util.Queue; import java.util.Set; import java.util.UUID; @@ -54,7 +56,6 @@ import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; -import org.mockito.stubbing.Answer; @RunWith(MockitoJUnitRunner.class) public class LoadBalancingPolicyWrapperTest { @@ -63,9 +64,8 @@ public class LoadBalancingPolicyWrapperTest { private DefaultNode node2; private DefaultNode node3; - private Map allNodes; private Set contactPoints; - private Queue defaultPolicysQueryPlan; + private Queue defaultPolicyQueryPlan; @Mock private InternalDriverContext context; @Mock private LoadBalancingPolicy policy1; @@ -88,16 +88,18 @@ public void setup() { node3 = TestNodeFactory.newNode(3, context); contactPoints = ImmutableSet.of(node1, node2); - allNodes = + Map allNodes = ImmutableMap.of( - node1.getHostId(), node1, node2.getHostId(), node2, node3.getHostId(), node3); + Objects.requireNonNull(node1.getHostId()), node1, + Objects.requireNonNull(node2.getHostId()), node2, + Objects.requireNonNull(node3.getHostId()), node3); when(metadataManager.getMetadata()).thenReturn(metadata); when(metadata.getNodes()).thenReturn(allNodes); when(metadataManager.getContactPoints()).thenReturn(contactPoints); when(context.getMetadataManager()).thenReturn(metadataManager); - defaultPolicysQueryPlan = Lists.newLinkedList(ImmutableList.of(node3, node2, node1)); - when(policy1.newQueryPlan(null, null)).thenReturn(defaultPolicysQueryPlan); + defaultPolicyQueryPlan = Lists.newLinkedList(ImmutableList.of(node3, node2, node1)); + when(policy1.newQueryPlan(null, null)).thenReturn(defaultPolicyQueryPlan); eventBus = spy(new EventBus("test")); when(context.getEventBus()).thenReturn(eventBus); @@ -125,7 +127,7 @@ public void should_build_query_plan_from_contact_points_before_init() { for (LoadBalancingPolicy policy : ImmutableList.of(policy1, policy2, policy3)) { verify(policy, never()).newQueryPlan(null, null); } - assertThat(queryPlan).containsOnlyElementsOf(contactPoints); + assertThat(queryPlan).hasSameElementsAs(contactPoints); } @Test @@ -142,7 +144,7 @@ public void should_fetch_query_plan_from_policy_after_init() { // Then // no-arg newQueryPlan() uses the default profile verify(policy1).newQueryPlan(null, null); - assertThat(queryPlan).isEqualTo(defaultPolicysQueryPlan); + assertThat(queryPlan).isEqualTo(defaultPolicyQueryPlan); } @Test @@ -236,25 +238,16 @@ public void should_propagate_node_states_to_policies_after_init() { @Test public void should_accumulate_events_during_init_and_replay() throws InterruptedException { // Given - // Hack to obtain concurrency: the main thread blocks in init, while another thread fires an - // event on the bus - CountDownLatch eventLatch = new CountDownLatch(3); + // Hack to obtain concurrency: the main thread releases another thread and blocks; then the + // other thread fires an event on the bus and unblocks the main thread. + CountDownLatch eventLatch = new CountDownLatch(1); CountDownLatch initLatch = new CountDownLatch(1); - Answer mockInit = - i -> { - eventLatch.countDown(); - initLatch.await(500, TimeUnit.MILLISECONDS); - return null; - }; - for (LoadBalancingPolicy policy : ImmutableList.of(policy1, policy2, policy3)) { - doAnswer(mockInit).when(policy).init(anyMap(), any(DistanceReporter.class)); - } // When Runnable runnable = () -> { try { - eventLatch.await(500, TimeUnit.MILLISECONDS); + eventLatch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } @@ -266,15 +259,14 @@ public void should_accumulate_events_during_init_and_replay() throws Interrupted wrapper.init(); // Then - // wait for init launch to signal that runnable is complete. - initLatch.await(500, TimeUnit.MILLISECONDS); + // unblock the thread that will fire the event, and waits until it finishes + eventLatch.countDown(); + boolean ok = initLatch.await(500, TimeUnit.MILLISECONDS); + assertThat(ok).isTrue(); for (LoadBalancingPolicy policy : ImmutableList.of(policy1, policy2, policy3)) { verify(policy).onDown(node1); } - if (thread.isAlive()) { - // thread still completing - sleep to allow thread to complete. - Thread.sleep(500); - } + thread.join(500); assertThat(thread.isAlive()).isFalse(); } } diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/MetadataManagerTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/MetadataManagerTest.java index e56462bb42e..f9a909400f9 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/MetadataManagerTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/MetadataManagerTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -18,6 +20,7 @@ import static com.datastax.oss.driver.Assertions.assertThat; import static com.datastax.oss.driver.Assertions.assertThatStage; import static org.awaitility.Awaitility.await; +import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; @@ -31,6 +34,7 @@ import com.datastax.oss.driver.internal.core.context.EventBus; import com.datastax.oss.driver.internal.core.context.InternalDriverContext; import com.datastax.oss.driver.internal.core.context.NettyOptions; +import com.datastax.oss.driver.internal.core.control.ControlConnection; import com.datastax.oss.driver.internal.core.metadata.schema.parsing.SchemaParserFactory; import com.datastax.oss.driver.internal.core.metadata.schema.queries.SchemaQueriesFactory; import com.datastax.oss.driver.internal.core.metrics.MetricsFactory; @@ -62,6 +66,7 @@ public class MetadataManagerTest { @Mock private InternalDriverContext context; @Mock private NettyOptions nettyOptions; + @Mock private ControlConnection controlConnection; @Mock private TopologyMonitor topologyMonitor; @Mock private DriverConfig config; @Mock private DriverExecutionProfile defaultProfile; @@ -83,6 +88,7 @@ public void setup() { when(context.getNettyOptions()).thenReturn(nettyOptions); when(context.getTopologyMonitor()).thenReturn(topologyMonitor); + when(context.getControlConnection()).thenReturn(controlConnection); when(defaultProfile.getDuration(DefaultDriverOption.METADATA_SCHEMA_WINDOW)) .thenReturn(Duration.ZERO); @@ -284,6 +290,29 @@ public void should_remove_node() { assertThat(refresh.broadcastRpcAddressToRemove).isEqualTo(broadcastRpcAddress2); } + @Test + public void refreshSchema_should_work() { + // Given + IllegalStateException expectedException = new IllegalStateException("Error we're testing"); + when(schemaQueriesFactory.newInstance()).thenThrow(expectedException); + when(topologyMonitor.refreshNodeList()) + .thenReturn(CompletableFuture.completedFuture(ImmutableList.of(mock(NodeInfo.class)))); + when(topologyMonitor.checkSchemaAgreement()) + .thenReturn(CompletableFuture.completedFuture(Boolean.TRUE)); + when(controlConnection.init(anyBoolean(), anyBoolean(), anyBoolean())) + .thenReturn(CompletableFuture.completedFuture(null)); + metadataManager.refreshNodes(); // required internal state setup for this + waitForPendingAdminTasks(() -> metadataManager.refreshes.size() == 1); // sanity check + + // When + CompletionStage result = + metadataManager.refreshSchema("foo", true, true); + + // Then + waitForPendingAdminTasks(() -> result.toCompletableFuture().isDone()); + assertThatStage(result).isFailed(t -> assertThat(t).isEqualTo(expectedException)); + } + private static class TestMetadataManager extends MetadataManager { private List refreshes = new CopyOnWriteArrayList<>(); diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/MultiplexingNodeStateListenerTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/MultiplexingNodeStateListenerTest.java new file mode 100644 index 00000000000..8e9f591510a --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/MultiplexingNodeStateListenerTest.java @@ -0,0 +1,196 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.metadata; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Mockito.verify; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.Appender; +import com.datastax.oss.driver.api.core.metadata.Node; +import com.datastax.oss.driver.api.core.metadata.NodeStateListener; +import com.datastax.oss.driver.api.core.session.Session; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.slf4j.LoggerFactory; + +@RunWith(MockitoJUnitRunner.Strict.class) +public class MultiplexingNodeStateListenerTest { + + @Mock private NodeStateListener child1; + @Mock private NodeStateListener child2; + @Mock private Node node; + @Mock private Session session; + + @Mock private Appender appender; + @Captor private ArgumentCaptor loggingEventCaptor; + + private Logger logger; + private Level initialLogLevel; + + @Before + public void addAppenders() { + logger = (Logger) LoggerFactory.getLogger(MultiplexingNodeStateListener.class); + initialLogLevel = logger.getLevel(); + logger.setLevel(Level.WARN); + logger.addAppender(appender); + } + + @After + public void removeAppenders() { + logger.detachAppender(appender); + logger.setLevel(initialLogLevel); + } + + @Test + public void should_register() { + // given + MultiplexingNodeStateListener listener = new MultiplexingNodeStateListener(); + // when + listener.register(child1); + listener.register(child2); + // then + assertThat(listener).extracting("listeners").asList().hasSize(2).contains(child1, child2); + } + + @Test + public void should_flatten_child_multiplexing_listener_via_constructor() { + // given + MultiplexingNodeStateListener listener = + new MultiplexingNodeStateListener(new MultiplexingNodeStateListener(child1, child2)); + // when + // then + assertThat(listener).extracting("listeners").asList().hasSize(2).contains(child1, child2); + } + + @Test + public void should_flatten_child_multiplexing_listener_via_register() { + // given + MultiplexingNodeStateListener listener = new MultiplexingNodeStateListener(); + // when + listener.register(new MultiplexingNodeStateListener(child1, child2)); + // then + assertThat(listener).extracting("listeners").asList().hasSize(2).contains(child1, child2); + } + + @Test + public void should_notify_onUp() { + // given + MultiplexingNodeStateListener listener = new MultiplexingNodeStateListener(child1, child2); + willThrow(new NullPointerException()).given(child1).onUp(node); + // when + listener.onUp(node); + // then + verify(child1).onUp(node); + verify(child2).onUp(node); + verify(appender).doAppend(loggingEventCaptor.capture()); + assertThat(loggingEventCaptor.getAllValues().stream().map(ILoggingEvent::getFormattedMessage)) + .contains( + "Unexpected error while notifying node state listener child1 of an onUp event. (NullPointerException: null)"); + } + + @Test + public void should_notify_onDown() { + // given + MultiplexingNodeStateListener listener = new MultiplexingNodeStateListener(child1, child2); + willThrow(new NullPointerException()).given(child1).onDown(node); + // when + listener.onDown(node); + // then + verify(child1).onDown(node); + verify(child2).onDown(node); + verify(appender).doAppend(loggingEventCaptor.capture()); + assertThat(loggingEventCaptor.getAllValues().stream().map(ILoggingEvent::getFormattedMessage)) + .contains( + "Unexpected error while notifying node state listener child1 of an onDown event. (NullPointerException: null)"); + } + + @Test + public void should_notify_onAdd() { + // given + MultiplexingNodeStateListener listener = new MultiplexingNodeStateListener(child1, child2); + willThrow(new NullPointerException()).given(child1).onAdd(node); + // when + listener.onAdd(node); + // then + verify(child1).onAdd(node); + verify(child2).onAdd(node); + verify(appender).doAppend(loggingEventCaptor.capture()); + assertThat(loggingEventCaptor.getAllValues().stream().map(ILoggingEvent::getFormattedMessage)) + .contains( + "Unexpected error while notifying node state listener child1 of an onAdd event. (NullPointerException: null)"); + } + + @Test + public void should_notify_onRemove() { + // given + MultiplexingNodeStateListener listener = new MultiplexingNodeStateListener(child1, child2); + willThrow(new NullPointerException()).given(child1).onRemove(node); + // when + listener.onRemove(node); + // then + verify(child1).onRemove(node); + verify(child2).onRemove(node); + verify(appender).doAppend(loggingEventCaptor.capture()); + assertThat(loggingEventCaptor.getAllValues().stream().map(ILoggingEvent::getFormattedMessage)) + .contains( + "Unexpected error while notifying node state listener child1 of an onRemove event. (NullPointerException: null)"); + } + + @Test + public void should_notify_onSessionReady() { + // given + MultiplexingNodeStateListener listener = new MultiplexingNodeStateListener(child1, child2); + willThrow(new NullPointerException()).given(child1).onSessionReady(session); + // when + listener.onSessionReady(session); + // then + verify(child1).onSessionReady(session); + verify(child2).onSessionReady(session); + verify(appender).doAppend(loggingEventCaptor.capture()); + assertThat(loggingEventCaptor.getAllValues().stream().map(ILoggingEvent::getFormattedMessage)) + .contains( + "Unexpected error while notifying node state listener child1 of an onSessionReady event. (NullPointerException: null)"); + } + + @Test + public void should_notify_close() throws Exception { + // given + MultiplexingNodeStateListener listener = new MultiplexingNodeStateListener(child1, child2); + Exception child1Error = new NullPointerException(); + willThrow(child1Error).given(child1).close(); + // when + listener.close(); + // then + verify(child1).close(); + verify(child2).close(); + verify(appender).doAppend(loggingEventCaptor.capture()); + assertThat(loggingEventCaptor.getAllValues().stream().map(ILoggingEvent::getFormattedMessage)) + .contains( + "Unexpected error while closing node state listener child1. (NullPointerException: null)"); + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/NodeStateManagerTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/NodeStateManagerTest.java index d1b2f47d8dc..d99b06a33ae 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/NodeStateManagerTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/NodeStateManagerTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -147,7 +149,7 @@ public void should_apply_up_event_if_node_is_unknown_or_down() { } @Test - public void should_add_node_if_up_event_and_not_in_metadata() { + public void should_refresh_node_list_if_up_event_and_not_in_metadata() { // Given new NodeStateManager(context); @@ -157,7 +159,7 @@ public void should_add_node_if_up_event_and_not_in_metadata() { // Then verify(eventBus, never()).fire(any(NodeStateEvent.class)); - verify(metadataManager).addNode(NEW_ADDRESS); + verify(metadataManager).refreshNodes(); } @Test diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/PeerRowValidatorTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/PeerRowValidatorTest.java new file mode 100644 index 00000000000..c1a189259d7 --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/PeerRowValidatorTest.java @@ -0,0 +1,124 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.datastax.oss.driver.internal.core.metadata; + +import static com.datastax.oss.driver.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.datastax.oss.driver.internal.core.adminrequest.AdminRow; +import com.tngtech.java.junit.dataprovider.DataProvider; +import com.tngtech.java.junit.dataprovider.DataProviderRunner; +import com.tngtech.java.junit.dataprovider.UseDataProvider; +import org.junit.Test; +import org.junit.runner.RunWith; + +@RunWith(DataProviderRunner.class) +public class PeerRowValidatorTest { + + @DataProvider + public static Object[][] nullColumnsV1() { + return new Object[][] { + {"rpc_address"}, {"host_id"}, {"data_center"}, {"rack"}, {"tokens"}, {"schema_version"} + }; + } + + @DataProvider + public static Object[][] nullColumnsV2() { + return new Object[][] { + {"native_address"}, + {"native_port"}, + {"host_id"}, + {"data_center"}, + {"rack"}, + {"tokens"}, + {"schema_version"} + }; + } + + @Test + @UseDataProvider("nullColumnsV1") + public void should_fail_for_invalid_peer_v1(String nullColumn) { + assertThat(PeerRowValidator.isValid(mockRowV1(nullColumn))).isFalse(); + } + + @Test + @UseDataProvider("nullColumnsV2") + public void should_fail_for_invalid_peer_v2(String nullColumn) { + assertThat(PeerRowValidator.isValid(mockRowV2(nullColumn))).isFalse(); + } + + @Test + public void should_succeed_for_valid_peer_v1() { + AdminRow peerRow = mock(AdminRow.class); + when(peerRow.isNull("host_id")).thenReturn(false); + when(peerRow.isNull("rpc_address")).thenReturn(false); + when(peerRow.isNull("native_address")).thenReturn(true); + when(peerRow.isNull("native_port")).thenReturn(true); + when(peerRow.isNull("data_center")).thenReturn(false); + when(peerRow.isNull("rack")).thenReturn(false); + when(peerRow.isNull("tokens")).thenReturn(false); + when(peerRow.isNull("schema_version")).thenReturn(false); + + assertThat(PeerRowValidator.isValid(peerRow)).isTrue(); + } + + @Test + public void should_succeed_for_valid_peer_v2() { + AdminRow peerRow = mock(AdminRow.class); + when(peerRow.isNull("host_id")).thenReturn(false); + when(peerRow.isNull("rpc_address")).thenReturn(true); + when(peerRow.isNull("native_address")).thenReturn(false); + when(peerRow.isNull("native_port")).thenReturn(false); + when(peerRow.isNull("data_center")).thenReturn(false); + when(peerRow.isNull("rack")).thenReturn(false); + when(peerRow.isNull("tokens")).thenReturn(false); + when(peerRow.isNull("schema_version")).thenReturn(false); + + assertThat(PeerRowValidator.isValid(peerRow)).isTrue(); + } + + private AdminRow mockRowV1(String nullColumn) { + AdminRow peerRow = mock(AdminRow.class); + when(peerRow.isNull("host_id")).thenReturn(nullColumn.equals("host_id")); + when(peerRow.isNull("rpc_address")).thenReturn(nullColumn.equals("rpc_address")); + when(peerRow.isNull("native_address")).thenReturn(true); + when(peerRow.isNull("native_port")).thenReturn(true); + when(peerRow.isNull("data_center")).thenReturn(nullColumn.equals("data_center")); + when(peerRow.isNull("rack")).thenReturn(nullColumn.equals("rack")); + when(peerRow.isNull("tokens")).thenReturn(nullColumn.equals("tokens")); + when(peerRow.isNull("schema_version")).thenReturn(nullColumn.equals("schema_version")); + + return peerRow; + } + + private AdminRow mockRowV2(String nullColumn) { + AdminRow peerRow = mock(AdminRow.class); + when(peerRow.isNull("host_id")).thenReturn(nullColumn.equals("host_id")); + when(peerRow.isNull("native_address")).thenReturn(nullColumn.equals("native_address")); + when(peerRow.isNull("native_port")).thenReturn(nullColumn.equals("native_port")); + when(peerRow.isNull("rpc_address")).thenReturn(true); + when(peerRow.isNull("data_center")).thenReturn(nullColumn.equals("data_center")); + when(peerRow.isNull("rack")).thenReturn(nullColumn.equals("rack")); + when(peerRow.isNull("tokens")).thenReturn(nullColumn.equals("tokens")); + when(peerRow.isNull("schema_version")).thenReturn(nullColumn.equals("schema_version")); + + return peerRow; + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/RemoveNodeRefreshTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/RemoveNodeRefreshTest.java index c783750fe5c..f2a4b36a3c3 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/RemoveNodeRefreshTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/RemoveNodeRefreshTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/SchemaAgreementCheckerTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/SchemaAgreementCheckerTest.java index dc143327ecb..5e0dfbd7802 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/SchemaAgreementCheckerTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/SchemaAgreementCheckerTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -35,11 +37,15 @@ import com.datastax.oss.driver.internal.core.metrics.MetricsFactory; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap; import com.datastax.oss.driver.shaded.guava.common.collect.Iterators; +import com.tngtech.java.junit.dataprovider.DataProvider; +import com.tngtech.java.junit.dataprovider.DataProviderRunner; +import com.tngtech.java.junit.dataprovider.UseDataProvider; import io.netty.channel.EventLoop; import java.time.Duration; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Map; +import java.util.Objects; import java.util.Queue; import java.util.UUID; import java.util.concurrent.CompletableFuture; @@ -49,14 +55,16 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.MockitoAnnotations; -@RunWith(MockitoJUnitRunner.class) +@RunWith(DataProviderRunner.class) public class SchemaAgreementCheckerTest { private static final UUID VERSION1 = UUID.randomUUID(); private static final UUID VERSION2 = UUID.randomUUID(); + private static final UUID NODE_2_HOST_ID = UUID.randomUUID(); + @Mock private InternalDriverContext context; @Mock private DriverConfig config; @Mock private DriverExecutionProfile defaultConfig; @@ -70,10 +78,11 @@ public class SchemaAgreementCheckerTest { @Before public void setup() { + MockitoAnnotations.initMocks(this); when(context.getMetricsFactory()).thenReturn(metricsFactory); node1 = TestNodeFactory.newNode(1, context); - node2 = TestNodeFactory.newNode(2, context); + node2 = TestNodeFactory.newNode(2, NODE_2_HOST_ID, context); when(defaultConfig.getDuration(DefaultDriverOption.CONTROL_CONNECTION_TIMEOUT)) .thenReturn(Duration.ofSeconds(1)); @@ -86,7 +95,12 @@ public void setup() { when(config.getDefaultProfile()).thenReturn(defaultConfig); when(context.getConfig()).thenReturn(config); - Map nodes = ImmutableMap.of(node1.getHostId(), node1, node2.getHostId(), node2); + Map nodes = + ImmutableMap.of( + Objects.requireNonNull(node1.getHostId()), + node1, + Objects.requireNonNull(node2.getHostId()), + node2); when(metadata.getNodes()).thenReturn(nodes); when(metadataManager.getMetadata()).thenReturn(metadata); when(context.getMetadataManager()).thenReturn(metadataManager); @@ -124,9 +138,8 @@ public void should_succeed_if_only_one_node() { checker.stubQueries( new StubbedQuery( "SELECT schema_version FROM system.local WHERE key='local'", - mockResult(mockRow(null, VERSION1))), - new StubbedQuery( - "SELECT host_id, schema_version FROM system.peers", mockResult(/*empty*/ ))); + mockResult(mockLocalRow(VERSION1))), + new StubbedQuery("SELECT * FROM system.peers", mockResult(/*empty*/ ))); // When CompletionStage future = checker.run(); @@ -142,10 +155,8 @@ public void should_succeed_if_versions_match_on_first_try() { checker.stubQueries( new StubbedQuery( "SELECT schema_version FROM system.local WHERE key='local'", - mockResult(mockRow(null, VERSION1))), - new StubbedQuery( - "SELECT host_id, schema_version FROM system.peers", - mockResult(mockRow(node2.getHostId(), VERSION1)))); + mockResult(mockLocalRow(VERSION1))), + new StubbedQuery("SELECT * FROM system.peers", mockResult(mockValidPeerRow(VERSION1)))); // When CompletionStage future = checker.run(); @@ -162,10 +173,8 @@ public void should_ignore_down_peers() { checker.stubQueries( new StubbedQuery( "SELECT schema_version FROM system.local WHERE key='local'", - mockResult(mockRow(null, VERSION1))), - new StubbedQuery( - "SELECT host_id, schema_version FROM system.peers", - mockResult(mockRow(node2.getHostId(), VERSION2)))); + mockResult(mockLocalRow(VERSION1))), + new StubbedQuery("SELECT * FROM system.peers", mockResult(mockValidPeerRow(VERSION2)))); // When CompletionStage future = checker.run(); @@ -174,17 +183,34 @@ public void should_ignore_down_peers() { assertThatStage(future).isSuccess(b -> assertThat(b).isTrue()); } + @DataProvider + public static Object[][] malformedPeer() { + return new Object[][] { + // missing host id + {mockPeerRow(null, VERSION2, true, true, true, true)}, + // missing schema version + {mockPeerRow(NODE_2_HOST_ID, null, true, true, true, true)}, + // missing datacenter + {mockPeerRow(NODE_2_HOST_ID, VERSION2, false, true, true, true)}, + // missing rack + {mockPeerRow(NODE_2_HOST_ID, VERSION2, true, false, true, true)}, + // missing RPC address + {mockPeerRow(NODE_2_HOST_ID, VERSION2, true, true, false, true)}, + // missing tokens + {mockPeerRow(NODE_2_HOST_ID, VERSION2, true, true, true, false)}, + }; + } + @Test - public void should_ignore_malformed_rows() { + @UseDataProvider("malformedPeer") + public void should_ignore_malformed_rows(AdminRow malformedPeer) { // Given TestSchemaAgreementChecker checker = new TestSchemaAgreementChecker(channel, context); checker.stubQueries( new StubbedQuery( "SELECT schema_version FROM system.local WHERE key='local'", - mockResult(mockRow(null, VERSION1))), - new StubbedQuery( - "SELECT host_id, schema_version FROM system.peers", - mockResult(mockRow(null, VERSION2)))); // missing host_id + mockResult(mockLocalRow(VERSION1))), + new StubbedQuery("SELECT * FROM system.peers", mockResult(malformedPeer))); // When CompletionStage future = checker.run(); @@ -201,18 +227,14 @@ public void should_reschedule_if_versions_do_not_match_on_first_try() { // First round new StubbedQuery( "SELECT schema_version FROM system.local WHERE key='local'", - mockResult(mockRow(null, VERSION1))), - new StubbedQuery( - "SELECT host_id, schema_version FROM system.peers", - mockResult(mockRow(node2.getHostId(), VERSION2))), + mockResult(mockLocalRow(VERSION1))), + new StubbedQuery("SELECT * FROM system.peers", mockResult(mockValidPeerRow(VERSION2))), // Second round new StubbedQuery( "SELECT schema_version FROM system.local WHERE key='local'", - mockResult(mockRow(null, VERSION1))), - new StubbedQuery( - "SELECT host_id, schema_version FROM system.peers", - mockResult(mockRow(node2.getHostId(), VERSION1)))); + mockResult(mockLocalRow(VERSION1))), + new StubbedQuery("SELECT * FROM system.peers", mockResult(mockValidPeerRow(VERSION1)))); // When CompletionStage future = checker.run(); @@ -230,10 +252,8 @@ public void should_fail_if_versions_do_not_match_after_timeout() { checker.stubQueries( new StubbedQuery( "SELECT schema_version FROM system.local WHERE key='local'", - mockResult(mockRow(null, VERSION1))), - new StubbedQuery( - "SELECT host_id, schema_version FROM system.peers", - mockResult(mockRow(node2.getHostId(), VERSION1)))); + mockResult(mockLocalRow(VERSION1))), + new StubbedQuery("SELECT * FROM system.peers", mockResult(mockValidPeerRow(VERSION1)))); // When CompletionStage future = checker.run(); @@ -274,10 +294,35 @@ private StubbedQuery(String queryString, AdminResult result) { } } - private AdminRow mockRow(UUID hostId, UUID schemaVersion) { + private AdminRow mockLocalRow(@SuppressWarnings("SameParameterValue") UUID schemaVersion) { + AdminRow row = mock(AdminRow.class); + when(row.getUuid("host_id")).thenReturn(node1.getHostId()); + when(row.getUuid("schema_version")).thenReturn(schemaVersion); + return row; + } + + private AdminRow mockValidPeerRow(UUID schemaVersion) { + return mockPeerRow(node2.getHostId(), schemaVersion, true, true, true, true); + } + + private static AdminRow mockPeerRow( + UUID hostId, + UUID schemaVersion, + boolean hasDatacenter, + boolean hasRack, + boolean hasRpcAddress, + boolean hasTokens) { AdminRow row = mock(AdminRow.class); when(row.getUuid("host_id")).thenReturn(hostId); + when(row.isNull("host_id")).thenReturn(hostId == null); when(row.getUuid("schema_version")).thenReturn(schemaVersion); + when(row.isNull("schema_version")).thenReturn(schemaVersion == null); + when(row.isNull("data_center")).thenReturn(!hasDatacenter); + when(row.isNull("rack")).thenReturn(!hasRack); + when(row.isNull("tokens")).thenReturn(!hasTokens); + when(row.isNull("rpc_address")).thenReturn(!hasRpcAddress); + when(row.isNull("native_address")).thenReturn(true); + when(row.isNull("native_port")).thenReturn(true); return row; } diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/TestNodeFactory.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/TestNodeFactory.java index 54ab7755c51..7986834bca2 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/TestNodeFactory.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/TestNodeFactory.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -28,6 +30,13 @@ public static DefaultNode newNode(int lastIpByte, InternalDriverContext context) return node; } + public static DefaultNode newNode(int lastIpByte, UUID hostId, InternalDriverContext context) { + DefaultNode node = newContactPoint(lastIpByte, context); + node.hostId = hostId; + node.broadcastRpcAddress = ((InetSocketAddress) node.getEndPoint().resolve()); + return node; + } + public static DefaultNode newContactPoint(int lastIpByte, InternalDriverContext context) { DefaultEndPoint endPoint = newEndPoint(lastIpByte); return new DefaultNode(endPoint, context); diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/IndexMetadataTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/IndexMetadataTest.java index b2113052092..b772d243976 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/IndexMetadataTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/IndexMetadataTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/MultiplexingSchemaChangeListenerTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/MultiplexingSchemaChangeListenerTest.java new file mode 100644 index 00000000000..a7dee02f5e3 --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/MultiplexingSchemaChangeListenerTest.java @@ -0,0 +1,452 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.metadata.schema; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Mockito.verify; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.Appender; +import com.datastax.oss.driver.api.core.metadata.schema.AggregateMetadata; +import com.datastax.oss.driver.api.core.metadata.schema.FunctionMetadata; +import com.datastax.oss.driver.api.core.metadata.schema.KeyspaceMetadata; +import com.datastax.oss.driver.api.core.metadata.schema.SchemaChangeListener; +import com.datastax.oss.driver.api.core.metadata.schema.TableMetadata; +import com.datastax.oss.driver.api.core.metadata.schema.ViewMetadata; +import com.datastax.oss.driver.api.core.session.Session; +import com.datastax.oss.driver.api.core.type.UserDefinedType; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.slf4j.LoggerFactory; + +@RunWith(MockitoJUnitRunner.Strict.class) +public class MultiplexingSchemaChangeListenerTest { + + @Mock private SchemaChangeListener child1; + @Mock private SchemaChangeListener child2; + @Mock private Session session; + @Mock private KeyspaceMetadata keyspace1, keyspace2; + @Mock private TableMetadata table1, table2; + @Mock private UserDefinedType userDefinedType1, userDefinedType2; + @Mock private FunctionMetadata function1, function2; + @Mock private AggregateMetadata aggregate1, aggregate2; + @Mock private ViewMetadata view1, view2; + + @Mock private Appender appender; + @Captor private ArgumentCaptor loggingEventCaptor; + + private Logger logger; + private Level initialLogLevel; + + @Before + public void addAppenders() { + logger = (Logger) LoggerFactory.getLogger(MultiplexingSchemaChangeListener.class); + initialLogLevel = logger.getLevel(); + logger.setLevel(Level.WARN); + logger.addAppender(appender); + } + + @After + public void removeAppenders() { + logger.detachAppender(appender); + logger.setLevel(initialLogLevel); + } + + @Test + public void should_register() { + // given + MultiplexingSchemaChangeListener listener = new MultiplexingSchemaChangeListener(); + // when + listener.register(child1); + listener.register(child2); + // then + assertThat(listener).extracting("listeners").asList().hasSize(2).contains(child1, child2); + } + + @Test + public void should_flatten_child_multiplexing_listener_via_constructor() { + // given + MultiplexingSchemaChangeListener listener = + new MultiplexingSchemaChangeListener(new MultiplexingSchemaChangeListener(child1, child2)); + // when + // then + assertThat(listener).extracting("listeners").asList().hasSize(2).contains(child1, child2); + } + + @Test + public void should_flatten_child_multiplexing_listener_via_register() { + // given + MultiplexingSchemaChangeListener listener = new MultiplexingSchemaChangeListener(); + // when + listener.register(new MultiplexingSchemaChangeListener(child1, child2)); + // then + assertThat(listener).extracting("listeners").asList().hasSize(2).contains(child1, child2); + } + + @Test + public void should_notify_onKeyspaceCreated() { + // given + MultiplexingSchemaChangeListener listener = + new MultiplexingSchemaChangeListener(child1, child2); + willThrow(new NullPointerException()).given(child1).onKeyspaceCreated(keyspace1); + // when + listener.onKeyspaceCreated(keyspace1); + // then + verify(child1).onKeyspaceCreated(keyspace1); + verify(child2).onKeyspaceCreated(keyspace1); + verify(appender).doAppend(loggingEventCaptor.capture()); + assertThat(loggingEventCaptor.getAllValues().stream().map(ILoggingEvent::getFormattedMessage)) + .contains( + "Unexpected error while notifying schema change listener child1 of an onKeyspaceCreated event. (NullPointerException: null)"); + } + + @Test + public void should_notify_onKeyspaceDropped() { + // given + MultiplexingSchemaChangeListener listener = + new MultiplexingSchemaChangeListener(child1, child2); + willThrow(new NullPointerException()).given(child1).onKeyspaceDropped(keyspace1); + // when + listener.onKeyspaceDropped(keyspace1); + // then + verify(child1).onKeyspaceDropped(keyspace1); + verify(child2).onKeyspaceDropped(keyspace1); + verify(appender).doAppend(loggingEventCaptor.capture()); + assertThat(loggingEventCaptor.getAllValues().stream().map(ILoggingEvent::getFormattedMessage)) + .contains( + "Unexpected error while notifying schema change listener child1 of an onKeyspaceDropped event. (NullPointerException: null)"); + } + + @Test + public void should_notify_onKeyspaceUpdated() { + // given + MultiplexingSchemaChangeListener listener = + new MultiplexingSchemaChangeListener(child1, child2); + willThrow(new NullPointerException()).given(child1).onKeyspaceUpdated(keyspace1, keyspace2); + // when + listener.onKeyspaceUpdated(keyspace1, keyspace2); + // then + verify(child1).onKeyspaceUpdated(keyspace1, keyspace2); + verify(child2).onKeyspaceUpdated(keyspace1, keyspace2); + verify(appender).doAppend(loggingEventCaptor.capture()); + assertThat(loggingEventCaptor.getAllValues().stream().map(ILoggingEvent::getFormattedMessage)) + .contains( + "Unexpected error while notifying schema change listener child1 of an onKeyspaceUpdated event. (NullPointerException: null)"); + } + + @Test + public void should_notify_onTableCreated() { + // given + MultiplexingSchemaChangeListener listener = + new MultiplexingSchemaChangeListener(child1, child2); + willThrow(new NullPointerException()).given(child1).onTableCreated(table1); + // when + listener.onTableCreated(table1); + // then + verify(child1).onTableCreated(table1); + verify(child2).onTableCreated(table1); + verify(appender).doAppend(loggingEventCaptor.capture()); + assertThat(loggingEventCaptor.getAllValues().stream().map(ILoggingEvent::getFormattedMessage)) + .contains( + "Unexpected error while notifying schema change listener child1 of an onTableCreated event. (NullPointerException: null)"); + } + + @Test + public void should_notify_onTableDropped() { + // given + MultiplexingSchemaChangeListener listener = + new MultiplexingSchemaChangeListener(child1, child2); + willThrow(new NullPointerException()).given(child1).onTableDropped(table1); + // when + listener.onTableDropped(table1); + // then + verify(child1).onTableDropped(table1); + verify(child2).onTableDropped(table1); + verify(appender).doAppend(loggingEventCaptor.capture()); + assertThat(loggingEventCaptor.getAllValues().stream().map(ILoggingEvent::getFormattedMessage)) + .contains( + "Unexpected error while notifying schema change listener child1 of an onTableDropped event. (NullPointerException: null)"); + } + + @Test + public void should_notify_onTableUpdated() { + // given + MultiplexingSchemaChangeListener listener = + new MultiplexingSchemaChangeListener(child1, child2); + willThrow(new NullPointerException()).given(child1).onTableUpdated(table1, table2); + // when + listener.onTableUpdated(table1, table2); + // then + verify(child1).onTableUpdated(table1, table2); + verify(child2).onTableUpdated(table1, table2); + verify(appender).doAppend(loggingEventCaptor.capture()); + assertThat(loggingEventCaptor.getAllValues().stream().map(ILoggingEvent::getFormattedMessage)) + .contains( + "Unexpected error while notifying schema change listener child1 of an onTableUpdated event. (NullPointerException: null)"); + } + + @Test + public void should_notify_onUserDefinedTypeCreated() { + // given + MultiplexingSchemaChangeListener listener = + new MultiplexingSchemaChangeListener(child1, child2); + willThrow(new NullPointerException()).given(child1).onUserDefinedTypeCreated(userDefinedType1); + // when + listener.onUserDefinedTypeCreated(userDefinedType1); + // then + verify(child1).onUserDefinedTypeCreated(userDefinedType1); + verify(child2).onUserDefinedTypeCreated(userDefinedType1); + verify(appender).doAppend(loggingEventCaptor.capture()); + assertThat(loggingEventCaptor.getAllValues().stream().map(ILoggingEvent::getFormattedMessage)) + .contains( + "Unexpected error while notifying schema change listener child1 of an onUserDefinedTypeCreated event. (NullPointerException: null)"); + } + + @Test + public void should_notify_onUserDefinedTypeDropped() { + // given + MultiplexingSchemaChangeListener listener = + new MultiplexingSchemaChangeListener(child1, child2); + willThrow(new NullPointerException()).given(child1).onUserDefinedTypeDropped(userDefinedType1); + // when + listener.onUserDefinedTypeDropped(userDefinedType1); + // then + verify(child1).onUserDefinedTypeDropped(userDefinedType1); + verify(child2).onUserDefinedTypeDropped(userDefinedType1); + verify(appender).doAppend(loggingEventCaptor.capture()); + assertThat(loggingEventCaptor.getAllValues().stream().map(ILoggingEvent::getFormattedMessage)) + .contains( + "Unexpected error while notifying schema change listener child1 of an onUserDefinedTypeDropped event. (NullPointerException: null)"); + } + + @Test + public void should_notify_onUserDefinedTypeUpdated() { + // given + MultiplexingSchemaChangeListener listener = + new MultiplexingSchemaChangeListener(child1, child2); + willThrow(new NullPointerException()) + .given(child1) + .onUserDefinedTypeUpdated(userDefinedType1, userDefinedType2); + // when + listener.onUserDefinedTypeUpdated(userDefinedType1, userDefinedType2); + // then + verify(child1).onUserDefinedTypeUpdated(userDefinedType1, userDefinedType2); + verify(child2).onUserDefinedTypeUpdated(userDefinedType1, userDefinedType2); + verify(appender).doAppend(loggingEventCaptor.capture()); + assertThat(loggingEventCaptor.getAllValues().stream().map(ILoggingEvent::getFormattedMessage)) + .contains( + "Unexpected error while notifying schema change listener child1 of an onUserDefinedTypeUpdated event. (NullPointerException: null)"); + } + + @Test + public void should_notify_onFunctionCreated() { + // given + MultiplexingSchemaChangeListener listener = + new MultiplexingSchemaChangeListener(child1, child2); + willThrow(new NullPointerException()).given(child1).onFunctionCreated(function1); + // when + listener.onFunctionCreated(function1); + // then + verify(child1).onFunctionCreated(function1); + verify(child2).onFunctionCreated(function1); + verify(appender).doAppend(loggingEventCaptor.capture()); + assertThat(loggingEventCaptor.getAllValues().stream().map(ILoggingEvent::getFormattedMessage)) + .contains( + "Unexpected error while notifying schema change listener child1 of an onFunctionCreated event. (NullPointerException: null)"); + } + + @Test + public void should_notify_onFunctionDropped() { + // given + MultiplexingSchemaChangeListener listener = + new MultiplexingSchemaChangeListener(child1, child2); + willThrow(new NullPointerException()).given(child1).onFunctionDropped(function1); + // when + listener.onFunctionDropped(function1); + // then + verify(child1).onFunctionDropped(function1); + verify(child2).onFunctionDropped(function1); + verify(appender).doAppend(loggingEventCaptor.capture()); + assertThat(loggingEventCaptor.getAllValues().stream().map(ILoggingEvent::getFormattedMessage)) + .contains( + "Unexpected error while notifying schema change listener child1 of an onFunctionDropped event. (NullPointerException: null)"); + } + + @Test + public void should_notify_onFunctionUpdated() { + // given + MultiplexingSchemaChangeListener listener = + new MultiplexingSchemaChangeListener(child1, child2); + willThrow(new NullPointerException()).given(child1).onFunctionUpdated(function1, function2); + // when + listener.onFunctionUpdated(function1, function2); + // then + verify(child1).onFunctionUpdated(function1, function2); + verify(child2).onFunctionUpdated(function1, function2); + verify(appender).doAppend(loggingEventCaptor.capture()); + assertThat(loggingEventCaptor.getAllValues().stream().map(ILoggingEvent::getFormattedMessage)) + .contains( + "Unexpected error while notifying schema change listener child1 of an onFunctionUpdated event. (NullPointerException: null)"); + } + + @Test + public void should_notify_onAggregateCreated() { + // given + MultiplexingSchemaChangeListener listener = + new MultiplexingSchemaChangeListener(child1, child2); + willThrow(new NullPointerException()).given(child1).onAggregateCreated(aggregate1); + // when + listener.onAggregateCreated(aggregate1); + // then + verify(child1).onAggregateCreated(aggregate1); + verify(child2).onAggregateCreated(aggregate1); + verify(appender).doAppend(loggingEventCaptor.capture()); + assertThat(loggingEventCaptor.getAllValues().stream().map(ILoggingEvent::getFormattedMessage)) + .contains( + "Unexpected error while notifying schema change listener child1 of an onAggregateCreated event. (NullPointerException: null)"); + } + + @Test + public void should_notify_onAggregateDropped() { + // given + MultiplexingSchemaChangeListener listener = + new MultiplexingSchemaChangeListener(child1, child2); + willThrow(new NullPointerException()).given(child1).onAggregateDropped(aggregate1); + // when + listener.onAggregateDropped(aggregate1); + // then + verify(child1).onAggregateDropped(aggregate1); + verify(child2).onAggregateDropped(aggregate1); + verify(appender).doAppend(loggingEventCaptor.capture()); + assertThat(loggingEventCaptor.getAllValues().stream().map(ILoggingEvent::getFormattedMessage)) + .contains( + "Unexpected error while notifying schema change listener child1 of an onAggregateDropped event. (NullPointerException: null)"); + } + + @Test + public void should_notify_onAggregateUpdated() { + // given + MultiplexingSchemaChangeListener listener = + new MultiplexingSchemaChangeListener(child1, child2); + willThrow(new NullPointerException()).given(child1).onAggregateUpdated(aggregate1, aggregate2); + // when + listener.onAggregateUpdated(aggregate1, aggregate2); + // then + verify(child1).onAggregateUpdated(aggregate1, aggregate2); + verify(child2).onAggregateUpdated(aggregate1, aggregate2); + verify(appender).doAppend(loggingEventCaptor.capture()); + assertThat(loggingEventCaptor.getAllValues().stream().map(ILoggingEvent::getFormattedMessage)) + .contains( + "Unexpected error while notifying schema change listener child1 of an onAggregateUpdated event. (NullPointerException: null)"); + } + + @Test + public void should_notify_onViewCreated() { + // given + MultiplexingSchemaChangeListener listener = + new MultiplexingSchemaChangeListener(child1, child2); + willThrow(new NullPointerException()).given(child1).onViewCreated(view1); + // when + listener.onViewCreated(view1); + // then + verify(child1).onViewCreated(view1); + verify(child2).onViewCreated(view1); + verify(appender).doAppend(loggingEventCaptor.capture()); + assertThat(loggingEventCaptor.getAllValues().stream().map(ILoggingEvent::getFormattedMessage)) + .contains( + "Unexpected error while notifying schema change listener child1 of an onViewCreated event. (NullPointerException: null)"); + } + + @Test + public void should_notify_onViewDropped() { + // given + MultiplexingSchemaChangeListener listener = + new MultiplexingSchemaChangeListener(child1, child2); + willThrow(new NullPointerException()).given(child1).onViewDropped(view1); + // when + listener.onViewDropped(view1); + // then + verify(child1).onViewDropped(view1); + verify(child2).onViewDropped(view1); + verify(appender).doAppend(loggingEventCaptor.capture()); + assertThat(loggingEventCaptor.getAllValues().stream().map(ILoggingEvent::getFormattedMessage)) + .contains( + "Unexpected error while notifying schema change listener child1 of an onViewDropped event. (NullPointerException: null)"); + } + + @Test + public void should_notify_onViewUpdated() { + // given + MultiplexingSchemaChangeListener listener = + new MultiplexingSchemaChangeListener(child1, child2); + willThrow(new NullPointerException()).given(child1).onViewUpdated(view1, view2); + // when + listener.onViewUpdated(view1, view2); + // then + verify(child1).onViewUpdated(view1, view2); + verify(child2).onViewUpdated(view1, view2); + verify(appender).doAppend(loggingEventCaptor.capture()); + assertThat(loggingEventCaptor.getAllValues().stream().map(ILoggingEvent::getFormattedMessage)) + .contains( + "Unexpected error while notifying schema change listener child1 of an onViewUpdated event. (NullPointerException: null)"); + } + + @Test + public void should_notify_onSessionReady() { + // given + MultiplexingSchemaChangeListener listener = + new MultiplexingSchemaChangeListener(child1, child2); + willThrow(new NullPointerException()).given(child1).onSessionReady(session); + // when + listener.onSessionReady(session); + // then + verify(child1).onSessionReady(session); + verify(child2).onSessionReady(session); + verify(appender).doAppend(loggingEventCaptor.capture()); + assertThat(loggingEventCaptor.getAllValues().stream().map(ILoggingEvent::getFormattedMessage)) + .contains( + "Unexpected error while notifying schema change listener child1 of an onSessionReady event. (NullPointerException: null)"); + } + + @Test + public void should_notify_close() throws Exception { + // given + MultiplexingSchemaChangeListener listener = + new MultiplexingSchemaChangeListener(child1, child2); + Exception child1Error = new NullPointerException(); + willThrow(child1Error).given(child1).close(); + // when + listener.close(); + // then + verify(child1).close(); + verify(child2).close(); + verify(appender).doAppend(loggingEventCaptor.capture()); + assertThat(loggingEventCaptor.getAllValues().stream().map(ILoggingEvent::getFormattedMessage)) + .contains( + "Unexpected error while closing schema change listener child1. (NullPointerException: null)"); + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/TableMetadataTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/TableMetadataTest.java new file mode 100644 index 00000000000..03d63230992 --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/TableMetadataTest.java @@ -0,0 +1,67 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.metadata.schema; + +import static com.datastax.oss.driver.api.core.CqlIdentifier.fromCql; +import static org.assertj.core.api.Assertions.assertThat; + +import com.datastax.oss.driver.api.core.metadata.schema.TableMetadata; +import com.datastax.oss.driver.internal.core.type.DefaultVectorType; +import com.datastax.oss.driver.internal.core.type.PrimitiveType; +import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap; +import com.datastax.oss.protocol.internal.ProtocolConstants.DataType; +import com.google.common.collect.ImmutableList; +import java.util.UUID; +import org.junit.Test; + +public class TableMetadataTest { + + /** Tests CASSJAVA-2 */ + @Test + public void should_describe_table_with_vector_correctly() { + TableMetadata tableMetadata = + new DefaultTableMetadata( + fromCql("ks"), + fromCql("tb"), + UUID.randomUUID(), + false, + false, + ImmutableList.of( + new DefaultColumnMetadata( + fromCql("ks"), + fromCql("ks"), + fromCql("tb"), + new PrimitiveType(DataType.ASCII), + false)), + ImmutableMap.of(), + ImmutableMap.of( + fromCql("a"), + new DefaultColumnMetadata( + fromCql("ks"), + fromCql("ks"), + fromCql("tb"), + new DefaultVectorType(new PrimitiveType(DataType.INT), 3), + false)), + ImmutableMap.of(), + ImmutableMap.of()); + + String describe1 = tableMetadata.describe(true); + + assertThat(describe1).contains("vector,"); + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/AggregateParserTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/AggregateParserTest.java index ee26b25c95d..9cf5ba60983 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/AggregateParserTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/AggregateParserTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -56,7 +58,9 @@ public class AggregateParserTest extends SchemaParserTestBase { "0"); @Before + @Override public void setup() { + super.setup(); when(context.getCodecRegistry()).thenReturn(CodecRegistry.DEFAULT); when(context.getProtocolVersion()).thenReturn(ProtocolVersion.DEFAULT); } diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/DataTypeClassNameParserTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/DataTypeClassNameParserTest.java index 21ff579464d..84f5c09317f 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/DataTypeClassNameParserTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/DataTypeClassNameParserTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -19,6 +21,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; +import com.datastax.oss.driver.TestDataProviders; import com.datastax.oss.driver.api.core.CqlIdentifier; import com.datastax.oss.driver.api.core.type.DataType; import com.datastax.oss.driver.api.core.type.DataTypes; @@ -27,14 +30,17 @@ import com.datastax.oss.driver.api.core.type.UserDefinedType; import com.datastax.oss.driver.internal.core.context.InternalDriverContext; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap; +import com.tngtech.java.junit.dataprovider.DataProviderRunner; +import com.tngtech.java.junit.dataprovider.UseDataProvider; +import java.util.Locale; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.MockitoAnnotations; -@RunWith(MockitoJUnitRunner.class) +@RunWith(DataProviderRunner.class) public class DataTypeClassNameParserTest { private static final CqlIdentifier KEYSPACE_ID = CqlIdentifier.fromInternal("ks"); @@ -44,131 +50,167 @@ public class DataTypeClassNameParserTest { @Before public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); parser = new DataTypeClassNameParser(); } @Test - public void should_parse_native_types() { - for (Map.Entry entry : - DataTypeClassNameParser.NATIVE_TYPES_BY_CLASS_NAME.entrySet()) { - - String className = entry.getKey(); - DataType expectedType = entry.getValue(); - - assertThat(parse(className)).isEqualTo(expectedType); + @UseDataProvider(location = TestDataProviders.class, value = "locales") + public void should_parse_native_types(Locale locale) { + Locale def = Locale.getDefault(); + try { + Locale.setDefault(locale); + for (Map.Entry entry : + DataTypeClassNameParser.NATIVE_TYPES_BY_CLASS_NAME.entrySet()) { + + String className = entry.getKey(); + DataType expectedType = entry.getValue(); + + assertThat(parse(className)).isEqualTo(expectedType); + } + } finally { + Locale.setDefault(def); } } @Test - public void should_parse_collection_types() { - assertThat( - parse( - "org.apache.cassandra.db.marshal.ListType(" - + "org.apache.cassandra.db.marshal.UTF8Type)")) - .isEqualTo(DataTypes.listOf(DataTypes.TEXT)); - - assertThat( - parse( - "org.apache.cassandra.db.marshal.FrozenType(" - + ("org.apache.cassandra.db.marshal.ListType(" - + "org.apache.cassandra.db.marshal.UTF8Type))"))) - .isEqualTo(DataTypes.frozenListOf(DataTypes.TEXT)); - - assertThat( - parse( - "org.apache.cassandra.db.marshal.SetType(" - + "org.apache.cassandra.db.marshal.UTF8Type)")) - .isEqualTo(DataTypes.setOf(DataTypes.TEXT)); - - assertThat( - parse( - "org.apache.cassandra.db.marshal.MapType(" - + "org.apache.cassandra.db.marshal.UTF8Type," - + "org.apache.cassandra.db.marshal.UTF8Type)")) - .isEqualTo(DataTypes.mapOf(DataTypes.TEXT, DataTypes.TEXT)); - - assertThat( - parse( - "org.apache.cassandra.db.marshal.MapType(" - + "org.apache.cassandra.db.marshal.UTF8Type," - + "org.apache.cassandra.db.marshal.FrozenType(" - + ("org.apache.cassandra.db.marshal.MapType(" - + "org.apache.cassandra.db.marshal.Int32Type," - + "org.apache.cassandra.db.marshal.Int32Type)))"))) - .isEqualTo( - DataTypes.mapOf(DataTypes.TEXT, DataTypes.frozenMapOf(DataTypes.INT, DataTypes.INT))); + @UseDataProvider(location = TestDataProviders.class, value = "locales") + public void should_parse_collection_types(Locale locale) { + Locale def = Locale.getDefault(); + try { + Locale.setDefault(locale); + assertThat( + parse( + "org.apache.cassandra.db.marshal.ListType(" + + "org.apache.cassandra.db.marshal.UTF8Type)")) + .isEqualTo(DataTypes.listOf(DataTypes.TEXT)); + + assertThat( + parse( + "org.apache.cassandra.db.marshal.FrozenType(" + + ("org.apache.cassandra.db.marshal.ListType(" + + "org.apache.cassandra.db.marshal.UTF8Type))"))) + .isEqualTo(DataTypes.frozenListOf(DataTypes.TEXT)); + + assertThat( + parse( + "org.apache.cassandra.db.marshal.SetType(" + + "org.apache.cassandra.db.marshal.UTF8Type)")) + .isEqualTo(DataTypes.setOf(DataTypes.TEXT)); + + assertThat( + parse( + "org.apache.cassandra.db.marshal.MapType(" + + "org.apache.cassandra.db.marshal.UTF8Type," + + "org.apache.cassandra.db.marshal.UTF8Type)")) + .isEqualTo(DataTypes.mapOf(DataTypes.TEXT, DataTypes.TEXT)); + + assertThat( + parse( + "org.apache.cassandra.db.marshal.MapType(" + + "org.apache.cassandra.db.marshal.UTF8Type," + + "org.apache.cassandra.db.marshal.FrozenType(" + + ("org.apache.cassandra.db.marshal.MapType(" + + "org.apache.cassandra.db.marshal.Int32Type," + + "org.apache.cassandra.db.marshal.Int32Type)))"))) + .isEqualTo( + DataTypes.mapOf(DataTypes.TEXT, DataTypes.frozenMapOf(DataTypes.INT, DataTypes.INT))); + } finally { + Locale.setDefault(def); + } } @Test - public void should_parse_user_type_when_definition_not_already_available() { - UserDefinedType addressType = - (UserDefinedType) - parse( - "org.apache.cassandra.db.marshal.UserType(" - + "foo,61646472657373," - + ("737472656574:org.apache.cassandra.db.marshal.UTF8Type," - + "7a6970636f6465:org.apache.cassandra.db.marshal.Int32Type," - + ("70686f6e6573:org.apache.cassandra.db.marshal.SetType(" - + "org.apache.cassandra.db.marshal.UserType(foo,70686f6e65," - + "6e616d65:org.apache.cassandra.db.marshal.UTF8Type," - + "6e756d626572:org.apache.cassandra.db.marshal.UTF8Type)") - + "))")); - - assertThat(addressType.getKeyspace().asInternal()).isEqualTo("foo"); - assertThat(addressType.getName().asInternal()).isEqualTo("address"); - assertThat(addressType.isFrozen()).isTrue(); - assertThat(addressType.getFieldNames().size()).isEqualTo(3); - - assertThat(addressType.getFieldNames().get(0).asInternal()).isEqualTo("street"); - assertThat(addressType.getFieldTypes().get(0)).isEqualTo(DataTypes.TEXT); - - assertThat(addressType.getFieldNames().get(1).asInternal()).isEqualTo("zipcode"); - assertThat(addressType.getFieldTypes().get(1)).isEqualTo(DataTypes.INT); - - assertThat(addressType.getFieldNames().get(2).asInternal()).isEqualTo("phones"); - DataType phonesType = addressType.getFieldTypes().get(2); - assertThat(phonesType).isInstanceOf(SetType.class); - UserDefinedType phoneType = ((UserDefinedType) ((SetType) phonesType).getElementType()); - - assertThat(phoneType.getKeyspace().asInternal()).isEqualTo("foo"); - assertThat(phoneType.getName().asInternal()).isEqualTo("phone"); - assertThat(phoneType.isFrozen()).isTrue(); - assertThat(phoneType.getFieldNames().size()).isEqualTo(2); - - assertThat(phoneType.getFieldNames().get(0).asInternal()).isEqualTo("name"); - assertThat(phoneType.getFieldTypes().get(0)).isEqualTo(DataTypes.TEXT); - - assertThat(phoneType.getFieldNames().get(1).asInternal()).isEqualTo("number"); - assertThat(phoneType.getFieldTypes().get(1)).isEqualTo(DataTypes.TEXT); + @UseDataProvider(location = TestDataProviders.class, value = "locales") + public void should_parse_user_type_when_definition_not_already_available(Locale locale) { + Locale def = Locale.getDefault(); + try { + Locale.setDefault(locale); + UserDefinedType addressType = + (UserDefinedType) + parse( + "org.apache.cassandra.db.marshal.UserType(" + + "foo,61646472657373," + + ("737472656574:org.apache.cassandra.db.marshal.UTF8Type," + + "7a6970636f6465:org.apache.cassandra.db.marshal.Int32Type," + + ("70686f6e6573:org.apache.cassandra.db.marshal.SetType(" + + "org.apache.cassandra.db.marshal.UserType(foo,70686f6e65," + + "6e616d65:org.apache.cassandra.db.marshal.UTF8Type," + + "6e756d626572:org.apache.cassandra.db.marshal.UTF8Type)") + + "))")); + + assertThat(addressType.getKeyspace().asInternal()).isEqualTo("foo"); + assertThat(addressType.getName().asInternal()).isEqualTo("address"); + assertThat(addressType.isFrozen()).isTrue(); + assertThat(addressType.getFieldNames().size()).isEqualTo(3); + + assertThat(addressType.getFieldNames().get(0).asInternal()).isEqualTo("street"); + assertThat(addressType.getFieldTypes().get(0)).isEqualTo(DataTypes.TEXT); + + assertThat(addressType.getFieldNames().get(1).asInternal()).isEqualTo("zipcode"); + assertThat(addressType.getFieldTypes().get(1)).isEqualTo(DataTypes.INT); + + assertThat(addressType.getFieldNames().get(2).asInternal()).isEqualTo("phones"); + DataType phonesType = addressType.getFieldTypes().get(2); + assertThat(phonesType).isInstanceOf(SetType.class); + UserDefinedType phoneType = ((UserDefinedType) ((SetType) phonesType).getElementType()); + + assertThat(phoneType.getKeyspace().asInternal()).isEqualTo("foo"); + assertThat(phoneType.getName().asInternal()).isEqualTo("phone"); + assertThat(phoneType.isFrozen()).isTrue(); + assertThat(phoneType.getFieldNames().size()).isEqualTo(2); + + assertThat(phoneType.getFieldNames().get(0).asInternal()).isEqualTo("name"); + assertThat(phoneType.getFieldTypes().get(0)).isEqualTo(DataTypes.TEXT); + + assertThat(phoneType.getFieldNames().get(1).asInternal()).isEqualTo("number"); + assertThat(phoneType.getFieldTypes().get(1)).isEqualTo(DataTypes.TEXT); + } finally { + Locale.setDefault(def); + } } @Test - public void should_make_a_frozen_copy_user_type_when_definition_already_available() { - UserDefinedType existing = mock(UserDefinedType.class); - - parse( - "org.apache.cassandra.db.marshal.UserType(foo,70686f6e65," - + "6e616d65:org.apache.cassandra.db.marshal.UTF8Type," - + "6e756d626572:org.apache.cassandra.db.marshal.UTF8Type)", - ImmutableMap.of(CqlIdentifier.fromInternal("phone"), existing)); - - verify(existing).copy(true); + @UseDataProvider(location = TestDataProviders.class, value = "locales") + public void should_make_a_frozen_copy_user_type_when_definition_already_available(Locale locale) { + Locale def = Locale.getDefault(); + try { + Locale.setDefault(locale); + UserDefinedType existing = mock(UserDefinedType.class); + + parse( + "org.apache.cassandra.db.marshal.UserType(foo,70686f6e65," + + "6e616d65:org.apache.cassandra.db.marshal.UTF8Type," + + "6e756d626572:org.apache.cassandra.db.marshal.UTF8Type)", + ImmutableMap.of(CqlIdentifier.fromInternal("phone"), existing)); + + verify(existing).copy(true); + } finally { + Locale.setDefault(def); + } } @Test - public void should_parse_tuple() { - TupleType tupleType = - (TupleType) - parse( - "org.apache.cassandra.db.marshal.TupleType(" - + "org.apache.cassandra.db.marshal.Int32Type," - + "org.apache.cassandra.db.marshal.UTF8Type," - + "org.apache.cassandra.db.marshal.FloatType)"); - - assertThat(tupleType.getComponentTypes().size()).isEqualTo(3); - assertThat(tupleType.getComponentTypes().get(0)).isEqualTo(DataTypes.INT); - assertThat(tupleType.getComponentTypes().get(1)).isEqualTo(DataTypes.TEXT); - assertThat(tupleType.getComponentTypes().get(2)).isEqualTo(DataTypes.FLOAT); + @UseDataProvider(location = TestDataProviders.class, value = "locales") + public void should_parse_tuple(Locale locale) { + Locale def = Locale.getDefault(); + try { + Locale.setDefault(locale); + TupleType tupleType = + (TupleType) + parse( + "org.apache.cassandra.db.marshal.TupleType(" + + "org.apache.cassandra.db.marshal.Int32Type," + + "org.apache.cassandra.db.marshal.UTF8Type," + + "org.apache.cassandra.db.marshal.FloatType)"); + + assertThat(tupleType.getComponentTypes().size()).isEqualTo(3); + assertThat(tupleType.getComponentTypes().get(0)).isEqualTo(DataTypes.INT); + assertThat(tupleType.getComponentTypes().get(1)).isEqualTo(DataTypes.TEXT); + assertThat(tupleType.getComponentTypes().get(2)).isEqualTo(DataTypes.FLOAT); + } finally { + Locale.setDefault(def); + } } private DataType parse(String toParse) { diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/DataTypeCqlNameParserTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/DataTypeCqlNameParserTest.java index a7000a8536e..04ebaf4d68a 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/DataTypeCqlNameParserTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/DataTypeCqlNameParserTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/FunctionParserTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/FunctionParserTest.java index ba6928472ed..ab2d2e725ea 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/FunctionParserTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/FunctionParserTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/SchemaParserTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/SchemaParserTest.java index 037234b0632..a08a6cba838 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/SchemaParserTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/SchemaParserTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -137,7 +139,8 @@ public void should_parse_multiple_keyspaces() { } private MetadataRefresh parse(Consumer builderConfig) { - CassandraSchemaRows.Builder builder = new CassandraSchemaRows.Builder(NODE_3_0, "test"); + CassandraSchemaRows.Builder builder = + new CassandraSchemaRows.Builder(NODE_3_0, keyspaceFilter, "test"); builderConfig.accept(builder); SchemaRows rows = builder.build(); return new CassandraSchemaParser(rows, context).parse(); diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/SchemaParserTestBase.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/SchemaParserTestBase.java index 009a2db614f..e5f0c732f7a 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/SchemaParserTestBase.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/SchemaParserTestBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,6 +18,7 @@ package com.datastax.oss.driver.internal.core.metadata.schema.parsing; import static org.assertj.core.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -25,11 +28,13 @@ import com.datastax.oss.driver.internal.core.adminrequest.AdminRow; import com.datastax.oss.driver.internal.core.context.InternalDriverContext; import com.datastax.oss.driver.internal.core.metadata.DefaultMetadata; +import com.datastax.oss.driver.internal.core.metadata.schema.queries.KeyspaceFilter; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableSet; import java.nio.ByteBuffer; import java.util.Collections; import java.util.List; +import org.junit.Before; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; @@ -42,6 +47,12 @@ public abstract class SchemaParserTestBase { protected static final CqlIdentifier KEYSPACE_ID = CqlIdentifier.fromInternal("ks"); @Mock protected DefaultMetadata currentMetadata; @Mock protected InternalDriverContext context; + @Mock protected KeyspaceFilter keyspaceFilter; + + @Before + public void setup() { + when(keyspaceFilter.includes(anyString())).thenReturn(true); + } protected static AdminRow mockFunctionRow( String keyspace, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/TableParserTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/TableParserTest.java index fe106165f67..a316473d071 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/TableParserTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/TableParserTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -204,7 +206,7 @@ private SchemaRows modernRows( private SchemaRows rows( AdminRow tableRow, Iterable columnRows, Iterable indexesRows, Node node) { CassandraSchemaRows.Builder builder = - new CassandraSchemaRows.Builder(node, "test") + new CassandraSchemaRows.Builder(node, keyspaceFilter, "test") .withTables(ImmutableList.of(tableRow)) .withColumns(columnRows); if (indexesRows != null) { diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/UserDefinedTypeListParserTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/UserDefinedTypeListParserTest.java index b77919d6dea..f90d07ebe6d 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/UserDefinedTypeListParserTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/UserDefinedTypeListParserTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/ViewParserTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/ViewParserTest.java index 4fe83cf34b6..1ba471e08f5 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/ViewParserTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/parsing/ViewParserTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -86,7 +88,7 @@ public void should_parse_view() { } private SchemaRows rows(AdminRow viewRow, Iterable columnRows) { - return new CassandraSchemaRows.Builder(NODE_3_0, "test") + return new CassandraSchemaRows.Builder(NODE_3_0, keyspaceFilter, "test") .withViews(ImmutableList.of(viewRow)) .withColumns(columnRows) .build(); diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/Cassandra21SchemaQueriesTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/Cassandra21SchemaQueriesTest.java index 5625be4dddc..2dd216474df 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/Cassandra21SchemaQueriesTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/Cassandra21SchemaQueriesTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/Cassandra22SchemaQueriesTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/Cassandra22SchemaQueriesTest.java index a867bfcccdb..fd28be59120 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/Cassandra22SchemaQueriesTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/Cassandra22SchemaQueriesTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/Cassandra3SchemaQueriesTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/Cassandra3SchemaQueriesTest.java index e41fd78d3ed..3b533e89ed5 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/Cassandra3SchemaQueriesTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/Cassandra3SchemaQueriesTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -58,7 +60,7 @@ public void should_query_with_keyspace_filter() { DefaultDriverOption.METADATA_SCHEMA_REFRESHED_KEYSPACES, Collections.emptyList())) .thenReturn(ImmutableList.of("ks1", "ks2")); - should_query_with_where_clause(" WHERE keyspace_name in ('ks1','ks2')"); + should_query_with_where_clause(" WHERE keyspace_name IN ('ks1','ks2')"); } private void should_query_with_where_clause(String whereClause) { diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/DefaultSchemaQueriesFactoryTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/DefaultSchemaQueriesFactoryTest.java index 3bb32c7089e..f9ac6c05576 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/DefaultSchemaQueriesFactoryTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/DefaultSchemaQueriesFactoryTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/KeyspaceFilterTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/KeyspaceFilterTest.java new file mode 100644 index 00000000000..7e2f6219eac --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/KeyspaceFilterTest.java @@ -0,0 +1,143 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.metadata.schema.queries; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableSet; +import java.util.Arrays; +import java.util.Set; +import java.util.stream.Collectors; +import org.junit.Test; + +public class KeyspaceFilterTest { + + private static final ImmutableSet KEYSPACES = + ImmutableSet.of( + "system", "inventory_test", "inventory_prod", "customers_test", "customers_prod"); + + @Test + public void should_not_filter_when_no_rules() { + KeyspaceFilter filter = KeyspaceFilter.newInstance("test", Arrays.asList()); + assertThat(filter.getWhereClause()).isEmpty(); + assertThat(apply(filter, KEYSPACES)).isEqualTo(KEYSPACES); + } + + @Test + public void should_filter_on_server_when_only_exact_rules() { + KeyspaceFilter filter = + KeyspaceFilter.newInstance( + "test", Arrays.asList("inventory_test", "customers_test", "!system")); + // Note that exact excludes are redundant in this case: either they match an include and will be + // ignored, or they don't and the keyspace is already ignored. + // We let it slide, but a warning is logged. + assertThat(filter.getWhereClause()) + .isEqualTo(" WHERE keyspace_name IN ('inventory_test','customers_test')"); + assertThat(apply(filter, KEYSPACES)).containsOnly("inventory_test", "customers_test"); + } + + @Test + public void should_ignore_exact_exclude_that_collides_with_exact_include() { + KeyspaceFilter filter = + KeyspaceFilter.newInstance("test", Arrays.asList("inventory_test", "!inventory_test")); + assertThat(filter.getWhereClause()).isEqualTo(" WHERE keyspace_name IN ('inventory_test')"); + assertThat(apply(filter, KEYSPACES)).containsOnly("inventory_test"); + + // Order does not matter + filter = KeyspaceFilter.newInstance("test", Arrays.asList("!inventory_test", "inventory_test")); + assertThat(filter.getWhereClause()).isEqualTo(" WHERE keyspace_name IN ('inventory_test')"); + assertThat(apply(filter, KEYSPACES)).containsOnly("inventory_test"); + } + + @Test + public void should_apply_disjoint_exact_and_regex_rules() { + KeyspaceFilter filter = + KeyspaceFilter.newInstance("test", Arrays.asList("inventory_test", "/^customers.*/")); + assertThat(filter.getWhereClause()).isEmpty(); + assertThat(apply(filter, KEYSPACES)) + .containsOnly("inventory_test", "customers_test", "customers_prod"); + + filter = KeyspaceFilter.newInstance("test", Arrays.asList("!system", "!/^inventory.*/")); + assertThat(filter.getWhereClause()).isEmpty(); + assertThat(apply(filter, KEYSPACES)).containsOnly("customers_test", "customers_prod"); + + // The remaining cases could be simplified, but they are supported nevertheless: + /*redundant:*/ + filter = KeyspaceFilter.newInstance("test", Arrays.asList("!/^customers.*/", "inventory_test")); + assertThat(filter.getWhereClause()).isEmpty(); + assertThat(apply(filter, KEYSPACES)).containsOnly("inventory_test", "inventory_prod", "system"); + + /*redundant:*/ + filter = KeyspaceFilter.newInstance("test", Arrays.asList("/^customers.*/", "!system")); + assertThat(filter.getWhereClause()).isEmpty(); + assertThat(apply(filter, KEYSPACES)).containsOnly("customers_test", "customers_prod"); + } + + @Test + public void should_apply_intersecting_exact_and_regex_rules() { + // Include all customer keyspaces except one: + KeyspaceFilter filter = + KeyspaceFilter.newInstance("test", Arrays.asList("/^customers.*/", "!customers_test")); + assertThat(filter.getWhereClause()).isEmpty(); + assertThat(apply(filter, KEYSPACES)).containsOnly("customers_prod"); + + // Exclude all customer keyspaces except one (also implies include every other keyspace): + filter = KeyspaceFilter.newInstance("test", Arrays.asList("!/^customers.*/", "customers_test")); + assertThat(filter.getWhereClause()).isEmpty(); + assertThat(apply(filter, KEYSPACES)) + .containsOnly("customers_test", "inventory_test", "inventory_prod", "system"); + } + + @Test + public void should_apply_intersecting_regex_rules() { + KeyspaceFilter filter = + KeyspaceFilter.newInstance("test", Arrays.asList("/^customers.*/", "!/.*test$/")); + assertThat(filter.getWhereClause()).isEmpty(); + assertThat(apply(filter, KEYSPACES)).containsOnly("customers_prod"); + + // Throwing an exact name in the mix doesn't change the other rules + filter = + KeyspaceFilter.newInstance( + "test", Arrays.asList("inventory_prod", "/^customers.*/", "!/.*test$/")); + assertThat(filter.getWhereClause()).isEmpty(); + assertThat(apply(filter, KEYSPACES)).containsOnly("inventory_prod", "customers_prod"); + } + + @Test + public void should_skip_malformed_rule() { + KeyspaceFilter filter = + KeyspaceFilter.newInstance("test", Arrays.asList("inventory_test", "customers_test", "//")); + assertThat(filter.getWhereClause()) + .isEqualTo(" WHERE keyspace_name IN ('inventory_test','customers_test')"); + assertThat(apply(filter, KEYSPACES)).containsOnly("inventory_test", "customers_test"); + } + + @Test + public void should_skip_invalid_regex() { + KeyspaceFilter filter = + KeyspaceFilter.newInstance( + "test", Arrays.asList("inventory_test", "customers_test", "/*/")); + assertThat(filter.getWhereClause()) + .isEqualTo(" WHERE keyspace_name IN ('inventory_test','customers_test')"); + assertThat(apply(filter, KEYSPACES)).containsOnly("inventory_test", "customers_test"); + } + + private static Set apply(KeyspaceFilter filter, Set keyspaces) { + return keyspaces.stream().filter(filter::includes).collect(Collectors.toSet()); + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/SchemaQueriesTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/SchemaQueriesTest.java index dd309ffac37..e0da405993b 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/SchemaQueriesTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/queries/SchemaQueriesTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/refresh/SchemaRefreshTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/refresh/SchemaRefreshTest.java index 4f148db1dcc..4f124d2c4a0 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/refresh/SchemaRefreshTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/schema/refresh/SchemaRefreshTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/ByteOrderedTokenRangeTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/ByteOrderedTokenRangeTest.java index b0c0922d7fd..238f4e0687a 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/ByteOrderedTokenRangeTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/ByteOrderedTokenRangeTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/DefaultTokenMapTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/DefaultTokenMapTest.java index fc4a8a3a7e5..3170e2dd6b2 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/DefaultTokenMapTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/DefaultTokenMapTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/Murmur3TokenRangeTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/Murmur3TokenRangeTest.java index 3d14f21c741..e5c1a0fc47c 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/Murmur3TokenRangeTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/Murmur3TokenRangeTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/NetworkTopologyReplicationStrategyTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/NetworkTopologyReplicationStrategyTest.java index f6a6cfc3c07..42dc5e69199 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/NetworkTopologyReplicationStrategyTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/NetworkTopologyReplicationStrategyTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/RandomTokenRangeTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/RandomTokenRangeTest.java index 57a22f463cf..54ac8a99738 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/RandomTokenRangeTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/RandomTokenRangeTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/ReplicationFactorTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/ReplicationFactorTest.java index 3c2e8a12ce3..d58d13933c2 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/ReplicationFactorTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/ReplicationFactorTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/SimpleReplicationStrategyTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/SimpleReplicationStrategyTest.java index 2a849df3306..517d8cfdb84 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/SimpleReplicationStrategyTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/SimpleReplicationStrategyTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/TokenRangeAssert.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/TokenRangeAssert.java index 174fa69519a..7fcd56ba86e 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/TokenRangeAssert.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/TokenRangeAssert.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/TokenRangeTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/TokenRangeTest.java index 42111947ec2..77cfbb30d77 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/TokenRangeTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metadata/token/TokenRangeTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metrics/DefaultMetricIdGeneratorTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metrics/DefaultMetricIdGeneratorTest.java new file mode 100644 index 00000000000..13efda4b352 --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metrics/DefaultMetricIdGeneratorTest.java @@ -0,0 +1,110 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.metrics; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; + +import com.datastax.oss.driver.api.core.config.DefaultDriverOption; +import com.datastax.oss.driver.api.core.config.DriverConfig; +import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; +import com.datastax.oss.driver.api.core.metadata.EndPoint; +import com.datastax.oss.driver.api.core.metadata.Node; +import com.datastax.oss.driver.api.core.metrics.DefaultNodeMetric; +import com.datastax.oss.driver.api.core.metrics.DefaultSessionMetric; +import com.datastax.oss.driver.internal.core.context.InternalDriverContext; +import com.tngtech.java.junit.dataprovider.DataProvider; +import com.tngtech.java.junit.dataprovider.DataProviderRunner; +import com.tngtech.java.junit.dataprovider.UseDataProvider; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +@RunWith(DataProviderRunner.class) +public class DefaultMetricIdGeneratorTest { + + @Mock private InternalDriverContext context; + + @Mock private DriverConfig config; + + @Mock private DriverExecutionProfile profile; + + @Mock private Node node; + + @Mock private EndPoint endpoint; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + given(context.getConfig()).willReturn(config); + given(context.getSessionName()).willReturn("s0"); + given(config.getDefaultProfile()).willReturn(profile); + given(node.getEndPoint()).willReturn(endpoint); + given(endpoint.asMetricPrefix()).willReturn("10_1_2_3:9042"); + } + + @Test + @UseDataProvider("sessionMetrics") + public void should_generate_session_metric(String prefix, String expectedName) { + // given + given(profile.getString(DefaultDriverOption.METRICS_ID_GENERATOR_PREFIX, "")) + .willReturn(prefix); + DefaultMetricIdGenerator generator = new DefaultMetricIdGenerator(context); + // when + MetricId id = generator.sessionMetricId(DefaultSessionMetric.CONNECTED_NODES); + // then + assertThat(id.getName()).isEqualTo(expectedName); + assertThat(id.getTags()).isEmpty(); + } + + @Test + @UseDataProvider("nodeMetrics") + public void should_generate_node_metric(String prefix, String expectedName) { + // given + given(profile.getString(DefaultDriverOption.METRICS_ID_GENERATOR_PREFIX, "")) + .willReturn(prefix); + DefaultMetricIdGenerator generator = new DefaultMetricIdGenerator(context); + // when + MetricId id = generator.nodeMetricId(node, DefaultNodeMetric.CQL_MESSAGES); + // then + assertThat(id.getName()).isEqualTo(expectedName); + assertThat(id.getTags()).isEmpty(); + } + + @DataProvider + public static Object[][] sessionMetrics() { + String suffix = DefaultSessionMetric.CONNECTED_NODES.getPath(); + return new Object[][] { + new Object[] {"", "s0." + suffix}, + new Object[] {"cassandra", "cassandra.s0." + suffix}, + new Object[] {"app.cassandra", "app.cassandra.s0." + suffix} + }; + } + + @DataProvider + public static Object[][] nodeMetrics() { + String suffix = DefaultNodeMetric.CQL_MESSAGES.getPath(); + return new Object[][] { + new Object[] {"", "s0.nodes.10_1_2_3:9042." + suffix}, + new Object[] {"cassandra", "cassandra.s0.nodes.10_1_2_3:9042." + suffix}, + new Object[] {"app.cassandra", "app.cassandra.s0.nodes.10_1_2_3:9042." + suffix} + }; + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metrics/DefaultMetricIdTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metrics/DefaultMetricIdTest.java new file mode 100644 index 00000000000..339f9235dc2 --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metrics/DefaultMetricIdTest.java @@ -0,0 +1,63 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.metrics; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.google.common.collect.ImmutableMap; +import org.junit.Test; + +public class DefaultMetricIdTest { + + @Test + public void testGetName() { + DefaultMetricId id = new DefaultMetricId("metric1", ImmutableMap.of()); + assertThat(id.getName()).isEqualTo("metric1"); + } + + @Test + public void testGetTags() { + DefaultMetricId id = + new DefaultMetricId("metric1", ImmutableMap.of("tag1", "value1", "tag2", "value2")); + assertThat(id.getTags()) + .hasSize(2) + .containsEntry("tag1", "value1") + .containsEntry("tag2", "value2"); + } + + @Test + public void testEquals() { + DefaultMetricId id1 = + new DefaultMetricId("metric1", ImmutableMap.of("tag1", "value1", "tag2", "value2")); + DefaultMetricId id2 = + new DefaultMetricId("metric1", ImmutableMap.of("tag1", "value1", "tag2", "value2")); + DefaultMetricId id3 = + new DefaultMetricId("metric2", ImmutableMap.of("tag1", "value1", "tag2", "value2")); + DefaultMetricId id4 = new DefaultMetricId("metric1", ImmutableMap.of("tag2", "value2")); + assertThat(id1).isEqualTo(id2).isNotEqualTo(id3).isNotEqualTo(id4); + } + + @Test + public void testHashCode() { + DefaultMetricId id1 = + new DefaultMetricId("metric1", ImmutableMap.of("tag1", "value1", "tag2", "value2")); + DefaultMetricId id2 = + new DefaultMetricId("metric1", ImmutableMap.of("tag1", "value1", "tag2", "value2")); + assertThat(id1).hasSameHashCodeAs(id2); + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metrics/DropwizardMetricsFactoryTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metrics/DropwizardMetricsFactoryTest.java index 44d0131283f..e5983c4f4fd 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/metrics/DropwizardMetricsFactoryTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metrics/DropwizardMetricsFactoryTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -15,95 +17,32 @@ */ package com.datastax.oss.driver.internal.core.metrics; -import static com.datastax.oss.driver.internal.core.metrics.DropwizardMetricsFactory.LOWEST_ACCEPTABLE_EXPIRE_AFTER; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.timeout; -import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import ch.qos.logback.classic.Level; import com.codahale.metrics.MetricRegistry; import com.datastax.oss.driver.api.core.config.DefaultDriverOption; import com.datastax.oss.driver.api.core.config.DriverConfig; import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; import com.datastax.oss.driver.api.core.metrics.DefaultSessionMetric; import com.datastax.oss.driver.internal.core.context.InternalDriverContext; -import com.datastax.oss.driver.internal.core.util.LoggerTest; -import com.tngtech.java.junit.dataprovider.DataProvider; -import com.tngtech.java.junit.dataprovider.DataProviderRunner; -import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.time.Duration; -import java.util.Arrays; +import java.util.Collections; import java.util.List; import org.junit.Test; -import org.junit.runner.RunWith; -@RunWith(DataProviderRunner.class) public class DropwizardMetricsFactoryTest { - private static final String LOG_PREFIX = "prefix"; - - @Test - public void should_log_warning_when_provided_eviction_time_setting_is_too_low() { - // given - Duration expireAfter = LOWEST_ACCEPTABLE_EXPIRE_AFTER.minusMinutes(1); - LoggerTest.LoggerSetup logger = - LoggerTest.setupTestLogger(DropwizardMetricsFactory.class, Level.WARN); - DriverExecutionProfile driverExecutionProfile = mock(DriverExecutionProfile.class); - - // when - when(driverExecutionProfile.getDuration(DefaultDriverOption.METRICS_NODE_EXPIRE_AFTER)) - .thenReturn(expireAfter); - DropwizardMetricsFactory.getAndValidateEvictionTime(driverExecutionProfile, LOG_PREFIX); - - // then - verify(logger.appender, timeout(500).times(1)).doAppend(logger.loggingEventCaptor.capture()); - assertThat(logger.loggingEventCaptor.getValue().getMessage()).isNotNull(); - assertThat(logger.loggingEventCaptor.getValue().getFormattedMessage()) - .contains( - String.format( - "[%s] Value too low for %s: %s. Forcing to %s instead.", - LOG_PREFIX, - DefaultDriverOption.METRICS_NODE_EXPIRE_AFTER.getPath(), - expireAfter, - LOWEST_ACCEPTABLE_EXPIRE_AFTER)); - } - - @Test - @UseDataProvider(value = "acceptableEvictionTimes") - public void should_not_log_warning_when_provided_eviction_time_setting_is_acceptable( - Duration expireAfter) { - // given - LoggerTest.LoggerSetup logger = - LoggerTest.setupTestLogger(DropwizardMetricsFactory.class, Level.WARN); - DriverExecutionProfile driverExecutionProfile = mock(DriverExecutionProfile.class); - - // when - when(driverExecutionProfile.getDuration(DefaultDriverOption.METRICS_NODE_EXPIRE_AFTER)) - .thenReturn(expireAfter); - DropwizardMetricsFactory.getAndValidateEvictionTime(driverExecutionProfile, LOG_PREFIX); - - // then - verify(logger.appender, timeout(500).times(0)).doAppend(logger.loggingEventCaptor.capture()); - } - - @DataProvider - public static Object[][] acceptableEvictionTimes() { - return new Object[][] { - {LOWEST_ACCEPTABLE_EXPIRE_AFTER}, {LOWEST_ACCEPTABLE_EXPIRE_AFTER.plusMinutes(1)} - }; - } - @Test public void should_throw_if_registry_of_wrong_type() { // given InternalDriverContext context = mock(InternalDriverContext.class); DriverExecutionProfile profile = mock(DriverExecutionProfile.class); DriverConfig config = mock(DriverConfig.class); - Duration expireAfter = LOWEST_ACCEPTABLE_EXPIRE_AFTER.minusMinutes(1); - List enabledMetrics = Arrays.asList(DefaultSessionMetric.CQL_REQUESTS.getPath()); + List enabledMetrics = + Collections.singletonList(DefaultSessionMetric.CQL_REQUESTS.getPath()); // when when(config.getDefaultProfile()).thenReturn(profile); when(context.getConfig()).thenReturn(config); @@ -111,23 +50,21 @@ public void should_throw_if_registry_of_wrong_type() { // registry object is not a registry type when(context.getMetricRegistry()).thenReturn(Integer.MAX_VALUE); when(profile.getDuration(DefaultDriverOption.METRICS_NODE_EXPIRE_AFTER)) - .thenReturn(expireAfter); + .thenReturn(Duration.ofHours(1)); when(profile.getStringList(DefaultDriverOption.METRICS_SESSION_ENABLED)) .thenReturn(enabledMetrics); // then try { new DropwizardMetricsFactory(context); fail( - "MetricsFactory should require correct registy object type: " + "MetricsFactory should require correct registry object type: " + MetricRegistry.class.getName()); } catch (IllegalArgumentException iae) { assertThat(iae.getMessage()) .isEqualTo( - "Unexpected Metrics registry object. Expected registry object to be of type '" - + MetricRegistry.class.getName() - + "', but was '" - + Integer.class.getName() - + "'"); + "Unexpected Metrics registry object. " + + "Expected registry object to be of type '%s', but was '%s'", + MetricRegistry.class.getName(), Integer.class.getName()); } } } diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metrics/DropwizardNodeMetricUpdaterTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metrics/DropwizardNodeMetricUpdaterTest.java new file mode 100644 index 00000000000..ccc42a7027d --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metrics/DropwizardNodeMetricUpdaterTest.java @@ -0,0 +1,162 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.metrics; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.timeout; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import ch.qos.logback.classic.Level; +import com.codahale.metrics.MetricRegistry; +import com.datastax.oss.driver.api.core.config.DefaultDriverOption; +import com.datastax.oss.driver.api.core.config.DriverConfig; +import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; +import com.datastax.oss.driver.api.core.config.DriverOption; +import com.datastax.oss.driver.api.core.metadata.Node; +import com.datastax.oss.driver.api.core.metrics.DefaultNodeMetric; +import com.datastax.oss.driver.api.core.metrics.NodeMetric; +import com.datastax.oss.driver.internal.core.context.InternalDriverContext; +import com.datastax.oss.driver.internal.core.util.LoggerTest; +import com.tngtech.java.junit.dataprovider.DataProvider; +import com.tngtech.java.junit.dataprovider.DataProviderRunner; +import com.tngtech.java.junit.dataprovider.UseDataProvider; +import java.time.Duration; +import java.util.Collections; +import java.util.Set; +import java.util.function.Supplier; +import org.junit.Test; +import org.junit.runner.RunWith; + +@RunWith(DataProviderRunner.class) +public class DropwizardNodeMetricUpdaterTest { + + @Test + public void should_log_warning_when_provided_eviction_time_setting_is_too_low() { + // given + LoggerTest.LoggerSetup logger = + LoggerTest.setupTestLogger(AbstractMetricUpdater.class, Level.WARN); + Node node = mock(Node.class); + InternalDriverContext context = mock(InternalDriverContext.class); + DriverExecutionProfile profile = mock(DriverExecutionProfile.class); + DriverConfig config = mock(DriverConfig.class); + Set enabledMetrics = Collections.singleton(DefaultNodeMetric.CQL_MESSAGES); + Duration expireAfter = AbstractMetricUpdater.MIN_EXPIRE_AFTER.minusMinutes(1); + + // when + when(context.getSessionName()).thenReturn("prefix"); + when(context.getConfig()).thenReturn(config); + when(config.getDefaultProfile()).thenReturn(profile); + when(profile.getDuration(DefaultDriverOption.METRICS_NODE_EXPIRE_AFTER)) + .thenReturn(expireAfter); + + DropwizardNodeMetricUpdater updater = + new DropwizardNodeMetricUpdater(node, context, enabledMetrics, new MetricRegistry()) { + @Override + protected void initializeGauge( + NodeMetric metric, DriverExecutionProfile profile, Supplier supplier) { + // do nothing + } + + @Override + protected void initializeCounter(NodeMetric metric, DriverExecutionProfile profile) { + // do nothing + } + + @Override + protected void initializeHdrTimer( + NodeMetric metric, + DriverExecutionProfile profile, + DriverOption highestLatency, + DriverOption significantDigits, + DriverOption interval) { + // do nothing + } + }; + + // then + assertThat(updater.getExpireAfter()).isEqualTo(AbstractMetricUpdater.MIN_EXPIRE_AFTER); + verify(logger.appender, timeout(500).times(1)).doAppend(logger.loggingEventCaptor.capture()); + assertThat(logger.loggingEventCaptor.getValue().getMessage()).isNotNull(); + assertThat(logger.loggingEventCaptor.getValue().getFormattedMessage()) + .contains( + String.format( + "[prefix] Value too low for %s: %s. Forcing to %s instead.", + DefaultDriverOption.METRICS_NODE_EXPIRE_AFTER.getPath(), + expireAfter, + AbstractMetricUpdater.MIN_EXPIRE_AFTER)); + } + + @Test + @UseDataProvider(value = "acceptableEvictionTimes") + public void should_not_log_warning_when_provided_eviction_time_setting_is_acceptable( + Duration expireAfter) { + // given + LoggerTest.LoggerSetup logger = + LoggerTest.setupTestLogger(AbstractMetricUpdater.class, Level.WARN); + Node node = mock(Node.class); + InternalDriverContext context = mock(InternalDriverContext.class); + DriverExecutionProfile profile = mock(DriverExecutionProfile.class); + DriverConfig config = mock(DriverConfig.class); + Set enabledMetrics = Collections.singleton(DefaultNodeMetric.CQL_MESSAGES); + + // when + when(context.getSessionName()).thenReturn("prefix"); + when(context.getConfig()).thenReturn(config); + when(config.getDefaultProfile()).thenReturn(profile); + when(profile.getDuration(DefaultDriverOption.METRICS_NODE_EXPIRE_AFTER)) + .thenReturn(expireAfter); + + DropwizardNodeMetricUpdater updater = + new DropwizardNodeMetricUpdater(node, context, enabledMetrics, new MetricRegistry()) { + @Override + protected void initializeGauge( + NodeMetric metric, DriverExecutionProfile profile, Supplier supplier) { + // do nothing + } + + @Override + protected void initializeCounter(NodeMetric metric, DriverExecutionProfile profile) { + // do nothing + } + + @Override + protected void initializeHdrTimer( + NodeMetric metric, + DriverExecutionProfile profile, + DriverOption highestLatency, + DriverOption significantDigits, + DriverOption interval) { + // do nothing + } + }; + + // then + assertThat(updater.getExpireAfter()).isEqualTo(expireAfter); + verify(logger.appender, timeout(500).times(0)).doAppend(logger.loggingEventCaptor.capture()); + } + + @DataProvider + public static Object[][] acceptableEvictionTimes() { + return new Object[][] { + {AbstractMetricUpdater.MIN_EXPIRE_AFTER}, + {AbstractMetricUpdater.MIN_EXPIRE_AFTER.plusMinutes(1)} + }; + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metrics/NoopMetricsFactoryTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metrics/NoopMetricsFactoryTest.java new file mode 100644 index 00000000000..3a563be4453 --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metrics/NoopMetricsFactoryTest.java @@ -0,0 +1,64 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.metrics; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import ch.qos.logback.classic.Level; +import com.datastax.oss.driver.api.core.config.DefaultDriverOption; +import com.datastax.oss.driver.api.core.config.DriverConfig; +import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; +import com.datastax.oss.driver.api.core.metrics.DefaultSessionMetric; +import com.datastax.oss.driver.internal.core.context.InternalDriverContext; +import com.datastax.oss.driver.internal.core.util.LoggerTest; +import com.tngtech.java.junit.dataprovider.DataProviderRunner; +import java.util.Collections; +import org.junit.Test; +import org.junit.runner.RunWith; + +@RunWith(DataProviderRunner.class) +public class NoopMetricsFactoryTest { + + @Test + public void should_log_warning_when_metrics_enabled() { + // given + InternalDriverContext context = mock(InternalDriverContext.class); + DriverConfig config = mock(DriverConfig.class); + DriverExecutionProfile profile = mock(DriverExecutionProfile.class); + when(context.getSessionName()).thenReturn("MockSession"); + when(context.getConfig()).thenReturn(config); + when(config.getDefaultProfile()).thenReturn(profile); + when(profile.getStringList(DefaultDriverOption.METRICS_SESSION_ENABLED)) + .thenReturn(Collections.singletonList(DefaultSessionMetric.CQL_REQUESTS.getPath())); + LoggerTest.LoggerSetup logger = + LoggerTest.setupTestLogger(NoopMetricsFactory.class, Level.WARN); + + // when + new NoopMetricsFactory(context); + + // then + verify(logger.appender, times(1)).doAppend(logger.loggingEventCaptor.capture()); + assertThat(logger.loggingEventCaptor.getValue().getMessage()).isNotNull(); + assertThat(logger.loggingEventCaptor.getValue().getFormattedMessage()) + .contains("[MockSession] Some session-level or node-level metrics were enabled"); + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/metrics/TaggingMetricIdGeneratorTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/metrics/TaggingMetricIdGeneratorTest.java new file mode 100644 index 00000000000..809a7419ba4 --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/metrics/TaggingMetricIdGeneratorTest.java @@ -0,0 +1,116 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.metrics; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; + +import com.datastax.oss.driver.api.core.config.DefaultDriverOption; +import com.datastax.oss.driver.api.core.config.DriverConfig; +import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; +import com.datastax.oss.driver.api.core.metadata.EndPoint; +import com.datastax.oss.driver.api.core.metadata.Node; +import com.datastax.oss.driver.api.core.metrics.DefaultNodeMetric; +import com.datastax.oss.driver.api.core.metrics.DefaultSessionMetric; +import com.datastax.oss.driver.internal.core.context.InternalDriverContext; +import com.google.common.collect.ImmutableMap; +import com.tngtech.java.junit.dataprovider.DataProvider; +import com.tngtech.java.junit.dataprovider.DataProviderRunner; +import com.tngtech.java.junit.dataprovider.UseDataProvider; +import java.util.Map; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +@RunWith(DataProviderRunner.class) +public class TaggingMetricIdGeneratorTest { + + @Mock private InternalDriverContext context; + + @Mock private DriverConfig config; + + @Mock private DriverExecutionProfile profile; + + @Mock private Node node; + + @Mock private EndPoint endpoint; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + given(context.getConfig()).willReturn(config); + given(context.getSessionName()).willReturn("s0"); + given(config.getDefaultProfile()).willReturn(profile); + given(node.getEndPoint()).willReturn(endpoint); + given(endpoint.toString()).willReturn("/10.1.2.3:9042"); + } + + @Test + @UseDataProvider("sessionMetrics") + public void should_generate_session_metric( + String prefix, String expectedName, Map expectedTags) { + // given + given(profile.getString(DefaultDriverOption.METRICS_ID_GENERATOR_PREFIX, "")) + .willReturn(prefix); + TaggingMetricIdGenerator generator = new TaggingMetricIdGenerator(context); + // when + MetricId id = generator.sessionMetricId(DefaultSessionMetric.CONNECTED_NODES); + // then + assertThat(id.getName()).isEqualTo(expectedName); + assertThat(id.getTags()).isEqualTo(expectedTags); + } + + @Test + @UseDataProvider("nodeMetrics") + public void should_generate_node_metric( + String prefix, String expectedName, Map expectedTags) { + // given + given(profile.getString(DefaultDriverOption.METRICS_ID_GENERATOR_PREFIX, "")) + .willReturn(prefix); + TaggingMetricIdGenerator generator = new TaggingMetricIdGenerator(context); + // when + MetricId id = generator.nodeMetricId(node, DefaultNodeMetric.CQL_MESSAGES); + // then + assertThat(id.getName()).isEqualTo(expectedName); + assertThat(id.getTags()).isEqualTo(expectedTags); + } + + @DataProvider + public static Object[][] sessionMetrics() { + String suffix = DefaultSessionMetric.CONNECTED_NODES.getPath(); + ImmutableMap tags = ImmutableMap.of("session", "s0"); + return new Object[][] { + new Object[] {"", "session." + suffix, tags}, + new Object[] {"cassandra", "cassandra.session." + suffix, tags}, + new Object[] {"app.cassandra", "app.cassandra.session." + suffix, tags} + }; + } + + @DataProvider + public static Object[][] nodeMetrics() { + String suffix = DefaultNodeMetric.CQL_MESSAGES.getPath(); + ImmutableMap tags = ImmutableMap.of("session", "s0", "node", "/10.1.2.3:9042"); + return new Object[][] { + new Object[] {"", "nodes." + suffix, tags}, + new Object[] {"cassandra", "cassandra.nodes." + suffix, tags}, + new Object[] {"app.cassandra", "app.cassandra.nodes." + suffix, tags} + }; + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/os/JnrLibcTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/os/JnrLibcTest.java index e3bf9a876db..30dee7847c4 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/os/JnrLibcTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/os/JnrLibcTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -15,7 +17,7 @@ */ package com.datastax.oss.driver.internal.core.os; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThat; import java.time.Instant; import java.time.temporal.ChronoUnit; diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/os/NativeTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/os/NativeTest.java index 309fd28d6d8..aeaf28d1fdf 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/os/NativeTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/os/NativeTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/pool/ChannelPoolInitTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/pool/ChannelPoolInitTest.java index 3ca09a65092..5c7257d8c3f 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/pool/ChannelPoolInitTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/pool/ChannelPoolInitTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/pool/ChannelPoolKeyspaceTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/pool/ChannelPoolKeyspaceTest.java index 85631ca5ab6..4273a51f891 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/pool/ChannelPoolKeyspaceTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/pool/ChannelPoolKeyspaceTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/pool/ChannelPoolReconnectTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/pool/ChannelPoolReconnectTest.java index f6b811ddbe7..c4538f78bdb 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/pool/ChannelPoolReconnectTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/pool/ChannelPoolReconnectTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/pool/ChannelPoolResizeTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/pool/ChannelPoolResizeTest.java index da1c5e3d2a2..6992bb7742a 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/pool/ChannelPoolResizeTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/pool/ChannelPoolResizeTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -125,7 +127,7 @@ public void should_shrink_during_reconnection() throws Exception { factoryHelper.waitForCalls(node, 2); - // Pool should have shrinked back to 2. We keep the most recent channels so 1 and 2 get closed. + // Pool should have shrunk back to 2. We keep the most recent channels so 1 and 2 get closed. inOrder.verify(eventBus, VERIFY_TIMEOUT.times(2)).fire(ChannelEvent.channelOpened(node)); inOrder.verify(eventBus, VERIFY_TIMEOUT.times(2)).fire(ChannelEvent.channelClosed(node)); inOrder.verify(eventBus, VERIFY_TIMEOUT).fire(ChannelEvent.reconnectionStopped(node)); diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/pool/ChannelPoolShutdownTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/pool/ChannelPoolShutdownTest.java index a2a099981a2..b40bcb4aa39 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/pool/ChannelPoolShutdownTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/pool/ChannelPoolShutdownTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/pool/ChannelPoolTestBase.java b/core/src/test/java/com/datastax/oss/driver/internal/core/pool/ChannelPoolTestBase.java index cc18e7d2842..2f8056e49e0 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/pool/ChannelPoolTestBase.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/pool/ChannelPoolTestBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -50,7 +52,7 @@ abstract class ChannelPoolTestBase { /** How long we wait when verifying mocks for async invocations */ - protected static final VerificationWithTimeout VERIFY_TIMEOUT = timeout(500); + protected static final VerificationWithTimeout VERIFY_TIMEOUT = timeout(2000); @Mock protected InternalDriverContext context; @Mock private DriverConfig config; diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/pool/ChannelSetTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/pool/ChannelSetTest.java index bb24bf615fc..628110bc1df 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/pool/ChannelSetTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/pool/ChannelSetTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/protocol/BuiltInCompressorsTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/protocol/BuiltInCompressorsTest.java new file mode 100644 index 00000000000..1911c7c7227 --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/protocol/BuiltInCompressorsTest.java @@ -0,0 +1,72 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.protocol; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.datastax.oss.driver.TestDataProviders; +import com.datastax.oss.driver.api.core.context.DriverContext; +import com.datastax.oss.protocol.internal.NoopCompressor; +import com.tngtech.java.junit.dataprovider.DataProviderRunner; +import com.tngtech.java.junit.dataprovider.UseDataProvider; +import java.util.Locale; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +@RunWith(DataProviderRunner.class) +public class BuiltInCompressorsTest { + + @Mock private DriverContext context; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + } + + @Test + @UseDataProvider(location = TestDataProviders.class, value = "locales") + public void should_create_instance_for_supported_algorithms(Locale locale) { + Locale def = Locale.getDefault(); + try { + Locale.setDefault(locale); + assertThat(BuiltInCompressors.newInstance("lz4", context)).isInstanceOf(Lz4Compressor.class); + assertThat(BuiltInCompressors.newInstance("snappy", context)) + .isInstanceOf(SnappyCompressor.class); + assertThat(BuiltInCompressors.newInstance("none", context)) + .isInstanceOf(NoopCompressor.class); + assertThat(BuiltInCompressors.newInstance("LZ4", context)).isInstanceOf(Lz4Compressor.class); + assertThat(BuiltInCompressors.newInstance("SNAPPY", context)) + .isInstanceOf(SnappyCompressor.class); + assertThat(BuiltInCompressors.newInstance("NONE", context)) + .isInstanceOf(NoopCompressor.class); + } finally { + Locale.setDefault(def); + } + } + + @Test + public void should_throw_when_unsupported_algorithm() { + assertThatThrownBy(() -> BuiltInCompressors.newInstance("GZIP", context)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unsupported compression algorithm 'GZIP'"); + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/protocol/ByteBufPrimitiveCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/protocol/ByteBufPrimitiveCodecTest.java index fadb80f871b..895a650b292 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/protocol/ByteBufPrimitiveCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/protocol/ByteBufPrimitiveCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,6 +18,7 @@ package com.datastax.oss.driver.internal.core.protocol; import static com.datastax.oss.driver.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.datastax.oss.driver.internal.core.util.ByteBufs; import com.datastax.oss.protocol.internal.util.Bytes; @@ -24,9 +27,7 @@ import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.ByteBuffer; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; /** * Note: we don't test trivial methods that simply delegate to ByteBuf, nor default implementations @@ -35,8 +36,6 @@ public class ByteBufPrimitiveCodecTest { private ByteBufPrimitiveCodec codec = new ByteBufPrimitiveCodec(ByteBufAllocator.DEFAULT); - @Rule public ExpectedException expectedException = ExpectedException.none(); - @Test public void should_concatenate() { ByteBuf left = ByteBufs.wrap(0xca, 0xfe); @@ -91,8 +90,6 @@ public void should_read_inet_v6() { @Test public void should_fail_to_read_inet_if_length_invalid() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Invalid address length: 3 ([127, 0, 1])"); ByteBuf source = ByteBufs.wrap( // length (as a byte) @@ -106,7 +103,9 @@ public void should_fail_to_read_inet_if_length_invalid() { 0x00, 0x23, 0x52); - codec.readInet(source); + assertThatThrownBy(() -> codec.readInet(source)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid address length: 3 ([127, 0, 1])"); } @Test @@ -136,9 +135,6 @@ public void should_read_inetaddr_v6() { @Test public void should_fail_to_read_inetaddr_if_length_invalid() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Invalid address length: 3 ([127, 0, 1])"); - ByteBuf source = ByteBufs.wrap( // length (as a byte) @@ -147,7 +143,9 @@ public void should_fail_to_read_inetaddr_if_length_invalid() { 0x7f, 0x00, 0x01); - codec.readInetAddr(source); + assertThatThrownBy(() -> codec.readInetAddr(source)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid address length: 3 ([127, 0, 1])"); } @Test @@ -168,6 +166,64 @@ public void should_read_bytes() { assertThat(Bytes.toHexString(bytes)).isEqualTo("0xcafebabe"); } + @Test + public void should_read_bytes_when_extra_data() { + ByteBuf source = + ByteBufs.wrap( + // length (as an int) + 0x00, + 0x00, + 0x00, + 0x04, + // contents + 0xca, + 0xfe, + 0xba, + 0xbe, + 0xde, + 0xda, + 0xdd); + ByteBuffer bytes = codec.readBytes(source); + assertThat(Bytes.toHexString(bytes)).isEqualTo("0xcafebabe"); + } + + @Test + public void read_bytes_should_udpate_reader_index() { + ByteBuf source = + ByteBufs.wrap( + // length (as an int) + 0x00, + 0x00, + 0x00, + 0x04, + // contents + 0xca, + 0xfe, + 0xba, + 0xbe, + 0xde, + 0xda, + 0xdd); + codec.readBytes(source); + + assertThat(source.readerIndex()).isEqualTo(8); + } + + @Test + public void read_bytes_should_throw_when_not_enough_content() { + ByteBuf source = + ByteBufs.wrap( + // length (as an int) : 4 bytes + 0x00, + 0x00, + 0x00, + 0x04, + // contents : only 2 bytes + 0xca, + 0xfe); + assertThatThrownBy(() -> codec.readBytes(source)).isInstanceOf(IndexOutOfBoundsException.class); + } + @Test public void should_read_null_bytes() { ByteBuf source = ByteBufs.wrap(0xFF, 0xFF, 0xFF, 0xFF); // -1 (as an int) @@ -207,14 +263,12 @@ public void should_read_string() { @Test public void should_fail_to_read_string_if_not_enough_characters() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage( - "Not enough bytes to read an UTF-8 serialized string of size 4"); - ByteBuf source = codec.allocate(2); source.writeShort(4); - codec.readString(source); + assertThatThrownBy(() -> codec.readString(source)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Not enough bytes to read an UTF-8 serialized string of size 4"); } @Test @@ -237,13 +291,12 @@ public void should_read_long_string() { @Test public void should_fail_to_read_long_string_if_not_enough_characters() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage( - "Not enough bytes to read an UTF-8 serialized string of size 4"); ByteBuf source = codec.allocate(4); source.writeInt(4); - codec.readLongString(source); + assertThatThrownBy(() -> codec.readLongString(source)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Not enough bytes to read an UTF-8 serialized string of size 4"); } @Test diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/protocol/BytesToSegmentDecoderTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/protocol/BytesToSegmentDecoderTest.java index f4376a3f2ee..d151da309c1 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/protocol/BytesToSegmentDecoderTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/protocol/BytesToSegmentDecoderTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/protocol/FrameDecoderTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/protocol/FrameDecoderTest.java index c223cb15462..0ab61771da0 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/protocol/FrameDecoderTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/protocol/FrameDecoderTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/protocol/SegmentToFrameDecoderTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/protocol/SegmentToFrameDecoderTest.java index 2bb93f0901b..2886adeab4e 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/protocol/SegmentToFrameDecoderTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/protocol/SegmentToFrameDecoderTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -73,7 +75,8 @@ public void should_decode_sequence_of_slices() { encodeFrame(new AuthResponse(Bytes.fromHexString("0x" + Strings.repeat("aa", 1011)))); int sliceLength = 100; do { - ByteBuf payload = encodedFrame.readSlice(Math.min(sliceLength, encodedFrame.readableBytes())); + ByteBuf payload = + encodedFrame.readRetainedSlice(Math.min(sliceLength, encodedFrame.readableBytes())); channel.writeInbound(new Segment<>(payload, false)); } while (encodedFrame.isReadable()); diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/protocol/SliceWriteListenerTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/protocol/SliceWriteListenerTest.java index 6e2d0655195..736bcb66d56 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/protocol/SliceWriteListenerTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/protocol/SliceWriteListenerTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/session/DefaultSessionPoolsTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/session/DefaultSessionPoolsTest.java index b42f281a02a..58d1783038d 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/session/DefaultSessionPoolsTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/session/DefaultSessionPoolsTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -105,14 +107,13 @@ public class DefaultSessionPoolsTest { private DefaultNode node1; private DefaultNode node2; private DefaultNode node3; - private DefaultEventLoopGroup adminEventLoopGroup; private EventBus eventBus; @Before public void setup() { MockitoAnnotations.initMocks(this); - adminEventLoopGroup = new DefaultEventLoopGroup(1); + DefaultEventLoopGroup adminEventLoopGroup = new DefaultEventLoopGroup(1); when(nettyOptions.adminEventExecutorGroup()).thenReturn(adminEventLoopGroup); when(context.getNettyOptions()).thenReturn(nettyOptions); @@ -153,6 +154,7 @@ public void setup() { node1 = mockLocalNode(1); node2 = mockLocalNode(2); node3 = mockLocalNode(3); + @SuppressWarnings("ConstantConditions") ImmutableMap nodes = ImmutableMap.of( node1.getHostId(), node1, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/session/MockChannelPoolFactoryHelper.java b/core/src/test/java/com/datastax/oss/driver/internal/core/session/MockChannelPoolFactoryHelper.java index 4aa7e414939..6c3dc7f3689 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/session/MockChannelPoolFactoryHelper.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/session/MockChannelPoolFactoryHelper.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/session/PoolManagerTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/session/PoolManagerTest.java new file mode 100644 index 00000000000..60483da4c72 --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/session/PoolManagerTest.java @@ -0,0 +1,70 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +import com.datastax.oss.driver.api.core.config.DefaultDriverOption; +import com.datastax.oss.driver.api.core.config.DriverConfig; +import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; +import com.datastax.oss.driver.internal.core.context.EventBus; +import com.datastax.oss.driver.internal.core.context.InternalDriverContext; +import com.datastax.oss.driver.internal.core.context.NettyOptions; +import io.netty.channel.DefaultEventLoopGroup; +import java.util.concurrent.ConcurrentHashMap; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +public class PoolManagerTest { + @Mock private InternalDriverContext context; + @Mock private NettyOptions nettyOptions; + @Mock private DriverConfig config; + @Mock private DriverExecutionProfile defaultProfile; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + + DefaultEventLoopGroup adminEventLoopGroup = new DefaultEventLoopGroup(1); + when(nettyOptions.adminEventExecutorGroup()).thenReturn(adminEventLoopGroup); + when(context.getNettyOptions()).thenReturn(nettyOptions); + when(context.getEventBus()).thenReturn(new EventBus("test")); + when(config.getDefaultProfile()).thenReturn(defaultProfile); + when(context.getConfig()).thenReturn(config); + } + + @Test + public void should_use_weak_values_if_config_is_true_or_undefined() { + when(defaultProfile.getBoolean(DefaultDriverOption.PREPARED_CACHE_WEAK_VALUES, true)) + .thenReturn(true); + // As weak values map class is MapMakerInternalMap + assertThat(new PoolManager(context).getRepreparePayloads()) + .isNotInstanceOf(ConcurrentHashMap.class); + } + + @Test + public void should_not_use_weak_values_if_config_is_false() { + when(defaultProfile.getBoolean(DefaultDriverOption.PREPARED_CACHE_WEAK_VALUES, true)) + .thenReturn(false); + assertThat(new PoolManager(context).getRepreparePayloads()) + .isInstanceOf(ConcurrentHashMap.class); + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/session/ReprepareOnUpTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/session/ReprepareOnUpTest.java index 2be35a00ab7..555ed2e8806 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/session/ReprepareOnUpTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/session/ReprepareOnUpTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/session/throttling/ConcurrencyLimitingRequestThrottlerTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/session/throttling/ConcurrencyLimitingRequestThrottlerTest.java index a9f4233513b..7eb682070cd 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/session/throttling/ConcurrencyLimitingRequestThrottlerTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/session/throttling/ConcurrencyLimitingRequestThrottlerTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -27,6 +29,7 @@ import com.datastax.oss.driver.api.core.session.throttling.Throttled; import com.datastax.oss.driver.shaded.guava.common.collect.Lists; import java.util.List; +import java.util.concurrent.CountDownLatch; import java.util.function.Consumer; import org.junit.Before; import org.junit.Test; @@ -65,7 +68,7 @@ public void should_start_immediately_when_under_capacity() { throttler.register(request); // Then - assertThatStage(request.started).isSuccess(wasDelayed -> assertThat(wasDelayed).isFalse()); + assertThatStage(request.ended).isSuccess(wasDelayed -> assertThat(wasDelayed).isFalse()); assertThat(throttler.getConcurrentRequests()).isEqualTo(1); assertThat(throttler.getQueue()).isEmpty(); } @@ -86,12 +89,17 @@ public void should_allow_new_request_when_active_one_times_out() { should_allow_new_request_when_active_one_completes(throttler::signalTimeout); } + @Test + public void should_allow_new_request_when_active_one_canceled() { + should_allow_new_request_when_active_one_completes(throttler::signalCancel); + } + private void should_allow_new_request_when_active_one_completes( Consumer completeCallback) { // Given MockThrottled first = new MockThrottled(); throttler.register(first); - assertThatStage(first.started).isSuccess(wasDelayed -> assertThat(wasDelayed).isFalse()); + assertThatStage(first.ended).isSuccess(wasDelayed -> assertThat(wasDelayed).isFalse()); for (int i = 0; i < 4; i++) { // fill to capacity throttler.register(new MockThrottled()); } @@ -106,7 +114,7 @@ private void should_allow_new_request_when_active_one_completes( throttler.register(incoming); // Then - assertThatStage(incoming.started).isSuccess(wasDelayed -> assertThat(wasDelayed).isFalse()); + assertThatStage(incoming.ended).isSuccess(wasDelayed -> assertThat(wasDelayed).isFalse()); assertThat(throttler.getConcurrentRequests()).isEqualTo(5); assertThat(throttler.getQueue()).isEmpty(); } @@ -125,7 +133,7 @@ public void should_enqueue_when_over_capacity() { throttler.register(incoming); // Then - assertThatStage(incoming.started).isNotDone(); + assertThatStage(incoming.ended).isNotDone(); assertThat(throttler.getConcurrentRequests()).isEqualTo(5); assertThat(throttler.getQueue()).containsExactly(incoming); } @@ -150,20 +158,20 @@ private void should_dequeue_when_active_completes(Consumer completeCa // Given MockThrottled first = new MockThrottled(); throttler.register(first); - assertThatStage(first.started).isSuccess(wasDelayed -> assertThat(wasDelayed).isFalse()); + assertThatStage(first.ended).isSuccess(wasDelayed -> assertThat(wasDelayed).isFalse()); for (int i = 0; i < 4; i++) { throttler.register(new MockThrottled()); } MockThrottled incoming = new MockThrottled(); throttler.register(incoming); - assertThatStage(incoming.started).isNotDone(); + assertThatStage(incoming.ended).isNotDone(); // When completeCallback.accept(first); // Then - assertThatStage(incoming.started).isSuccess(wasDelayed -> assertThat(wasDelayed).isTrue()); + assertThatStage(incoming.ended).isSuccess(wasDelayed -> assertThat(wasDelayed).isTrue()); assertThat(throttler.getConcurrentRequests()).isEqualTo(5); assertThat(throttler.getQueue()).isEmpty(); } @@ -182,7 +190,7 @@ public void should_reject_when_queue_is_full() { throttler.register(incoming); // Then - assertThatStage(incoming.started) + assertThatStage(incoming.ended) .isFailed(error -> assertThat(error).isInstanceOf(RequestThrottlingException.class)); } @@ -201,7 +209,7 @@ public void should_remove_timed_out_request_from_queue() { throttler.signalTimeout(queued1); // Then - assertThatStage(queued2.started).isNotDone(); + assertThatStage(queued2.ended).isNotDone(); assertThat(throttler.getConcurrentRequests()).isEqualTo(5); assertThat(throttler.getQueue()).hasSize(1); } @@ -216,7 +224,7 @@ public void should_reject_enqueued_when_closing() { for (int i = 0; i < 10; i++) { MockThrottled request = new MockThrottled(); throttler.register(request); - assertThatStage(request.started).isNotDone(); + assertThatStage(request.ended).isNotDone(); enqueued.add(request); } @@ -225,7 +233,7 @@ public void should_reject_enqueued_when_closing() { // Then for (MockThrottled request : enqueued) { - assertThatStage(request.started) + assertThatStage(request.ended) .isFailed(error -> assertThat(error).isInstanceOf(RequestThrottlingException.class)); } @@ -234,7 +242,125 @@ public void should_reject_enqueued_when_closing() { throttler.register(request); // Then - assertThatStage(request.started) + assertThatStage(request.ended) .isFailed(error -> assertThat(error).isInstanceOf(RequestThrottlingException.class)); } + + @Test + public void should_run_throttle_callbacks_concurrently() throws InterruptedException { + // Given + + // a task is enqueued, which when in onThrottleReady, will stall latch countDown()ed + // register() should automatically start onThrottleReady on same thread + + // start a parallel thread + CountDownLatch firstRelease = new CountDownLatch(1); + MockThrottled first = new MockThrottled(firstRelease); + Runnable r = + () -> { + throttler.register(first); + first.ended.toCompletableFuture().thenRun(() -> throttler.signalSuccess(first)); + }; + Thread t = new Thread(r); + t.start(); + + // wait for the registration threads to reach await state + assertThatStage(first.started).isSuccess(); + assertThatStage(first.ended).isNotDone(); + + // When + // we concurrently submit a second shorter task + MockThrottled second = new MockThrottled(); + // (on a second thread, so that we can join and force a timeout in case + // registration is delayed) + Thread t2 = new Thread(() -> throttler.register(second)); + t2.start(); + t2.join(1_000); + + // Then + // registration will trigger callback, should complete ~immediately + assertThatStage(second.ended).isSuccess(wasDelayed -> assertThat(wasDelayed).isFalse()); + // first should still be unfinished + assertThatStage(first.started).isDone(); + assertThatStage(first.ended).isNotDone(); + // now finish, and verify + firstRelease.countDown(); + assertThatStage(first.ended).isSuccess(wasDelayed -> assertThat(wasDelayed).isFalse()); + + t.join(1_000); + } + + @Test + public void should_enqueue_tasks_quickly_when_callbacks_blocked() throws InterruptedException { + // Given + + // Multiple tasks are registered, up to the limit, and proceed into their + // callback + + // start five parallel threads + final int THREADS = 5; + Thread[] threads = new Thread[THREADS]; + CountDownLatch[] latches = new CountDownLatch[THREADS]; + MockThrottled[] throttled = new MockThrottled[THREADS]; + for (int i = 0; i < threads.length; i++) { + latches[i] = new CountDownLatch(1); + final MockThrottled itThrottled = new MockThrottled(latches[i]); + throttled[i] = itThrottled; + threads[i] = + new Thread( + () -> { + throttler.register(itThrottled); + itThrottled + .ended + .toCompletableFuture() + .thenRun(() -> throttler.signalSuccess(itThrottled)); + }); + threads[i].start(); + } + + // wait for the registration threads to be launched + // they are all waiting now + for (int i = 0; i < throttled.length; i++) { + assertThatStage(throttled[i].started).isSuccess(); + assertThatStage(throttled[i].ended).isNotDone(); + } + + // When + // we concurrently submit another task + MockThrottled last = new MockThrottled(); + throttler.register(last); + + // Then + // registration will enqueue the callback, and it should not + // take any time to proceed (ie: we should not be blocked) + // and there should be an element in the queue + assertThatStage(last.started).isNotDone(); + assertThatStage(last.ended).isNotDone(); + assertThat(throttler.getQueue()).containsExactly(last); + + // we still have not released, so old throttled threads should be waiting + for (int i = 0; i < throttled.length; i++) { + assertThatStage(throttled[i].started).isDone(); + assertThatStage(throttled[i].ended).isNotDone(); + } + + // now let us release .. + for (int i = 0; i < latches.length; i++) { + latches[i].countDown(); + } + + // .. and check everything finished up OK + for (int i = 0; i < latches.length; i++) { + assertThatStage(throttled[i].started).isSuccess(); + assertThatStage(throttled[i].ended).isSuccess(); + } + + // for good measure, we will also wait for the enqueued to complete + assertThatStage(last.started).isSuccess(); + assertThatStage(last.ended).isSuccess(); + + for (int i = 0; i < threads.length; i++) { + threads[i].join(1_000); + } + } } diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/session/throttling/MockThrottled.java b/core/src/test/java/com/datastax/oss/driver/internal/core/session/throttling/MockThrottled.java index ab723b150b0..9e54e3d511f 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/session/throttling/MockThrottled.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/session/throttling/MockThrottled.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -17,21 +19,45 @@ import com.datastax.oss.driver.api.core.RequestThrottlingException; import com.datastax.oss.driver.api.core.session.throttling.Throttled; +import com.datastax.oss.driver.shaded.guava.common.util.concurrent.Uninterruptibles; import edu.umd.cs.findbugs.annotations.NonNull; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; +import java.util.concurrent.CountDownLatch; class MockThrottled implements Throttled { + final CompletionStage started = new CompletableFuture<>(); + final CompletionStage ended = new CompletableFuture<>(); + final CountDownLatch canRelease; + + public MockThrottled() { + this(new CountDownLatch(0)); + } - final CompletionStage started = new CompletableFuture<>(); + /* + * The releaseLatch can be provided to add some delay before the + * task readiness/fail callbacks complete. This can be used, eg, to + * imitate a slow callback. + */ + public MockThrottled(CountDownLatch releaseLatch) { + this.canRelease = releaseLatch; + } @Override public void onThrottleReady(boolean wasDelayed) { - started.toCompletableFuture().complete(wasDelayed); + started.toCompletableFuture().complete(null); + awaitRelease(); + ended.toCompletableFuture().complete(wasDelayed); } @Override public void onThrottleFailure(@NonNull RequestThrottlingException error) { - started.toCompletableFuture().completeExceptionally(error); + started.toCompletableFuture().complete(null); + awaitRelease(); + ended.toCompletableFuture().completeExceptionally(error); + } + + private void awaitRelease() { + Uninterruptibles.awaitUninterruptibly(canRelease); } } diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/session/throttling/RateLimitingRequestThrottlerTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/session/throttling/RateLimitingRequestThrottlerTest.java index 26b52403e8f..1e15610bf7b 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/session/throttling/RateLimitingRequestThrottlerTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/session/throttling/RateLimitingRequestThrottlerTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -23,6 +25,7 @@ import com.datastax.oss.driver.api.core.config.DefaultDriverOption; import com.datastax.oss.driver.api.core.config.DriverConfig; import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; +import com.datastax.oss.driver.api.core.session.throttling.Throttled; import com.datastax.oss.driver.internal.core.context.InternalDriverContext; import com.datastax.oss.driver.internal.core.context.NettyOptions; import com.datastax.oss.driver.internal.core.util.concurrent.ScheduledTaskCapturingEventLoop; @@ -31,6 +34,7 @@ import java.time.Duration; import java.util.List; import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -94,7 +98,7 @@ public void should_start_immediately_when_under_capacity() { throttler.register(request); // Then - assertThatStage(request.started).isSuccess(wasDelayed -> assertThat(wasDelayed).isFalse()); + assertThatStage(request.ended).isSuccess(wasDelayed -> assertThat(wasDelayed).isFalse()); assertThat(throttler.getStoredPermits()).isEqualTo(4); assertThat(throttler.getQueue()).isEmpty(); } @@ -113,7 +117,7 @@ public void should_allow_new_request_when_under_rate() { throttler.register(request); // Then - assertThatStage(request.started).isSuccess(wasDelayed -> assertThat(wasDelayed).isFalse()); + assertThatStage(request.ended).isSuccess(wasDelayed -> assertThat(wasDelayed).isFalse()); assertThat(throttler.getStoredPermits()).isEqualTo(0); assertThat(throttler.getQueue()).isEmpty(); } @@ -132,7 +136,7 @@ public void should_enqueue_when_over_rate() { throttler.register(request); // Then - assertThatStage(request.started).isNotDone(); + assertThatStage(request.ended).isNotDone(); assertThat(throttler.getStoredPermits()).isEqualTo(0); assertThat(throttler.getQueue()).containsExactly(request); @@ -156,12 +160,21 @@ public void should_reject_when_queue_is_full() { throttler.register(request); // Then - assertThatStage(request.started) + assertThatStage(request.ended) .isFailed(error -> assertThat(error).isInstanceOf(RequestThrottlingException.class)); } @Test public void should_remove_timed_out_request_from_queue() { + testRemoveInvalidEventFromQueue(throttler::signalTimeout); + } + + @Test + public void should_remove_cancel_request_from_queue() { + testRemoveInvalidEventFromQueue(throttler::signalCancel); + } + + private void testRemoveInvalidEventFromQueue(Consumer completeCallback) { // Given for (int i = 0; i < 5; i++) { throttler.register(new MockThrottled()); @@ -172,10 +185,10 @@ public void should_remove_timed_out_request_from_queue() { throttler.register(queued2); // When - throttler.signalTimeout(queued1); + completeCallback.accept(queued1); // Then - assertThatStage(queued2.started).isNotDone(); + assertThatStage(queued2.ended).isNotDone(); assertThat(throttler.getStoredPermits()).isEqualTo(0); assertThat(throttler.getQueue()).containsExactly(queued2); } @@ -189,10 +202,10 @@ public void should_dequeue_when_draining_task_runs() { MockThrottled queued1 = new MockThrottled(); throttler.register(queued1); - assertThatStage(queued1.started).isNotDone(); + assertThatStage(queued1.ended).isNotDone(); MockThrottled queued2 = new MockThrottled(); throttler.register(queued2); - assertThatStage(queued2.started).isNotDone(); + assertThatStage(queued2.ended).isNotDone(); assertThat(throttler.getStoredPermits()).isEqualTo(0); assertThat(throttler.getQueue()).hasSize(2); @@ -217,8 +230,8 @@ public void should_dequeue_when_draining_task_runs() { task.run(); // Then - assertThatStage(queued1.started).isSuccess(wasDelayed -> assertThat(wasDelayed).isTrue()); - assertThatStage(queued2.started).isNotDone(); + assertThatStage(queued1.ended).isSuccess(wasDelayed -> assertThat(wasDelayed).isTrue()); + assertThatStage(queued2.ended).isNotDone(); assertThat(throttler.getStoredPermits()).isEqualTo(0); assertThat(throttler.getQueue()).containsExactly(queued2); // task reschedules itself since it did not empty the queue @@ -231,7 +244,7 @@ public void should_dequeue_when_draining_task_runs() { task.run(); // Then - assertThatStage(queued2.started).isSuccess(wasDelayed -> assertThat(wasDelayed).isTrue()); + assertThatStage(queued2.ended).isSuccess(wasDelayed -> assertThat(wasDelayed).isTrue()); assertThat(throttler.getStoredPermits()).isEqualTo(0); assertThat(throttler.getQueue()).isEmpty(); assertThat(adminExecutor.nextTask()).isNull(); @@ -273,14 +286,14 @@ public void should_keep_accumulating_time_if_no_permits_created() { // Then MockThrottled queued = new MockThrottled(); throttler.register(queued); - assertThatStage(queued.started).isNotDone(); + assertThatStage(queued.ended).isNotDone(); // When clock.add(ONE_HUNDRED_MILLISECONDS); adminExecutor.nextTask().run(); // Then - assertThatStage(queued.started).isSuccess(wasDelayed -> assertThat(wasDelayed).isTrue()); + assertThatStage(queued.ended).isSuccess(wasDelayed -> assertThat(wasDelayed).isTrue()); } @Test @@ -293,7 +306,7 @@ public void should_reject_enqueued_when_closing() { for (int i = 0; i < 10; i++) { MockThrottled request = new MockThrottled(); throttler.register(request); - assertThatStage(request.started).isNotDone(); + assertThatStage(request.ended).isNotDone(); enqueued.add(request); } @@ -302,7 +315,7 @@ public void should_reject_enqueued_when_closing() { // Then for (MockThrottled request : enqueued) { - assertThatStage(request.started) + assertThatStage(request.ended) .isFailed(error -> assertThat(error).isInstanceOf(RequestThrottlingException.class)); } @@ -311,7 +324,7 @@ public void should_reject_enqueued_when_closing() { throttler.register(request); // Then - assertThatStage(request.started) + assertThatStage(request.ended) .isFailed(error -> assertThat(error).isInstanceOf(RequestThrottlingException.class)); } } diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/session/throttling/SettableNanoClock.java b/core/src/test/java/com/datastax/oss/driver/internal/core/session/throttling/SettableNanoClock.java index 51cbd666f51..1489d1da345 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/session/throttling/SettableNanoClock.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/session/throttling/SettableNanoClock.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/ssl/ReloadingKeyManagerFactoryTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/ssl/ReloadingKeyManagerFactoryTest.java new file mode 100644 index 00000000000..d07b45c21df --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/ssl/ReloadingKeyManagerFactoryTest.java @@ -0,0 +1,270 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.ssl; + +import static java.nio.file.StandardCopyOption.COPY_ATTRIBUTES; +import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; + +import java.io.IOException; +import java.io.InputStream; +import java.math.BigInteger; +import java.net.InetSocketAddress; +import java.net.SocketAddress; +import java.net.SocketException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.KeyManagementException; +import java.security.KeyStore; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.security.cert.X509Certificate; +import java.util.Optional; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; +import java.util.function.Supplier; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLPeerUnverifiedException; +import javax.net.ssl.SSLServerSocket; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.TrustManagerFactory; +import org.junit.Assert; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ReloadingKeyManagerFactoryTest { + private static final Logger logger = + LoggerFactory.getLogger(ReloadingKeyManagerFactoryTest.class); + + static final Path CERT_BASE = + Paths.get( + ReloadingKeyManagerFactoryTest.class + .getResource( + String.format("/%s/certs/", ReloadingKeyManagerFactoryTest.class.getSimpleName())) + .getPath()); + static final Path SERVER_KEYSTORE_PATH = CERT_BASE.resolve("server.keystore"); + static final Path SERVER_TRUSTSTORE_PATH = CERT_BASE.resolve("server.truststore"); + + static final Path ORIGINAL_CLIENT_KEYSTORE_PATH = CERT_BASE.resolve("client-original.keystore"); + static final Path ALTERNATE_CLIENT_KEYSTORE_PATH = CERT_BASE.resolve("client-alternate.keystore"); + static final BigInteger ORIGINAL_CLIENT_KEYSTORE_CERT_SERIAL = + convertSerial("7372a966"); // 1936894310 + static final BigInteger ALTERNATE_CLIENT_KEYSTORE_CERT_SERIAL = + convertSerial("e50bf31"); // 240172849 + + // File at this path will change content + static final Path TMP_CLIENT_KEYSTORE_PATH; + + static { + try { + TMP_CLIENT_KEYSTORE_PATH = + Files.createTempFile(ReloadingKeyManagerFactoryTest.class.getSimpleName(), null); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + static final Path CLIENT_TRUSTSTORE_PATH = CERT_BASE.resolve("client.truststore"); + static final String CERTSTORE_PASSWORD = "changeit"; + + private static TrustManagerFactory buildTrustManagerFactory() { + TrustManagerFactory tmf; + try (InputStream tsf = Files.newInputStream(CLIENT_TRUSTSTORE_PATH)) { + KeyStore ts = KeyStore.getInstance("JKS"); + char[] password = CERTSTORE_PASSWORD.toCharArray(); + ts.load(tsf, password); + tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + tmf.init(ts); + } catch (Exception e) { + throw new RuntimeException(e); + } + return tmf; + } + + private static SSLContext buildServerSslContext() { + try { + SSLContext context = SSLContext.getInstance("SSL"); + + TrustManagerFactory tmf; + try (InputStream tsf = Files.newInputStream(SERVER_TRUSTSTORE_PATH)) { + KeyStore ts = KeyStore.getInstance("JKS"); + char[] password = CERTSTORE_PASSWORD.toCharArray(); + ts.load(tsf, password); + tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + tmf.init(ts); + } + + KeyManagerFactory kmf; + try (InputStream ksf = Files.newInputStream(SERVER_KEYSTORE_PATH)) { + KeyStore ks = KeyStore.getInstance("JKS"); + char[] password = CERTSTORE_PASSWORD.toCharArray(); + ks.load(ksf, password); + kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + kmf.init(ks, password); + } + + context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom()); + return context; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Test + public void client_certificates_should_reload() throws Exception { + Files.copy( + ORIGINAL_CLIENT_KEYSTORE_PATH, TMP_CLIENT_KEYSTORE_PATH, REPLACE_EXISTING, COPY_ATTRIBUTES); + + final BlockingQueue> peerCertificates = + new LinkedBlockingQueue<>(1); + + // Create a listening socket. Make sure there's no backlog so each accept is in order. + SSLContext serverSslContext = buildServerSslContext(); + final SSLServerSocket server = + (SSLServerSocket) serverSslContext.getServerSocketFactory().createServerSocket(); + server.bind(new InetSocketAddress(0), 1); + server.setUseClientMode(false); + server.setNeedClientAuth(true); + Thread serverThread = + new Thread( + () -> { + while (true) { + try { + logger.info("Server accepting client"); + final SSLSocket conn = (SSLSocket) server.accept(); + logger.info("Server accepted client {}", conn); + conn.addHandshakeCompletedListener( + event -> { + boolean offer; + try { + // Transfer certificates to client thread once handshake is complete, so + // it can safely close + // the socket + offer = + peerCertificates.offer( + Optional.of((X509Certificate[]) event.getPeerCertificates())); + } catch (SSLPeerUnverifiedException e) { + offer = peerCertificates.offer(Optional.empty()); + } + Assert.assertTrue(offer); + }); + logger.info("Server starting handshake"); + // Without this, client handshake blocks + conn.startHandshake(); + } catch (IOException e) { + // Not sure why I sometimes see ~thousands of these locally + if (e instanceof SocketException && e.getMessage().contains("Socket closed")) + return; + logger.info("Server accept error", e); + } + } + }); + serverThread.setName(String.format("%s-serverThread", this.getClass().getSimpleName())); + serverThread.setDaemon(true); + serverThread.start(); + + final ReloadingKeyManagerFactory kmf = + ReloadingKeyManagerFactory.create( + TMP_CLIENT_KEYSTORE_PATH, CERTSTORE_PASSWORD, Optional.empty()); + // Need a tmf that tells the server to send its certs + final TrustManagerFactory tmf = buildTrustManagerFactory(); + + // Check original client certificate + testClientCertificates( + kmf, + tmf, + server.getLocalSocketAddress(), + () -> { + try { + return peerCertificates.poll(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + }, + certs -> { + Assert.assertEquals(1, certs.length); + X509Certificate cert = certs[0]; + Assert.assertEquals(ORIGINAL_CLIENT_KEYSTORE_CERT_SERIAL, cert.getSerialNumber()); + }); + + // Update keystore content + logger.info("Updating keystore file with new content"); + Files.copy( + ALTERNATE_CLIENT_KEYSTORE_PATH, + TMP_CLIENT_KEYSTORE_PATH, + REPLACE_EXISTING, + COPY_ATTRIBUTES); + kmf.reload(); + + // Check that alternate client certificate was applied + testClientCertificates( + kmf, + tmf, + server.getLocalSocketAddress(), + () -> { + try { + return peerCertificates.poll(30, TimeUnit.SECONDS); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + }, + certs -> { + Assert.assertEquals(1, certs.length); + X509Certificate cert = certs[0]; + Assert.assertEquals(ALTERNATE_CLIENT_KEYSTORE_CERT_SERIAL, cert.getSerialNumber()); + }); + + kmf.close(); + server.close(); + } + + private static void testClientCertificates( + KeyManagerFactory kmf, + TrustManagerFactory tmf, + SocketAddress serverAddress, + Supplier> certsSupplier, + Consumer certsConsumer) + throws NoSuchAlgorithmException, KeyManagementException, IOException { + SSLContext clientSslContext = SSLContext.getInstance("TLS"); + clientSslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); + final SSLSocket client = (SSLSocket) clientSslContext.getSocketFactory().createSocket(); + logger.info("Client connecting"); + client.connect(serverAddress); + logger.info("Client doing handshake"); + client.startHandshake(); + + final Optional lastCertificate = certsSupplier.get(); + logger.info("Client got its certificate back from the server; closing socket"); + client.close(); + Assert.assertNotNull(lastCertificate); + Assert.assertTrue(lastCertificate.isPresent()); + logger.info("Client got its certificate back from server: {}", lastCertificate); + + certsConsumer.accept(lastCertificate.get()); + } + + private static BigInteger convertSerial(String hex) { + final BigInteger serial = new BigInteger(Integer.valueOf(hex, 16).toString()); + logger.info("Serial hex {} is {}", hex, serial); + return serial; + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/time/AtomicTimestampGeneratorTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/time/AtomicTimestampGeneratorTest.java index fa4adec9e6c..f1827eb8a86 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/time/AtomicTimestampGeneratorTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/time/AtomicTimestampGeneratorTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/time/MonotonicTimestampGeneratorTestBase.java b/core/src/test/java/com/datastax/oss/driver/internal/core/time/MonotonicTimestampGeneratorTestBase.java index 59324205872..7074dd4ccc2 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/time/MonotonicTimestampGeneratorTestBase.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/time/MonotonicTimestampGeneratorTestBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/time/ThreadLocalTimestampGeneratorTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/time/ThreadLocalTimestampGeneratorTest.java index 6de3a2b5e41..5d9ed8b2ceb 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/time/ThreadLocalTimestampGeneratorTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/time/ThreadLocalTimestampGeneratorTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/tracker/MultiplexingRequestTrackerTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/tracker/MultiplexingRequestTrackerTest.java new file mode 100644 index 00000000000..8dcad99b459 --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/tracker/MultiplexingRequestTrackerTest.java @@ -0,0 +1,213 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.tracker; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Mockito.verify; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.Appender; +import com.datastax.oss.driver.api.core.DriverExecutionException; +import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; +import com.datastax.oss.driver.api.core.metadata.Node; +import com.datastax.oss.driver.api.core.session.Request; +import com.datastax.oss.driver.api.core.session.Session; +import com.datastax.oss.driver.api.core.tracker.RequestTracker; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.slf4j.LoggerFactory; + +@RunWith(MockitoJUnitRunner.Strict.class) +public class MultiplexingRequestTrackerTest { + + @Mock private RequestTracker child1; + @Mock private RequestTracker child2; + @Mock private Request request; + @Mock private DriverExecutionProfile profile; + @Mock private Node node; + @Mock private Session session; + + @Mock private Appender appender; + @Captor private ArgumentCaptor loggingEventCaptor; + + private Logger logger; + private Level initialLogLevel; + + private final Exception error = new DriverExecutionException(new NullPointerException()); + + @Before + public void addAppenders() { + logger = (Logger) LoggerFactory.getLogger(MultiplexingRequestTracker.class); + initialLogLevel = logger.getLevel(); + logger.setLevel(Level.WARN); + logger.addAppender(appender); + } + + @After + public void removeAppenders() { + logger.detachAppender(appender); + logger.setLevel(initialLogLevel); + } + + @Test + public void should_register() { + // given + MultiplexingRequestTracker tracker = new MultiplexingRequestTracker(); + // when + tracker.register(child1); + tracker.register(child2); + // then + assertThat(tracker).extracting("trackers").asList().hasSize(2).contains(child1, child2); + } + + @Test + public void should_flatten_child_multiplexing_tracker_via_constructor() { + // given + MultiplexingRequestTracker tracker = + new MultiplexingRequestTracker(new MultiplexingRequestTracker(child1, child2)); + // when + // then + assertThat(tracker).extracting("trackers").asList().hasSize(2).contains(child1, child2); + } + + @Test + public void should_flatten_child_multiplexing_tracker_via_register() { + // given + MultiplexingRequestTracker tracker = new MultiplexingRequestTracker(); + // when + tracker.register(new MultiplexingRequestTracker(child1, child2)); + // then + assertThat(tracker).extracting("trackers").asList().hasSize(2).contains(child1, child2); + } + + @Test + public void should_notify_onSuccess() { + // given + MultiplexingRequestTracker tracker = new MultiplexingRequestTracker(child1, child2); + willThrow(new NullPointerException()) + .given(child1) + .onSuccess(request, 123456L, profile, node, "test"); + // when + tracker.onSuccess(request, 123456L, profile, node, "test"); + // then + verify(child1).onSuccess(request, 123456L, profile, node, "test"); + verify(child2).onSuccess(request, 123456L, profile, node, "test"); + verify(appender).doAppend(loggingEventCaptor.capture()); + assertThat(loggingEventCaptor.getAllValues().stream().map(ILoggingEvent::getFormattedMessage)) + .contains( + "[test] Unexpected error while notifying request tracker child1 of an onSuccess event. (NullPointerException: null)"); + } + + @Test + public void should_notify_onError() { + // given + MultiplexingRequestTracker tracker = new MultiplexingRequestTracker(child1, child2); + willThrow(new NullPointerException()) + .given(child1) + .onError(request, error, 123456L, profile, node, "test"); + // when + tracker.onError(request, error, 123456L, profile, node, "test"); + // then + verify(child1).onError(request, error, 123456L, profile, node, "test"); + verify(child2).onError(request, error, 123456L, profile, node, "test"); + verify(appender).doAppend(loggingEventCaptor.capture()); + assertThat(loggingEventCaptor.getAllValues().stream().map(ILoggingEvent::getFormattedMessage)) + .contains( + "[test] Unexpected error while notifying request tracker child1 of an onError event. (NullPointerException: null)"); + } + + @Test + public void should_notify_onNodeSuccess() { + // given + MultiplexingRequestTracker tracker = new MultiplexingRequestTracker(child1, child2); + willThrow(new NullPointerException()) + .given(child1) + .onNodeSuccess(request, 123456L, profile, node, "test"); + // when + tracker.onNodeSuccess(request, 123456L, profile, node, "test"); + // then + verify(child1).onNodeSuccess(request, 123456L, profile, node, "test"); + verify(child2).onNodeSuccess(request, 123456L, profile, node, "test"); + verify(appender).doAppend(loggingEventCaptor.capture()); + assertThat(loggingEventCaptor.getAllValues().stream().map(ILoggingEvent::getFormattedMessage)) + .contains( + "[test] Unexpected error while notifying request tracker child1 of an onNodeSuccess event. (NullPointerException: null)"); + } + + @Test + public void should_notify_onNodeError() { + // given + MultiplexingRequestTracker tracker = new MultiplexingRequestTracker(child1, child2); + willThrow(new NullPointerException()) + .given(child1) + .onNodeError(request, error, 123456L, profile, node, "test"); + // when + tracker.onNodeError(request, error, 123456L, profile, node, "test"); + // then + verify(child1).onNodeError(request, error, 123456L, profile, node, "test"); + verify(child2).onNodeError(request, error, 123456L, profile, node, "test"); + verify(appender).doAppend(loggingEventCaptor.capture()); + assertThat(loggingEventCaptor.getAllValues().stream().map(ILoggingEvent::getFormattedMessage)) + .contains( + "[test] Unexpected error while notifying request tracker child1 of an onNodeError event. (NullPointerException: null)"); + } + + @Test + public void should_notify_onSessionReady() { + // given + MultiplexingRequestTracker tracker = new MultiplexingRequestTracker(child1, child2); + willThrow(new NullPointerException()).given(child1).onSessionReady(session); + given(session.getName()).willReturn("test"); + // when + tracker.onSessionReady(session); + // then + verify(child1).onSessionReady(session); + verify(child2).onSessionReady(session); + verify(appender).doAppend(loggingEventCaptor.capture()); + assertThat(loggingEventCaptor.getAllValues().stream().map(ILoggingEvent::getFormattedMessage)) + .contains( + "[test] Unexpected error while notifying request tracker child1 of an onSessionReady event. (NullPointerException: null)"); + } + + @Test + public void should_notify_close() throws Exception { + // given + MultiplexingRequestTracker tracker = new MultiplexingRequestTracker(child1, child2); + Exception child1Error = new NullPointerException(); + willThrow(child1Error).given(child1).close(); + // when + tracker.close(); + // then + verify(child1).close(); + verify(child2).close(); + verify(appender).doAppend(loggingEventCaptor.capture()); + assertThat(loggingEventCaptor.getAllValues().stream().map(ILoggingEvent::getFormattedMessage)) + .contains( + "Unexpected error while closing request tracker child1. (NullPointerException: null)"); + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/tracker/RequestIdGeneratorTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/tracker/RequestIdGeneratorTest.java new file mode 100644 index 00000000000..fb1883e125f --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/tracker/RequestIdGeneratorTest.java @@ -0,0 +1,80 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.tracker; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.datastax.oss.driver.api.core.cql.Statement; +import com.datastax.oss.driver.api.core.tracker.RequestIdGenerator; +import com.datastax.oss.driver.internal.core.context.InternalDriverContext; +import org.apache.commons.lang3.RandomStringUtils; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.Strict.class) +public class RequestIdGeneratorTest { + @Mock private InternalDriverContext context; + @Mock private Statement statement; + + @Test + public void uuid_generator_should_generate() { + // given + UuidRequestIdGenerator generator = new UuidRequestIdGenerator(context); + // when + String parentId = generator.getSessionRequestId(); + String requestId = generator.getNodeRequestId(statement, parentId); + // then + // e.g. "550e8400-e29b-41d4-a716-446655440000", which is 36 characters long + assertThat(parentId.length()).isEqualTo(36); + // e.g. "550e8400-e29b-41d4-a716-446655440000-550e8400-e29b-41d4-a716-446655440000", which is 73 + // characters long + assertThat(requestId.length()).isEqualTo(73); + } + + @Test + public void w3c_generator_should_generate() { + // given + W3CContextRequestIdGenerator generator = new W3CContextRequestIdGenerator(context); + // when + String parentId = generator.getSessionRequestId(); + String requestId = generator.getNodeRequestId(statement, parentId); + // then + // e.g. "4bf92f3577b34da6a3ce929d0e0e4736", which is 32 characters long + assertThat(parentId.length()).isEqualTo(32); + // According to W3C "traceparent" spec, + // https://www.w3.org/TR/trace-context/#traceparent-header-field-values + // e.g. "00-4bf92f3577b34da6a3ce929d0e0e4736-a3ce929d0e0e4736-01", which 55 characters long + assertThat(requestId.length()).isEqualTo(55); + } + + @Test + public void w3c_generator_default_payloadkey() { + W3CContextRequestIdGenerator w3cGenerator = new W3CContextRequestIdGenerator(context); + assertThat(w3cGenerator.getCustomPayloadKey()) + .isEqualTo(RequestIdGenerator.DEFAULT_PAYLOAD_KEY); + } + + @Test + public void w3c_generator_provided_payloadkey() { + String someString = RandomStringUtils.random(12); + W3CContextRequestIdGenerator w3cGenerator = new W3CContextRequestIdGenerator(someString); + assertThat(w3cGenerator.getCustomPayloadKey()).isEqualTo(someString); + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/tracker/RequestLogFormatterTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/tracker/RequestLogFormatterTest.java index 160e5d04dd9..e9fb518b51f 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/tracker/RequestLogFormatterTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/tracker/RequestLogFormatterTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/DataTypeDetachableTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/DataTypeDetachableTest.java index e8dac19237b..d798df8d191 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/DataTypeDetachableTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/DataTypeDetachableTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/DataTypeSerializationTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/DataTypeSerializationTest.java index ed53b0b4e65..ccf53dd3a65 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/DataTypeSerializationTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/DataTypeSerializationTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/PrimitiveTypeTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/PrimitiveTypeTest.java new file mode 100644 index 00000000000..f9ae1d24f77 --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/PrimitiveTypeTest.java @@ -0,0 +1,120 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.type; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.datastax.oss.driver.TestDataProviders; +import com.datastax.oss.driver.api.core.type.DataTypes; +import com.datastax.oss.protocol.internal.ProtocolConstants; +import com.tngtech.java.junit.dataprovider.DataProviderRunner; +import com.tngtech.java.junit.dataprovider.UseDataProvider; +import java.util.Locale; +import org.junit.Test; +import org.junit.runner.RunWith; + +@RunWith(DataProviderRunner.class) +public class PrimitiveTypeTest { + + @Test + public void should_report_protocol_code() { + assertThat(DataTypes.ASCII.getProtocolCode()).isEqualTo(ProtocolConstants.DataType.ASCII); + assertThat(DataTypes.BIGINT.getProtocolCode()).isEqualTo(ProtocolConstants.DataType.BIGINT); + assertThat(DataTypes.BLOB.getProtocolCode()).isEqualTo(ProtocolConstants.DataType.BLOB); + assertThat(DataTypes.BOOLEAN.getProtocolCode()).isEqualTo(ProtocolConstants.DataType.BOOLEAN); + assertThat(DataTypes.COUNTER.getProtocolCode()).isEqualTo(ProtocolConstants.DataType.COUNTER); + assertThat(DataTypes.DECIMAL.getProtocolCode()).isEqualTo(ProtocolConstants.DataType.DECIMAL); + assertThat(DataTypes.DOUBLE.getProtocolCode()).isEqualTo(ProtocolConstants.DataType.DOUBLE); + assertThat(DataTypes.FLOAT.getProtocolCode()).isEqualTo(ProtocolConstants.DataType.FLOAT); + assertThat(DataTypes.INT.getProtocolCode()).isEqualTo(ProtocolConstants.DataType.INT); + assertThat(DataTypes.TIMESTAMP.getProtocolCode()) + .isEqualTo(ProtocolConstants.DataType.TIMESTAMP); + assertThat(DataTypes.UUID.getProtocolCode()).isEqualTo(ProtocolConstants.DataType.UUID); + assertThat(DataTypes.VARINT.getProtocolCode()).isEqualTo(ProtocolConstants.DataType.VARINT); + assertThat(DataTypes.TIMEUUID.getProtocolCode()).isEqualTo(ProtocolConstants.DataType.TIMEUUID); + assertThat(DataTypes.INET.getProtocolCode()).isEqualTo(ProtocolConstants.DataType.INET); + assertThat(DataTypes.DATE.getProtocolCode()).isEqualTo(ProtocolConstants.DataType.DATE); + assertThat(DataTypes.TEXT.getProtocolCode()).isEqualTo(ProtocolConstants.DataType.VARCHAR); + assertThat(DataTypes.TIME.getProtocolCode()).isEqualTo(ProtocolConstants.DataType.TIME); + assertThat(DataTypes.SMALLINT.getProtocolCode()).isEqualTo(ProtocolConstants.DataType.SMALLINT); + assertThat(DataTypes.TINYINT.getProtocolCode()).isEqualTo(ProtocolConstants.DataType.TINYINT); + assertThat(DataTypes.DURATION.getProtocolCode()).isEqualTo(ProtocolConstants.DataType.DURATION); + } + + @Test + @UseDataProvider(location = TestDataProviders.class, value = "locales") + public void should_format_as_cql(Locale locale) { + Locale def = Locale.getDefault(); + try { + Locale.setDefault(locale); + assertThat(DataTypes.ASCII.asCql(true, true)).isEqualTo("ascii"); + assertThat(DataTypes.BIGINT.asCql(true, true)).isEqualTo("bigint"); + assertThat(DataTypes.BLOB.asCql(true, true)).isEqualTo("blob"); + assertThat(DataTypes.BOOLEAN.asCql(true, true)).isEqualTo("boolean"); + assertThat(DataTypes.COUNTER.asCql(true, true)).isEqualTo("counter"); + assertThat(DataTypes.DECIMAL.asCql(true, true)).isEqualTo("decimal"); + assertThat(DataTypes.DOUBLE.asCql(true, true)).isEqualTo("double"); + assertThat(DataTypes.FLOAT.asCql(true, true)).isEqualTo("float"); + assertThat(DataTypes.INT.asCql(true, true)).isEqualTo("int"); + assertThat(DataTypes.TIMESTAMP.asCql(true, true)).isEqualTo("timestamp"); + assertThat(DataTypes.UUID.asCql(true, true)).isEqualTo("uuid"); + assertThat(DataTypes.VARINT.asCql(true, true)).isEqualTo("varint"); + assertThat(DataTypes.TIMEUUID.asCql(true, true)).isEqualTo("timeuuid"); + assertThat(DataTypes.INET.asCql(true, true)).isEqualTo("inet"); + assertThat(DataTypes.DATE.asCql(true, true)).isEqualTo("date"); + assertThat(DataTypes.TEXT.asCql(true, true)).isEqualTo("text"); + assertThat(DataTypes.TIME.asCql(true, true)).isEqualTo("time"); + assertThat(DataTypes.SMALLINT.asCql(true, true)).isEqualTo("smallint"); + assertThat(DataTypes.TINYINT.asCql(true, true)).isEqualTo("tinyint"); + assertThat(DataTypes.DURATION.asCql(true, true)).isEqualTo("duration"); + } finally { + Locale.setDefault(def); + } + } + + @Test + @UseDataProvider(location = TestDataProviders.class, value = "locales") + public void should_format_as_string(Locale locale) { + Locale def = Locale.getDefault(); + try { + Locale.setDefault(locale); + assertThat(DataTypes.ASCII.toString()).isEqualTo("ASCII"); + assertThat(DataTypes.BIGINT.toString()).isEqualTo("BIGINT"); + assertThat(DataTypes.BLOB.toString()).isEqualTo("BLOB"); + assertThat(DataTypes.BOOLEAN.toString()).isEqualTo("BOOLEAN"); + assertThat(DataTypes.COUNTER.toString()).isEqualTo("COUNTER"); + assertThat(DataTypes.DECIMAL.toString()).isEqualTo("DECIMAL"); + assertThat(DataTypes.DOUBLE.toString()).isEqualTo("DOUBLE"); + assertThat(DataTypes.FLOAT.toString()).isEqualTo("FLOAT"); + assertThat(DataTypes.INT.toString()).isEqualTo("INT"); + assertThat(DataTypes.TIMESTAMP.toString()).isEqualTo("TIMESTAMP"); + assertThat(DataTypes.UUID.toString()).isEqualTo("UUID"); + assertThat(DataTypes.VARINT.toString()).isEqualTo("VARINT"); + assertThat(DataTypes.TIMEUUID.toString()).isEqualTo("TIMEUUID"); + assertThat(DataTypes.INET.toString()).isEqualTo("INET"); + assertThat(DataTypes.DATE.toString()).isEqualTo("DATE"); + assertThat(DataTypes.TEXT.toString()).isEqualTo("TEXT"); + assertThat(DataTypes.TIME.toString()).isEqualTo("TIME"); + assertThat(DataTypes.SMALLINT.toString()).isEqualTo("SMALLINT"); + assertThat(DataTypes.TINYINT.toString()).isEqualTo("TINYINT"); + assertThat(DataTypes.DURATION.toString()).isEqualTo("DURATION"); + } finally { + Locale.setDefault(def); + } + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/AsciiCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/AsciiCodecTest.java index fda9d72ea40..43c01ea35dc 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/AsciiCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/AsciiCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/BigIntCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/BigIntCodecTest.java index a2d7fd91ee0..c5360c90a7b 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/BigIntCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/BigIntCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -67,7 +69,7 @@ public void should_fail_to_parse_invalid_input() { @Test(expected = IllegalArgumentException.class) public void should_fail_to_parse_if_out_of_range() { - parse(Long.toString(Long.MAX_VALUE) + "0"); + parse(Long.MAX_VALUE + "0"); } @Test diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/BlobCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/BlobCodecTest.java index c0448e38dbd..ec1ab294911 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/BlobCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/BlobCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/BooleanCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/BooleanCodecTest.java index 9433984011f..57fcef1235d 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/BooleanCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/BooleanCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/CodecTestBase.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/CodecTestBase.java index 5fba391f94f..8a00cceda09 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/CodecTestBase.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/CodecTestBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/CounterCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/CounterCodecTest.java index 70dbd91c305..c18c6e76d7c 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/CounterCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/CounterCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -67,7 +69,7 @@ public void should_fail_to_parse_invalid_input() { @Test(expected = IllegalArgumentException.class) public void should_fail_to_parse_if_out_of_range() { - parse(Long.toString(Long.MAX_VALUE) + "0"); + parse(Long.MAX_VALUE + "0"); } @Test diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/CqlDurationCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/CqlDurationCodecTest.java index 3a8e36d8c42..43526f72e57 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/CqlDurationCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/CqlDurationCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/CqlIntToStringCodec.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/CqlIntToStringCodec.java index bb006794656..4f04f3defec 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/CqlIntToStringCodec.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/CqlIntToStringCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/CustomCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/CustomCodecTest.java index 545b03c1f4f..a832b51cfec 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/CustomCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/CustomCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/DateCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/DateCodecTest.java index 55fcf4c78a9..48388fbc692 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/DateCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/DateCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/DecimalCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/DecimalCodecTest.java index b0c7e2bec79..eac360fdcc5 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/DecimalCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/DecimalCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/DoubleCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/DoubleCodecTest.java index 2c72249b597..f27081aa784 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/DoubleCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/DoubleCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/FloatCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/FloatCodecTest.java index 6864e3a788a..62d5b549153 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/FloatCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/FloatCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/InetCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/InetCodecTest.java index e47c74ba8c1..e10fa695ba0 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/InetCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/InetCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/IntCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/IntCodecTest.java index 931934e3f55..b5268a7e844 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/IntCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/IntCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/ListCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/ListCodecTest.java index 34e870998ec..975aa3a1428 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/ListCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/ListCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/MapCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/MapCodecTest.java index 0fbeace16b1..94cb33a5a99 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/MapCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/MapCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/MappingCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/MappingCodecTest.java index 80bbb15a8e0..f78dc774f62 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/MappingCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/MappingCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/SetCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/SetCodecTest.java index 6f8f8878c65..a302357c9f3 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/SetCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/SetCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/SimpleBlobCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/SimpleBlobCodecTest.java index c5fd0b88899..3f40efb16ac 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/SimpleBlobCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/SimpleBlobCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/SmallIntCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/SmallIntCodecTest.java index 75c436e0475..483dd0b65bd 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/SmallIntCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/SmallIntCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/TextCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/TextCodecTest.java index f983534de2a..a42178544d4 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/TextCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/TextCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/TimeCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/TimeCodecTest.java index 6c346b145aa..6d77efd396a 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/TimeCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/TimeCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/TimeUuidCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/TimeUuidCodecTest.java index ae89ce5d9a8..416bee8e4df 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/TimeUuidCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/TimeUuidCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/TimestampCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/TimestampCodecTest.java index 97a57c2fabc..5cfd17da622 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/TimestampCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/TimestampCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/TinyIntCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/TinyIntCodecTest.java index ae31be9dc42..358c36e9386 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/TinyIntCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/TinyIntCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/TupleCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/TupleCodecTest.java index 394d34147cc..c51eea20c2e 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/TupleCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/TupleCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/UdtCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/UdtCodecTest.java index 1bbaaf0a2d5..af94247f937 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/UdtCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/UdtCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -133,6 +135,21 @@ public void should_decode_udt() { verify(textCodec).decode(Bytes.fromHexString("0x61"), ProtocolVersion.DEFAULT); } + @Test + public void should_decode_udt_when_too_many_fields() { + UdtValue udt = + decode( + "0x" + + ("00000004" + "00000001") + + "ffffffff" + + ("00000001" + "61") + // extra contents + + "ffffffff"); + assertThat(udt.getInt(0)).isEqualTo(1); + assertThat(udt.isNull(1)).isTrue(); + assertThat(udt.getString(2)).isEqualTo("a"); + } + /** Test for JAVA-2557. Ensures that the codec can decode null fields with any negative length. */ @Test public void should_decode_negative_element_length_as_null_field() { diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/UuidCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/UuidCodecTest.java index 16baada6810..e62fb4af15b 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/UuidCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/UuidCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/VarintCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/VarintCodecTest.java index e52dd93919c..a3472d4b8ce 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/VarintCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/VarintCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/VectorCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/VectorCodecTest.java new file mode 100644 index 00000000000..17c78514127 --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/VectorCodecTest.java @@ -0,0 +1,274 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.type.codec; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.datastax.oss.driver.api.core.ProtocolVersion; +import com.datastax.oss.driver.api.core.data.CqlVector; +import com.datastax.oss.driver.api.core.type.DataType; +import com.datastax.oss.driver.api.core.type.DataTypes; +import com.datastax.oss.driver.api.core.type.codec.TypeCodec; +import com.datastax.oss.driver.api.core.type.codec.TypeCodecs; +import com.datastax.oss.driver.api.core.type.codec.registry.CodecRegistry; +import com.datastax.oss.driver.internal.core.type.DefaultVectorType; +import com.datastax.oss.protocol.internal.util.Bytes; +import com.tngtech.java.junit.dataprovider.DataProvider; +import com.tngtech.java.junit.dataprovider.DataProviderRunner; +import com.tngtech.java.junit.dataprovider.UseDataProvider; +import java.nio.ByteBuffer; +import java.time.LocalTime; +import java.util.HashMap; +import org.apache.commons.lang3.ArrayUtils; +import org.junit.Test; +import org.junit.runner.RunWith; + +@RunWith(DataProviderRunner.class) +public class VectorCodecTest { + + @DataProvider + public static Object[] dataProvider() { + HashMap map1 = new HashMap<>(); + map1.put(1, "a"); + HashMap map2 = new HashMap<>(); + map2.put(2, "b"); + return new TestDataContainer[] { + new TestDataContainer( + DataTypes.FLOAT, + new Float[] {1.0f, 2.5f}, + "[1.0, 2.5]", + Bytes.fromHexString("0x3f80000040200000")), + new TestDataContainer( + DataTypes.ASCII, + new String[] {"ab", "cde"}, + "['ab', 'cde']", + Bytes.fromHexString("0x02616203636465")), + new TestDataContainer( + DataTypes.BIGINT, + new Long[] {1L, 2L}, + "[1, 2]", + Bytes.fromHexString("0x00000000000000010000000000000002")), + new TestDataContainer( + DataTypes.BLOB, + new ByteBuffer[] {Bytes.fromHexString("0xCAFE"), Bytes.fromHexString("0xABCD")}, + "[0xcafe, 0xabcd]", + Bytes.fromHexString("0x02cafe02abcd")), + new TestDataContainer( + DataTypes.BOOLEAN, + new Boolean[] {true, false}, + "[true, false]", + Bytes.fromHexString("0x0100")), + new TestDataContainer( + DataTypes.TIME, + new LocalTime[] {LocalTime.ofNanoOfDay(1), LocalTime.ofNanoOfDay(2)}, + "['00:00:00.000000001', '00:00:00.000000002']", + Bytes.fromHexString("0x080000000000000001080000000000000002")), + new TestDataContainer( + DataTypes.mapOf(DataTypes.INT, DataTypes.ASCII), + new HashMap[] {map1, map2}, + "[{1:'a'}, {2:'b'}]", + Bytes.fromHexString( + "0x110000000100000004000000010000000161110000000100000004000000020000000162")), + new TestDataContainer( + DataTypes.vectorOf(DataTypes.INT, 1), + new CqlVector[] {CqlVector.newInstance(1), CqlVector.newInstance(2)}, + "[[1], [2]]", + Bytes.fromHexString("0x0000000100000002")), + new TestDataContainer( + DataTypes.vectorOf(DataTypes.TEXT, 1), + new CqlVector[] {CqlVector.newInstance("ab"), CqlVector.newInstance("cdef")}, + "[['ab'], ['cdef']]", + Bytes.fromHexString("0x03026162050463646566")), + new TestDataContainer( + DataTypes.vectorOf(DataTypes.vectorOf(DataTypes.FLOAT, 2), 1), + new CqlVector[] { + CqlVector.newInstance(CqlVector.newInstance(1.0f, 2.5f)), + CqlVector.newInstance(CqlVector.newInstance(3.0f, 4.5f)) + }, + "[[[1.0, 2.5]], [[3.0, 4.5]]]", + Bytes.fromHexString("0x3f800000402000004040000040900000")) + }; + } + + @UseDataProvider("dataProvider") + @Test + public void should_encode(TestDataContainer testData) { + TypeCodec> codec = getCodec(testData.getDataType()); + CqlVector vector = CqlVector.newInstance(testData.getValues()); + assertThat(codec.encode(vector, ProtocolVersion.DEFAULT)).isEqualTo(testData.getBytes()); + } + + @Test + @UseDataProvider("dataProvider") + public void should_throw_on_encode_with_too_few_elements(TestDataContainer testData) { + TypeCodec> codec = getCodec(testData.getDataType()); + assertThatThrownBy( + () -> + codec.encode( + CqlVector.newInstance(testData.getValues()[0]), ProtocolVersion.DEFAULT)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @UseDataProvider("dataProvider") + public void should_throw_on_encode_with_too_many_elements(TestDataContainer testData) { + Object[] doubled = ArrayUtils.addAll(testData.getValues(), testData.getValues()); + TypeCodec> codec = getCodec(testData.getDataType()); + assertThatThrownBy(() -> codec.encode(CqlVector.newInstance(doubled), ProtocolVersion.DEFAULT)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @UseDataProvider("dataProvider") + public void should_decode(TestDataContainer testData) { + TypeCodec> codec = getCodec(testData.getDataType()); + assertThat(codec.decode(testData.getBytes(), ProtocolVersion.DEFAULT)) + .isEqualTo(CqlVector.newInstance(testData.getValues())); + } + + @Test + @UseDataProvider("dataProvider") + public void should_throw_on_decode_if_too_few_bytes(TestDataContainer testData) { + TypeCodec> codec = getCodec(testData.getDataType()); + int lastIndex = testData.getBytes().remaining() - 1; + assertThatThrownBy( + () -> + codec.decode( + (ByteBuffer) testData.getBytes().duplicate().limit(lastIndex), + ProtocolVersion.DEFAULT)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @UseDataProvider("dataProvider") + public void should_throw_on_decode_if_too_many_bytes(TestDataContainer testData) { + ByteBuffer doubled = ByteBuffer.allocate(testData.getBytes().remaining() * 2); + doubled.put(testData.getBytes().duplicate()).put(testData.getBytes().duplicate()).flip(); + TypeCodec> codec = getCodec(testData.getDataType()); + assertThatThrownBy(() -> codec.decode(doubled, ProtocolVersion.DEFAULT)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @UseDataProvider("dataProvider") + public void should_format(TestDataContainer testData) { + TypeCodec> codec = getCodec(testData.getDataType()); + CqlVector vector = CqlVector.newInstance(testData.getValues()); + assertThat(codec.format(vector)).isEqualTo(testData.getFormatted()); + } + + @Test + @UseDataProvider("dataProvider") + public void should_parse(TestDataContainer testData) { + TypeCodec> codec = getCodec(testData.getDataType()); + assertThat(codec.parse(testData.getFormatted())) + .isEqualTo(CqlVector.newInstance(testData.getValues())); + } + + @Test + @UseDataProvider("dataProvider") + public void should_accept_data_type(TestDataContainer testData) { + TypeCodec> codec = getCodec(testData.getDataType()); + assertThat(codec.accepts(new DefaultVectorType(testData.getDataType(), 2))).isTrue(); + assertThat(codec.accepts(new DefaultVectorType(DataTypes.custom("non-existent"), 2))).isFalse(); + } + + @Test + @UseDataProvider("dataProvider") + public void should_accept_vector_type_correct_dimension_only(TestDataContainer testData) { + TypeCodec> codec = getCodec(testData.getDataType()); + assertThat(codec.accepts(new DefaultVectorType(testData.getDataType(), 0))).isFalse(); + assertThat(codec.accepts(new DefaultVectorType(testData.getDataType(), 1))).isFalse(); + assertThat(codec.accepts(new DefaultVectorType(testData.getDataType(), 3))).isFalse(); + } + + @Test + @UseDataProvider("dataProvider") + public void should_accept_generic_type(TestDataContainer testData) { + TypeCodec> codec = getCodec(testData.getDataType()); + assertThat(codec.accepts(codec.getJavaType())).isTrue(); + } + + @Test + @UseDataProvider("dataProvider") + public void should_accept_raw_type(TestDataContainer testData) { + TypeCodec> codec = getCodec(testData.getDataType()); + assertThat(codec.accepts(CqlVector.class)).isTrue(); + assertThat(codec.accepts(Integer.class)).isFalse(); + } + + @Test + @UseDataProvider("dataProvider") + public void should_accept_object(TestDataContainer testData) { + TypeCodec> codec = getCodec(testData.getDataType()); + CqlVector vector = CqlVector.newInstance(testData.getValues()); + assertThat(codec.accepts(vector)).isTrue(); + assertThat(codec.accepts(Integer.MIN_VALUE)).isFalse(); + } + + @Test + public void should_handle_null_and_empty() { + TypeCodec> codec = getCodec(DataTypes.FLOAT); + assertThat(codec.encode(null, ProtocolVersion.DEFAULT)).isNull(); + assertThat(codec.decode(Bytes.fromHexString("0x"), ProtocolVersion.DEFAULT)).isNull(); + assertThat(codec.format(null)).isEqualTo("NULL"); + assertThat(codec.parse("NULL")).isNull(); + assertThat(codec.parse("null")).isNull(); + assertThat(codec.parse("")).isNull(); + assertThat(codec.parse(null)).isNull(); + assertThatThrownBy(() -> codec.encode(CqlVector.newInstance(), ProtocolVersion.DEFAULT)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static TypeCodec> getCodec(DataType dataType) { + return TypeCodecs.vectorOf( + DataTypes.vectorOf(dataType, 2), CodecRegistry.DEFAULT.codecFor(dataType)); + } + + private static class TestDataContainer { + private final DataType dataType; + private final Object[] values; + private final String formatted; + private final ByteBuffer bytes; + + public TestDataContainer( + DataType dataType, Object[] values, String formatted, ByteBuffer bytes) { + this.dataType = dataType; + this.values = values; + this.formatted = formatted; + this.bytes = bytes; + } + + public DataType getDataType() { + return dataType; + } + + public Object[] getValues() { + return values; + } + + public String getFormatted() { + return formatted; + } + + public ByteBuffer getBytes() { + return bytes; + } + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/OptionalCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/OptionalCodecTest.java index 21fc0959177..745ba7a3aa8 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/OptionalCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/OptionalCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/BooleanArrayCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/BooleanArrayCodecTest.java index c43c88c4f28..4a175cdf306 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/BooleanArrayCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/BooleanArrayCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/ByteArrayCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/ByteArrayCodecTest.java index 1d545d3b5a5..761b568fcea 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/ByteArrayCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/ByteArrayCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/DoubleArrayCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/DoubleArrayCodecTest.java index 1a3ae412cb3..8e951f8ed55 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/DoubleArrayCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/DoubleArrayCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/FloatArrayCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/FloatArrayCodecTest.java index cca7604f9ac..77f3eafdcd7 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/FloatArrayCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/FloatArrayCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/IntArrayCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/IntArrayCodecTest.java index c26defda4fe..ac00f1f8e1c 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/IntArrayCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/IntArrayCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/LongArrayCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/LongArrayCodecTest.java index 67f34c924c9..737dcfae3c0 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/LongArrayCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/LongArrayCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/ObjectArrayCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/ObjectArrayCodecTest.java index 05912864f37..a2afc652002 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/ObjectArrayCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/ObjectArrayCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/ShortArrayCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/ShortArrayCodecTest.java index 3cf3ec4bd90..3d489ada38f 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/ShortArrayCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/array/ShortArrayCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/enums/EnumNameCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/enums/EnumNameCodecTest.java index d1d5024b5ed..093ec8a0be8 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/enums/EnumNameCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/enums/EnumNameCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/enums/EnumOrdinalCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/enums/EnumOrdinalCodecTest.java index fe4cc91d10d..7162bc51ff2 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/enums/EnumOrdinalCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/enums/EnumOrdinalCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/json/JsonCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/json/JsonCodecTest.java index f977bded44a..f9c37075b36 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/json/JsonCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/json/JsonCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/time/LocalTimestampCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/time/LocalTimestampCodecTest.java index d9e235a010b..7d87cbbba9f 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/time/LocalTimestampCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/time/LocalTimestampCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/time/PersistentZonedTimestampCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/time/PersistentZonedTimestampCodecTest.java index d8a125e170f..9bf1cac1007 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/time/PersistentZonedTimestampCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/time/PersistentZonedTimestampCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/time/TimestampMillisCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/time/TimestampMillisCodecTest.java index 05e71dfda0d..36ee71eebe6 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/time/TimestampMillisCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/time/TimestampMillisCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/time/ZonedTimestampCodecTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/time/ZonedTimestampCodecTest.java index cef8af71d50..cd31d13d5ca 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/time/ZonedTimestampCodecTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/extras/time/ZonedTimestampCodecTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/registry/CachingCodecRegistryTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/registry/CachingCodecRegistryTest.java index 58e42a6149b..231f67a93e7 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/registry/CachingCodecRegistryTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/registry/CachingCodecRegistryTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/registry/CachingCodecRegistryTestDataProviders.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/registry/CachingCodecRegistryTestDataProviders.java index 64bbd800c92..4c0298bafad 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/registry/CachingCodecRegistryTestDataProviders.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/codec/registry/CachingCodecRegistryTestDataProviders.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -17,6 +19,7 @@ import com.datastax.oss.driver.api.core.CqlIdentifier; import com.datastax.oss.driver.api.core.data.CqlDuration; +import com.datastax.oss.driver.api.core.data.CqlVector; import com.datastax.oss.driver.api.core.data.TupleValue; import com.datastax.oss.driver.api.core.data.UdtValue; import com.datastax.oss.driver.api.core.type.DataTypes; @@ -285,6 +288,75 @@ public static Object[][] collectionsWithCqlAndJavaTypes() ImmutableMap.of( ImmutableMap.of(udtValue, udtValue), ImmutableMap.of(tupleValue, tupleValue)) }, + // vectors + { + DataTypes.vectorOf(DataTypes.INT, 1), + GenericType.vectorOf(Integer.class), + GenericType.vectorOf(Integer.class), + CqlVector.newInstance(1) + }, + { + DataTypes.vectorOf(DataTypes.BIGINT, 1), + GenericType.vectorOf(Long.class), + GenericType.vectorOf(Long.class), + CqlVector.newInstance(1l) + }, + { + DataTypes.vectorOf(DataTypes.SMALLINT, 1), + GenericType.vectorOf(Short.class), + GenericType.vectorOf(Short.class), + CqlVector.newInstance((short) 1) + }, + { + DataTypes.vectorOf(DataTypes.TINYINT, 1), + GenericType.vectorOf(Byte.class), + GenericType.vectorOf(Byte.class), + CqlVector.newInstance((byte) 1) + }, + { + DataTypes.vectorOf(DataTypes.FLOAT, 1), + GenericType.vectorOf(Float.class), + GenericType.vectorOf(Float.class), + CqlVector.newInstance(1.0f) + }, + { + DataTypes.vectorOf(DataTypes.DOUBLE, 1), + GenericType.vectorOf(Double.class), + GenericType.vectorOf(Double.class), + CqlVector.newInstance(1.0d) + }, + { + DataTypes.vectorOf(DataTypes.DECIMAL, 1), + GenericType.vectorOf(BigDecimal.class), + GenericType.vectorOf(BigDecimal.class), + CqlVector.newInstance(BigDecimal.ONE) + }, + { + DataTypes.vectorOf(DataTypes.VARINT, 1), + GenericType.vectorOf(BigInteger.class), + GenericType.vectorOf(BigInteger.class), + CqlVector.newInstance(BigInteger.ONE) + }, + // vector with arbitrary types + { + DataTypes.vectorOf(DataTypes.TEXT, 2), + GenericType.vectorOf(String.class), + GenericType.vectorOf(String.class), + CqlVector.newInstance("abc", "de") + }, + { + DataTypes.vectorOf(DataTypes.TIME, 2), + GenericType.vectorOf(LocalTime.class), + GenericType.vectorOf(LocalTime.class), + CqlVector.newInstance(LocalTime.MIDNIGHT, LocalTime.NOON) + }, + { + DataTypes.vectorOf(DataTypes.vectorOf(DataTypes.TINYINT, 2), 2), + GenericType.vectorOf(GenericType.vectorOf(Byte.class)), + GenericType.vectorOf(GenericType.vectorOf(Byte.class)), + CqlVector.newInstance( + CqlVector.newInstance((byte) 1, (byte) 2), CqlVector.newInstance((byte) 3, (byte) 4)) + }, }; } diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/type/util/VIntCodingTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/type/util/VIntCodingTest.java new file mode 100644 index 00000000000..b85d6d66844 --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/type/util/VIntCodingTest.java @@ -0,0 +1,86 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.type.util; + +import static org.junit.Assert.assertEquals; + +import com.tngtech.java.junit.dataprovider.DataProvider; +import com.tngtech.java.junit.dataprovider.DataProviderRunner; +import com.tngtech.java.junit.dataprovider.UseDataProvider; +import java.nio.ByteBuffer; +import org.junit.Test; +import org.junit.runner.RunWith; + +@RunWith(DataProviderRunner.class) +public class VIntCodingTest { + @DataProvider + public static Object[] roundTripTestValues() { + return new Integer[] { + Integer.MAX_VALUE + 1, + Integer.MAX_VALUE, + Integer.MAX_VALUE - 1, + Integer.MIN_VALUE, + Integer.MIN_VALUE + 1, + Integer.MIN_VALUE - 1, + 0, + -1, + 1 + }; + }; + + private static final long[] LONGS = + new long[] { + 53L, + 10201L, + 1097151L, + 168435455L, + 33251130335L, + 3281283447775L, + 417672546086779L, + 52057592037927932L, + 72057594037927937L + }; + + @Test + public void should_compute_unsigned_vint_size() { + for (int i = 0; i < LONGS.length; i++) { + long val = LONGS[i]; + assertEquals(i + 1, VIntCoding.computeUnsignedVIntSize(val)); + } + } + + @Test + @UseDataProvider("roundTripTestValues") + public void should_write_and_read_unsigned_vint_32(int value) { + ByteBuffer bb = ByteBuffer.allocate(9); + + VIntCoding.writeUnsignedVInt32(value, bb); + bb.flip(); + assertEquals(value, VIntCoding.getUnsignedVInt32(bb, 0)); + } + + @Test + @UseDataProvider("roundTripTestValues") + public void should_write_and_read_unsigned_vint(int value) { + ByteBuffer bb = ByteBuffer.allocate(9); + + VIntCoding.writeUnsignedVInt(value, bb); + bb.flip(); + assertEquals(value, VIntCoding.getUnsignedVInt(bb, 0)); + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/util/ArrayUtilsTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/util/ArrayUtilsTest.java index e6a878f7450..c2df6449fdb 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/util/ArrayUtilsTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/util/ArrayUtilsTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -20,7 +22,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import java.util.concurrent.ThreadLocalRandom; +import java.util.Random; import org.junit.Test; public class ArrayUtilsTest { @@ -84,7 +86,7 @@ public void should_not_bubble_down_when_target_index_lower() { @Test public void should_shuffle_head() { String[] array = {"a", "b", "c", "d", "e"}; - ThreadLocalRandom random = mock(ThreadLocalRandom.class); + Random random = mock(Random.class); when(random.nextInt(anyInt())) .thenAnswer( (invocation) -> { diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/util/ByteBufs.java b/core/src/test/java/com/datastax/oss/driver/internal/core/util/ByteBufs.java index 0983c1b8900..f526e2f12d4 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/util/ByteBufs.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/util/ByteBufs.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/util/CollectionsUtilsTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/util/CollectionsUtilsTest.java index 3ae49f12338..5a95e7f3b74 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/util/CollectionsUtilsTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/util/CollectionsUtilsTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/util/DirectedGraphTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/util/DirectedGraphTest.java index b673edcf1d2..1b37a5e5b19 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/util/DirectedGraphTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/util/DirectedGraphTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/util/LoggerTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/util/LoggerTest.java index 415d887ee45..eec3669efca 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/util/LoggerTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/util/LoggerTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/util/ReflectionTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/util/ReflectionTest.java index 5b58dc5bf91..f2614775be4 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/util/ReflectionTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/util/ReflectionTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/util/StringsTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/util/StringsTest.java new file mode 100644 index 00000000000..d5cc9dae161 --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/util/StringsTest.java @@ -0,0 +1,170 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.util; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.datastax.oss.driver.TestDataProviders; +import com.tngtech.java.junit.dataprovider.DataProviderRunner; +import com.tngtech.java.junit.dataprovider.UseDataProvider; +import java.util.Locale; +import org.junit.Test; +import org.junit.runner.RunWith; + +@RunWith(DataProviderRunner.class) +public class StringsTest { + + @Test + @UseDataProvider(location = TestDataProviders.class, value = "locales") + public void should_report_cql_keyword(Locale locale) { + Locale def = Locale.getDefault(); + try { + Locale.setDefault(locale); + + assertThat(Strings.isReservedCqlKeyword(null)).isFalse(); + assertThat(Strings.isReservedCqlKeyword("NOT A RESERVED KEYWORD")).isFalse(); + + assertThat(Strings.isReservedCqlKeyword("add")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("allow")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("alter")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("and")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("apply")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("asc")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("authorize")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("batch")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("begin")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("by")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("columnfamily")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("create")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("default")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("delete")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("desc")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("describe")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("drop")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("entries")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("execute")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("from")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("full")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("grant")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("if")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("in")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("index")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("infinity")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("insert")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("into")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("is")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("keyspace")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("limit")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("materialized")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("mbean")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("mbeans")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("modify")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("nan")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("norecursive")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("not")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("null")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("of")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("on")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("or")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("order")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("primary")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("rename")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("replace")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("revoke")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("schema")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("select")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("set")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("table")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("to")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("token")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("truncate")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("unlogged")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("unset")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("update")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("use")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("using")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("view")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("where")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("with")).isTrue(); + + assertThat(Strings.isReservedCqlKeyword("ALLOW")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("ALTER")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("AND")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("APPLY")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("ASC")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("AUTHORIZE")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("BATCH")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("BEGIN")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("BY")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("COLUMNFAMILY")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("CREATE")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("DEFAULT")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("DELETE")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("DESC")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("DESCRIBE")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("DROP")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("ENTRIES")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("EXECUTE")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("FROM")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("FULL")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("GRANT")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("IF")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("IN")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("INDEX")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("INFINITY")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("INSERT")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("INTO")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("IS")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("KEYSPACE")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("LIMIT")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("MATERIALIZED")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("MBEAN")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("MBEANS")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("MODIFY")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("NAN")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("NORECURSIVE")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("NOT")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("NULL")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("OF")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("ON")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("OR")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("ORDER")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("PRIMARY")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("RENAME")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("REPLACE")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("REVOKE")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("SCHEMA")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("SELECT")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("SET")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("TABLE")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("TO")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("TOKEN")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("TRUNCATE")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("UNLOGGED")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("UNSET")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("UPDATE")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("USE")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("USING")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("VIEW")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("WHERE")).isTrue(); + assertThat(Strings.isReservedCqlKeyword("WITH")).isTrue(); + } finally { + Locale.setDefault(def); + } + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/util/collection/CompositeQueryPlanTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/util/collection/CompositeQueryPlanTest.java new file mode 100644 index 00000000000..1adc06a79d3 --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/util/collection/CompositeQueryPlanTest.java @@ -0,0 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.util.collection; + +import com.datastax.oss.driver.api.core.metadata.Node; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public class CompositeQueryPlanTest extends QueryPlanTestBase { + + @Override + protected QueryPlan newQueryPlan(Node... nodes) { + Object[] n1 = new Object[nodes.length / 2]; + Object[] n2 = new Object[nodes.length - n1.length]; + System.arraycopy(nodes, 0, n1, 0, n1.length); + System.arraycopy(nodes, n1.length, n2, 0, n2.length); + return new CompositeQueryPlan( + new SimpleQueryPlan(n1), + new LazyQueryPlan() { + @Override + protected Object[] computeNodes() { + return n2; + } + }); + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/util/collection/LazyQueryPlanTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/util/collection/LazyQueryPlanTest.java new file mode 100644 index 00000000000..99c72bace06 --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/util/collection/LazyQueryPlanTest.java @@ -0,0 +1,36 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.util.collection; + +import com.datastax.oss.driver.api.core.metadata.Node; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public class LazyQueryPlanTest extends QueryPlanTestBase { + + @Override + protected QueryPlan newQueryPlan(Node... nodes) { + return new LazyQueryPlan() { + @Override + protected Object[] computeNodes() { + return nodes; + } + }; + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/util/collection/QueryPlanTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/util/collection/QueryPlanTest.java deleted file mode 100644 index 8157a2662ee..00000000000 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/util/collection/QueryPlanTest.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.datastax.oss.driver.internal.core.util.collection; - -import static com.datastax.oss.driver.Assertions.assertThat; - -import com.datastax.oss.driver.api.core.metadata.Node; -import java.util.Iterator; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -@RunWith(MockitoJUnitRunner.class) -public class QueryPlanTest { - - @Mock private Node node1; - @Mock private Node node2; - @Mock private Node node3; - - @Test - public void should_poll_elements() { - QueryPlan queryPlan = new QueryPlan(node1, node2, node3); - assertThat(queryPlan.poll()).isSameAs(node1); - assertThat(queryPlan.poll()).isSameAs(node2); - assertThat(queryPlan.poll()).isSameAs(node3); - assertThat(queryPlan.poll()).isNull(); - assertThat(queryPlan.poll()).isNull(); - } - - @Test - public void should_return_size() { - QueryPlan queryPlan = new QueryPlan(node1, node2, node3); - assertThat(queryPlan.size()).isEqualTo(3); - queryPlan.poll(); - assertThat(queryPlan.size()).isEqualTo(2); - queryPlan.poll(); - assertThat(queryPlan.size()).isEqualTo(1); - queryPlan.poll(); - assertThat(queryPlan.size()).isEqualTo(0); - queryPlan.poll(); - assertThat(queryPlan.size()).isEqualTo(0); - } - - @Test - public void should_return_iterator() { - QueryPlan queryPlan = new QueryPlan(node1, node2, node3); - Iterator iterator3 = queryPlan.iterator(); - queryPlan.poll(); - Iterator iterator2 = queryPlan.iterator(); - queryPlan.poll(); - Iterator iterator1 = queryPlan.iterator(); - queryPlan.poll(); - Iterator iterator0 = queryPlan.iterator(); - queryPlan.poll(); - Iterator iterator00 = queryPlan.iterator(); - - assertThat(iterator3).toIterable().containsExactly(node1, node2, node3); - assertThat(iterator2).toIterable().containsExactly(node2, node3); - assertThat(iterator1).toIterable().containsExactly(node3); - assertThat(iterator0).toIterable().isEmpty(); - assertThat(iterator00).toIterable().isEmpty(); - } -} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/util/collection/QueryPlanTestBase.java b/core/src/test/java/com/datastax/oss/driver/internal/core/util/collection/QueryPlanTestBase.java new file mode 100644 index 00000000000..8689c282117 --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/util/collection/QueryPlanTestBase.java @@ -0,0 +1,126 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.util.collection; + +import static com.datastax.oss.driver.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.datastax.oss.driver.api.core.metadata.Node; +import java.util.Comparator; +import java.util.Iterator; +import java.util.Set; +import java.util.concurrent.ConcurrentSkipListSet; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public abstract class QueryPlanTestBase { + + @Mock private Node node1; + @Mock private Node node2; + @Mock private Node node3; + + @Test + public void should_poll_elements() { + QueryPlan queryPlan = newQueryPlan(node1, node2, node3); + assertThat(queryPlan.poll()).isSameAs(node1); + assertThat(queryPlan.poll()).isSameAs(node2); + assertThat(queryPlan.poll()).isSameAs(node3); + assertThat(queryPlan.poll()).isNull(); + assertThat(queryPlan.poll()).isNull(); + } + + @Test + public void should_poll_elements_concurrently() throws InterruptedException { + for (int runs = 0; runs < 5; runs++) { + Node[] nodes = new Node[1000]; + for (int i = 0; i < 1000; i++) { + nodes[i] = mock(Node.class, "node" + i); + when(nodes[i].getOpenConnections()).thenReturn(i); + } + QueryPlan queryPlan = newQueryPlan(nodes); + Set actual = + new ConcurrentSkipListSet<>(Comparator.comparingInt(Node::getOpenConnections)); + Thread[] threads = new Thread[5]; + for (int i = 0; i < 5; i++) { + threads[i] = + new Thread( + () -> { + while (true) { + Node node = queryPlan.poll(); + if (node == null) { + return; + } + actual.add(node); + } + }); + } + for (Thread thread : threads) { + thread.start(); + } + for (Thread thread : threads) { + thread.join(); + } + assertThat(actual).hasSize(1000); + Iterator iterator = actual.iterator(); + for (int i = 0; iterator.hasNext(); i++) { + Node node = iterator.next(); + assertThat(node.getOpenConnections()).isEqualTo(i); + } + } + } + + @Test + public void should_return_size() { + QueryPlan queryPlan = newQueryPlan(node1, node2, node3); + assertThat(queryPlan.size()).isEqualTo(3); + queryPlan.poll(); + assertThat(queryPlan.size()).isEqualTo(2); + queryPlan.poll(); + assertThat(queryPlan.size()).isEqualTo(1); + queryPlan.poll(); + assertThat(queryPlan.size()).isEqualTo(0); + queryPlan.poll(); + assertThat(queryPlan.size()).isEqualTo(0); + } + + @Test + public void should_return_iterator() { + QueryPlan queryPlan = newQueryPlan(node1, node2, node3); + Iterator iterator3 = queryPlan.iterator(); + queryPlan.poll(); + Iterator iterator2 = queryPlan.iterator(); + queryPlan.poll(); + Iterator iterator1 = queryPlan.iterator(); + queryPlan.poll(); + Iterator iterator0 = queryPlan.iterator(); + queryPlan.poll(); + Iterator iterator00 = queryPlan.iterator(); + + assertThat(iterator3).toIterable().containsExactly(node1, node2, node3); + assertThat(iterator2).toIterable().containsExactly(node2, node3); + assertThat(iterator1).toIterable().containsExactly(node3); + assertThat(iterator0).toIterable().isEmpty(); + assertThat(iterator00).toIterable().isEmpty(); + } + + protected abstract QueryPlan newQueryPlan(Node... nodes); +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/util/collection/SimpleQueryPlanTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/util/collection/SimpleQueryPlanTest.java new file mode 100644 index 00000000000..31e3e1006d7 --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/util/collection/SimpleQueryPlanTest.java @@ -0,0 +1,31 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.util.collection; + +import com.datastax.oss.driver.api.core.metadata.Node; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public class SimpleQueryPlanTest extends QueryPlanTestBase { + + @Override + protected QueryPlan newQueryPlan(Node... nodes) { + return new SimpleQueryPlan((Object[]) nodes); + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/CapturingTimer.java b/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/CapturingTimer.java index 4e2ed6426ce..88cdfa80104 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/CapturingTimer.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/CapturingTimer.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/CompletableFuturesTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/CompletableFuturesTest.java new file mode 100644 index 00000000000..04f96f185fd --- /dev/null +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/CompletableFuturesTest.java @@ -0,0 +1,48 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.internal.core.util.concurrent; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.fail; + +import java.util.Arrays; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import org.junit.Test; + +public class CompletableFuturesTest { + @Test + public void should_not_suppress_identical_exceptions() throws Exception { + RuntimeException error = new RuntimeException(); + CompletableFuture future1 = new CompletableFuture<>(); + future1.completeExceptionally(error); + CompletableFuture future2 = new CompletableFuture<>(); + future2.completeExceptionally(error); + try { + // if timeout exception is thrown, it indicates that CompletableFutures.allSuccessful() + // did not complete the returned future and potentially caller will wait infinitely + CompletableFutures.allSuccessful(Arrays.asList(future1, future2)) + .toCompletableFuture() + .get(1, TimeUnit.SECONDS); + fail(); + } catch (ExecutionException e) { + assertThat(e.getCause()).isEqualTo(error); + } + } +} diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/CycleDetectorTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/CycleDetectorTest.java index d8de58564f5..74e0801ff61 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/CycleDetectorTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/CycleDetectorTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/DebouncerTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/DebouncerTest.java index 2cd6c9eed21..71c844e7051 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/DebouncerTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/DebouncerTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/PromiseCombinerTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/PromiseCombinerTest.java index 0b0ce45644d..45d0239b604 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/PromiseCombinerTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/PromiseCombinerTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/ReconnectionTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/ReconnectionTest.java index 24bd02b1b73..0e541c13f92 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/ReconnectionTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/ReconnectionTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/ReplayingEventFilterTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/ReplayingEventFilterTest.java index 6dcda9119f1..65a2ee69b76 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/ReplayingEventFilterTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/ReplayingEventFilterTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/ScheduledTaskCapturingEventLoop.java b/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/ScheduledTaskCapturingEventLoop.java index 79f56fb3215..295fa545c76 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/ScheduledTaskCapturingEventLoop.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/ScheduledTaskCapturingEventLoop.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -47,7 +49,7 @@ @SuppressWarnings("FunctionalInterfaceClash") // does not matter for test code public class ScheduledTaskCapturingEventLoop extends DefaultEventLoop { - private final BlockingQueue capturedTasks = new ArrayBlockingQueue<>(100); + private final BlockingQueue> capturedTasks = new ArrayBlockingQueue<>(100); public ScheduledTaskCapturingEventLoop(EventLoopGroup parent) { super(parent); diff --git a/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/ScheduledTaskCapturingEventLoopTest.java b/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/ScheduledTaskCapturingEventLoopTest.java index 61bc52c99e1..cf0314cc335 100644 --- a/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/ScheduledTaskCapturingEventLoopTest.java +++ b/core/src/test/java/com/datastax/oss/driver/internal/core/util/concurrent/ScheduledTaskCapturingEventLoopTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/resources/ReloadingKeyManagerFactoryTest/README.md b/core/src/test/resources/ReloadingKeyManagerFactoryTest/README.md new file mode 100644 index 00000000000..9ff9b622e5b --- /dev/null +++ b/core/src/test/resources/ReloadingKeyManagerFactoryTest/README.md @@ -0,0 +1,39 @@ +# How to create cert stores for ReloadingKeyManagerFactoryTest + +Need the following cert stores: +- `server.keystore` +- `client-original.keystore` +- `client-alternate.keystore` +- `server.truststore`: trusts `client-original.keystore` and `client-alternate.keystore` +- `client.truststore`: trusts `server.keystore` + +We shouldn't need any signing requests or chains of trust, since truststores are just including certs directly. + +First create the three keystores: +``` +$ keytool -genkeypair -keyalg RSA -alias server -keystore server.keystore -dname "CN=server" -storepass changeit -keypass changeit +$ keytool -genkeypair -keyalg RSA -alias client-original -keystore client-original.keystore -dname "CN=client-original" -storepass changeit -keypass changeit +$ keytool -genkeypair -keyalg RSA -alias client-alternate -keystore client-alternate.keystore -dname "CN=client-alternate" -storepass changeit -keypass changeit +``` + +Note that we need to use `-keyalg RSA` because keytool's default keyalg is DSA, which TLS 1.3 doesn't support. If DSA is +used, the handshake will fail due to the server not being able to find any authentication schemes compatible with its +x509 certificate ("Unavailable authentication scheme"). + +Then export all the certs: +``` +$ keytool -exportcert -keystore server.keystore -alias server -file server.cert -storepass changeit +$ keytool -exportcert -keystore client-original.keystore -alias client-original -file client-original.cert -storepass changeit +$ keytool -exportcert -keystore client-alternate.keystore -alias client-alternate -file client-alternate.cert -storepass changeit +``` + +Then create the server.truststore that trusts the two client certs: +``` +$ keytool -import -file client-original.cert -alias client-original -keystore server.truststore -storepass changeit +$ keytool -import -file client-alternate.cert -alias client-alternate -keystore server.truststore -storepass changeit +``` + +Then create the client.truststore that trusts the server cert: +``` +$ keytool -import -file server.cert -alias server -keystore client.truststore -storepass changeit +``` diff --git a/core/src/test/resources/ReloadingKeyManagerFactoryTest/certs/client-alternate.keystore b/core/src/test/resources/ReloadingKeyManagerFactoryTest/certs/client-alternate.keystore new file mode 100644 index 00000000000..91cee636a0b Binary files /dev/null and b/core/src/test/resources/ReloadingKeyManagerFactoryTest/certs/client-alternate.keystore differ diff --git a/core/src/test/resources/ReloadingKeyManagerFactoryTest/certs/client-original.keystore b/core/src/test/resources/ReloadingKeyManagerFactoryTest/certs/client-original.keystore new file mode 100644 index 00000000000..74e31f7bc6f Binary files /dev/null and b/core/src/test/resources/ReloadingKeyManagerFactoryTest/certs/client-original.keystore differ diff --git a/core/src/test/resources/ReloadingKeyManagerFactoryTest/certs/client.truststore b/core/src/test/resources/ReloadingKeyManagerFactoryTest/certs/client.truststore new file mode 100644 index 00000000000..3ce9a720dbc Binary files /dev/null and b/core/src/test/resources/ReloadingKeyManagerFactoryTest/certs/client.truststore differ diff --git a/core/src/test/resources/ReloadingKeyManagerFactoryTest/certs/server.keystore b/core/src/test/resources/ReloadingKeyManagerFactoryTest/certs/server.keystore new file mode 100644 index 00000000000..7d279638a34 Binary files /dev/null and b/core/src/test/resources/ReloadingKeyManagerFactoryTest/certs/server.keystore differ diff --git a/core/src/test/resources/ReloadingKeyManagerFactoryTest/certs/server.truststore b/core/src/test/resources/ReloadingKeyManagerFactoryTest/certs/server.truststore new file mode 100644 index 00000000000..c9b06b5fbe1 Binary files /dev/null and b/core/src/test/resources/ReloadingKeyManagerFactoryTest/certs/server.truststore differ diff --git a/core/src/test/resources/application.conf b/core/src/test/resources/application.conf index 75cd8820639..efea37cc078 100644 --- a/core/src/test/resources/application.conf +++ b/core/src/test/resources/application.conf @@ -1,3 +1,20 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + datastax-java-driver { basic.request.timeout = ${datastax-java-driver.advanced.connection.init-query-timeout} -} \ No newline at end of file +} diff --git a/core/src/test/resources/config/customApplication.conf b/core/src/test/resources/config/customApplication.conf index 92b5f492b9c..c3e3dc7b468 100644 --- a/core/src/test/resources/config/customApplication.conf +++ b/core/src/test/resources/config/customApplication.conf @@ -1,3 +1,20 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + datastax-java-driver { // Check that references to other options in `reference.conf` are correctly resolved basic.request.timeout = ${datastax-java-driver.advanced.connection.init-query-timeout} diff --git a/core/src/test/resources/config/customApplication.properties b/core/src/test/resources/config/customApplication.properties index 26375fcc0f4..4c1d1ea0647 100644 --- a/core/src/test/resources/config/customApplication.properties +++ b/core/src/test/resources/config/customApplication.properties @@ -1,11 +1,13 @@ # -# Copyright DataStax, Inc. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/resources/insights/malformed-pom.properties b/core/src/test/resources/insights/malformed-pom.properties index dcb78b4b5ac..0a503062fbd 100644 --- a/core/src/test/resources/insights/malformed-pom.properties +++ b/core/src/test/resources/insights/malformed-pom.properties @@ -1,11 +1,13 @@ # -# Copyright DataStax, Inc. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/resources/insights/pom.properties b/core/src/test/resources/insights/pom.properties index 5f1c59124aa..e68a31c8fc7 100644 --- a/core/src/test/resources/insights/pom.properties +++ b/core/src/test/resources/insights/pom.properties @@ -1,11 +1,13 @@ # -# Copyright DataStax, Inc. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, diff --git a/core/src/test/resources/insights/test-dependencies.txt b/core/src/test/resources/insights/test-dependencies.txt index 6cabe8b257d..e9186a35e6b 100644 --- a/core/src/test/resources/insights/test-dependencies.txt +++ b/core/src/test/resources/insights/test-dependencies.txt @@ -17,7 +17,7 @@ The following files have been resolved: com.fasterxml.jackson.core:jackson-core:jar:2.8.11:compile org.hdrhistogram:HdrHistogram:jar:2.1.10:compile (optional) org.ow2.asm:asm-tree:jar:5.0.3:compile - org.lz4:lz4-java:jar:1.4.1:compile (optional) + at.yawk.lz4:lz4-java:jar:1.10.1:compile (optional) io.netty:netty-transport:jar:4.0.56.Final:compile io.dropwizard.metrics:metrics-core:jar:3.2.2:compile io.netty:netty-common:jar:4.0.56.Final:compile diff --git a/core/src/test/resources/logback-test.xml b/core/src/test/resources/logback-test.xml index 90dc593ef3b..1424331a31d 100644 --- a/core/src/test/resources/logback-test.xml +++ b/core/src/test/resources/logback-test.xml @@ -1,13 +1,15 @@ + + 4.0.0 + + org.apache.cassandra + java-driver-parent + 4.19.3-SNAPSHOT + + java-driver-distribution-source + pom + Apache Cassandra Java Driver - source distribution + + apache-cassandra-java-driver-${project.version}-source + + + maven-jar-plugin + + + + default-jar + none + + + + + maven-source-plugin + + true + + + + maven-install-plugin + + true + + + + maven-deploy-plugin + + true + + + + org.revapi + revapi-maven-plugin + + true + + + + org.sonatype.plugins + nexus-staging-maven-plugin + + true + + + + + + + release + + + + maven-assembly-plugin + + + assemble-source-tarball + package + + single + + + + + false + + src/assembly/source-tarball.xml + + posix + + + + net.nicoulaj.maven.plugins + checksum-maven-plugin + 1.7 + + + + artifacts + + + + + true + + sha256 + sha512 + + + + + + + + diff --git a/distribution-source/src/assembly/source-tarball.xml b/distribution-source/src/assembly/source-tarball.xml new file mode 100644 index 00000000000..b3e2d0f463a --- /dev/null +++ b/distribution-source/src/assembly/source-tarball.xml @@ -0,0 +1,43 @@ + + + + source-tarball + + tar.gz + + + + .. + . + true + + + **/*.iml + **/.classpath + **/.project + **/.java-version + **/.flattened-pom.xml + **/dependency-reduced-pom.xml + **/${project.build.directory}/** + + + + diff --git a/distribution-tests/pom.xml b/distribution-tests/pom.xml new file mode 100644 index 00000000000..9cef313f8a5 --- /dev/null +++ b/distribution-tests/pom.xml @@ -0,0 +1,122 @@ + + + + 4.0.0 + + org.apache.cassandra + java-driver-parent + 4.19.3-SNAPSHOT + + java-driver-distribution-tests + Apache Cassandra Java Driver - distribution tests + + + + ${project.groupId} + java-driver-bom + ${project.version} + pom + import + + + + + + org.apache.cassandra + java-driver-test-infra + test + + + org.apache.cassandra + java-driver-query-builder + test + + + org.apache.cassandra + java-driver-mapper-processor + test + + + org.apache.cassandra + java-driver-mapper-runtime + test + + + org.apache.cassandra + java-driver-core + test + + + org.apache.cassandra + java-driver-metrics-micrometer + test + + + org.apache.cassandra + java-driver-metrics-microprofile + test + + + junit + junit + test + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + ${testing.jvm}/bin/java + ${mockitoopens.argline} + 1 + + + + org.revapi + revapi-maven-plugin + + true + + + + maven-install-plugin + + true + + + + maven-deploy-plugin + + true + + + + org.sonatype.plugins + nexus-staging-maven-plugin + + true + + + + + diff --git a/distribution-tests/src/test/java/com/datastax/oss/driver/api/core/DriverDependencyTest.java b/distribution-tests/src/test/java/com/datastax/oss/driver/api/core/DriverDependencyTest.java new file mode 100644 index 00000000000..16952e3d771 --- /dev/null +++ b/distribution-tests/src/test/java/com/datastax/oss/driver/api/core/DriverDependencyTest.java @@ -0,0 +1,84 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.api.core; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.datastax.oss.driver.api.core.session.Session; +import com.datastax.oss.driver.api.mapper.MapperBuilder; +import com.datastax.oss.driver.api.querybuilder.QueryBuilder; +import com.datastax.oss.driver.api.testinfra.CassandraResourceRule; +import com.datastax.oss.driver.internal.core.util.Reflection; +import com.datastax.oss.driver.internal.mapper.processor.MapperProcessor; +import com.datastax.oss.driver.internal.metrics.micrometer.MicrometerMetricsFactory; +import com.datastax.oss.driver.internal.metrics.microprofile.MicroProfileMetricsFactory; +import org.junit.Test; + +public class DriverDependencyTest { + @Test + public void should_include_core_jar() { + assertThat(Reflection.loadClass(null, "com.datastax.oss.driver.api.core.session.Session")) + .isEqualTo(Session.class); + } + + @Test + public void should_include_query_builder_jar() { + assertThat(Reflection.loadClass(null, "com.datastax.oss.driver.api.querybuilder.QueryBuilder")) + .isEqualTo(QueryBuilder.class); + } + + @Test + public void should_include_mapper_processor_jar() { + assertThat( + Reflection.loadClass( + null, "com.datastax.oss.driver.internal.mapper.processor.MapperProcessor")) + .isEqualTo(MapperProcessor.class); + } + + @Test + public void should_include_mapper_runtime_jar() { + assertThat(Reflection.loadClass(null, "com.datastax.oss.driver.api.mapper.MapperBuilder")) + .isEqualTo(MapperBuilder.class); + } + + @Test + public void should_include_metrics_micrometer_jar() { + assertThat( + Reflection.loadClass( + null, + "com.datastax.oss.driver.internal.metrics.micrometer.MicrometerMetricsFactory")) + .isEqualTo(MicrometerMetricsFactory.class); + } + + @Test + public void should_include_metrics_microprofile_jar() { + assertThat( + Reflection.loadClass( + null, + "com.datastax.oss.driver.internal.metrics.microprofile.MicroProfileMetricsFactory")) + .isEqualTo(MicroProfileMetricsFactory.class); + } + + @Test + public void should_include_test_infra_jar() { + assertThat( + Reflection.loadClass( + null, "com.datastax.oss.driver.api.testinfra.CassandraResourceRule")) + .isEqualTo(CassandraResourceRule.class); + } +} diff --git a/distribution-tests/src/test/java/com/datastax/oss/driver/api/core/OptionalDependencyTest.java b/distribution-tests/src/test/java/com/datastax/oss/driver/api/core/OptionalDependencyTest.java new file mode 100644 index 00000000000..28626413487 --- /dev/null +++ b/distribution-tests/src/test/java/com/datastax/oss/driver/api/core/OptionalDependencyTest.java @@ -0,0 +1,54 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.api.core; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.datastax.oss.driver.internal.core.util.Dependency; +import com.datastax.oss.driver.internal.core.util.Reflection; +import org.junit.Test; + +public class OptionalDependencyTest { + @Test + public void should_not_include_snappy_jar() { + Dependency.SNAPPY + .classes() + .forEach(clazz -> assertThat(Reflection.loadClass(null, clazz)).isNull()); + } + + @Test + public void should_not_include_l4z_jar() { + Dependency.LZ4 + .classes() + .forEach(clazz -> assertThat(Reflection.loadClass(null, clazz)).isNull()); + } + + @Test + public void should_not_include_esri_jar() { + Dependency.ESRI + .classes() + .forEach(clazz -> assertThat(Reflection.loadClass(null, clazz)).isNull()); + } + + @Test + public void should_not_include_tinkerpop_jar() { + Dependency.TINKERPOP + .classes() + .forEach(clazz -> assertThat(Reflection.loadClass(null, clazz)).isNull()); + } +} diff --git a/distribution-tests/src/test/java/com/datastax/oss/driver/api/core/ProvidedDependencyTest.java b/distribution-tests/src/test/java/com/datastax/oss/driver/api/core/ProvidedDependencyTest.java new file mode 100644 index 00000000000..1070bbc2fb1 --- /dev/null +++ b/distribution-tests/src/test/java/com/datastax/oss/driver/api/core/ProvidedDependencyTest.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.api.core; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.datastax.oss.driver.internal.core.util.Reflection; +import org.junit.Test; + +public class ProvidedDependencyTest { + @Test + public void should_not_include_graal_sdk_jar() { + assertThat(Reflection.loadClass(null, "org.graalvm.nativeimage.VMRuntime")).isNull(); + } + + @Test + public void should_not_include_spotbugs_annotations_jar() { + assertThat(Reflection.loadClass(null, "edu.umd.cs.findbugs.annotations.NonNull")).isNull(); + } + + @Test + public void should_not_include_jicp_annotations_jar() { + assertThat(Reflection.loadClass(null, "net.jcip.annotations.ThreadSafe")).isNull(); + } + + @Test + public void should_not_include_blockhound_jar() { + assertThat(Reflection.loadClass(null, "reactor.blockhound.BlockHoundRuntime")).isNull(); + } +} diff --git a/distribution/pom.xml b/distribution/pom.xml index dd1e4e8c7b4..20b9afc1bcd 100644 --- a/distribution/pom.xml +++ b/distribution/pom.xml @@ -1,13 +1,15 @@ jar - DataStax Java driver for Apache Cassandra(R) - binary distribution + Apache Cassandra Java Driver - binary distribution - com.datastax.oss:java-driver-query-builder - com.datastax.oss:java-driver-mapper-runtime - com.datastax.oss:java-driver-mapper-processor + org.apache.cassandra:java-driver-query-builder + org.apache.cassandra:java-driver-mapper-runtime + org.apache.cassandra:java-driver-mapper-processor true @@ -53,7 +55,7 @@ true - com.datastax.oss:java-driver-query-builder + org.apache.cassandra:java-driver-query-builder lib/query-builder @@ -61,11 +63,11 @@ - com.datastax.oss:java-driver-core - com.datastax.oss:java-driver-mapper-runtime - com.datastax.oss:java-driver-mapper-processor + org.apache.cassandra:java-driver-core + org.apache.cassandra:java-driver-mapper-runtime + org.apache.cassandra:java-driver-mapper-processor + org.apache.cassandra:java-driver-guava-shaded - com.datastax.oss:java-driver-shaded-guava com.github.stephenc.jcip:jcip-annotations com.github.spotbugs:spotbugs-annotations @@ -78,7 +80,7 @@ true - com.datastax.oss:java-driver-mapper-runtime + org.apache.cassandra:java-driver-mapper-runtime lib/mapper-runtime @@ -86,11 +88,11 @@ - com.datastax.oss:java-driver-core - com.datastax.oss:java-driver-query-builder - com.datastax.oss:java-driver-mapper-processor + org.apache.cassandra:java-driver-core + org.apache.cassandra:java-driver-query-builder + org.apache.cassandra:java-driver-mapper-processor + org.apache.cassandra:java-driver-guava-shaded - com.datastax.oss:java-driver-shaded-guava com.github.stephenc.jcip:jcip-annotations com.github.spotbugs:spotbugs-annotations @@ -103,7 +105,7 @@ true - com.datastax.oss:java-driver-mapper-processor + org.apache.cassandra:java-driver-mapper-processor lib/mapper-processor @@ -111,11 +113,11 @@ - com.datastax.oss:java-driver-core - com.datastax.oss:java-driver-query-builder - com.datastax.oss:java-driver-mapper-runtime + org.apache.cassandra:java-driver-core + org.apache.cassandra:java-driver-query-builder + org.apache.cassandra:java-driver-mapper-runtime + org.apache.cassandra:java-driver-guava-shaded - com.datastax.oss:java-driver-shaded-guava com.github.stephenc.jcip:jcip-annotations com.github.spotbugs:spotbugs-annotations @@ -128,10 +130,10 @@ true - com.datastax.oss:java-driver-core - com.datastax.oss:java-driver-query-builder - com.datastax.oss:java-driver-mapper-runtime - com.datastax.oss:java-driver-mapper-processor + org.apache.cassandra:java-driver-core + org.apache.cassandra:java-driver-query-builder + org.apache.cassandra:java-driver-mapper-runtime + org.apache.cassandra:java-driver-mapper-processor false @@ -154,7 +156,8 @@ . README* - LICENSE* + LICENSE_binary + NOTICE_binary.txt diff --git a/docs.yaml b/docs.yaml index d7c3f1eb5b3..7c679a0f47e 100644 --- a/docs.yaml +++ b/docs.yaml @@ -1,5 +1,22 @@ -title: DataStax Java Driver -summary: DataStax Java Driver for Apache Cassandra® +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +title: Java Driver +summary: Java Driver for Apache Cassandra® homepage: http://docs.datastax.com/en/developer/java-driver theme: datastax sections: diff --git a/examples/README.md b/examples/README.md index 83c61f27971..9d2210d8a4a 100644 --- a/examples/README.md +++ b/examples/README.md @@ -1,6 +1,25 @@ -# DataStax Java Driver for Apache Cassandra(R) - Examples + + +# Java Driver for Apache Cassandra(R) - Examples + +This module contains examples of how to use the Java Driver for Apache Cassandra(R). ## Usage diff --git a/examples/pom.xml b/examples/pom.xml index f2124c8c3f3..12e42dfdf53 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -1,13 +1,15 @@ + + io.projectreactor + reactor-core + + + com.github.spotbugs + spotbugs-annotations + provided + @@ -145,7 +157,7 @@ 1.8 - com.datastax.oss + org.apache.cassandra java-driver-mapper-processor ${project.version} diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/astra/AstraReadCassandraVersion.java b/examples/src/main/java/com/datastax/oss/driver/examples/astra/AstraReadCassandraVersion.java index d434665552a..ff8dc6d96f4 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/astra/AstraReadCassandraVersion.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/astra/AstraReadCassandraVersion.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -41,7 +43,7 @@ * @see * Obtaining Astra secure connect bundle (GCP) - * @see Java driver online + * @see Java Driver online * manual */ public class AstraReadCassandraVersion { diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/basic/CreateAndPopulateKeyspace.java b/examples/src/main/java/com/datastax/oss/driver/examples/basic/CreateAndPopulateKeyspace.java index 3cf92424e9b..3dcfa702041 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/basic/CreateAndPopulateKeyspace.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/basic/CreateAndPopulateKeyspace.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -39,7 +41,7 @@ *
  • inserts a row in each table. * * - * @see Java driver online + * @see Java Driver online * manual */ @SuppressWarnings("CatchAndPrintStackTrace") diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/basic/ReadCassandraVersion.java b/examples/src/main/java/com/datastax/oss/driver/examples/basic/ReadCassandraVersion.java index 58e58fac497..63804ebfece 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/basic/ReadCassandraVersion.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/basic/ReadCassandraVersion.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -31,7 +33,7 @@ * *

    Side effects: none. * - * @see Java driver online + * @see Java Driver online * manual */ public class ReadCassandraVersion { diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/basic/ReadTopologyAndSchemaMetadata.java b/examples/src/main/java/com/datastax/oss/driver/examples/basic/ReadTopologyAndSchemaMetadata.java index 012c92702d9..d61911d19b9 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/basic/ReadTopologyAndSchemaMetadata.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/basic/ReadTopologyAndSchemaMetadata.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -34,7 +36,7 @@ * *

    Side effects: none. * - * @see Java driver online + * @see Java Driver online * manual */ public class ReadTopologyAndSchemaMetadata { diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/concurrent/LimitConcurrencyCustom.java b/examples/src/main/java/com/datastax/oss/driver/examples/concurrent/LimitConcurrencyCustom.java index 9962d414044..444d4f406b7 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/concurrent/LimitConcurrencyCustom.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/concurrent/LimitConcurrencyCustom.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -21,7 +23,7 @@ import com.datastax.oss.driver.api.core.CqlSession; import com.datastax.oss.driver.api.core.CqlSessionBuilder; import com.datastax.oss.driver.api.core.cql.PreparedStatement; -import java.util.UUID; +import com.datastax.oss.driver.api.core.uuid.Uuids; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; @@ -54,7 +56,7 @@ *

  • inserts a TOTAL_NUMBER_OF_INSERTS of rows into the table. * * - * @see Java driver online + * @see Java Driver online * manual */ @SuppressWarnings("CatchAndPrintStackTrace") @@ -103,7 +105,7 @@ private static void insertConcurrent(CqlSession session) throws InterruptedExcep executor.submit( () -> { try { - session.execute(pst.bind().setUuid("id", UUID.randomUUID()).setInt("value", counter)); + session.execute(pst.bind().setUuid("id", Uuids.random()).setInt("value", counter)); insertsCounter.incrementAndGet(); } catch (Throwable t) { // On production you should leverage logger and use logger.error() method. diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/concurrent/LimitConcurrencyCustomAsync.java b/examples/src/main/java/com/datastax/oss/driver/examples/concurrent/LimitConcurrencyCustomAsync.java index 45287098e5d..bec26eb7e81 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/concurrent/LimitConcurrencyCustomAsync.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/concurrent/LimitConcurrencyCustomAsync.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -22,9 +24,9 @@ import com.datastax.oss.driver.api.core.CqlSessionBuilder; import com.datastax.oss.driver.api.core.cql.AsyncResultSet; import com.datastax.oss.driver.api.core.cql.PreparedStatement; +import com.datastax.oss.driver.api.core.uuid.Uuids; import java.util.ArrayList; import java.util.List; -import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; @@ -53,7 +55,7 @@ *
  • inserts a TOTAL_NUMBER_OF_INSERTS of rows into the table. * * - * @see Java driver online manual + * @see Java Driver online manual */ public class LimitConcurrencyCustomAsync { private static final int CONCURRENCY_LEVEL = 32; @@ -124,7 +126,7 @@ private static CompletableFuture executeInsert( CqlSession session, PreparedStatement pst, int counter) { return session - .executeAsync(pst.bind().setUuid("id", UUID.randomUUID()).setInt("value", counter)) + .executeAsync(pst.bind().setUuid("id", Uuids.random()).setInt("value", counter)) .toCompletableFuture() .whenComplete( (BiConsumer) diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/concurrent/LimitConcurrencyRequestThrottler.java b/examples/src/main/java/com/datastax/oss/driver/examples/concurrent/LimitConcurrencyRequestThrottler.java index 995054f2c52..87293e50907 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/concurrent/LimitConcurrencyRequestThrottler.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/concurrent/LimitConcurrencyRequestThrottler.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -21,10 +23,10 @@ import com.datastax.oss.driver.api.core.CqlSession; import com.datastax.oss.driver.api.core.config.DefaultDriverOption; import com.datastax.oss.driver.api.core.cql.PreparedStatement; +import com.datastax.oss.driver.api.core.uuid.Uuids; import com.datastax.oss.driver.internal.core.session.throttling.ConcurrencyLimitingRequestThrottler; import java.util.ArrayList; import java.util.List; -import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; @@ -86,7 +88,7 @@ private static void insertConcurrent(CqlSession session) for (int i = 0; i < TOTAL_NUMBER_OF_INSERTS; i++) { pending.add( session - .executeAsync(pst.bind().setUuid("id", UUID.randomUUID()).setInt("value", i)) + .executeAsync(pst.bind().setUuid("id", Uuids.random()).setInt("value", i)) // Transform CompletionState toCompletableFuture to be able to wait for execution of // all using CompletableFuture.allOf .toCompletableFuture()); diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/datatypes/Blobs.java b/examples/src/main/java/com/datastax/oss/driver/examples/datatypes/Blobs.java index 5dc5802018f..750ee49f685 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/datatypes/Blobs.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/datatypes/Blobs.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -33,7 +35,7 @@ /** * Inserts and retrieves values in BLOB columns. * - *

    By default, the Java driver maps this type to {@link java.nio.ByteBuffer}. The ByteBuffer API + *

    By default, the Java Driver maps this type to {@link java.nio.ByteBuffer}. The ByteBuffer API * is a bit tricky to use at times, so we will show common pitfalls as well. We strongly recommend * that you read the {@link java.nio.Buffer} and {@link ByteBuffer} API docs and become familiar * with the capacity, limit and position properties. By default, the Java driver maps tuples to {@link TupleValue}. This example goes beyond that + *

    By default, the Java Driver maps tuples to {@link TupleValue}. This example goes beyond that * and shows how to map tuples to arbitrary Java types, leveraging the special {@link MappingCodec}. * *

    A simpler example of usage of tuples can be found in {@link TuplesSimple}. @@ -119,7 +121,9 @@ protected Coordinates innerToOuter(@Nullable TupleValue value) { @Nullable @Override protected TupleValue outerToInner(@Nullable Coordinates value) { - return value == null ? null : getCqlType().newValue().setInt(0, value.x).setInt(1, value.y); + return value == null + ? null + : this.getCqlType().newValue().setInt(0, value.x).setInt(1, value.y); } } diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/datatypes/TuplesSimple.java b/examples/src/main/java/com/datastax/oss/driver/examples/datatypes/TuplesSimple.java index 6f9c90f8482..6aee96bac7f 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/datatypes/TuplesSimple.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/datatypes/TuplesSimple.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -27,7 +29,7 @@ /** * Inserts and retrieves values in columns of tuple types. * - *

    By default, the Java driver maps tuples to {@link TupleValue}. This example shows how to + *

    By default, the Java Driver maps tuples to {@link TupleValue}. This example shows how to * create instances of {@link TupleValue}, how to insert them in the database, and how to retrieve * such instances from the database. * diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/datatypes/UserDefinedTypesMapped.java b/examples/src/main/java/com/datastax/oss/driver/examples/datatypes/UserDefinedTypesMapped.java index c634bd0eb9b..ef97f507746 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/datatypes/UserDefinedTypesMapped.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/datatypes/UserDefinedTypesMapped.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -33,7 +35,7 @@ /** * Inserts and retrieves values in columns of user-defined types. * - *

    By default, the Java driver maps user-defined types to {@link UdtValue}. This example goes + *

    By default, the Java Driver maps user-defined types to {@link UdtValue}. This example goes * beyond that and shows how to map user-defined types to arbitrary Java types, leveraging the * special {@link MappingCodec}. * diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/datatypes/UserDefinedTypesSimple.java b/examples/src/main/java/com/datastax/oss/driver/examples/datatypes/UserDefinedTypesSimple.java index 0d5ca5eb27d..4387cde5b0f 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/datatypes/UserDefinedTypesSimple.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/datatypes/UserDefinedTypesSimple.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -26,7 +28,7 @@ /** * Inserts and retrieves values in columns of user-defined types. * - *

    By default, the Java driver maps user-defined types to {@link UdtValue}. This example shows + *

    By default, the Java Driver maps user-defined types to {@link UdtValue}. This example shows * how to create instances of {@link UdtValue}, how to insert them in the database, and how to * retrieve such instances from the database. * diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/failover/CrossDatacenterFailover.java b/examples/src/main/java/com/datastax/oss/driver/examples/failover/CrossDatacenterFailover.java new file mode 100644 index 00000000000..07907af6886 --- /dev/null +++ b/examples/src/main/java/com/datastax/oss/driver/examples/failover/CrossDatacenterFailover.java @@ -0,0 +1,458 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.datastax.oss.driver.examples.failover; + +import com.datastax.dse.driver.api.core.cql.reactive.ReactiveRow; +import com.datastax.oss.driver.api.core.AllNodesFailedException; +import com.datastax.oss.driver.api.core.CqlSession; +import com.datastax.oss.driver.api.core.DriverException; +import com.datastax.oss.driver.api.core.DriverTimeoutException; +import com.datastax.oss.driver.api.core.NoNodeAvailableException; +import com.datastax.oss.driver.api.core.config.DriverConfigLoader; +import com.datastax.oss.driver.api.core.config.OptionsMap; +import com.datastax.oss.driver.api.core.config.TypedDriverOption; +import com.datastax.oss.driver.api.core.cql.AsyncResultSet; +import com.datastax.oss.driver.api.core.cql.SimpleStatement; +import com.datastax.oss.driver.api.core.cql.Statement; +import com.datastax.oss.driver.api.core.metadata.Node; +import com.datastax.oss.driver.api.core.servererrors.CoordinatorException; +import com.datastax.oss.driver.api.core.servererrors.QueryConsistencyException; +import com.datastax.oss.driver.api.core.servererrors.UnavailableException; +import com.datastax.oss.driver.internal.core.util.concurrent.CompletableFutures; +import java.util.Collections; +import java.util.List; +import java.util.Map.Entry; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.ExecutionException; +import reactor.core.publisher.Flux; + +/** + * This example illustrates how to implement a cross-datacenter failover strategy from application + * code. + * + *

    Starting with driver 4.10, cross-datacenter failover is also provided as a configuration + * option for built-in load balancing policies. See Load + * balancing in the manual. + * + *

    This example demonstrates how to achieve the same effect in application code, which confers + * more fained-grained control over which statements should be retried and where. + * + *

    The logic that decides whether or not a cross-DC failover should be attempted is presented in + * the {@link #shouldFailover(DriverException)} method below; study it carefully and adapt it to + * your needs if necessary. + * + *

    The actual request execution and failover code is presented in 3 different programming styles: + * + *

      + *
    1. Synchronous: see the {@link #writeSync()} method below; + *
    2. Asynchronous: see the {@link #writeAsync()} method below; + *
    3. Reactive (using Reactor): see the {@link + * #writeReactive()} method below. + *
    + * + * The 3 styles are identical in terms of failover effect; they are all included merely to help + * programmers pick the variant that is closest to the style they use. + * + *

    Preconditions: + * + *

      + *
    • An Apache Cassandra(R) cluster with two datacenters, dc1 and dc2, containing at least 3 + * nodes in each datacenter, is running and accessible through the contact point: + * 127.0.0.1:9042. + *
    + * + *

    Side effects: + * + *

      + *
    1. Creates a new keyspace {@code failover} in the cluster, with replication factor 3 in both + * datacenters. If a keyspace with this name already exists, it will be reused; + *
    2. Creates a new table {@code failover.orders}. If a table with that name exists already, it + * will be reused; + *
    3. Tries to write a row in the table using the local datacenter dc1; + *
    4. If the local datacenter dc1 is down, retries the write in the remote datacenter dc2. + *
    + * + * @see Java Driver online + * manual + */ +public class CrossDatacenterFailover { + + public static void main(String[] args) throws Exception { + + CrossDatacenterFailover client = new CrossDatacenterFailover(); + + try { + + // Note: when this example is executed, at least the local DC must be available + // since the driver will try to reach contact points in that DC. + + client.connect(); + client.createSchema(); + + // To fully exercise this example, try to stop the entire dc1 here; then observe how + // the writes executed below will first fail in dc1, then be diverted to dc2, where they will + // succeed. + + client.writeSync(); + client.writeAsync(); + client.writeReactive(); + + } finally { + client.close(); + } + } + + private CqlSession session; + + private CrossDatacenterFailover() {} + + /** Initiates a connection to the cluster. */ + private void connect() { + + // For simplicity, this example uses a 100% in-memory configuration loader, but the same + // configuration can be achieved with the more traditional file-based approach. + // Simply put the below snippet in your application.conf file to get the same config: + + /* + datastax-java-driver { + basic.contact-points = [ "127.0.0.1:9042" ] + basic.load-balancing-policy.local-datacenter = "dc1" + basic.request.consistency = LOCAL_QUORUM + profiles { + remote { + basic.load-balancing-policy.local-datacenter = "dc2" + basic.request.consistency = LOCAL_ONE + } + } + } + */ + + OptionsMap options = OptionsMap.driverDefaults(); + // set the datacenter to dc1 in the default profile; this makes dc1 the local datacenter + options.put(TypedDriverOption.LOAD_BALANCING_LOCAL_DATACENTER, "dc1"); + // set the datacenter to dc2 in the "remote" profile + options.put("remote", TypedDriverOption.LOAD_BALANCING_LOCAL_DATACENTER, "dc2"); + // make sure to provide a contact point belonging to dc1, not dc2! + options.put(TypedDriverOption.CONTACT_POINTS, Collections.singletonList("127.0.0.1:9042")); + // in this example, the default consistency level is LOCAL_QUORUM + options.put(TypedDriverOption.REQUEST_CONSISTENCY, "LOCAL_QUORUM"); + // but when failing over, the consistency level will be automatically downgraded to LOCAL_ONE + options.put("remote", TypedDriverOption.REQUEST_CONSISTENCY, "LOCAL_ONE"); + + session = CqlSession.builder().withConfigLoader(DriverConfigLoader.fromMap(options)).build(); + + System.out.println("Connected to cluster with session: " + session.getName()); + } + + /** Creates the schema (keyspace) and table for this example. */ + private void createSchema() { + + session.execute( + "CREATE KEYSPACE IF NOT EXISTS failover WITH replication " + + "= {'class':'NetworkTopologyStrategy', 'dc1':3, 'dc2':3}"); + + session.execute( + "CREATE TABLE IF NOT EXISTS failover.orders (" + + "product_id uuid," + + "timestamp timestamp," + + "price double," + + "PRIMARY KEY (product_id,timestamp)" + + ")"); + } + + /** Inserts data synchronously using the local DC, retrying if necessary in a remote DC. */ + private void writeSync() { + + System.out.println("------- DC failover (sync) ------- "); + + Statement statement = + SimpleStatement.newInstance( + "INSERT INTO failover.orders " + + "(product_id, timestamp, price) " + + "VALUES (" + + "756716f7-2e54-4715-9f00-91dcbea6cf50," + + "'2018-02-26T13:53:46.345+01:00'," + + "2.34)"); + + try { + + // try the statement using the default profile, which targets the local datacenter dc1. + session.execute(statement); + + System.out.println("Write succeeded"); + + } catch (DriverException e) { + + if (shouldFailover(e)) { + + System.out.println("Write failed in local DC, retrying in remote DC"); + + try { + + // try the statement using the remote profile, which targets the remote datacenter dc2. + session.execute(statement.setExecutionProfileName("remote")); + + System.out.println("Write succeeded"); + + } catch (DriverException e2) { + + System.out.println("Write failed in remote DC"); + + e2.printStackTrace(); + } + } + } + // let other errors propagate + } + + /** Inserts data asynchronously using the local DC, retrying if necessary in a remote DC. */ + private void writeAsync() throws ExecutionException, InterruptedException { + + System.out.println("------- DC failover (async) ------- "); + + Statement statement = + SimpleStatement.newInstance( + "INSERT INTO failover.orders " + + "(product_id, timestamp, price) " + + "VALUES (" + + "756716f7-2e54-4715-9f00-91dcbea6cf50," + + "'2018-02-26T13:53:46.345+01:00'," + + "2.34)"); + + CompletionStage result = + // try the statement using the default profile, which targets the local datacenter dc1. + session + .executeAsync(statement) + .handle( + (rs, error) -> { + if (error == null) { + return CompletableFuture.completedFuture(rs); + } else { + if (error instanceof DriverException + && shouldFailover((DriverException) error)) { + System.out.println("Write failed in local DC, retrying in remote DC"); + // try the statement using the remote profile, which targets the remote + // datacenter dc2. + return session.executeAsync(statement.setExecutionProfileName("remote")); + } + // let other errors propagate + return CompletableFutures.failedFuture(error); + } + }) + // unwrap (flatmap) the nested future + .thenCompose(future -> future) + .whenComplete( + (rs, error) -> { + if (error == null) { + System.out.println("Write succeeded"); + } else { + System.out.println("Write failed in remote DC"); + error.printStackTrace(); + } + }); + + // for the sake of this example, wait for the operation to finish + result.toCompletableFuture().get(); + } + + /** Inserts data reactively using the local DC, retrying if necessary in a remote DC. */ + private void writeReactive() { + + System.out.println("------- DC failover (reactive) ------- "); + + Statement statement = + SimpleStatement.newInstance( + "INSERT INTO failover.orders " + + "(product_id, timestamp, price) " + + "VALUES (" + + "756716f7-2e54-4715-9f00-91dcbea6cf50," + + "'2018-02-26T13:53:46.345+01:00'," + + "2.34)"); + + Flux result = + // try the statement using the default profile, which targets the local datacenter dc1. + Flux.from(session.executeReactive(statement)) + .onErrorResume( + DriverException.class, + error -> { + if (shouldFailover(error)) { + System.out.println("Write failed in local DC, retrying in remote DC"); + // try the statement using the remote profile, which targets the remote + // datacenter dc2. + return session.executeReactive(statement.setExecutionProfileName("remote")); + } else { + return Flux.error(error); + } + }) + .doOnComplete(() -> System.out.println("Write succeeded")) + .doOnError( + error -> { + System.out.println("Write failed"); + error.printStackTrace(); + }); + + // for the sake of this example, wait for the operation to finish + result.blockLast(); + } + + /** + * Analyzes the error and decides whether to failover to a remote DC. + * + *

    The logic below categorizes driver exceptions in four main groups: + * + *

      + *
    1. Total DC outage: all nodes in DC were known to be down when the request was executed; + *
    2. Partial DC outage: one or many nodes responded, but reported a replica availability + * problem; + *
    3. DC unreachable: one or many nodes were queried, but none responded (timeout); + *
    4. Other errors. + *
    + * + * A DC failover is authorized for the first three groups above: total DC outage, partial DC + * outage, and DC unreachable. + * + *

    This logic is provided as a good starting point for users to create their own DC failover + * strategy; please adjust it to your exact needs. + */ + private boolean shouldFailover(DriverException mainException) { + + if (mainException instanceof NoNodeAvailableException) { + + // No node could be tried, because all nodes in the query plan were down. This could be a + // total DC outage, so trying another DC makes sense. + System.out.println("All nodes were down in this datacenter, failing over"); + return true; + + } else if (mainException instanceof AllNodesFailedException) { + + // Many nodes were tried (as decided by the retry policy), but all failed. This could be a + // partial DC outage: some nodes were up, but the replicas were down. + + boolean failover = false; + + // Inspect the error to find out how many coordinators were tried, and which errors they + // returned. + for (Entry> entry : + ((AllNodesFailedException) mainException).getAllErrors().entrySet()) { + + Node coordinator = entry.getKey(); + List errors = entry.getValue(); + + System.out.printf( + "Node %s in DC %s was tried %d times but failed with:%n", + coordinator.getEndPoint(), coordinator.getDatacenter(), errors.size()); + + for (Throwable nodeException : errors) { + + System.out.printf("\t- %s%n", nodeException); + + // If the error was a replica availability error, then we know that some replicas were + // down in this DC. Retrying in another DC could solve the problem. Other errors don't + // necessarily mean that the DC is unavailable, so we ignore them. + if (isReplicaAvailabilityError(nodeException)) { + failover = true; + } + } + } + + // Authorize the failover if at least one of the coordinators reported a replica availability + // error that could be solved by trying another DC. + if (failover) { + System.out.println( + "Some nodes tried in this DC reported a replica availability error, failing over"); + } else { + System.out.println("All nodes tried in this DC failed unexpectedly, not failing over"); + } + return failover; + + } else if (mainException instanceof DriverTimeoutException) { + + // One or many nodes were tried, but none replied in a timely manner, and the timeout defined + // by the option `datastax-java-driver.basic.request.timeout` was triggered. + // This could be a DC outage as well, or a network partition issue, so trying another DC may + // make sense. + // Note about SLAs: if your application needs to comply with SLAs, and the maximum acceptable + // latency for a request is equal or very close to the request timeout, beware that failing + // over to a different datacenter here could potentially break your SLA. + + System.out.println( + "No node in this DC replied before the timeout was triggered, failing over"); + return true; + + } else if (mainException instanceof CoordinatorException) { + + // Only one node was tried, and it failed (and the retry policy did not tell the driver to + // retry this request, but rather to surface the error immediately). This is rather unusual + // as the driver's default retry policy retries most of these errors, but some custom retry + // policies could decide otherwise. So we apply the same logic as above: if the error is a + // replica availability error, we authorize the failover. + + Node coordinator = ((CoordinatorException) mainException).getCoordinator(); + System.out.printf( + "Node %s in DC %s was tried once but failed with: %s%n", + coordinator.getEndPoint(), coordinator.getDatacenter(), mainException); + + boolean failover = isReplicaAvailabilityError(mainException); + if (failover) { + System.out.println( + "The only node tried in this DC reported a replica availability error, failing over"); + } else { + System.out.println("The only node tried in this DC failed unexpectedly, not failing over"); + } + return failover; + + } else { + + // The request failed with a rather unusual error. This generally indicates a more serious + // issue, since the retry policy decided to surface the error immediately. Trying another DC + // is probably a bad idea. + System.out.println("The request failed unexpectedly, not failing over: " + mainException); + return false; + } + } + + /** + * Whether the given error is a replica availability error. + * + *

    A replica availability error means that the initial consistency level could not be met + * because not enough replicas were alive. + * + *

    When this error happens, it can be worth failing over to a remote DC, as long as at + * least one of the following conditions apply: + * + *

      + *
    1. if the initial consistency level was DC-local, trying another DC may succeed; + *
    2. if the initial consistency level can be downgraded, then retrying again may succeed (in + * the same DC, or in another one). + *
    + * + * In this example both conditions above apply, so we authorize the failover whenever we detect a + * replica availability error. + */ + private boolean isReplicaAvailabilityError(Throwable t) { + return t instanceof UnavailableException || t instanceof QueryConsistencyException; + } + + private void close() { + if (session != null) { + session.close(); + } + } +} diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/json/PlainTextJson.java b/examples/src/main/java/com/datastax/oss/driver/examples/json/PlainTextJson.java index 3d2982f0429..6bb2f8a9fdd 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/json/PlainTextJson.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/json/PlainTextJson.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/json/jackson/JacksonJsonColumn.java b/examples/src/main/java/com/datastax/oss/driver/examples/json/jackson/JacksonJsonColumn.java index 427059b6b68..0d1ed61d2f4 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/json/jackson/JacksonJsonColumn.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/json/jackson/JacksonJsonColumn.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/json/jackson/JacksonJsonFunction.java b/examples/src/main/java/com/datastax/oss/driver/examples/json/jackson/JacksonJsonFunction.java index 1cd94cc19d1..b3c2c6aaa95 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/json/jackson/JacksonJsonFunction.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/json/jackson/JacksonJsonFunction.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/json/jackson/JacksonJsonRow.java b/examples/src/main/java/com/datastax/oss/driver/examples/json/jackson/JacksonJsonRow.java index 2063e91c07b..1a5fed0bbf3 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/json/jackson/JacksonJsonRow.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/json/jackson/JacksonJsonRow.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/json/jsr/Jsr353JsonCodec.java b/examples/src/main/java/com/datastax/oss/driver/examples/json/jsr/Jsr353JsonCodec.java index 87e408f13cc..9b30d5d6c6b 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/json/jsr/Jsr353JsonCodec.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/json/jsr/Jsr353JsonCodec.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/json/jsr/Jsr353JsonColumn.java b/examples/src/main/java/com/datastax/oss/driver/examples/json/jsr/Jsr353JsonColumn.java index 0902f160169..9ded61f82e3 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/json/jsr/Jsr353JsonColumn.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/json/jsr/Jsr353JsonColumn.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/json/jsr/Jsr353JsonFunction.java b/examples/src/main/java/com/datastax/oss/driver/examples/json/jsr/Jsr353JsonFunction.java index 073035f6580..25b243eeb5d 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/json/jsr/Jsr353JsonFunction.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/json/jsr/Jsr353JsonFunction.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/json/jsr/Jsr353JsonRow.java b/examples/src/main/java/com/datastax/oss/driver/examples/json/jsr/Jsr353JsonRow.java index 70df8b8d5d0..595522fa964 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/json/jsr/Jsr353JsonRow.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/json/jsr/Jsr353JsonRow.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/mapper/KillrVideoMapperExample.java b/examples/src/main/java/com/datastax/oss/driver/examples/mapper/KillrVideoMapperExample.java index 4c845ba89e9..6284b16eac1 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/mapper/KillrVideoMapperExample.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/mapper/KillrVideoMapperExample.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -19,6 +21,7 @@ import com.datastax.oss.driver.api.core.CqlSession; import com.datastax.oss.driver.api.core.PagingIterable; import com.datastax.oss.driver.api.core.cql.SimpleStatement; +import com.datastax.oss.driver.api.core.uuid.Uuids; import com.datastax.oss.driver.examples.mapper.killrvideo.KillrVideoMapper; import com.datastax.oss.driver.examples.mapper.killrvideo.user.User; import com.datastax.oss.driver.examples.mapper.killrvideo.user.UserDao; @@ -39,7 +42,6 @@ import java.util.List; import java.util.Optional; import java.util.Set; -import java.util.UUID; import java.util.stream.Collectors; /** @@ -87,8 +89,7 @@ public static void main(String[] args) { // Create a new user UserDao userDao = mapper.userDao(); - User user = - new User(UUID.randomUUID(), "test", "user", "testuser@example.com", Instant.now()); + User user = new User(Uuids.random(), "test", "user", "testuser@example.com", Instant.now()); if (userDao.create(user, "fakePasswordForTests".toCharArray())) { System.out.println("Created " + user); @@ -99,7 +100,7 @@ public static void main(String[] args) { // Creating another user with the same email should fail assert !userDao.create( - new User(UUID.randomUUID(), "test2", "user", "testuser@example.com", Instant.now()), + new User(Uuids.random(), "test2", "user", "testuser@example.com", Instant.now()), "fakePasswordForTests2".toCharArray()); // Simulate login attempts @@ -112,7 +113,7 @@ public static void main(String[] args) { Video video = new Video(); video.setUserid(user.getUserid()); video.setName( - "Getting Started with DataStax Apache Cassandra as a Service on DataStax Constellation"); + "Getting Started with DataStax Apache Cassandra as a Service on DataStax Astra"); video.setLocation("https://www.youtube.com/watch?v=68xzKpcZURA"); Set tags = new HashSet<>(); tags.add("apachecassandra"); @@ -146,7 +147,7 @@ public static void main(String[] args) { Video template = new Video(); template.setVideoid(video.getVideoid()); template.setName( - "Getting Started with DataStax Apache Cassandra® as a Service on DataStax Constellation"); + "Getting Started with DataStax Apache Cassandra® as a Service on DataStax Astra"); videoDao.update(template); // Reload the whole entity and check the fields video = videoDao.get(video.getVideoid()); diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/KillrVideoMapper.java b/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/KillrVideoMapper.java index 81bbd0a1106..c28130481b4 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/KillrVideoMapper.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/KillrVideoMapper.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/user/CreateUserQueryProvider.java b/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/user/CreateUserQueryProvider.java index dd70ce39f95..baaeb13b67b 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/user/CreateUserQueryProvider.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/user/CreateUserQueryProvider.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -116,14 +118,14 @@ private boolean insertCredentialsIfNotExists(String email, char[] password, UUID UserCredentials credentials = new UserCredentials(Objects.requireNonNull(email), passwordHash, userId); BoundStatementBuilder insertCredentials = preparedInsertCredentials.boundStatementBuilder(); - credentialsHelper.set(credentials, insertCredentials, NullSavingStrategy.DO_NOT_SET); + credentialsHelper.set(credentials, insertCredentials, NullSavingStrategy.DO_NOT_SET, false); ResultSet resultSet = session.execute(insertCredentials.build()); return resultSet.wasApplied(); } private void insertUser(User user) { BoundStatementBuilder insertUser = preparedInsertUser.boundStatementBuilder(); - userHelper.set(user, insertUser, NullSavingStrategy.DO_NOT_SET); + userHelper.set(user, insertUser, NullSavingStrategy.DO_NOT_SET, false); session.execute(insertUser.build()); } } diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/user/LoginQueryProvider.java b/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/user/LoginQueryProvider.java index 7b968a65bc2..6d88423f046 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/user/LoginQueryProvider.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/user/LoginQueryProvider.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -62,7 +64,7 @@ Optional login(String email, char[] password) { throw new IllegalStateException( "Should have found matching row for userid " + userid); } else { - return Optional.of(userHelper.get(userRow)); + return Optional.of(userHelper.get(userRow, false)); } } else { return Optional.empty(); diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/user/PasswordHashing.java b/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/user/PasswordHashing.java index e20a628f594..def919bc1f8 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/user/PasswordHashing.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/user/PasswordHashing.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/user/User.java b/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/user/User.java index 3f1a53e00c2..f00b142dc7a 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/user/User.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/user/User.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/user/UserCredentials.java b/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/user/UserCredentials.java index d6ed8b4a4ab..0b6b32219ce 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/user/UserCredentials.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/user/UserCredentials.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/user/UserDao.java b/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/user/UserDao.java index f4aadc45a06..19f7f7cad0e 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/user/UserDao.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/user/UserDao.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/video/CreateVideoQueryProvider.java b/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/video/CreateVideoQueryProvider.java index 85704290903..132baa474d4 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/video/CreateVideoQueryProvider.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/video/CreateVideoQueryProvider.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -22,13 +24,13 @@ import com.datastax.oss.driver.api.core.cql.BoundStatementBuilder; import com.datastax.oss.driver.api.core.cql.DefaultBatchType; import com.datastax.oss.driver.api.core.cql.PreparedStatement; +import com.datastax.oss.driver.api.core.uuid.Uuids; import com.datastax.oss.driver.api.mapper.MapperContext; import com.datastax.oss.driver.api.mapper.entity.EntityHelper; import com.datastax.oss.driver.api.mapper.entity.saving.NullSavingStrategy; import java.time.Instant; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; -import java.util.UUID; /** * Provides the implementation of {@link VideoDao#create}. @@ -68,7 +70,7 @@ class CreateVideoQueryProvider { void create(Video video) { if (video.getVideoid() == null) { - video.setVideoid(UUID.randomUUID()); + video.setVideoid(Uuids.random()); } if (video.getAddedDate() == null) { video.setAddedDate(Instant.now()); @@ -95,7 +97,7 @@ private static PreparedStatement prepareInsert( private static BoundStatement bind( PreparedStatement preparedStatement, T entity, EntityHelper entityHelper) { BoundStatementBuilder boundStatement = preparedStatement.boundStatementBuilder(); - entityHelper.set(entity, boundStatement, NullSavingStrategy.DO_NOT_SET); + entityHelper.set(entity, boundStatement, NullSavingStrategy.DO_NOT_SET, false); return boundStatement.build(); } diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/video/LatestVideo.java b/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/video/LatestVideo.java index 5ced7dfe20b..f30684aa622 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/video/LatestVideo.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/video/LatestVideo.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/video/UserVideo.java b/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/video/UserVideo.java index 468a97e32c1..933d96872f6 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/video/UserVideo.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/video/UserVideo.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/video/Video.java b/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/video/Video.java index 406d13e1411..307f2cc19b1 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/video/Video.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/video/Video.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/video/VideoBase.java b/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/video/VideoBase.java index 7c397f32987..0c315c59bce 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/video/VideoBase.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/video/VideoBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/video/VideoByTag.java b/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/video/VideoByTag.java index d981efa2056..c1855269afe 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/video/VideoByTag.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/video/VideoByTag.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/video/VideoDao.java b/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/video/VideoDao.java index 55b44a37062..ca5798f77d4 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/video/VideoDao.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/mapper/killrvideo/video/VideoDao.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/paging/ForwardPagingRestUi.java b/examples/src/main/java/com/datastax/oss/driver/examples/paging/ForwardPagingRestUi.java index c59d22815c1..a512457d618 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/paging/ForwardPagingRestUi.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/paging/ForwardPagingRestUi.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/paging/RandomPagingRestUi.java b/examples/src/main/java/com/datastax/oss/driver/examples/paging/RandomPagingRestUi.java index 70cd27f500f..7eb3249b0ac 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/paging/RandomPagingRestUi.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/paging/RandomPagingRestUi.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/examples/src/main/java/com/datastax/oss/driver/examples/retry/DowngradingRetry.java b/examples/src/main/java/com/datastax/oss/driver/examples/retry/DowngradingRetry.java index c83e2ef2296..0577432600b 100644 --- a/examples/src/main/java/com/datastax/oss/driver/examples/retry/DowngradingRetry.java +++ b/examples/src/main/java/com/datastax/oss/driver/examples/retry/DowngradingRetry.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -39,9 +41,15 @@ /** * This example illustrates how to implement a downgrading retry strategy from application code. * - *

    This was provided as a built-in policy in driver 3 ({@code - * DowngradingConsistencyRetryPolicy}), but has been removed from driver 4. See the FAQ. + *

    This strategy is equivalent to the logic implemented by the consistency downgrading retry + * policy, but we think that such a logic should be implemented at application level whenever + * possible. + * + *

    See the FAQ + * and the manual + * section on retries. * *

    Preconditions: * @@ -71,7 +79,7 @@ * idempotence for more information. * * - * @see Java driver online + * @see Java Driver online * manual */ public class DowngradingRetry { diff --git a/examples/src/main/resources/application.conf b/examples/src/main/resources/application.conf index 12cb19a84d0..170c08d973a 100644 --- a/examples/src/main/resources/application.conf +++ b/examples/src/main/resources/application.conf @@ -1,3 +1,20 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + datastax-java-driver { basic.contact-points = ["127.0.0.1:9042"] basic { @@ -19,4 +36,4 @@ datastax-java-driver { basic.request.timeout = 10 seconds } } -} \ No newline at end of file +} diff --git a/examples/src/main/resources/killrvideo_schema.cql b/examples/src/main/resources/killrvideo_schema.cql index 24728d550d0..0c604ba5922 100644 --- a/examples/src/main/resources/killrvideo_schema.cql +++ b/examples/src/main/resources/killrvideo_schema.cql @@ -1,3 +1,22 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + // User credentials, keyed by email address so we can authenticate CREATE TABLE IF NOT EXISTS user_credentials ( email text, diff --git a/examples/src/main/resources/logback.xml b/examples/src/main/resources/logback.xml index d8084383a99..061ccccad37 100644 --- a/examples/src/main/resources/logback.xml +++ b/examples/src/main/resources/logback.xml @@ -1,13 +1,15 @@ + ## Frequently asked questions ### I'm modifying a statement and the changes get ignored, why? @@ -43,24 +62,47 @@ use a fully asynchronous programming model (chaining callbacks instead of blocki At any rate, `CompletionStage` has a `toCompletableFuture()` method. In current JDK versions, every `CompletionStage` is a `CompletableFuture`, so the conversion has no performance overhead. -### Where is `DowngradingConsistencyRetryPolicy`? +### Where is `DowngradingConsistencyRetryPolicy` from driver 3? + +**As of driver 4.10, this retry policy was made available again as a built-in alternative to the +default retry policy**: see the [manual](../manual/core/retries) to understand how to use it. +For versions between 4.0 and 4.9 inclusive, there is no built-in equivalent of driver 3 +`DowngradingConsistencyRetryPolicy`. + +That retry policy was indeed removed in driver 4.0.0. The main motivation is that this behavior +should be the application's concern, not the driver's. APIs provided by the driver should instead +encourage idiomatic use of a distributed system like Apache Cassandra, and a downgrading policy +works against this. It suggests that an anti-pattern such as "try to read at QUORUM, but fall back +to ONE if that fails" is a good idea in general use cases, when in reality it provides no better +consistency guarantees than working directly at ONE, but with higher latencies. + +However, we recognize that there are use cases where downgrading is good -- for instance, a +dashboard application would present the latest information by reading at QUORUM, but it's acceptable +for it to display stale information by reading at ONE sometimes. + +Thanks to [JAVA-2900], an equivalent retry policy with downgrading behavior was re-introduced in +driver 4.10. Nonetheless, we urge users to avoid using it unless strictly required, and instead, +carefully choose upfront the consistency level that works best for their use cases. Even if there +is a legitimate reason to downgrade and retry, that should be preferably handled by the application +code. An example of downgrading retries implemented at application level can be found in the driver +[examples repository]. + +[JAVA-2900]: https://datastax-oss.atlassian.net/browse/JAVA-2900 +[examples repository]: https://github.com/datastax/java-driver/blob/4.x/examples/src/main/java/com/datastax/oss/driver/examples/retry/DowngradingRetry.java + +### Where is the cross-datacenter failover feature that existed in driver 3? -That retry policy was deprecated in driver 3.5.0, and does not exist anymore in 4.0.0. The main -motivation is that this behavior should be the application's concern, not the driver's. +In driver 3, it was possible to configure the load balancing policy to automatically failover to +a remote datacenter, when the local datacenter is down. -We recognize that there are use cases where downgrading is good -- for instance, a dashboard -application would present the latest information by reading at QUORUM, but it's acceptable for it to -display stale information by reading at ONE sometimes. +This ability is considered a misfeature and has been removed from driver 4.0 onwards. -But APIs provided by the driver should instead encourage idiomatic use of a distributed system like -Apache Cassandra, and a downgrading policy works against this. It suggests that an anti-pattern such -as "try to read at QUORUM, but fall back to ONE if that fails" is a good idea in general use cases, -when in reality it provides no better consistency guarantees than working directly at ONE, but with -higher latencies. +However, due to popular demand, cross-datacenter failover has been brought back to driver 4 in +version 4.10.0. -We therefore urge users to carefully choose upfront the consistency level that works best for their -use cases. If there is a legitimate reason to downgrade and retry, that should be handled by the -application code. +If you are using a driver version >= 4.10.0, read the [manual](../manual/core/loadbalancing/) to +understand how to enable this feature; for driver versions < 4.10.0, this feature is simply not +available. ### I want to set a date on a bound statement, where did `setTimestamp()` go? diff --git a/guava-shaded/pom.xml b/guava-shaded/pom.xml new file mode 100644 index 00000000000..da2e82e0ab0 --- /dev/null +++ b/guava-shaded/pom.xml @@ -0,0 +1,242 @@ + + + + 4.0.0 + + org.apache.cassandra + java-driver-parent + 4.19.3-SNAPSHOT + + java-driver-guava-shaded + Apache Cassandra Java Driver - guava shaded dep + Shaded Guava artifact for use in the Java driver for Apache Cassandra® + + + com.google.guava + guava + + + com.google.code.findbugs + jsr305 + + + org.checkerframework + checker-qual + + + com.google.errorprone + error_prone_annotations + + + true + + + org.graalvm.nativeimage + svm + 20.0.0 + provided + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.12 + + + regex-property + + regex-property + + + maven.main.skip + ${java.version} + ^(?!1.8).+ + true + false + + + + + + maven-shade-plugin + + + shade-guava-dependency + package + + shade + + + + + org.apache.cassandra:java-driver-guava-shaded + com.google.guava:guava + com.google.guava:failureaccess + com.google.j2objc:j2objc-annotations + + + + + com.google + com.datastax.oss.driver.shaded.guava + + + + + com.google.guava:* + + META-INF/** + + + + true + true + + + + + + + maven-clean-plugin + + + clean-classes + package + + clean + + + ${project.build.outputDirectory} + + + + + + maven-dependency-plugin + + + unpack-shaded-classes + package + + unpack + + + ${project.build.outputDirectory} + + + org.apache.cassandra + java-driver-guava-shaded + ${project.version} + jar + + + + + + + + org.apache.felix + maven-bundle-plugin + + 3.5.0 + true + + + generate-shaded-manifest + package + + manifest + + + + com.datastax.oss.driver.shaded.guava + !com.datastax.oss.driver.shaded.guava.errorprone.*, !org.checkerframework.*, * + javax.annotation.*;resolution:=optional;version="[3.0,4)", javax.crypto.*;resolution:=optional, sun.misc.*;resolution:=optional, !com.oracle.svm.*, !com.datastax.oss.driver.shaded.guava.errorprone.*, !org.checkerframework.*, * + + + + + + + maven-assembly-plugin + + + generate-final-shaded-jar + package + + single + + + + + ${project.build.outputDirectory}/META-INF/MANIFEST.MF + + + src/assembly/shaded-jar.xml + + + false + + + + + + maven-jar-plugin + + + empty-javadoc-jar + + jar + + + javadoc + ${basedir}/src/main/javadoc + + + + + + org.revapi + revapi-maven-plugin + + true + + + + + diff --git a/guava-shaded/src/assembly/shaded-jar.xml b/guava-shaded/src/assembly/shaded-jar.xml new file mode 100644 index 00000000000..d762a27b20f --- /dev/null +++ b/guava-shaded/src/assembly/shaded-jar.xml @@ -0,0 +1,48 @@ + + + + shaded-jar + + jar + + false + + + + ${project.build.outputDirectory} + + META-INF/maven/org.apache.cassandra/java-driver-guava-shaded/pom.xml + + + + + + + + ${project.basedir}/dependency-reduced-pom.xml + META-INF/maven/org.apache.cassandra/java-driver-guava-shaded + pom.xml + + + diff --git a/guava-shaded/src/main/java/com/google/common/primitives/LexicographicalComparatorHolderSubstitution.java b/guava-shaded/src/main/java/com/google/common/primitives/LexicographicalComparatorHolderSubstitution.java new file mode 100644 index 00000000000..95e9c70cdbc --- /dev/null +++ b/guava-shaded/src/main/java/com/google/common/primitives/LexicographicalComparatorHolderSubstitution.java @@ -0,0 +1,39 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.common.primitives; + +import com.oracle.svm.core.annotate.Alias; +import com.oracle.svm.core.annotate.RecomputeFieldValue; +import com.oracle.svm.core.annotate.Substitute; +import com.oracle.svm.core.annotate.TargetClass; +import java.util.Comparator; + +@TargetClass(UnsignedBytes.LexicographicalComparatorHolder.class) +final class LexicographicalComparatorHolderSubstitution { + + @Alias + @RecomputeFieldValue(kind = RecomputeFieldValue.Kind.FromAlias) + static Comparator BEST_COMPARATOR = UnsignedBytes.lexicographicalComparatorJavaImpl(); + + /* All known cases should be covered by the field substitution above... keeping this only + * for sake of completeness */ + @Substitute + static Comparator getBestComparator() { + return UnsignedBytes.lexicographicalComparatorJavaImpl(); + } +} diff --git a/guava-shaded/src/main/java/com/google/common/primitives/UnsafeComparatorSubstitution.java b/guava-shaded/src/main/java/com/google/common/primitives/UnsafeComparatorSubstitution.java new file mode 100644 index 00000000000..549de0b5c02 --- /dev/null +++ b/guava-shaded/src/main/java/com/google/common/primitives/UnsafeComparatorSubstitution.java @@ -0,0 +1,25 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.common.primitives; + +import com.oracle.svm.core.annotate.Delete; +import com.oracle.svm.core.annotate.TargetClass; + +@TargetClass(UnsignedBytes.LexicographicalComparatorHolder.UnsafeComparator.class) +@Delete +final class UnsafeComparatorSubstitution {} diff --git a/guava-shaded/src/main/javadoc/README.txt b/guava-shaded/src/main/javadoc/README.txt new file mode 100644 index 00000000000..57f82b2a265 --- /dev/null +++ b/guava-shaded/src/main/javadoc/README.txt @@ -0,0 +1,2 @@ +This empty JAR is generated for compliance with Maven Central rules. Please refer to the original +Guava API docs. \ No newline at end of file diff --git a/install-snapshots.sh b/install-snapshots.sh index 4f5d79665ab..795b4098f52 100755 --- a/install-snapshots.sh +++ b/install-snapshots.sh @@ -1,4 +1,20 @@ #!/bin/sh +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. # Install dependencies in the Travis build environment if they are snapshots. # See .travis.yml diff --git a/integration-tests/pom.xml b/integration-tests/pom.xml index d9daac364a4..e302e12077f 100644 --- a/integration-tests/pom.xml +++ b/integration-tests/pom.xml @@ -1,13 +1,15 @@ - + diff --git a/licenses/HdrHistogram.txt b/licenses/HdrHistogram.txt new file mode 100644 index 00000000000..401ccfb0ec5 --- /dev/null +++ b/licenses/HdrHistogram.txt @@ -0,0 +1,41 @@ +The code in this repository code was Written by Gil Tene, Michael Barker, +and Matt Warren, and released to the public domain, as explained at +http://creativecommons.org/publicdomain/zero/1.0/ + +For users of this code who wish to consume it under the "BSD" license +rather than under the public domain or CC0 contribution text mentioned +above, the code found under this directory is *also* provided under the +following license (commonly referred to as the BSD 2-Clause License). This +license does not detract from the above stated release of the code into +the public domain, and simply represents an additional license granted by +the Author. + +----------------------------------------------------------------------------- +** Beginning of "BSD 2-Clause License" text. ** + + Copyright (c) 2012, 2013, 2014, 2015, 2016 Gil Tene + Copyright (c) 2014 Michael Barker + Copyright (c) 2014 Matt Warren + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + THE POSSIBILITY OF SUCH DAMAGE. diff --git a/licenses/asm.txt b/licenses/asm.txt new file mode 100644 index 00000000000..c71bb7bac5d --- /dev/null +++ b/licenses/asm.txt @@ -0,0 +1,27 @@ +ASM: a very small and fast Java bytecode manipulation framework +Copyright (c) 2000-2011 INRIA, France Telecom +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the copyright holders nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +THE POSSIBILITY OF SUCH DAMAGE. diff --git a/licenses/jnr-posix.txt b/licenses/jnr-posix.txt new file mode 100644 index 00000000000..4dc4217a306 --- /dev/null +++ b/licenses/jnr-posix.txt @@ -0,0 +1,1076 @@ +jnr-posix is released under a tri EPL/GPL/LGPL license. You can use it, +redistribute it and/or modify it under the terms of the: + + Eclipse Public License version 2.0 + OR + GNU General Public License version 2 + OR + GNU Lesser General Public License version 2.1 + +The complete text of the Eclipse Public License is as follows: + + Eclipse Public License - v 2.0 + + THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE + PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION + OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. + + 1. DEFINITIONS + + "Contribution" means: + + a) in the case of the initial Contributor, the initial content + Distributed under this Agreement, and + + b) in the case of each subsequent Contributor: + i) changes to the Program, and + ii) additions to the Program; + where such changes and/or additions to the Program originate from + and are Distributed by that particular Contributor. A Contribution + "originates" from a Contributor if it was added to the Program by + such Contributor itself or anyone acting on such Contributor's behalf. + Contributions do not include changes or additions to the Program that + are not Modified Works. + + "Contributor" means any person or entity that Distributes the Program. + + "Licensed Patents" mean patent claims licensable by a Contributor which + are necessarily infringed by the use or sale of its Contribution alone + or when combined with the Program. + + "Program" means the Contributions Distributed in accordance with this + Agreement. + + "Recipient" means anyone who receives the Program under this Agreement + or any Secondary License (as applicable), including Contributors. + + "Derivative Works" shall mean any work, whether in Source Code or other + form, that is based on (or derived from) the Program and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. + + "Modified Works" shall mean any work in Source Code or other form that + results from an addition to, deletion from, or modification of the + contents of the Program, including, for purposes of clarity any new file + in Source Code form that contains any contents of the Program. Modified + Works shall not include works that contain only declarations, + interfaces, types, classes, structures, or files of the Program solely + in each case in order to link to, bind by name, or subclass the Program + or Modified Works thereof. + + "Distribute" means the acts of a) distributing or b) making available + in any manner that enables the transfer of a copy. + + "Source Code" means the form of a Program preferred for making + modifications, including but not limited to software source code, + documentation source, and configuration files. + + "Secondary License" means either the GNU General Public License, + Version 2.0, or any later versions of that license, including any + exceptions or additional permissions as identified by the initial + Contributor. + + 2. GRANT OF RIGHTS + + a) Subject to the terms of this Agreement, each Contributor hereby + grants Recipient a non-exclusive, worldwide, royalty-free copyright + license to reproduce, prepare Derivative Works of, publicly display, + publicly perform, Distribute and sublicense the Contribution of such + Contributor, if any, and such Derivative Works. + + b) Subject to the terms of this Agreement, each Contributor hereby + grants Recipient a non-exclusive, worldwide, royalty-free patent + license under Licensed Patents to make, use, sell, offer to sell, + import and otherwise transfer the Contribution of such Contributor, + if any, in Source Code or other form. This patent license shall + apply to the combination of the Contribution and the Program if, at + the time the Contribution is added by the Contributor, such addition + of the Contribution causes such combination to be covered by the + Licensed Patents. The patent license shall not apply to any other + combinations which include the Contribution. No hardware per se is + licensed hereunder. + + c) Recipient understands that although each Contributor grants the + licenses to its Contributions set forth herein, no assurances are + provided by any Contributor that the Program does not infringe the + patent or other intellectual property rights of any other entity. + Each Contributor disclaims any liability to Recipient for claims + brought by any other entity based on infringement of intellectual + property rights or otherwise. As a condition to exercising the + rights and licenses granted hereunder, each Recipient hereby + assumes sole responsibility to secure any other intellectual + property rights needed, if any. For example, if a third party + patent license is required to allow Recipient to Distribute the + Program, it is Recipient's responsibility to acquire that license + before distributing the Program. + + d) Each Contributor represents that to its knowledge it has + sufficient copyright rights in its Contribution, if any, to grant + the copyright license set forth in this Agreement. + + e) Notwithstanding the terms of any Secondary License, no + Contributor makes additional grants to any Recipient (other than + those set forth in this Agreement) as a result of such Recipient's + receipt of the Program under the terms of a Secondary License + (if permitted under the terms of Section 3). + + 3. REQUIREMENTS + + 3.1 If a Contributor Distributes the Program in any form, then: + + a) the Program must also be made available as Source Code, in + accordance with section 3.2, and the Contributor must accompany + the Program with a statement that the Source Code for the Program + is available under this Agreement, and informs Recipients how to + obtain it in a reasonable manner on or through a medium customarily + used for software exchange; and + + b) the Contributor may Distribute the Program under a license + different than this Agreement, provided that such license: + i) effectively disclaims on behalf of all other Contributors all + warranties and conditions, express and implied, including + warranties or conditions of title and non-infringement, and + implied warranties or conditions of merchantability and fitness + for a particular purpose; + + ii) effectively excludes on behalf of all other Contributors all + liability for damages, including direct, indirect, special, + incidental and consequential damages, such as lost profits; + + iii) does not attempt to limit or alter the recipients' rights + in the Source Code under section 3.2; and + + iv) requires any subsequent distribution of the Program by any + party to be under a license that satisfies the requirements + of this section 3. + + 3.2 When the Program is Distributed as Source Code: + + a) it must be made available under this Agreement, or if the + Program (i) is combined with other material in a separate file or + files made available under a Secondary License, and (ii) the initial + Contributor attached to the Source Code the notice described in + Exhibit A of this Agreement, then the Program may be made available + under the terms of such Secondary Licenses, and + + b) a copy of this Agreement must be included with each copy of + the Program. + + 3.3 Contributors may not remove or alter any copyright, patent, + trademark, attribution notices, disclaimers of warranty, or limitations + of liability ("notices") contained within the Program from any copy of + the Program which they Distribute, provided that Contributors may add + their own appropriate notices. + + 4. COMMERCIAL DISTRIBUTION + + Commercial distributors of software may accept certain responsibilities + with respect to end users, business partners and the like. While this + license is intended to facilitate the commercial use of the Program, + the Contributor who includes the Program in a commercial product + offering should do so in a manner which does not create potential + liability for other Contributors. Therefore, if a Contributor includes + the Program in a commercial product offering, such Contributor + ("Commercial Contributor") hereby agrees to defend and indemnify every + other Contributor ("Indemnified Contributor") against any losses, + damages and costs (collectively "Losses") arising from claims, lawsuits + and other legal actions brought by a third party against the Indemnified + Contributor to the extent caused by the acts or omissions of such + Commercial Contributor in connection with its distribution of the Program + in a commercial product offering. The obligations in this section do not + apply to any claims or Losses relating to any actual or alleged + intellectual property infringement. In order to qualify, an Indemnified + Contributor must: a) promptly notify the Commercial Contributor in + writing of such claim, and b) allow the Commercial Contributor to control, + and cooperate with the Commercial Contributor in, the defense and any + related settlement negotiations. The Indemnified Contributor may + participate in any such claim at its own expense. + + For example, a Contributor might include the Program in a commercial + product offering, Product X. That Contributor is then a Commercial + Contributor. If that Commercial Contributor then makes performance + claims, or offers warranties related to Product X, those performance + claims and warranties are such Commercial Contributor's responsibility + alone. Under this section, the Commercial Contributor would have to + defend claims against the other Contributors related to those performance + claims and warranties, and if a court requires any other Contributor to + pay any damages as a result, the Commercial Contributor must pay + those damages. + + 5. NO WARRANTY + + EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT + PERMITTED BY APPLICABLE LAW, THE PROGRAM IS PROVIDED ON AN "AS IS" + BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR + IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF + TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR + PURPOSE. Each Recipient is solely responsible for determining the + appropriateness of using and distributing the Program and assumes all + risks associated with its exercise of rights under this Agreement, + including but not limited to the risks and costs of program errors, + compliance with applicable laws, damage to or loss of data, programs + or equipment, and unavailability or interruption of operations. + + 6. DISCLAIMER OF LIABILITY + + EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT + PERMITTED BY APPLICABLE LAW, NEITHER RECIPIENT NOR ANY CONTRIBUTORS + SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST + PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE + EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGES. + + 7. GENERAL + + If any provision of this Agreement is invalid or unenforceable under + applicable law, it shall not affect the validity or enforceability of + the remainder of the terms of this Agreement, and without further + action by the parties hereto, such provision shall be reformed to the + minimum extent necessary to make such provision valid and enforceable. + + If Recipient institutes patent litigation against any entity + (including a cross-claim or counterclaim in a lawsuit) alleging that the + Program itself (excluding combinations of the Program with other software + or hardware) infringes such Recipient's patent(s), then such Recipient's + rights granted under Section 2(b) shall terminate as of the date such + litigation is filed. + + All Recipient's rights under this Agreement shall terminate if it + fails to comply with any of the material terms or conditions of this + Agreement and does not cure such failure in a reasonable period of + time after becoming aware of such noncompliance. If all Recipient's + rights under this Agreement terminate, Recipient agrees to cease use + and distribution of the Program as soon as reasonably practicable. + However, Recipient's obligations under this Agreement and any licenses + granted by Recipient relating to the Program shall continue and survive. + + Everyone is permitted to copy and distribute copies of this Agreement, + but in order to avoid inconsistency the Agreement is copyrighted and + may only be modified in the following manner. The Agreement Steward + reserves the right to publish new versions (including revisions) of + this Agreement from time to time. No one other than the Agreement + Steward has the right to modify this Agreement. The Eclipse Foundation + is the initial Agreement Steward. The Eclipse Foundation may assign the + responsibility to serve as the Agreement Steward to a suitable separate + entity. Each new version of the Agreement will be given a distinguishing + version number. The Program (including Contributions) may always be + Distributed subject to the version of the Agreement under which it was + received. In addition, after a new version of the Agreement is published, + Contributor may elect to Distribute the Program (including its + Contributions) under the new version. + + Except as expressly stated in Sections 2(a) and 2(b) above, Recipient + receives no rights or licenses to the intellectual property of any + Contributor under this Agreement, whether expressly, by implication, + estoppel or otherwise. All rights in the Program not expressly granted + under this Agreement are reserved. Nothing in this Agreement is intended + to be enforceable by any entity that is not a Contributor or Recipient. + No third-party beneficiary rights are created under this Agreement. + + Exhibit A - Form of Secondary Licenses Notice + + "This Source Code may also be made available under the following + Secondary Licenses when the conditions for such availability set forth + in the Eclipse Public License, v. 2.0 are satisfied: {name license(s), + version(s), and exceptions or additional permissions here}." + + Simply including a copy of this Agreement, including this Exhibit A + is not sufficient to license the Source Code under Secondary Licenses. + + If it is not possible or desirable to put the notice in a particular + file, then You may include the notice in a location (such as a LICENSE + file in a relevant directory) where a recipient would be likely to + look for such a notice. + + You may add additional accurate notices of copyright ownership. + +The complete text of the GNU General Public License v2 is as follows: + + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your + freedom to share and change it. By contrast, the GNU General Public + License is intended to guarantee your freedom to share and change free + software--to make sure the software is free for all its users. This + General Public License applies to most of the Free Software + Foundation's software and to any other program whose authors commit to + using it. (Some other Free Software Foundation software is covered by + the GNU Library General Public License instead.) You can apply it to + your programs, too. + + When we speak of free software, we are referring to freedom, not + price. Our General Public Licenses are designed to make sure that you + have the freedom to distribute copies of free software (and charge for + this service if you wish), that you receive source code or can get it + if you want it, that you can change the software or use pieces of it + in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid + anyone to deny you these rights or to ask you to surrender the rights. + These restrictions translate to certain responsibilities for you if you + distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether + gratis or for a fee, you must give the recipients all the rights that + you have. You must make sure that they, too, receive or can get the + source code. And you must show them these terms so they know their + rights. + + We protect your rights with two steps: (1) copyright the software, and + (2) offer you this license which gives you legal permission to copy, + distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain + that everyone understands that there is no warranty for this free + software. If the software is modified by someone else and passed on, we + want its recipients to know that what they have is not the original, so + that any problems introduced by others will not reflect on the original + authors' reputations. + + Finally, any free program is threatened constantly by software + patents. We wish to avoid the danger that redistributors of a free + program will individually obtain patent licenses, in effect making the + program proprietary. To prevent this, we have made it clear that any + patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and + modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains + a notice placed by the copyright holder saying it may be distributed + under the terms of this General Public License. The "Program", below, + refers to any such program or work, and a "work based on the Program" + means either the Program or any derivative work under copyright law: + that is to say, a work containing the Program or a portion of it, + either verbatim or with modifications and/or translated into another + language. (Hereinafter, translation is included without limitation in + the term "modification".) Each licensee is addressed as "you". + + Activities other than copying, distribution and modification are not + covered by this License; they are outside its scope. The act of + running the Program is not restricted, and the output from the Program + is covered only if its contents constitute a work based on the + Program (independent of having been made by running the Program). + Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's + source code as you receive it, in any medium, provided that you + conspicuously and appropriately publish on each copy an appropriate + copyright notice and disclaimer of warranty; keep intact all the + notices that refer to this License and to the absence of any warranty; + and give any other recipients of the Program a copy of this License + along with the Program. + + You may charge a fee for the physical act of transferring a copy, and + you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion + of it, thus forming a work based on the Program, and copy and + distribute such modifications or work under the terms of Section 1 + above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + + These requirements apply to the modified work as a whole. If + identifiable sections of that work are not derived from the Program, + and can be reasonably considered independent and separate works in + themselves, then this License, and its terms, do not apply to those + sections when you distribute them as separate works. But when you + distribute the same sections as part of a whole which is a work based + on the Program, the distribution of the whole must be on the terms of + this License, whose permissions for other licensees extend to the + entire whole, and thus to each and every part regardless of who wrote it. + + Thus, it is not the intent of this section to claim rights or contest + your rights to work written entirely by you; rather, the intent is to + exercise the right to control the distribution of derivative or + collective works based on the Program. + + In addition, mere aggregation of another work not based on the Program + with the Program (or with a work based on the Program) on a volume of + a storage or distribution medium does not bring the other work under + the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, + under Section 2) in object code or executable form under the terms of + Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + + The source code for a work means the preferred form of the work for + making modifications to it. For an executable work, complete source + code means all the source code for all modules it contains, plus any + associated interface definition files, plus the scripts used to + control compilation and installation of the executable. However, as a + special exception, the source code distributed need not include + anything that is normally distributed (in either source or binary + form) with the major components (compiler, kernel, and so on) of the + operating system on which the executable runs, unless that component + itself accompanies the executable. + + If distribution of executable or object code is made by offering + access to copy from a designated place, then offering equivalent + access to copy the source code from the same place counts as + distribution of the source code, even though third parties are not + compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program + except as expressly provided under this License. Any attempt + otherwise to copy, modify, sublicense or distribute the Program is + void, and will automatically terminate your rights under this License. + However, parties who have received copies, or rights, from you under + this License will not have their licenses terminated so long as such + parties remain in full compliance. + + 5. You are not required to accept this License, since you have not + signed it. However, nothing else grants you permission to modify or + distribute the Program or its derivative works. These actions are + prohibited by law if you do not accept this License. Therefore, by + modifying or distributing the Program (or any work based on the + Program), you indicate your acceptance of this License to do so, and + all its terms and conditions for copying, distributing or modifying + the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the + Program), the recipient automatically receives a license from the + original licensor to copy, distribute or modify the Program subject to + these terms and conditions. You may not impose any further + restrictions on the recipients' exercise of the rights granted herein. + You are not responsible for enforcing compliance by third parties to + this License. + + 7. If, as a consequence of a court judgment or allegation of patent + infringement or for any other reason (not limited to patent issues), + conditions are imposed on you (whether by court order, agreement or + otherwise) that contradict the conditions of this License, they do not + excuse you from the conditions of this License. If you cannot + distribute so as to satisfy simultaneously your obligations under this + License and any other pertinent obligations, then as a consequence you + may not distribute the Program at all. For example, if a patent + license would not permit royalty-free redistribution of the Program by + all those who receive copies directly or indirectly through you, then + the only way you could satisfy both it and this License would be to + refrain entirely from distribution of the Program. + + If any portion of this section is held invalid or unenforceable under + any particular circumstance, the balance of the section is intended to + apply and the section as a whole is intended to apply in other + circumstances. + + It is not the purpose of this section to induce you to infringe any + patents or other property right claims or to contest validity of any + such claims; this section has the sole purpose of protecting the + integrity of the free software distribution system, which is + implemented by public license practices. Many people have made + generous contributions to the wide range of software distributed + through that system in reliance on consistent application of that + system; it is up to the author/donor to decide if he or she is willing + to distribute software through any other system and a licensee cannot + impose that choice. + + This section is intended to make thoroughly clear what is believed to + be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in + certain countries either by patents or by copyrighted interfaces, the + original copyright holder who places the Program under this License + may add an explicit geographical distribution limitation excluding + those countries, so that distribution is permitted only in or among + countries not thus excluded. In such case, this License incorporates + the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions + of the General Public License from time to time. Such new versions will + be similar in spirit to the present version, but may differ in detail to + address new problems or concerns. + + Each version is given a distinguishing version number. If the Program + specifies a version number of this License which applies to it and "any + later version", you have the option of following the terms and conditions + either of that version or of any later version published by the Free + Software Foundation. If the Program does not specify a version number of + this License, you may choose any version ever published by the Free Software + Foundation. + + 10. If you wish to incorporate parts of the Program into other free + programs whose distribution conditions are different, write to the author + to ask for permission. For software which is copyrighted by the Free + Software Foundation, write to the Free Software Foundation; we sometimes + make exceptions for this. Our decision will be guided by the two goals + of preserving the free status of all derivatives of our free software and + of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY + FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN + OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES + PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED + OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS + TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE + PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, + REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING + WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR + REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, + INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING + OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED + TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY + YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER + PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE + POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + +The complete text of the GNU Lesser General Public License 2.1 is as follows: + + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + [This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your + freedom to share and change it. By contrast, the GNU General Public + Licenses are intended to guarantee your freedom to share and change + free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some + specially designated software packages--typically libraries--of the + Free Software Foundation and other authors who decide to use it. You + can use it too, but we suggest you first think carefully about whether + this license or the ordinary General Public License is the better + strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, + not price. Our General Public Licenses are designed to make sure that + you have the freedom to distribute copies of free software (and charge + for this service if you wish); that you receive source code or can get + it if you want it; that you can change the software and use pieces of + it in new free programs; and that you are informed that you can do + these things. + + To protect your rights, we need to make restrictions that forbid + distributors to deny you these rights or to ask you to surrender these + rights. These restrictions translate to certain responsibilities for + you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis + or for a fee, you must give the recipients all the rights that we gave + you. You must make sure that they, too, receive or can get the source + code. If you link other code with the library, you must provide + complete object files to the recipients, so that they can relink them + with the library after making changes to the library and recompiling + it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the + library, and (2) we offer you this license, which gives you legal + permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that + there is no warranty for the free library. Also, if the library is + modified by someone else and passed on, the recipients should know + that what they have is not the original version, so that the original + author's reputation will not be affected by problems that might be + introduced by others. + + Finally, software patents pose a constant threat to the existence of + any free program. We wish to make sure that a company cannot + effectively restrict the users of a free program by obtaining a + restrictive license from a patent holder. Therefore, we insist that + any patent license obtained for a version of the library must be + consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the + ordinary GNU General Public License. This license, the GNU Lesser + General Public License, applies to certain designated libraries, and + is quite different from the ordinary General Public License. We use + this license for certain libraries in order to permit linking those + libraries into non-free programs. + + When a program is linked with a library, whether statically or using + a shared library, the combination of the two is legally speaking a + combined work, a derivative of the original library. The ordinary + General Public License therefore permits such linking only if the + entire combination fits its criteria of freedom. The Lesser General + Public License permits more lax criteria for linking other code with + the library. + + We call this license the "Lesser" General Public License because it + does Less to protect the user's freedom than the ordinary General + Public License. It also provides other free software developers Less + of an advantage over competing non-free programs. These disadvantages + are the reason we use the ordinary General Public License for many + libraries. However, the Lesser license provides advantages in certain + special circumstances. + + For example, on rare occasions, there may be a special need to + encourage the widest possible use of a certain library, so that it becomes + a de-facto standard. To achieve this, non-free programs must be + allowed to use the library. A more frequent case is that a free + library does the same job as widely used non-free libraries. In this + case, there is little to gain by limiting the free library to free + software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free + programs enables a greater number of people to use a large body of + free software. For example, permission to use the GNU C Library in + non-free programs enables many more people to use the whole GNU + operating system, as well as its variant, the GNU/Linux operating + system. + + Although the Lesser General Public License is Less protective of the + users' freedom, it does ensure that the user of a program that is + linked with the Library has the freedom and the wherewithal to run + that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and + modification follow. Pay close attention to the difference between a + "work based on the library" and a "work that uses the library". The + former contains code derived from the library, whereas the latter must + be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other + program which contains a notice placed by the copyright holder or + other authorized party saying it may be distributed under the terms of + this Lesser General Public License (also called "this License"). + Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data + prepared so as to be conveniently linked with application programs + (which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work + which has been distributed under these terms. A "work based on the + Library" means either the Library or any derivative work under + copyright law: that is to say, a work containing the Library or a + portion of it, either verbatim or with modifications and/or translated + straightforwardly into another language. (Hereinafter, translation is + included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for + making modifications to it. For a library, complete source code means + all the source code for all modules it contains, plus any associated + interface definition files, plus the scripts used to control compilation + and installation of the library. + + Activities other than copying, distribution and modification are not + covered by this License; they are outside its scope. The act of + running a program using the Library is not restricted, and output from + such a program is covered only if its contents constitute a work based + on the Library (independent of the use of the Library in a tool for + writing it). Whether that is true depends on what the Library does + and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's + complete source code as you receive it, in any medium, provided that + you conspicuously and appropriately publish on each copy an + appropriate copyright notice and disclaimer of warranty; keep intact + all the notices that refer to this License and to the absence of any + warranty; and distribute a copy of this License along with the + Library. + + You may charge a fee for the physical act of transferring a copy, + and you may at your option offer warranty protection in exchange for a + fee. + + 2. You may modify your copy or copies of the Library or any portion + of it, thus forming a work based on the Library, and copy and + distribute such modifications or work under the terms of Section 1 + above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + + These requirements apply to the modified work as a whole. If + identifiable sections of that work are not derived from the Library, + and can be reasonably considered independent and separate works in + themselves, then this License, and its terms, do not apply to those + sections when you distribute them as separate works. But when you + distribute the same sections as part of a whole which is a work based + on the Library, the distribution of the whole must be on the terms of + this License, whose permissions for other licensees extend to the + entire whole, and thus to each and every part regardless of who wrote + it. + + Thus, it is not the intent of this section to claim rights or contest + your rights to work written entirely by you; rather, the intent is to + exercise the right to control the distribution of derivative or + collective works based on the Library. + + In addition, mere aggregation of another work not based on the Library + with the Library (or with a work based on the Library) on a volume of + a storage or distribution medium does not bring the other work under + the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public + License instead of this License to a given copy of the Library. To do + this, you must alter all the notices that refer to this License, so + that they refer to the ordinary GNU General Public License, version 2, + instead of to this License. (If a newer version than version 2 of the + ordinary GNU General Public License has appeared, then you can specify + that version instead if you wish.) Do not make any other change in + these notices. + + Once this change is made in a given copy, it is irreversible for + that copy, so the ordinary GNU General Public License applies to all + subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of + the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or + derivative of it, under Section 2) in object code or executable form + under the terms of Sections 1 and 2 above provided that you accompany + it with the complete corresponding machine-readable source code, which + must be distributed under the terms of Sections 1 and 2 above on a + medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy + from a designated place, then offering equivalent access to copy the + source code from the same place satisfies the requirement to + distribute the source code, even though third parties are not + compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the + Library, but is designed to work with the Library by being compiled or + linked with it, is called a "work that uses the Library". Such a + work, in isolation, is not a derivative work of the Library, and + therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library + creates an executable that is a derivative of the Library (because it + contains portions of the Library), rather than a "work that uses the + library". The executable is therefore covered by this License. + Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file + that is part of the Library, the object code for the work may be a + derivative work of the Library even though the source code is not. + Whether this is true is especially significant if the work can be + linked without the Library, or if the work is itself a library. The + threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data + structure layouts and accessors, and small macros and small inline + functions (ten lines or less in length), then the use of the object + file is unrestricted, regardless of whether it is legally a derivative + work. (Executables containing this object code plus portions of the + Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may + distribute the object code for the work under the terms of Section 6. + Any executables containing that work also fall under Section 6, + whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or + link a "work that uses the Library" with the Library to produce a + work containing portions of the Library, and distribute that work + under terms of your choice, provided that the terms permit + modification of the work for the customer's own use and reverse + engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the + Library is used in it and that the Library and its use are covered by + this License. You must supply a copy of this License. If the work + during execution displays copyright notices, you must include the + copyright notice for the Library among them, as well as a reference + directing the user to the copy of this License. Also, you must do one + of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the + Library" must include any data and utility programs needed for + reproducing the executable from it. However, as a special exception, + the materials to be distributed need not include anything that is + normally distributed (in either source or binary form) with the major + components (compiler, kernel, and so on) of the operating system on + which the executable runs, unless that component itself accompanies + the executable. + + It may happen that this requirement contradicts the license + restrictions of other proprietary libraries that do not normally + accompany the operating system. Such a contradiction means you cannot + use both them and the Library together in an executable that you + distribute. + + 7. You may place library facilities that are a work based on the + Library side-by-side in a single library together with other library + facilities not covered by this License, and distribute such a combined + library, provided that the separate distribution of the work based on + the Library and of the other library facilities is otherwise + permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute + the Library except as expressly provided under this License. Any + attempt otherwise to copy, modify, sublicense, link with, or + distribute the Library is void, and will automatically terminate your + rights under this License. However, parties who have received copies, + or rights, from you under this License will not have their licenses + terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not + signed it. However, nothing else grants you permission to modify or + distribute the Library or its derivative works. These actions are + prohibited by law if you do not accept this License. Therefore, by + modifying or distributing the Library (or any work based on the + Library), you indicate your acceptance of this License to do so, and + all its terms and conditions for copying, distributing or modifying + the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the + Library), the recipient automatically receives a license from the + original licensor to copy, distribute, link with or modify the Library + subject to these terms and conditions. You may not impose any further + restrictions on the recipients' exercise of the rights granted herein. + You are not responsible for enforcing compliance by third parties with + this License. + + 11. If, as a consequence of a court judgment or allegation of patent + infringement or for any other reason (not limited to patent issues), + conditions are imposed on you (whether by court order, agreement or + otherwise) that contradict the conditions of this License, they do not + excuse you from the conditions of this License. If you cannot + distribute so as to satisfy simultaneously your obligations under this + License and any other pertinent obligations, then as a consequence you + may not distribute the Library at all. For example, if a patent + license would not permit royalty-free redistribution of the Library by + all those who receive copies directly or indirectly through you, then + the only way you could satisfy both it and this License would be to + refrain entirely from distribution of the Library. + + If any portion of this section is held invalid or unenforceable under any + particular circumstance, the balance of the section is intended to apply, + and the section as a whole is intended to apply in other circumstances. + + It is not the purpose of this section to induce you to infringe any + patents or other property right claims or to contest validity of any + such claims; this section has the sole purpose of protecting the + integrity of the free software distribution system which is + implemented by public license practices. Many people have made + generous contributions to the wide range of software distributed + through that system in reliance on consistent application of that + system; it is up to the author/donor to decide if he or she is willing + to distribute software through any other system and a licensee cannot + impose that choice. + + This section is intended to make thoroughly clear what is believed to + be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in + certain countries either by patents or by copyrighted interfaces, the + original copyright holder who places the Library under this License may add + an explicit geographical distribution limitation excluding those countries, + so that distribution is permitted only in or among countries not thus + excluded. In such case, this License incorporates the limitation as if + written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new + versions of the Lesser General Public License from time to time. + Such new versions will be similar in spirit to the present version, + but may differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the Library + specifies a version number of this License which applies to it and + "any later version", you have the option of following the terms and + conditions either of that version or of any later version published by + the Free Software Foundation. If the Library does not specify a + license version number, you may choose any version ever published by + the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free + programs whose distribution conditions are incompatible with these, + write to the author to ask for permission. For software which is + copyrighted by the Free Software Foundation, write to the Free + Software Foundation; we sometimes make exceptions for this. Our + decision will be guided by the two goals of preserving the free status + of all derivatives of our free software and of promoting the sharing + and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO + WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. + EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR + OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE + LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME + THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN + WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY + AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU + FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR + CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE + LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING + RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A + FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF + SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH + DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest + possible use to the public, we recommend making it free software that + everyone can redistribute and change. You can do so by permitting + redistribution under these terms (or, alternatively, under the terms of the + ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is + safest to attach them to the start of each source file to most effectively + convey the exclusion of warranty; and each file should have at least the + "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Also add information on how to contact you by electronic and paper mail. + + You should also get your employer (if you work as a programmer) or your + school, if any, to sign a "copyright disclaimer" for the library, if + necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + + That's all there is to it! diff --git a/licenses/jnr-x86asm.txt b/licenses/jnr-x86asm.txt new file mode 100644 index 00000000000..c9583db05fd --- /dev/null +++ b/licenses/jnr-x86asm.txt @@ -0,0 +1,24 @@ + + Copyright (C) 2010 Wayne Meissner + Copyright (c) 2008-2009, Petr Kobalicek + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation + files (the "Software"), to deal in the Software without + restriction, including without limitation the rights to use, + copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following + conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. diff --git a/licenses/reactive-streams.txt b/licenses/reactive-streams.txt new file mode 100644 index 00000000000..1e141c13ddb --- /dev/null +++ b/licenses/reactive-streams.txt @@ -0,0 +1,7 @@ +MIT No Attribution + +Copyright 2014 Reactive Streams + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/licenses/slf4j-api.txt b/licenses/slf4j-api.txt new file mode 100644 index 00000000000..bb09a9ad4ec --- /dev/null +++ b/licenses/slf4j-api.txt @@ -0,0 +1,21 @@ +Copyright (c) 2004-2023 QOS.ch +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/manual/README.md b/manual/README.md index c3111debe2f..049ddc8c8e9 100644 --- a/manual/README.md +++ b/manual/README.md @@ -1,3 +1,22 @@ + + ## Manual Driver modules: @@ -14,4 +33,4 @@ Common topics: * [API conventions](api_conventions/) * [Case sensitivity](case_sensitivity/) * [OSGi](osgi/) -* [Cloud](cloud/) \ No newline at end of file +* [Cloud](cloud/) diff --git a/manual/api_conventions/README.md b/manual/api_conventions/README.md index a76067ebef2..553392658dd 100644 --- a/manual/api_conventions/README.md +++ b/manual/api_conventions/README.md @@ -1,3 +1,22 @@ + + ## API conventions In previous versions, the driver relied solely on Java visibility rules: everything was either @@ -41,4 +60,4 @@ internalContext.getEventBus().fire(TopologyEvent.forceDown(address)); So the risk of unintentionally using the internal API is very low. To double-check, you can always grep `import com.datastax.oss.driver.internal` in your source files. -[semantic versioning]: http://semver.org/ \ No newline at end of file +[semantic versioning]: http://semver.org/ diff --git a/manual/case_sensitivity/README.md b/manual/case_sensitivity/README.md index a2a16ebfdbd..e9dbf1bf9a8 100644 --- a/manual/case_sensitivity/README.md +++ b/manual/case_sensitivity/README.md @@ -1,3 +1,22 @@ + + ## Case sensitivity ### In Cassandra @@ -106,18 +125,18 @@ For "consuming" methods, string overloads are also provided for convenience, for * in other cases, the string is always assumed to be in CQL form, and converted on the fly with `CqlIdentifier.fromCql`. -[CqlIdentifier]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/CqlIdentifier.html -[Row]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/Row.html -[UdtValue]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/data/UdtValue.html -[BoundStatement]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/BoundStatement.html -[AccessibleByName]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/data/AccessibleByName.html +[CqlIdentifier]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/CqlIdentifier.html +[Row]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/Row.html +[UdtValue]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/data/UdtValue.html +[BoundStatement]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/BoundStatement.html +[AccessibleByName]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/data/AccessibleByName.html ### Good practices As should be clear by now, case sensitivity introduces a lot of extra (and arguably unnecessary) complexity. -The Java driver team's recommendation is: +The Java Driver team's recommendation is: > **Always use case-insensitive identifiers in your data model.** @@ -130,4 +149,4 @@ If you worry about readability, use snake case (`shopping_cart`), or simply stic The only reason to use case sensitivity should be if you don't control the data model. In that case, either pass quoted strings to the driver, or use `CqlIdentifier` instances (stored as -constants to avoid creating them over and over). \ No newline at end of file +constants to avoid creating them over and over). diff --git a/manual/cloud/README.md b/manual/cloud/README.md index 161a8308c73..9116b03dac3 100644 --- a/manual/cloud/README.md +++ b/manual/cloud/README.md @@ -1,20 +1,38 @@ + + ## Connecting to Astra (Cloud) -Using the DataStax Java Driver to connect to a DataStax Astra database is almost identical to using +Using the Java Driver to connect to a DataStax Astra database is almost identical to using the driver to connect to any normal Apache Cassandra® database. The only differences are in how the driver is configured in an application and that you will need to obtain a *secure connect bundle*. ### Prerequisites 1. [Download][Download Maven] and [install][Install Maven] Maven. -2. Create an Astra database on [GCP][Create an Astra database - GCP] or - [AWS][Create an Astra database - AWS]; alternatively, have a team member provide access to their - Astra database (instructions for [GCP][Access an Astra database - GCP] and - [AWS][Access an Astra database - AWS]) to obtain database connection details. -3. Download the secure connect bundle (instructions for - [GCP][Download the secure connect bundle - GCP] and - [AWS][Download the secure connect bundle - AWS]), that contains connection information such as - contact points and certificates. +2. Create an Astra database on [AWS/Azure/GCP][Create an Astra database - AWS/Azure/GCP]; + alternatively, have a team member provide access to their + Astra database (see instructions for [AWS/Azure/GCP][Access an Astra database - AWS/Azure/GCP]) to + obtain database connection details. +3. Download the secure connect bundle (see instructions for + [AWS/Azure/GCP][Download the secure connect bundle - AWS/Azure/GCP]) that contains connection + information such as contact points and certificates. ### Procedure @@ -125,11 +143,8 @@ public class Main { [Download Maven]: https://maven.apache.org/download.cgi [Install Maven]: https://maven.apache.org/install.html -[Create an Astra database - GCP]: https://docs.datastax.com/en/astra/gcp/doc/dscloud/astra/dscloudGettingStarted.html#dscloudCreateCluster -[Create an Astra database - AWS]: https://docs.datastax.com/en/astra/aws/doc/dscloud/astra/dscloudGettingStarted.html#dscloudCreateCluster -[Access an Astra database - GCP]: https://docs.datastax.com/en/astra/gcp/doc/dscloud/astra/dscloudShareClusterDetails.html -[Access an Astra database - AWS]: https://docs.datastax.com/en/astra/aws/doc/dscloud/astra/dscloudShareClusterDetails.html -[Download the secure connect bundle - GCP]: https://docs.datastax.com/en/astra/gcp/doc/dscloud/astra/dscloudObtainingCredentials.html -[Download the secure connect bundle - AWS]: https://docs.datastax.com/en/astra/aws/doc/dscloud/astra/dscloudObtainingCredentials.html +[Create an Astra database - AWS/Azure/GCP]: https://docs.datastax.com/en/astra/docs/creating-your-astra-database.html +[Access an Astra database - AWS/Azure/GCP]: https://docs.datastax.com/en/astra/docs/obtaining-database-credentials.html#_sharing_your_secure_connect_bundle +[Download the secure connect bundle - AWS/Azure/GCP]: https://docs.datastax.com/en/astra/docs/obtaining-database-credentials.html [minimal project structure]: ../core/integration/#minimal-project-structure [driver documentation]: ../core/configuration/ diff --git a/manual/core/README.md b/manual/core/README.md index aeb21167fea..5ca4cd7872f 100644 --- a/manual/core/README.md +++ b/manual/core/README.md @@ -1,3 +1,22 @@ + + ## Core driver The core module handles cluster connectivity and request execution. It is published under the @@ -5,7 +24,7 @@ following coordinates: ```xml - com.datastax.oss + org.apache.cassandra java-driver-core ${driver.version} @@ -231,34 +250,35 @@ See [AccessibleByName] for an explanation of the conversion rules. ##### CQL to Java type mapping -| CQL3 data type | Getter name | Java type | See also | -|---------------------|----------------|----------------------|-------------------------------------| -| ascii | getString | java.lang.String | | -| bigint | getLong | long | | -| blob | getByteBuffer | java.nio.ByteBuffer | | -| boolean | getBoolean | boolean | | -| counter | getLong | long | | -| date | getLocalDate | java.time.LocalDate | [Temporal types](temporal_types/) | -| decimal | getBigDecimal | java.math.BigDecimal | | -| double | getDouble | double | | -| duration | getCqlDuration | [CqlDuration] | [Temporal types](temporal_types/) | -| float | getFloat | float | | -| inet | getInetAddress | java.net.InetAddress | | -| int | getInt | int | | -| list | getList | java.util.List | | -| map | getMap | java.util.Map | | -| set | getSet | java.util.Set | | -| smallint | getShort | short | | -| text | getString | java.lang.String | | -| time | getLocalTime | java.time.LocalTime | [Temporal types](temporal_types/) | -| timestamp | getInstant | java.time.Instant | [Temporal types](temporal_types/) | -| timeuuid | getUuid | java.util.UUID | | -| tinyint | getByte | byte | | -| tuple | getTupleValue | [TupleValue] | [Tuples](tuples/) | -| user-defined types | getUDTValue | [UDTValue] | [User-defined types](udts/) | -| uuid | getUuid | java.util.UUID | | -| varchar | getString | java.lang.String | | -| varint | getBigInteger | java.math.BigInteger | | +| CQL3 data type | Getter name | Java type | See also | +|--------------------|----------------|----------------------|-----------------------------------| +| ascii | getString | java.lang.String | | +| bigint | getLong | long | | +| blob | getByteBuffer | java.nio.ByteBuffer | | +| boolean | getBoolean | boolean | | +| counter | getLong | long | | +| date | getLocalDate | java.time.LocalDate | [Temporal types](temporal_types/) | +| decimal | getBigDecimal | java.math.BigDecimal | | +| double | getDouble | double | | +| duration | getCqlDuration | [CqlDuration] | [Temporal types](temporal_types/) | +| float | getFloat | float | | +| inet | getInetAddress | java.net.InetAddress | | +| int | getInt | int | | +| list | getList | java.util.List | | +| map | getMap | java.util.Map | | +| set | getSet | java.util.Set | | +| smallint | getShort | short | | +| text | getString | java.lang.String | | +| time | getLocalTime | java.time.LocalTime | [Temporal types](temporal_types/) | +| timestamp | getInstant | java.time.Instant | [Temporal types](temporal_types/) | +| timeuuid | getUuid | java.util.UUID | | +| tinyint | getByte | byte | | +| tuple | getTupleValue | [TupleValue] | [Tuples](tuples/) | +| user-defined types | getUDTValue | [UDTValue] | [User-defined types](udts/) | +| uuid | getUuid | java.util.UUID | | +| varchar | getString | java.lang.String | | +| varint | getBigInteger | java.math.BigInteger | | +| vector | getVector | [CqlVector] | [Custom Codecs](custom_codecs/) | Sometimes the driver has to infer a CQL type from a Java type (for example when handling the values of [simple statements](statements/simple/)); for those that have multiple CQL equivalents, it makes @@ -314,18 +334,19 @@ for (ColumnDefinitions.Definition definition : row.getColumnDefinitions()) { } ``` -[CqlSession]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/CqlSession.html -[CqlSession#builder()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/CqlSession.html#builder-- -[ResultSet]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/ResultSet.html -[Row]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/Row.html -[CqlIdentifier]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/CqlIdentifier.html -[AccessibleByName]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/data/AccessibleByName.html -[GenericType]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/reflect/GenericType.html -[CqlDuration]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/data/CqlDuration.html -[TupleValue]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/data/TupleValue.html -[UdtValue]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/data/UdtValue.html -[SessionBuilder.addContactPoint()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/session/SessionBuilder.html#addContactPoint-java.net.InetSocketAddress- -[SessionBuilder.addContactPoints()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/session/SessionBuilder.html#addContactPoints-java.util.Collection- -[SessionBuilder.withLocalDatacenter()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/session/SessionBuilder.html#withLocalDatacenter-java.lang.String- - -[CASSANDRA-10145]: https://issues.apache.org/jira/browse/CASSANDRA-10145 \ No newline at end of file +[CqlSession]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/CqlSession.html +[CqlSession#builder()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/CqlSession.html#builder-- +[ResultSet]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/ResultSet.html +[Row]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/Row.html +[CqlIdentifier]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/CqlIdentifier.html +[AccessibleByName]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/data/AccessibleByName.html +[GenericType]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/reflect/GenericType.html +[CqlDuration]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/data/CqlDuration.html +[CqlVector]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/data/CqlVector.html +[TupleValue]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/data/TupleValue.html +[UdtValue]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/data/UdtValue.html +[SessionBuilder.addContactPoint()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/SessionBuilder.html#addContactPoint-java.net.InetSocketAddress- +[SessionBuilder.addContactPoints()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/SessionBuilder.html#addContactPoints-java.util.Collection- +[SessionBuilder.withLocalDatacenter()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/SessionBuilder.html#withLocalDatacenter-java.lang.String- + +[CASSANDRA-10145]: https://issues.apache.org/jira/browse/CASSANDRA-10145 diff --git a/manual/core/address_resolution/README.md b/manual/core/address_resolution/README.md index 7d83c8ff748..5b2536feb18 100644 --- a/manual/core/address_resolution/README.md +++ b/manual/core/address_resolution/README.md @@ -1,3 +1,22 @@ + + ## Address resolution ### Quick overview @@ -99,6 +118,55 @@ datastax-java-driver.advanced.address-translator.class = com.mycompany.MyAddress Note: the contact points provided while creating the `CqlSession` are not translated, only addresses retrieved from or sent by Cassandra nodes are. +### Fixed proxy hostname + +If your client applications access Cassandra through some kind of proxy (eg. with AWS PrivateLink when all Cassandra +nodes are exposed via one hostname pointing to AWS Endpoint), you can configure driver with +`FixedHostNameAddressTranslator` to always translate all node addresses to that same proxy hostname, no matter what IP +address a node has but still using its native transport port. + +To use it, specify the following in the [configuration](../configuration): + +``` +datastax-java-driver.advanced.address-translator.class = FixedHostNameAddressTranslator +advertised-hostname = proxyhostname +``` + +### Fixed proxy hostname per subnet + +When running Cassandra in a private network and accessing it from outside of that private network via some kind of +proxy, we have an option to use `FixedHostNameAddressTranslator`. But for multi-datacenter Cassandra deployments, we +want to have more control over routing queries to a specific datacenter (eg. for optimizing latencies), which requires +setting up a separate proxy per datacenter. + +Normally, each Cassandra datacenter nodes are deployed to a different subnet to support internode communications in the +cluster and avoid IP address collisions. So when Cassandra broadcasts its nodes IP addresses, we can determine which +datacenter that node belongs to by checking its IP address against the given datacenter subnet. + +For such scenarios you can use `SubnetAddressTranslator` to translate node IPs to the datacenter proxy address +associated with it. + +To use it, specify the following in the [configuration](../configuration): +``` +datastax-java-driver.advanced.address-translator { + class = SubnetAddressTranslator + subnet-addresses { + "100.64.0.0/15" = "cassandra.datacenter1.com:9042" + "100.66.0.0/15" = "cassandra.datacenter2.com:9042" + # IPv6 example: + # "::ffff:6440:0/111" = "cassandra.datacenter1.com:9042" + # "::ffff:6442:0/111" = "cassandra.datacenter2.com:9042" + } + # Optional. When configured, addresses not matching the configured subnets are translated to this address. + default-address = "cassandra.datacenter1.com:9042" + # Whether to resolve the addresses once on initialization (if true) or on each node (re-)connection (if false). + # If not configured, defaults to false. + resolve-addresses = false +} +``` + +Such setup is common for running Cassandra on Kubernetes with [k8ssandra](https://docs.k8ssandra.io/). + ### EC2 multi-region If you deploy both Cassandra and client applications on Amazon EC2, and your cluster spans multiple regions, you'll have @@ -124,7 +192,7 @@ Cassandra node: domain name of the target instance. Then it performs a forward DNS lookup of the domain name; the EC2 DNS does the private/public switch automatically based on location). -[AddressTranslator]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/addresstranslation/AddressTranslator.html +[AddressTranslator]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/addresstranslation/AddressTranslator.html [cassandra.yaml]: https://docs.datastax.com/en/cassandra/3.x/cassandra/configuration/configCassandra_yaml.html [rpc_address]: https://docs.datastax.com/en/cassandra/3.x/cassandra/configuration/configCassandra_yaml.html?scroll=configCassandra_yaml__rpc_address diff --git a/manual/core/async/README.md b/manual/core/async/README.md index 66687509cf2..5b4bac3dccf 100644 --- a/manual/core/async/README.md +++ b/manual/core/async/README.md @@ -1,3 +1,22 @@ + + ## Asynchronous programming ### Quick overview @@ -61,8 +80,12 @@ resultStage.thenAccept(resultSet -> System.out.println(Thread.currentThread().ge // prints s0-io-n (I/O pool thread) ``` -As long as you use the asynchronous API, the driver never blocks. You can safely call a driver -method from inside a callback: +As long as you use the asynchronous API, the driver will behave in a non-blocking manner: its +internal threads will almost never block. There are a few exceptions to the rule though: see the +manual page on [non-blocking programming](../non_blocking) for details. + +Because the asynchronous API is non-blocking, you can safely call a driver method from inside a +callback, even when the callback's execution is triggered by a future returned by the driver: ```java // Get the department id for a given user: @@ -203,4 +226,4 @@ documentation for more details and an example. [CompletionStage]: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletionStage.html -[AsyncResultSet]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/AsyncResultSet.html \ No newline at end of file +[AsyncResultSet]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/AsyncResultSet.html diff --git a/manual/core/authentication/README.md b/manual/core/authentication/README.md index 4e77c3d3a61..516e47f558f 100644 --- a/manual/core/authentication/README.md +++ b/manual/core/authentication/README.md @@ -1,3 +1,22 @@ + + ## Authentication ### Quick overview @@ -108,8 +127,20 @@ CqlSession session = .build(); ``` -For convenience, there are shortcuts that take the credentials directly. This is equivalent to -using `PlainTextAuthProvider` in the configuration: +The driver also offers a simple, built-in plain text authentication provider: +[ProgrammaticPlainTextAuthProvider]. The following is equivalent to using `PlainTextAuthProvider` in +the configuration: + +```java +AuthProvider authProvider = new ProgrammaticPlainTextAuthProvider("user", "pass"); + +CqlSession session = + CqlSession.builder() + .withAuthProvider(authProvider) + .build(); +``` + +For convenience, there are shortcuts that take the credentials directly: ```java CqlSession session = @@ -124,9 +155,9 @@ CqlSession session = .build(); ``` -One downside of `withAuthCredentials` is that the credentials are stored in clear text in memory; -this means they are vulnerable to an attacker who is able to perform memory dumps. If this is not -acceptable for you, consider writing your own [AuthProvider] implementation; +One downside of the driver's built-in authentication providers is that the credentials are stored in +clear text in memory; this means they are vulnerable to an attacker who is able to perform memory +dumps. If this is not acceptable for you, consider writing your own [AuthProvider] implementation; [PlainTextAuthProviderBase] is a good starting point. Similarly, [ProgrammaticDseGssApiAuthProvider] lets you configure GSSAPI programmatically: @@ -215,12 +246,13 @@ session.execute(statement); [SASL]: https://en.wikipedia.org/wiki/Simple_Authentication_and_Security_Layer -[AuthProvider]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/auth/AuthProvider.html -[DriverContext]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/context/DriverContext.html -[PlainTextAuthProviderBase]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/auth/PlainTextAuthProviderBase.html -[DseGssApiAuthProviderBase]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/auth/DseGssApiAuthProviderBase.html -[ProgrammaticDseGssApiAuthProvider]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/auth/ProgrammaticDseGssApiAuthProvider.html -[ProxyAuthentication.executeAs]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/auth/ProxyAuthentication.html#executeAs-java.lang.String-StatementT- -[SessionBuilder.withAuthCredentials]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/session/SessionBuilder.html#withAuthCredentials-java.lang.String-java.lang.String- -[SessionBuilder.withAuthProvider]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/session/SessionBuilder.html#withAuthProvider-com.datastax.oss.driver.api.core.auth.AuthProvider- -[reference.conf]: ../configuration/reference/ \ No newline at end of file +[AuthProvider]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/auth/AuthProvider.html +[DriverContext]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/context/DriverContext.html +[PlainTextAuthProviderBase]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/auth/PlainTextAuthProviderBase.html +[ProgrammaticPlainTextAuthProvider]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/auth/ProgrammaticPlainTextAuthProvider.html +[DseGssApiAuthProviderBase]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/auth/DseGssApiAuthProviderBase.html +[ProgrammaticDseGssApiAuthProvider]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/auth/ProgrammaticDseGssApiAuthProvider.html +[ProxyAuthentication.executeAs]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/auth/ProxyAuthentication.html#executeAs-java.lang.String-StatementT- +[SessionBuilder.withAuthCredentials]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/SessionBuilder.html#withAuthCredentials-java.lang.String-java.lang.String- +[SessionBuilder.withAuthProvider]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/SessionBuilder.html#withAuthProvider-com.datastax.oss.driver.api.core.auth.AuthProvider- +[reference.conf]: ../configuration/reference/ diff --git a/manual/core/bom/README.md b/manual/core/bom/README.md index 922bcffba24..235edcf632c 100644 --- a/manual/core/bom/README.md +++ b/manual/core/bom/README.md @@ -1,3 +1,22 @@ + + ## Bill of Materials (BOM) A "Bill Of Materials" is a special Maven descriptor that defines the versions of a set of related @@ -11,9 +30,9 @@ To import the driver's BOM, add the following section in your application's own - com.datastax.oss + org.apache.cassandra java-driver-bom - 4.9.0 + 4.17.0 pom import @@ -28,7 +47,7 @@ This allows you to omit the version when you later reference the driver artifact ... - com.datastax.oss + org.apache.cassandra java-driver-query-builder @@ -52,7 +71,7 @@ scope: ```xml - com.datastax.oss + org.apache.cassandra java-driver-mapper-processor provided @@ -65,12 +84,12 @@ good idea to extract a property to keep it in sync with the BOM: ```xml - 4.9.0 + 4.17.0 - com.datastax.oss + org.apache.cassandra java-driver-bom ${java-driver.version} pom @@ -81,7 +100,7 @@ good idea to extract a property to keep it in sync with the BOM: - com.datastax.oss + org.apache.cassandra java-driver-mapper-runtime @@ -93,7 +112,7 @@ good idea to extract a property to keep it in sync with the BOM: - com.datastax.oss + org.apache.cassandra java-driver-mapper-processor ${java-driver.version} @@ -104,4 +123,4 @@ good idea to extract a property to keep it in sync with the BOM: ``` -[MCOMPILER-391]: https://issues.apache.org/jira/browse/MCOMPILER-391 \ No newline at end of file +[MCOMPILER-391]: https://issues.apache.org/jira/browse/MCOMPILER-391 diff --git a/manual/core/compression/README.md b/manual/core/compression/README.md index 32d18a8ac2f..9f7ae3c4854 100644 --- a/manual/core/compression/README.md +++ b/manual/core/compression/README.md @@ -1,3 +1,22 @@ + + ## Compression ### Quick overview @@ -27,8 +46,7 @@ datastax-java-driver { Compression must be set before opening a session, it cannot be changed at runtime. - -Two algorithms are supported out of the box: [LZ4](https://github.com/jpountz/lz4-java) and +Two algorithms are supported out of the box: [LZ4](https://github.com/yawkat/lz4-java) and [Snappy](http://google.github.io/snappy/). The LZ4 implementation is a good first choice; it offers fallback implementations in case native libraries fail to load and [benchmarks](http://java-performance.info/performance-general-compression/) suggest that it offers @@ -45,9 +63,9 @@ Dependency: ```xml - org.lz4 + at.yawk.lz4 lz4-java - 1.4.1 + 1.10.1 ``` @@ -79,6 +97,8 @@ Dependency: ``` +**Important: Snappy is not supported when building a [GraalVM native image](../graalvm).** + Always double-check the exact Snappy version needed; you can find it in the driver's [parent POM]. -[parent POM]: https://search.maven.org/search?q=g:com.datastax.oss%20AND%20a:java-driver-parent&core=gav \ No newline at end of file +[parent POM]: https://search.maven.org/search?q=g:com.datastax.oss%20AND%20a:java-driver-parent&core=gav diff --git a/manual/core/configuration/README.md b/manual/core/configuration/README.md index c99f7c29963..deefadbe3d4 100644 --- a/manual/core/configuration/README.md +++ b/manual/core/configuration/README.md @@ -1,3 +1,22 @@ + + ## Configuration ### Quick overview @@ -351,9 +370,28 @@ CqlSession session = CqlSession.builder().withConfigLoader(loader).build(); If Typesafe Config doesn't work for you, it is possible to get rid of it entirely. -You will need to provide your own implementations of [DriverConfig] and [DriverExecutionProfile]. -Then write a [DriverConfigLoader] and pass it to the session at initialization, as shown in the -previous sections. Study the built-in implementation (package +Start by excluding Typesafe Config from the list of dependencies required by the driver; if you are +using Maven, this can be achieved as follows: + +```xml + + + org.apache.cassandra + java-driver-core + ... + + + com.typesafe + config + + + + + +``` +Next, you will need to provide your own implementations of [DriverConfig] and +[DriverExecutionProfile]. Then write a [DriverConfigLoader] and pass it to the session at +initialization, as shown in the previous sections. Study the built-in implementation (package `com.datastax.oss.driver.internal.core.config.typesafe`) for reference. Reloading is not mandatory: you can choose not to implement it, and the driver will simply keep @@ -501,16 +539,16 @@ config.getDefaultProfile().getString(MyCustomOption.ADMIN_EMAIL); config.getDefaultProfile().getInt(MyCustomOption.AWESOMENESS_FACTOR); ``` -[DriverConfig]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/config/DriverConfig.html -[DriverExecutionProfile]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/config/DriverExecutionProfile.html -[DriverContext]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/context/DriverContext.html -[DriverOption]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/config/DriverOption.html -[DefaultDriverOption]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/config/DefaultDriverOption.html -[DriverConfigLoader]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/config/DriverConfigLoader.html -[DriverConfigLoader.fromClasspath]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/config/DriverConfigLoader.html#fromClasspath-java.lang.String- -[DriverConfigLoader.fromFile]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/config/DriverConfigLoader.html#fromFile-java.io.File- -[DriverConfigLoader.fromUrl]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/config/DriverConfigLoader.html#fromUrl-java.net.URL- -[DriverConfigLoader.programmaticBuilder]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/config/DriverConfigLoader.html#programmaticBuilder-- +[DriverConfig]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/config/DriverConfig.html +[DriverExecutionProfile]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/config/DriverExecutionProfile.html +[DriverContext]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/context/DriverContext.html +[DriverOption]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/config/DriverOption.html +[DefaultDriverOption]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/config/DefaultDriverOption.html +[DriverConfigLoader]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/config/DriverConfigLoader.html +[DriverConfigLoader.fromClasspath]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/config/DriverConfigLoader.html#fromClasspath-java.lang.String- +[DriverConfigLoader.fromFile]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/config/DriverConfigLoader.html#fromFile-java.io.File- +[DriverConfigLoader.fromUrl]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/config/DriverConfigLoader.html#fromUrl-java.net.URL- +[DriverConfigLoader.programmaticBuilder]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/config/DriverConfigLoader.html#programmaticBuilder-- [Typesafe Config]: https://github.com/typesafehub/config [config standard behavior]: https://github.com/typesafehub/config#standard-behavior diff --git a/manual/core/configuration/reference/README.rst b/manual/core/configuration/reference/README.rst index e6da9306a75..d4989ecf641 100644 --- a/manual/core/configuration/reference/README.rst +++ b/manual/core/configuration/reference/README.rst @@ -1,3 +1,21 @@ +.. + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + Reference configuration ----------------------- diff --git a/manual/core/control_connection/README.md b/manual/core/control_connection/README.md index f688aa88172..38544797aed 100644 --- a/manual/core/control_connection/README.md +++ b/manual/core/control_connection/README.md @@ -1,3 +1,22 @@ + + ## Control connection The control connection is a dedicated connection used for administrative tasks: @@ -23,4 +42,4 @@ There are a few options to fine tune the control connection behavior in the `advanced.control-connection` and `advanced.metadata` sections; see the [metadata](../metadata/) pages and the [reference configuration](../configuration/reference/) for all the details. -[Node.getOpenConnections]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/metadata/Node.html#getOpenConnections-- \ No newline at end of file +[Node.getOpenConnections]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/metadata/Node.html#getOpenConnections-- diff --git a/manual/core/custom_codecs/README.md b/manual/core/custom_codecs/README.md index 5bda597058b..f3b7be1e3d9 100644 --- a/manual/core/custom_codecs/README.md +++ b/manual/core/custom_codecs/README.md @@ -1,3 +1,22 @@ + + ## Custom codecs ### Quick overview @@ -256,6 +275,17 @@ that maps instances of that class to Json strings, using a newly-allocated, defa It is also possible to pass a custom `ObjectMapper` instance using [ExtraTypeCodecs.json(Class, ObjectMapper)] instead. +#### Mapping CQL vectors to Java array + +By default, the driver maps CQL `vector` to the [CqlVector] value type. If you prefer to deal with +arrays, the driver offers the following codec: + +| Codec | CQL type | Java type | +|-------------------------------------------|-----------------|-----------| +| [ExtraTypeCodecs.floatVectorToArray(int)] | `vector` | `float[]` | + +This release only provides a codec for vectors containing float values. + ### Writing codecs If none of the driver built-in codecs above suits you, it is also possible to roll your own. @@ -660,13 +690,13 @@ private static String formatRow(Row row) { } ``` -[CodecRegistry]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/registry/CodecRegistry.html -[GenericType]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/reflect/GenericType.html -[TypeCodec]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/TypeCodec.html -[format()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/TypeCodec.html#format-JavaTypeT- -[parse()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/TypeCodec.html#parse-java.lang.String- -[MappingCodec]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/MappingCodec.html -[SessionBuilder.addTypeCodecs]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/session/SessionBuilder.html#addTypeCodecs-com.datastax.oss.driver.api.core.type.codec.TypeCodec...- +[CodecRegistry]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/registry/CodecRegistry.html +[GenericType]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/reflect/GenericType.html +[TypeCodec]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/TypeCodec.html +[format()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/TypeCodec.html#format-JavaTypeT- +[parse()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/TypeCodec.html#parse-java.lang.String- +[MappingCodec]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/MappingCodec.html +[SessionBuilder.addTypeCodecs]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/SessionBuilder.html#addTypeCodecs-com.datastax.oss.driver.api.core.type.codec.TypeCodec...- [Enums]: https://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html [Enum.name()]: https://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html#name-- @@ -680,38 +710,39 @@ private static String formatRow(Row row) { [java.time.LocalDateTime]: https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html [java.time.ZoneId]: https://docs.oracle.com/javase/8/docs/api/java/time/ZoneId.html -[ExtraTypeCodecs]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html -[ExtraTypeCodecs.BLOB_TO_ARRAY]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#BLOB_TO_ARRAY -[ExtraTypeCodecs.BOOLEAN_LIST_TO_ARRAY]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#BOOLEAN_LIST_TO_ARRAY -[ExtraTypeCodecs.BYTE_LIST_TO_ARRAY]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#BYTE_LIST_TO_ARRAY -[ExtraTypeCodecs.SHORT_LIST_TO_ARRAY]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#SHORT_LIST_TO_ARRAY -[ExtraTypeCodecs.INT_LIST_TO_ARRAY]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#INT_LIST_TO_ARRAY -[ExtraTypeCodecs.LONG_LIST_TO_ARRAY]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#LONG_LIST_TO_ARRAY -[ExtraTypeCodecs.FLOAT_LIST_TO_ARRAY]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#FLOAT_LIST_TO_ARRAY -[ExtraTypeCodecs.DOUBLE_LIST_TO_ARRAY]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#DOUBLE_LIST_TO_ARRAY -[ExtraTypeCodecs.listToArrayOf(TypeCodec)]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#listToArrayOf-com.datastax.oss.driver.api.core.type.codec.TypeCodec- -[ExtraTypeCodecs.TIMESTAMP_UTC]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#TIMESTAMP_UTC -[ExtraTypeCodecs.timestampAt(ZoneId)]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#timestampAt-java.time.ZoneId- -[ExtraTypeCodecs.TIMESTAMP_MILLIS_SYSTEM]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#TIMESTAMP_MILLIS_SYSTEM -[ExtraTypeCodecs.TIMESTAMP_MILLIS_UTC]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#TIMESTAMP_MILLIS_UTC -[ExtraTypeCodecs.timestampMillisAt(ZoneId)]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#timestampMillisAt-java.time.ZoneId- -[ExtraTypeCodecs.ZONED_TIMESTAMP_SYSTEM]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#ZONED_TIMESTAMP_SYSTEM -[ExtraTypeCodecs.ZONED_TIMESTAMP_UTC]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#ZONED_TIMESTAMP_UTC -[ExtraTypeCodecs.zonedTimestampAt(ZoneId)]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#zonedTimestampAt-java.time.ZoneId- -[ExtraTypeCodecs.LOCAL_TIMESTAMP_SYSTEM]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#LOCAL_TIMESTAMP_SYSTEM -[ExtraTypeCodecs.LOCAL_TIMESTAMP_UTC]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#LOCAL_TIMESTAMP_UTC -[ExtraTypeCodecs.localTimestampAt(ZoneId)]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#localTimestampAt-java.time.ZoneId- -[ExtraTypeCodecs.ZONED_TIMESTAMP_PERSISTED]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#ZONED_TIMESTAMP_PERSISTED -[ExtraTypeCodecs.optionalOf(TypeCodec)]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#optionalOf-com.datastax.oss.driver.api.core.type.codec.TypeCodec- -[ExtraTypeCodecs.enumNamesOf(Class)]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#enumNamesOf-java.lang.Class- -[ExtraTypeCodecs.enumOrdinalsOf(Class)]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#enumOrdinalsOf-java.lang.Class- -[ExtraTypeCodecs.json(Class)]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#json-java.lang.Class- -[ExtraTypeCodecs.json(Class, ObjectMapper)]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#json-java.lang.Class-com.fasterxml.jackson.databind.ObjectMapper- - -[TypeCodecs.BLOB]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/TypeCodecs.html#BLOB -[TypeCodecs.TIMESTAMP]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/TypeCodecs.html#TIMESTAMP +[ExtraTypeCodecs]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html +[ExtraTypeCodecs.BLOB_TO_ARRAY]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#BLOB_TO_ARRAY +[ExtraTypeCodecs.BOOLEAN_LIST_TO_ARRAY]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#BOOLEAN_LIST_TO_ARRAY +[ExtraTypeCodecs.BYTE_LIST_TO_ARRAY]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#BYTE_LIST_TO_ARRAY +[ExtraTypeCodecs.SHORT_LIST_TO_ARRAY]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#SHORT_LIST_TO_ARRAY +[ExtraTypeCodecs.INT_LIST_TO_ARRAY]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#INT_LIST_TO_ARRAY +[ExtraTypeCodecs.LONG_LIST_TO_ARRAY]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#LONG_LIST_TO_ARRAY +[ExtraTypeCodecs.FLOAT_LIST_TO_ARRAY]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#FLOAT_LIST_TO_ARRAY +[ExtraTypeCodecs.DOUBLE_LIST_TO_ARRAY]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#DOUBLE_LIST_TO_ARRAY +[ExtraTypeCodecs.listToArrayOf(TypeCodec)]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#listToArrayOf-com.datastax.oss.driver.api.core.type.codec.TypeCodec- +[ExtraTypeCodecs.TIMESTAMP_UTC]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#TIMESTAMP_UTC +[ExtraTypeCodecs.timestampAt(ZoneId)]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#timestampAt-java.time.ZoneId- +[ExtraTypeCodecs.TIMESTAMP_MILLIS_SYSTEM]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#TIMESTAMP_MILLIS_SYSTEM +[ExtraTypeCodecs.TIMESTAMP_MILLIS_UTC]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#TIMESTAMP_MILLIS_UTC +[ExtraTypeCodecs.timestampMillisAt(ZoneId)]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#timestampMillisAt-java.time.ZoneId- +[ExtraTypeCodecs.ZONED_TIMESTAMP_SYSTEM]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#ZONED_TIMESTAMP_SYSTEM +[ExtraTypeCodecs.ZONED_TIMESTAMP_UTC]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#ZONED_TIMESTAMP_UTC +[ExtraTypeCodecs.zonedTimestampAt(ZoneId)]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#zonedTimestampAt-java.time.ZoneId- +[ExtraTypeCodecs.LOCAL_TIMESTAMP_SYSTEM]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#LOCAL_TIMESTAMP_SYSTEM +[ExtraTypeCodecs.LOCAL_TIMESTAMP_UTC]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#LOCAL_TIMESTAMP_UTC +[ExtraTypeCodecs.localTimestampAt(ZoneId)]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#localTimestampAt-java.time.ZoneId- +[ExtraTypeCodecs.ZONED_TIMESTAMP_PERSISTED]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#ZONED_TIMESTAMP_PERSISTED +[ExtraTypeCodecs.optionalOf(TypeCodec)]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#optionalOf-com.datastax.oss.driver.api.core.type.codec.TypeCodec- +[ExtraTypeCodecs.enumNamesOf(Class)]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#enumNamesOf-java.lang.Class- +[ExtraTypeCodecs.enumOrdinalsOf(Class)]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#enumOrdinalsOf-java.lang.Class- +[ExtraTypeCodecs.json(Class)]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#json-java.lang.Class- +[ExtraTypeCodecs.json(Class, ObjectMapper)]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#json-java.lang.Class-com.fasterxml.jackson.databind.ObjectMapper- +[ExtraTypeCodecs.floatVectorToArray(int)]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/ExtraTypeCodecs.html#floatVectorToArray-int- + +[TypeCodecs.BLOB]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/TypeCodecs.html#BLOB +[TypeCodecs.TIMESTAMP]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/TypeCodecs.html#TIMESTAMP [ObjectMapper]: http://fasterxml.github.io/jackson-databind/javadoc/2.10/com/fasterxml/jackson/databind/ObjectMapper.html -[CQL blob example]: https://github.com/datastax/java-driver/blob/4.x/examples/src/main/java/com/datastax/oss/driver/examples/datatypes/Blobs.java \ No newline at end of file +[CQL blob example]: https://github.com/datastax/java-driver/blob/4.x/examples/src/main/java/com/datastax/oss/driver/examples/datatypes/Blobs.java diff --git a/manual/core/detachable_types/README.md b/manual/core/detachable_types/README.md index ec033d6e522..7968835dd8a 100644 --- a/manual/core/detachable_types/README.md +++ b/manual/core/detachable_types/README.md @@ -1,3 +1,22 @@ + + ## Detachable types ### Quick overview @@ -131,19 +150,19 @@ Even then, the defaults used by detached objects might be good enough for you: * the default codec registry works if you don't have any [custom codec](../custom_codecs/); * the binary encoding format is stable across modern protocol versions. The last changes were for - collection encoding from v2 to v3; Java driver 4 only supports v3 and above. When in doubt, check + collection encoding from v2 to v3; Java Driver 4 only supports v3 and above. When in doubt, check the "Changes" section of the [protocol specifications]. Otherwise, just make sure you reattach objects any time you deserialize them or create them from scratch. -[CodecRegistry]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/registry/CodecRegistry.html -[CodecRegistry#DEFAULT]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/registry/CodecRegistry.html#DEFAULT -[DataType]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/DataType.html -[Detachable]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/detach/Detachable.html -[Session]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/session/Session.html -[ColumnDefinition]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/ColumnDefinition.html -[Row]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/Row.html +[CodecRegistry]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/registry/CodecRegistry.html +[CodecRegistry#DEFAULT]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/registry/CodecRegistry.html#DEFAULT +[DataType]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/DataType.html +[Detachable]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/detach/Detachable.html +[Session]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/Session.html +[ColumnDefinition]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/ColumnDefinition.html +[Row]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/Row.html [Java serialization]: https://docs.oracle.com/javase/tutorial/jndi/objects/serial.html [protocol specifications]: https://github.com/datastax/native-protocol/tree/1.x/src/main/resources diff --git a/manual/core/dse/README.md b/manual/core/dse/README.md index e0d41ef38c7..75abeafb3d7 100644 --- a/manual/core/dse/README.md +++ b/manual/core/dse/README.md @@ -1,6 +1,25 @@ + + ## DSE-specific features -Some driver features only work with Datastax Enterprise: +Some driver features only work with DataStax Enterprise: * [Graph](graph/); * [Geospatial types](geotypes/); @@ -8,4 +27,4 @@ Some driver features only work with Datastax Enterprise: Note that, if you don't use these features, you might be able to exclude certain dependencies in order to limit the number of JARs in your classpath. See the -[Integration](../integration/#driver-dependencies) page. \ No newline at end of file +[Integration](../integration/#driver-dependencies) page. diff --git a/manual/core/dse/geotypes/README.md b/manual/core/dse/geotypes/README.md index a37704eede2..eb414de4f8d 100644 --- a/manual/core/dse/geotypes/README.md +++ b/manual/core/dse/geotypes/README.md @@ -1,3 +1,22 @@ + + ## Geospatial types The driver comes with client-side representations of the DSE geospatial data types: [Point], @@ -166,9 +185,9 @@ All geospatial types interoperate with three standard formats: [ESRI]: https://github.com/Esri/geometry-api-java -[LineString]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/data/geometry/LineString.html -[Point]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/data/geometry/Point.html -[Polygon]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/data/geometry/Polygon.html +[LineString]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/data/geometry/LineString.html +[Point]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/data/geometry/Point.html +[Polygon]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/data/geometry/Polygon.html [Well-known text]: https://en.wikipedia.org/wiki/Well-known_text [Well-known binary]: https://en.wikipedia.org/wiki/Well-known_text#Well-known_binary diff --git a/manual/core/dse/graph/README.md b/manual/core/dse/graph/README.md index 145f8a84f38..6bcacd44c4e 100644 --- a/manual/core/dse/graph/README.md +++ b/manual/core/dse/graph/README.md @@ -1,3 +1,22 @@ + + ## Graph The driver provides full support for DSE graph, the distributed graph database available in DataStax @@ -74,8 +93,8 @@ fluent API returns Apache TinkerPop™ types directly. [Apache TinkerPop™]: http://tinkerpop.apache.org/ -[CqlSession]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/CqlSession.html -[GraphSession]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/graph/GraphSession.html +[CqlSession]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/CqlSession.html +[GraphSession]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/graph/GraphSession.html [DSE developer guide]: https://docs.datastax.com/en/dse/6.0/dse-dev/datastax_enterprise/graph/graphTOC.html [Gremlin]: https://docs.datastax.com/en/dse/6.0/dse-dev/datastax_enterprise/graph/dseGraphAbout.html#dseGraphAbout__what-is-cql diff --git a/manual/core/dse/graph/fluent/README.md b/manual/core/dse/graph/fluent/README.md index 072c2193c71..c1645fdb234 100644 --- a/manual/core/dse/graph/fluent/README.md +++ b/manual/core/dse/graph/fluent/README.md @@ -1,3 +1,22 @@ + + ## Fluent API The driver depends on [Apache TinkerPop™], a graph computing framework that provides a fluent API to @@ -109,8 +128,8 @@ All the DSE predicates are available on the driver side: .values("name"); ``` -[Search]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/graph/predicates/Search.html -[Geo]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/graph/predicates/Geo.html +[Search]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/graph/predicates/Search.html +[Geo]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/graph/predicates/Geo.html [Apache TinkerPop™]: http://tinkerpop.apache.org/ [TinkerPop DSL]: http://tinkerpop.apache.org/docs/current/reference/#dsl diff --git a/manual/core/dse/graph/fluent/explicit/README.md b/manual/core/dse/graph/fluent/explicit/README.md index 04b447c7919..163180a4a8a 100644 --- a/manual/core/dse/graph/fluent/explicit/README.md +++ b/manual/core/dse/graph/fluent/explicit/README.md @@ -1,3 +1,22 @@ + + ## Explicit execution Fluent traversals can be wrapped into a [FluentGraphStatement] and passed to the session: @@ -105,9 +124,9 @@ added in a future version. See also the [parent page](../) for topics common to all fluent traversals. -[FluentGraphStatement]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/graph/FluentGraphStatement.html -[FluentGraphStatement.newInstance]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/graph/FluentGraphStatement.html#newInstance-org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal- -[FluentGraphStatement.builder]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/graph/FluentGraphStatement.html#builder-org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal- -[BatchGraphStatement]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/graph/BatchGraphStatement.html -[BatchGraphStatement.newInstance]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/graph/BatchGraphStatement.html#newInstance-- -[BatchGraphStatement.builder]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/graph/BatchGraphStatement.html#builder-- +[FluentGraphStatement]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/graph/FluentGraphStatement.html +[FluentGraphStatement.newInstance]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/graph/FluentGraphStatement.html#newInstance-org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal- +[FluentGraphStatement.builder]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/graph/FluentGraphStatement.html#builder-org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal- +[BatchGraphStatement]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/graph/BatchGraphStatement.html +[BatchGraphStatement.newInstance]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/graph/BatchGraphStatement.html#newInstance-- +[BatchGraphStatement.builder]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/graph/BatchGraphStatement.html#builder-- diff --git a/manual/core/dse/graph/fluent/implicit/README.md b/manual/core/dse/graph/fluent/implicit/README.md index 797189a9ae1..f838c376022 100644 --- a/manual/core/dse/graph/fluent/implicit/README.md +++ b/manual/core/dse/graph/fluent/implicit/README.md @@ -1,3 +1,22 @@ + + ## Implicit execution Instead of passing traversals to the driver, you can create a *remote traversal source* connected to diff --git a/manual/core/dse/graph/options/README.md b/manual/core/dse/graph/options/README.md index ad439448aa0..e4649ff34f3 100644 --- a/manual/core/dse/graph/options/README.md +++ b/manual/core/dse/graph/options/README.md @@ -1,3 +1,22 @@ + + ## Graph options There are various [configuration](../../../configuration/) options that control the execution of @@ -157,4 +176,4 @@ not explicitly set through `advanced.graph.sub-protocol` in configuration, the v which the driver is connected will determine the default sub-protocol version used by the driver. For DSE 6.8.0 and later, the driver will pick "graph-binary-1.0" as the default sub-protocol version. For DSE 6.7.x and older (or in cases where the driver can't determine the DSE version), the -driver will pick "graphson-2.0" as the default sub-protocol version. \ No newline at end of file +driver will pick "graphson-2.0" as the default sub-protocol version. diff --git a/manual/core/dse/graph/results/README.md b/manual/core/dse/graph/results/README.md index 7ac4a6c4e8f..3b4d25fa012 100644 --- a/manual/core/dse/graph/results/README.md +++ b/manual/core/dse/graph/results/README.md @@ -1,3 +1,22 @@ + + ## Handling graph results [Script queries](../script/) and [explicit fluent traversals](../fluent/explicit/) return graph @@ -109,7 +128,7 @@ translate into specific Java classes when the data is returned from the server. Here is an exhaustive compatibility matrix (for DSE 6.0): -| DSE graph | Java driver | +| DSE graph | Java Driver | |------------|---------------------| | bigint | Long | | blob | byte[] | @@ -137,8 +156,8 @@ If a type doesn't have a corresponding `asXxx()` method, use the variant that ta UUID uuid = graphNode.as(UUID.class); ``` -[GraphNode]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/graph/GraphNode.html -[GraphResultSet]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/graph/GraphResultSet.html -[AsyncGraphResultSet]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/graph/AsyncGraphResultSet.html +[GraphNode]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/graph/GraphNode.html +[GraphResultSet]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/graph/GraphResultSet.html +[AsyncGraphResultSet]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/graph/AsyncGraphResultSet.html -[DSE data types]: https://docs.datastax.com/en/dse/6.0/dse-dev/datastax_enterprise/graph/reference/refDSEGraphDataTypes.html \ No newline at end of file +[DSE data types]: https://docs.datastax.com/en/dse/6.0/dse-dev/datastax_enterprise/graph/reference/refDSEGraphDataTypes.html diff --git a/manual/core/dse/graph/script/README.md b/manual/core/dse/graph/script/README.md index 929f80531ca..cec8e4e94ef 100644 --- a/manual/core/dse/graph/script/README.md +++ b/manual/core/dse/graph/script/README.md @@ -1,3 +1,22 @@ + + ## Script API The script API handles Gremlin-groovy requests provided as plain Java strings. To execute a script, @@ -101,6 +120,6 @@ Note however that some types of queries can only be performed through the script * configuration; * DSE graph schema queries. -[ScriptGraphStatement]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/graph/ScriptGraphStatement.html -[ScriptGraphStatement.newInstance]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/graph/ScriptGraphStatement.html#newInstance-java.lang.String- -[ScriptGraphStatement.builder]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/graph/ScriptGraphStatement.html#builder-java.lang.String- \ No newline at end of file +[ScriptGraphStatement]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/graph/ScriptGraphStatement.html +[ScriptGraphStatement.newInstance]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/graph/ScriptGraphStatement.html#newInstance-java.lang.String- +[ScriptGraphStatement.builder]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/graph/ScriptGraphStatement.html#builder-java.lang.String- diff --git a/manual/core/graalvm/README.md b/manual/core/graalvm/README.md new file mode 100644 index 00000000000..d20fb739f19 --- /dev/null +++ b/manual/core/graalvm/README.md @@ -0,0 +1,334 @@ + + +## GraalVM native images + +### Quick overview + +* [GraalVM native images](https://www.graalvm.org/reference-manual/native-image/) can be built with + no additional configuration starting with driver 4.13.0. +* But extra configurations are required in a few cases: + * When using [reactive programming](../reactive); + * When using [Jackson](../integration#Jackson); + * When using LZ4 [compression](../compression/); + * Depending on the [logging backend](../logging) in use. +* DSE-specific features: + * [Geospatial types](../dse/geotypes) are supported. + * [DSE Graph](../dse/graph) is not officially supported, although it may work. +* The [shaded jar](../shaded_jar) is not officially supported, although it may work. + +----- + +### Concepts + +Starting with version 4.13.0, the driver ships with [embedded GraalVM configuration files] that +allow GraalVM native images including the driver to be built without hassle, barring a few +exceptions and caveats listed below. + +[embedded GraalVM configuration files]:https://www.graalvm.org/reference-manual/native-image/BuildConfiguration/#embedding-a-configuration-file + +### Classes instantiated by reflection + +The driver instantiates its components by reflection. The actual classes that will be instantiated +in this way need to be registered for reflection. All built-in implementations of various driver +components, such as `LoadBalancingPolicy` or `TimestampGenerator`, are automatically registered for +reflection, along with a few other internal components tha are also instantiated by reflection. +_You don't need to manually register any of these built-in implementations_. + +But if you intend to use a custom implementation in lieu of a driver built-in class, then it is your +responsibility to register that custom implementation for reflection. + +For example, assuming that you have the following load balancing policy implementation: + +```java + +package com.example.app; + +import com.datastax.oss.driver.api.core.context.DriverContext; +import com.datastax.oss.driver.api.core.metadata.Node; +import com.datastax.oss.driver.internal.core.loadbalancing.DefaultLoadBalancingPolicy; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; + +public class CustomLoadBalancingPolicy extends DefaultLoadBalancingPolicy { + + public CustomLoadBalancingPolicy(DriverContext context, String profileName) { + super(context, profileName); + } + // rest of class omitted for brevity +} +``` + +And assuming that you declared the above class in your application.conf file as follows: + +```hocon +datastax-java-driver.basic{ + load-balancing-policy.class = com.example.app.CustomLoadBalancingPolicy +} +``` + +Then you will have to register that class for reflection: + +1. Create the following reflection.json file, or add the entry to an existing file: + +```json +[ + { "name": "com.example.app.CustomLoadBalancingPolicy", "allPublicConstructors": true } +] +``` + +2. When invoking the native image builder, add a `-H:ReflectionConfigurationFiles=reflection.json` + flag and point it to the file created above. + +Note: some frameworks allow you to simplify the registration process. For example, Quarkus offers +the `io.quarkus.runtime.annotations.RegisterForReflection` annotation that you can use to annotate +your class: + +```java +@RegisterForReflection +public class CustomLoadBalancingPolicy extends DefaultLoadBalancingPolicy { + //... +} +``` + +In this case, no other manual configuration is required for the above class to be correctly +registered for reflection. + +### Configuration resources + +The default driver [configuration](../configuration) mechanism is based on the TypeSafe Config +library. TypeSafe Config looks for a few classpath resources when initializing the configuration: +`reference.conf`, `application.conf`, `application.json`, `application.properties`. _These classpath +resources are all automatically included in the native image: you should not need to do it +manually_. See [Accessing Resources in Native Images] for more information on how classpath +resources are handled in native images. + +[Accessing Resources in Native Images]: https://www.graalvm.org/reference-manual/native-image/Resources/ + +### Configuring the logging backend + +When configuring [logging](../logging), the choice of a backend must be considered carefully, as +most logging backends resort to reflection during their configuration phase. + +By default, GraalVM native images provide support for the java.util.logging (JUL) backend. See +[this page](https://www.graalvm.org/reference-manual/native-image/Logging/) for more information. + +For other logging backends, please refer to the logging library documentation to find out if GraalVM +native images are supported. + +### Using reactive-style programming + +The [reactive execution model](../reactive) is compatible with GraalVM native images, but the +following configurations must be added: + +1. Create the following reflection.json file, or add the entry to an existing file: + +```json +[ + { "name": "org.reactivestreams.Publisher" } +] +``` + +2. When invoking the native image builder, add a `-H:ReflectionConfigurationFiles=reflection.json` + flag and point it to the file created above. + +### Using the Jackson JSON library + +[Jackson](https://github.com/FasterXML/jackson) is used in [a few places](../integration#jackson) in +the driver, but is an optional dependency; if you intend to use Jackson, the following +configurations must be added: + +1. Create the following reflection.json file, or add these entries to an existing file: + +```json +[ + { "name": "com.fasterxml.jackson.core.JsonParser" }, + { "name": "com.fasterxml.jackson.databind.ObjectMapper" } +] +``` + +**Important**: when using the shaded jar – which is not officially supported on GraalVM native +images, see below for more details – replace the above entries with the below ones: + +```json +[ + { "name": "com.datastax.oss.driver.shaded.fasterxml.jackson.core.JsonParser" }, + { "name": "com.datastax.oss.driver.shaded.fasterxml.jackson.databind.ObjectMapper" } +] +``` +2. When invoking the native image builder, add a `-H:ReflectionConfigurationFiles=reflection.json` + flag and point it to the file created above. + +### Enabling compression + +When using [compression](../compression/), only LZ4 can be enabled in native images. **Snappy +compression is not supported.** + +In order for LZ4 compression to work in a native image, the following additional GraalVM +configuration is required: + +1. Create the following reflection.json file, or add these entries to an existing file: + +```json +[ + { "name" : "net.jpountz.lz4.LZ4Compressor" }, + { + "name" : "net.jpountz.lz4.LZ4JNICompressor", + "allDeclaredConstructors": true, + "allPublicFields": true + }, + { + "name" : "net.jpountz.lz4.LZ4JavaSafeCompressor", + "allDeclaredConstructors": true, + "allPublicFields": true + }, + { + "name" : "net.jpountz.lz4.LZ4JavaUnsafeCompressor", + "allDeclaredConstructors": true, + "allPublicFields": true + }, + { + "name" : "net.jpountz.lz4.LZ4HCJavaSafeCompressor", + "allDeclaredConstructors": true, + "allPublicFields": true + }, + { + "name" : "net.jpountz.lz4.LZ4HCJavaUnsafeCompressor", + "allDeclaredConstructors": true, + "allPublicFields": true + }, + { + "name" : "net.jpountz.lz4.LZ4JavaSafeSafeDecompressor", + "allDeclaredConstructors": true, + "allPublicFields": true + }, + { + "name" : "net.jpountz.lz4.LZ4JavaSafeFastDecompressor", + "allDeclaredConstructors": true, + "allPublicFields": true + }, + { + "name" : "net.jpountz.lz4.LZ4JavaUnsafeSafeDecompressor", + "allDeclaredConstructors": true, + "allPublicFields": true + }, + { + "name" : "net.jpountz.lz4.LZ4JavaUnsafeFastDecompressor", + "allDeclaredConstructors": true, + "allPublicFields": true + } +] +``` + +2. When invoking the native image builder, add a `-H:ReflectionConfigurationFiles=reflection.json` + flag and point it to the file created above. + +### Native calls + +The driver performs a few [native calls](../integration#native-libraries) using +[JNR](https://github.com/jnr). + +Starting with driver 4.7.0, native calls are also possible in a GraalVM native image, without any +extra configuration. + +### Using DataStax Enterprise (DSE) features + +#### DSE Geospatial types + +DSE [Geospatial types](../dse/geotypes) are supported on GraalVM native images; the following +configurations must be added: + +1. Create the following reflection.json file, or add the entry to an existing file: + +```json +[ + { "name": "com.esri.core.geometry.ogc.OGCGeometry" } +] +``` + +**Important**: when using the shaded jar – which is not officially supported on GraalVM native +images, as stated above – replace the above entry with the below one: + +```json +[ + { "name": "com.datastax.oss.driver.shaded.esri.core.geometry.ogc.OGCGeometry" } +] +``` + +2. When invoking the native image builder, add a `-H:ReflectionConfigurationFiles=reflection.json` + flag and point it to the file created above. + +#### DSE Graph + +**[DSE Graph](../dse/graph) is not officially supported on GraalVM native images.** + +The following configuration can be used as a starting point for users wishing to build a native +image for a DSE Graph application. DataStax does not guarantee however that the below configuration +will work in all cases. If the native image build fails, a good option is to use GraalVM's +[Tracing Agent](https://www.graalvm.org/reference-manual/native-image/Agent/) to understand why. + +1. Create the following reflection.json file, or add these entries to an existing file: + +```json +[ + { "name": "org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV3d0" }, + { "name": "org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal" }, + { "name": "org.apache.tinkerpop.gremlin.structure.Graph", + "allDeclaredConstructors": true, + "allPublicConstructors": true, + "allDeclaredMethods": true, + "allPublicMethods": true + }, + { "name": "org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph", + "allDeclaredConstructors": true, + "allPublicConstructors": true, + "allDeclaredMethods": true, + "allPublicMethods": true + }, + { "name": " org.apache.tinkerpop.gremlin.structure.util.empty.EmptyGraph", + "allDeclaredConstructors": true, + "allPublicConstructors": true, + "allDeclaredMethods": true, + "allPublicMethods": true + }, + { "name": "org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource", + "allDeclaredConstructors": true, + "allPublicConstructors": true, + "allDeclaredMethods": true, + "allPublicMethods": true + } +] +``` + +2. When invoking the native image builder, add the following flags: + +``` +-H:ReflectionConfigurationFiles=reflection.json +--initialize-at-build-time=org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerIoRegistryV3d0 +--initialize-at-build-time=org.apache.tinkerpop.shaded.jackson.databind.deser.std.StdDeserializer +``` + +### Using the shaded jar + +**The [shaded jar](../shaded_jar) is not officially supported in a GraalVM native image.** + +However, it has been reported that the shaded jar can be included in a GraalVM native image as a +drop-in replacement for the regular driver jar for simple applications, without any extra GraalVM +configuration. diff --git a/manual/core/idempotence/README.md b/manual/core/idempotence/README.md index fdddaff26f8..be784dfa40b 100644 --- a/manual/core/idempotence/README.md +++ b/manual/core/idempotence/README.md @@ -1,3 +1,22 @@ + + ## Query idempotence ### Quick overview @@ -60,5 +79,5 @@ assert bs.isIdempotent(); The query builder tries to infer idempotence automatically; refer to [its manual](../../query_builder/idempotence/) for more details. -[Statement.setIdempotent]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/Statement.html#setIdempotent-java.lang.Boolean- -[StatementBuilder.setIdempotence]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/StatementBuilder.html#setIdempotence-java.lang.Boolean- +[Statement.setIdempotent]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/Statement.html#setIdempotent-java.lang.Boolean- +[StatementBuilder.setIdempotence]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/StatementBuilder.html#setIdempotence-java.lang.Boolean- diff --git a/manual/core/integration/README.md b/manual/core/integration/README.md index 382983a106d..e2c7bc218ee 100644 --- a/manual/core/integration/README.md +++ b/manual/core/integration/README.md @@ -1,3 +1,22 @@ + + ## Integration ### Quick overview @@ -6,6 +25,8 @@ * explanations about [driver dependencies](#driver-dependencies) and when they can be manually excluded. +Note: guidelines to build a GraalVM native image can be found [here](../graalvm). + ----- ### Which artifact(s) should I use? @@ -56,6 +77,20 @@ right dependencies: See this page. + + + Instrumenting the driver and gathering metrics using the Micrometer metrics library. + + java‑driver‑metrics‑micrometer + See this page. + + + + Instrumenting the driver and gathering metrics using the MicroProfile Metrics library. + + java‑driver‑metrics‑microprofile + See this page. + "Bill Of Materials": can help manage versions if you use multiple driver artifacts. @@ -114,7 +149,7 @@ dependencies, and tell Maven that we're going to use Java 8: - com.datastax.oss + org.apache.cassandra java-driver-core ${driver.version} @@ -221,7 +256,7 @@ You should see output similar to: [INFO] Nothing to compile - all classes are up to date [INFO] [INFO] --- exec-maven-plugin:1.3.1:java (default-cli) @ yourapp --- -11:39:45.355 [Main.main()] INFO c.d.o.d.i.c.DefaultMavenCoordinates - DataStax Java driver for Apache Cassandra(R) (com.datastax.oss:java-driver-core) version 4.0.1 +11:39:45.355 [Main.main()] INFO c.d.o.d.i.c.DefaultMavenCoordinates - Apache Cassandra Java Driver (com.datastax.oss:java-driver-core) version 4.0.1 11:39:45.648 [poc-admin-0] INFO c.d.o.d.internal.core.time.Clock - Using native clock for microsecond precision 11:39:45.649 [poc-admin-0] INFO c.d.o.d.i.c.metadata.MetadataManager - [poc] No contact points provided, defaulting to /127.0.0.1:9042 3.11.2 @@ -291,7 +326,7 @@ $ ./gradlew execute :processResources :classes :execute -13:32:25.339 [main] INFO c.d.o.d.i.c.DefaultMavenCoordinates - DataStax Java driver for Apache Cassandra(R) (com.datastax.oss:java-driver-core) version 4.0.1-alpha4-SNAPSHOT +13:32:25.339 [main] INFO c.d.o.d.i.c.DefaultMavenCoordinates - Apache Cassandra Java Driver (com.datastax.oss:java-driver-core) version 4.0.1-alpha4-SNAPSHOT 13:32:25.682 [poc-admin-0] INFO c.d.o.d.internal.core.time.Clock - Using native clock for microsecond precision 13:32:25.683 [poc-admin-0] INFO c.d.o.d.i.c.metadata.MetadataManager - [poc] No contact points provided, defaulting to /127.0.0.1:9042 3.11.2 @@ -339,7 +374,7 @@ In that case, you can exclude the dependency: ```xml - com.datastax.oss + org.apache.cassandra java-driver-core ${driver.version} @@ -367,7 +402,7 @@ are not available on your platform, you can exclude the following dependency: ```xml - com.datastax.oss + org.apache.cassandra java-driver-core ${driver.version} @@ -381,7 +416,7 @@ are not available on your platform, you can exclude the following dependency: #### Compression libraries -The driver supports compression with either [LZ4](https://github.com/jpountz/lz4-java) or +The driver supports compression with either [LZ4](https://github.com/yawkat/lz4-java) or [Snappy](http://google.github.io/snappy/). These dependencies are optional; you have to add them explicitly in your application in order to @@ -390,16 +425,15 @@ enable compression. See the [Compression](../compression/) page for more details #### Metrics The driver exposes [metrics](../metrics/) through the -[Dropwizard](http://metrics.dropwizard.io/4.0.0/manual/index.html) library. +[Dropwizard](http://metrics.dropwizard.io/4.1.2/) library. The dependency is declared as required, but metrics are optional. If you've disabled all metrics, or -if you are using a [different metrics framework](../metrics/#changing-the-metrics-frameworks), and -you never call [Session.getMetrics] anywhere in your application, then you can remove the -dependency: +if you are using a different metrics library, and you never call [Session.getMetrics] anywhere in +your application, then you can remove the dependency: ```xml - com.datastax.oss + org.apache.cassandra java-driver-core ${driver.version} @@ -411,16 +445,18 @@ dependency: ``` -In addition, "timer" metrics use [HdrHistogram](http://hdrhistogram.github.io/HdrHistogram/) to -record latency percentiles. At the time of writing, these metrics are: `cql-requests`, -`throttling.delay` and `cql-messages`; you can also identify them by reading the comments in the -[configuration reference](../configuration/reference/) (look for "exposed as a Timer"). +In addition, when using Dropwizard, "timer" metrics use +[HdrHistogram](http://hdrhistogram.github.io/HdrHistogram/) to record latency percentiles. At the +time of writing, these metrics are: `cql-requests`, `throttling.delay` and `cql-messages`; you can +also identify them by reading the comments in the [configuration +reference](../configuration/reference/) (look for "exposed as a Timer"). -If all of these metrics are disabled, you can remove the dependency: +If all of these metrics are disabled, or if you use a different metrics library, you can remove the +dependency: ```xml - com.datastax.oss + org.apache.cassandra java-driver-core ${driver.version} @@ -436,15 +472,16 @@ If all of these metrics are disabled, you can remove the dependency: [Jackson](https://github.com/FasterXML/jackson) is used: -* when connecting to [Datastax Astra](../../cloud/); +* when connecting to [DataStax Astra](../../cloud/); * when Insights monitoring is enabled; * when [Json codecs](../custom_codecs) are being used. -If you don't use either of those features, you can safely exclude the dependency: +Jackson is declared as a required dependency, but the driver can operate normally without it. If you +don't use any of the above features, you can safely exclude the dependency: ```xml - com.datastax.oss + org.apache.cassandra java-driver-core ${driver.version} @@ -461,31 +498,53 @@ If you don't use either of those features, you can safely exclude the dependency Our [geospatial types](../dse/geotypes/) implementation is based on the [Esri Geometry API](https://github.com/Esri/geometry-api-java). -If you don't use geospatial types anywhere in your application, you can exclude the dependency: +For driver versions >= 4.4.0 and < 4.14.0 Esri is declared as a required dependency, +although the driver can operate normally without it. If you don't use geospatial types +anywhere in your application you can exclude the dependency: ```xml - com.datastax.oss + org.apache.cassandra java-driver-core ${driver.version} com.esri.geometry - esri-geometry-api + * ``` +Starting with driver 4.14.0 Esri has been changed to an optional dependency. You no longer have to +explicitly exclude the dependency if it's not used, but if you do wish to make use of the Esri +library you must now explicitly specify it as a dependency : + +```xml + + com.esri.geometry + esri-geometry-api + ${esri.version} + +``` + +In the dependency specification above you should use any 1.2.x version of Esri (we recommend +1.2.1). These versions are older than the current 2.x versions of the library but they are +guaranteed to be fully compatible with DSE. + #### TinkerPop -[Apache TinkerPop™](http://tinkerpop.apache.org/) is used in our [graph API](../dse/graph/). +[Apache TinkerPop™](http://tinkerpop.apache.org/) is used in our [graph API](../dse/graph/), +introduced in the OSS driver in version 4.4.0 (it was previously a feature only available in the +now-retired DSE driver). -If you don't use DSE graph at all, you can exclude the dependencies: +For driver versions ranging from 4.4.0 to 4.9.0 inclusive, TinkerPop is declared as a required +dependency, but the driver can operate normally without it. If you don't use the graph API at all, +you can exclude the TinkerPop dependencies: ```xml - com.datastax.oss + org.apache.cassandra java-driver-core ${driver.version} @@ -497,21 +556,59 @@ If you don't use DSE graph at all, you can exclude the dependencies: ``` +Starting with driver 4.10 however, TinkerPop switched to an optional dependency. Excluding TinkerPop +explicitly is not required anymore if you don't use it. _If you do use the graph API though, you now +need to explicitly include the dependencies below in your application_: + +```xml + + org.apache.tinkerpop + gremlin-core + ${tinkerpop.version} + + + org.apache.tinkerpop + tinkergraph-gremlin + ${tinkerpop.version} + +``` + If you do use graph, it is important to keep the precise TinkerPop version that the driver depends on: unlike the driver, TinkerPop does not follow semantic versioning, so even a patch version change -(e.g. 3.3.0 vs 3.3.3) could introduce incompatibilities. So do not declare an explicit dependency in -your application, let the driver pull it transitively. +(e.g. 3.3.0 vs 3.3.3) could introduce incompatibilities. + +Here are the recommended TinkerPop versions for each driver version: + + + + + + + + + + + + + + + + + + +
    Driver versionTinkerPop version
    4.17.03.5.3
    4.16.03.5.3
    4.15.03.5.3
    4.14.13.5.3
    4.14.03.4.10
    4.13.03.4.10
    4.12.03.4.10
    4.11.03.4.10
    4.10.03.4.9
    4.9.03.4.8
    4.8.03.4.5
    4.7.03.4.5
    4.6.03.4.5
    4.5.03.4.5
    4.4.03.3.3
    #### Reactive Streams [Reactive Streams](https://www.reactive-streams.org/) types are referenced in our [reactive API](../reactive/). -If you never call any of the `executeReactive` methods, you can exclude the dependency: +The Reactive Streams API is declared as a required dependency, but the driver can operate normally +without it. If you never call any of the `executeReactive` methods, you can exclude the dependency: ```xml - com.datastax.oss + org.apache.cassandra java-driver-core ${driver.version} @@ -532,25 +629,22 @@ The driver team uses annotations to document certain aspects of the code: * nullability with [SpotBugs](https://spotbugs.github.io/) annotations `@Nullable` and `@NonNull`. This is mostly used during development; while these annotations are retained in class files, they -serve no purpose at runtime. If you want to minimize the number of JARs in your classpath, you can -exclude them: +serve no purpose at runtime. This class is an optional dependency of the driver. If you wish to +make use of these annotations in your own code you have to explicitly depend on these jars: ```xml - - com.datastax.oss - java-driver-core - ${driver.version} - - - com.github.stephenc.jcip - jcip-annotations - - - com.github.spotbugs - spotbugs-annotations - - - + + + com.github.stephenc.jcip + jcip-annotations + 1.0-1 + + + com.github.spotbugs + spotbugs-annotations + 3.1.12 + + ``` However, there is one case when excluding those dependencies won't work: if you use [annotation @@ -577,7 +671,7 @@ The remaining core driver dependencies are the only ones that are truly mandator * the [native protocol](https://github.com/datastax/native-protocol) layer. This is essentially part of the driver code, but was externalized for reuse in other projects; -* `java-driver-shaded-guava`, a shaded version of [Guava](https://github.com/google/guava). It is +* `java-driver-guava-shaded`, a shaded version of [Guava](https://github.com/google/guava). It is relocated to a different package, and only used by internal driver code, so it should be completely transparent to third-party code; * the [SLF4J](https://www.slf4j.org/) API for [logging](../logging/). @@ -589,6 +683,6 @@ The remaining core driver dependencies are the only ones that are truly mandator [guava]: https://github.com/google/guava/issues/2721 [annotation processing]: https://docs.oracle.com/javase/8/docs/technotes/tools/windows/javac.html#sthref65 -[Session.getMetrics]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/session/Session.html#getMetrics-- -[SessionBuilder.addContactPoint]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/session/SessionBuilder.html#addContactPoint-java.net.InetSocketAddress- -[Uuids]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/uuid/Uuids.html +[Session.getMetrics]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/Session.html#getMetrics-- +[SessionBuilder.addContactPoint]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/SessionBuilder.html#addContactPoint-java.net.InetSocketAddress- +[Uuids]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/uuid/Uuids.html diff --git a/manual/core/load_balancing/README.md b/manual/core/load_balancing/README.md index dbb22712e32..3f391c14f56 100644 --- a/manual/core/load_balancing/README.md +++ b/manual/core/load_balancing/README.md @@ -1,3 +1,22 @@ + + ## Load balancing ### Quick overview @@ -37,6 +56,9 @@ For each node, the policy computes a *distance* that determines how connections Typically, the distance will reflect network topology (e.g. local vs. remote datacenter), although that is entirely up to each policy implementation. It can also change over time. +The driver built-in policies only ever assign the `LOCAL` or `IGNORED` distance, to avoid cross- +datacenter traffic (see below to understand how to change this behavior). + #### Query plan Each time the driver executes a query, it asks the policy to compute a *query plan*, in other words @@ -50,23 +72,40 @@ return plans that: * only contain nodes that are known to be able to process queries, i.e. neither ignored nor down; * favor local nodes over remote ones. -### Default policy +### Built-in policies In previous versions, the driver provided a wide variety of built-in load balancing policies; in addition, they could be nested into each other, yielding an even higher number of choices. In our experience, this has proven to be too complicated: it's not obvious which policy(ies) to choose for -a given use case, and nested policies can sometimes affect each other's effects in subtle and hard -to predict ways. - -In driver 4+, we are taking a more opinionated approach: we provide a default load balancing policy, -that we consider the best choice for most cases. You can still write a -[custom implementation](#custom-implementation) if you have special requirements. - -#### Local only - -The default policy **only connects to a single datacenter**. The rationale is that a typical -multi-region deployment will collocate one or more application instances with each Cassandra -datacenter: +a given use case, and nested policies can sometimes affect each other's effects in subtle and hard- +to-predict ways. + +In driver 4+, we are taking a different approach: we provide only a handful of load balancing +policies, that we consider the best choices for most cases: + +- `DefaultLoadBalancingPolicy` should almost always be used; it requires a local datacenter to be + specified either programmatically when creating the session, or via the configuration (see below). + It can also use a highly efficient slow replica avoidance mechanism, which is by default enabled. +- `DcInferringLoadBalancingPolicy` is similar to `DefaultLoadBalancingPolicy`, but does not require + a local datacenter to be defined, in which case it will attempt to infer the local datacenter from + the provided contact points. If that's not possible, it will throw an error during session + initialization. This policy is intended mostly for ETL tools and is not recommended for normal + applications. +- `BasicLoadBalancingPolicy` is similar to `DefaultLoadBalancingPolicy`, but does not have the slow + replica avoidance mechanism. More importantly, it is the only policy capable of operating without + local datacenter defined, in which case it will consider nodes in the cluster in a datacenter- + agnostic way. Beware that this could cause spikes in cross-datacenter traffic! This policy is + provided mostly as a starting point for users wishing to implement their own load balancing + policy; it should not be used as is in normal applications. + +You can still write a [custom implementation](#custom-implementation) if you have special +requirements. + +#### Datacenter locality + +By default, both `DefaultLoadBalancingPolicy` and `DcInferringLoadBalancingPolicy` **only connect to +a single datacenter**. The rationale is that a typical multi-region deployment will collocate one or +more application instances with each Cassandra datacenter: ```ditaa /----+----\ @@ -96,14 +135,7 @@ datacenter: +-------------------+ +-------------------+ ``` -In previous driver versions, you could configure application-level failover, such as: "if all the -Cassandra nodes in DC1 are down, allow app1 to connect to the nodes in DC2". We now believe that -this is not the right place to handle this: if a whole datacenter went down at once, it probably -means a catastrophic failure happened in Region1, and the application node is down as well. -Failover should be cross-region instead (handled by the load balancer in this example). - -Therefore the default policy does not allow remote nodes; it only ever assigns the `LOCAL` or -`IGNORED` distance. You **must** provide a local datacenter name, either in the configuration: +When using these policies you **must** provide a local datacenter name, either in the configuration: ``` datastax-java-driver.basic.load-balancing-policy { @@ -126,7 +158,7 @@ that case, the driver will connect to 127.0.0.1:9042, and use that node's datace for a better out-of-the-box experience for users who have just downloaded the driver; beyond that initial development phase, you should provide explicit contact points and a local datacenter. -#### Finding the local datacenter +##### Finding the local datacenter To check which datacenters are defined in a given cluster, you can run [`nodetool status`]. It will print information about each node in the cluster, grouped by datacenters. Here is an example: @@ -165,6 +197,82 @@ data_center DC1 ``` +#### Cross-datacenter failover + +Since the driver by default only contacts nodes in the local datacenter, what happens if the whole +datacenter is down? Resuming the example shown in the diagram above, shouldn't the driver +temporarily allow app1 to connect to the nodes in DC2? + +We believe that, while appealing by its simplicity, such ability is not the right way to handle a +datacenter failure: resuming our example above, if the whole DC1 datacenter went down at once, it +probably means a catastrophic failure happened in Region1, and the application node is down as well. +Failover should be cross-region instead (handled by the load balancer in the above example). + +However, due to popular demand, starting with driver 4.10, we re-introduced cross-datacenter +failover in the driver built-in load balancing policies. + +Cross-datacenter failover is enabled with the following configuration option: + +``` +datastax-java-driver.advanced.load-balancing-policy.dc-failover { + max-nodes-per-remote-dc = 2 +} +``` + +The default for `max-nodes-per-remote-dc` is zero, which means that failover is disabled. Setting +this option to any value greater than zero will have the following effects: + +- The load balancing policies will assign the `REMOTE` distance to that many nodes *in each remote + datacenter*. +- The driver will then attempt to open connections to those nodes. The actual number of connections + to open to each one of those nodes is configurable, see [Connection pools](../pooling/) for + more details. By default, the driver opens only one connection to each node. +- Those remote nodes (and only those) will then become eligible for inclusion in query plans, + effectively enabling cross-datacenter failover. + +Beware that enabling such failover can result in cross-datacenter network traffic spikes, if the +local datacenter is down or experiencing high latencies! + +Cross-datacenter failover can also have unexpected consequences when using local consistency levels +(LOCAL_ONE, LOCAL_QUORUM and LOCAL_SERIAL). Indeed, a local consistency level may have different +semantics depending on the replication factor (RF) in use in each datacenter: if the local DC has +RF=3 for a given keyspace, but the remote DC has RF=1 for it, achieving LOCAL_QUORUM in the local DC +means 2 replicas required, but in the remote DC, only one will be required. + +For this reason, cross-datacenter failover for local consistency levels is disabled by default. If +you want to enable this and understand the consequences, then set the following option to true: + +``` +datastax-java-driver.advanced.load-balancing-policy.dc-failover { + allow-for-local-consistency-levels = true +} +``` + +##### Alternatives to driver-level cross-datacenter failover + +Before you jump into the failover technique explained above, please also consider the following +alternatives: + +1. **Application-level failover**: instead of letting the driver do the failover, implement the +failover logic in your application. Granted, this solution wouldn't be much better if the +application servers are co-located with the Cassandra datacenter itself. It's also a bit more work, +but at least, you would have full control over the failover procedure: you could for example decide, +based on the exact error that prevented the local datacenter from fulfilling a given request, +whether a failover would make sense, and which remote datacenter to use for that specific request. +Such a fine-grained logic is not possible with a driver-level failover. Besides, if you opt for this +approach, execution profiles can come in handy. See "Using multiple policies" below and also check +our [application-level failover example] for a good starting point. + +2. **Infrastructure-level failover**: in this scenario, the failover is handled by the +infrastructure. To resume our example above, if Region1 goes down, the load balancers in your +infrastructure would transparently switch all the traffic intended for that region to Region2, +possibly scaling up its bandwidth to cope with the network traffic spike. This is by far the best +solution for the cross-datacenter failover issue in general, but we acknowledge that it also +requires a purpose-built infrastructure. To help you explore this option, read our [white paper]. + +[application-level failover example]: https://github.com/datastax/java-driver/blob/4.x/examples/src/main/java/com/datastax/oss/driver/examples/failover/CrossDatacenterFailover.java +[white paper]: https://www.datastax.com/sites/default/files/content/whitepaper/files/2019-09/Designing-Fault-Tolerant-Applications-DataStax.pdf + #### Token-aware The default policy is **token-aware** by default: requests will be routed in priority to the @@ -242,49 +350,63 @@ routing information, you need to provide it manually. ##### Policy behavior When the policy computes a query plan, it first inspects the statement's routing information. If -there isn't any, the query plan is a simple round-robin shuffle of all connected nodes. +there isn't any, the query plan is a simple round-robin shuffle of all connected nodes that are +located in the local datacenter. + +If the statement has routing information, the policy uses it to determine the *local* replicas that +hold the corresponding data. Then it returns a query plan containing these replicas shuffled in +random order, followed by a round-robin shuffle of the rest of the nodes. -If the statement has routing information, the policy uses it to determine the replicas that hold the -corresponding data. Then it returns a query plan containing the replicas shuffled in random order, -followed by a round-robin shuffle of the rest of the nodes. +If cross-datacenter failover has been activated as explained above, some remote nodes may appear in +query plans as well. With the driver built-in policies, remote nodes always come after local nodes +in query plans: this way, if the local datacenter is up, local nodes will be tried first, and remote +nodes are unlikely to ever be queried. If the local datacenter goes down however, all the local +nodes in query plans will likely fail, causing the query plans to eventually try remote nodes +instead. If the local datacenter unavailability persists, local nodes will be eventually marked down +and will be removed from query plans completely from query plans, until they are back up again. -#### Optional node filtering +#### Customizing node distance assignment -Finally, the default policy accepts an optional node filter that gets applied just after the test -for inclusion in the local DC. If a node doesn't pass this test, it will be set at distance -`IGNORED` and the driver will never try to connect to it. This is a good way to exclude nodes on -some custom criteria. +Finally, all the driver the built-in policies accept an optional node distance evaluator that gets +invoked each time a node is added to the cluster or comes back up. If the evaluator returns a +non-null distance for the node, that distance will be used, otherwise the driver will use its +built-in logic to assign a default distance to it. This is a good way to exclude nodes or to adjust +their distance according to custom, dynamic criteria. -You can pass the filter through the configuration: +You can pass the node distance evaluator through the configuration: ``` datastax-java-driver.basic.load-balancing-policy { class = DefaultLoadBalancingPolicy local-datacenter = datacenter1 - filter-class = com.acme.MyNodeFilter + evaluator.class = com.acme.MyNodeDistanceEvaluator } ``` -The filter class must implement `java.util.function.predicate`, and have a public constructor -that takes a [DriverContext] argument: `public MyNodeFilter(DriverContext context)`. +The node distance evaluator class must implement [NodeDistanceEvaluator], and have a public +constructor that takes a [DriverContext] argument: `public MyNodeDistanceEvaluator(DriverContext +context)`. -Sometimes it's more convenient to pass the filter programmatically; you can do that with -`SessionBuilder.withNodeFilter`: +Sometimes it's more convenient to pass the evaluator programmatically; you can do that with +`SessionBuilder.withNodeDistanceEvaluator`: ```java -List whiteList = ... +Map distances = ... CqlSession session = CqlSession.builder() - .withNodeFilter(whiteList::contains) + .withNodeDistanceEvaluator((node, dc) -> distances.get(node)) .build(); ``` -If a programmatic filter is provided, the configuration option is ignored. +If a programmatic node distance evaluator evaluator is provided, the configuration option is +ignored. ### Custom implementation You can use your own implementation by specifying its fully-qualified name in the configuration. -Study the [LoadBalancingPolicy] interface and the default implementation for the low-level details. +Study the [LoadBalancingPolicy] interface and the built-in [BasicLoadingBalancingPolicy] for the +low-level details. Feel free to extend `BasicLoadingBalancingPolicy` and override only the methods +that you wish to modify – but keep in mind that it may be simpler to just start from scratch. ### Using multiple policies @@ -323,10 +445,12 @@ Then it uses the "closest" distance for any given node. For example: * policy1 changes its suggestion to IGNORED. node1 is set to REMOTE; * policy1 changes its suggestion to REMOTE. node1 stays at REMOTE. -[DriverContext]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/context/DriverContext.html -[LoadBalancingPolicy]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/loadbalancing/LoadBalancingPolicy.html -[getRoutingKeyspace()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/session/Request.html#getRoutingKeyspace-- -[getRoutingToken()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/session/Request.html#getRoutingToken-- -[getRoutingKey()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/session/Request.html#getRoutingKey-- +[DriverContext]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/context/DriverContext.html +[LoadBalancingPolicy]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/loadbalancing/LoadBalancingPolicy.html +[BasicLoadBalancingPolicy]: https://github.com/datastax/java-driver/blob/4.x/core/src/main/java/com/datastax/oss/driver/internal/core/loadbalancing/BasicLoadBalancingPolicy.java +[getRoutingKeyspace()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/Request.html#getRoutingKeyspace-- +[getRoutingToken()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/Request.html#getRoutingToken-- +[getRoutingKey()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/Request.html#getRoutingKey-- +[NodeDistanceEvaluator]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/loadbalancing/NodeDistanceEvaluator.html [`nodetool status`]: https://docs.datastax.com/en/dse/6.7/dse-dev/datastax_enterprise/tools/nodetool/toolsStatus.html [cqlsh]: https://docs.datastax.com/en/dse/6.7/cql/cql/cql_using/startCqlshStandalone.html diff --git a/manual/core/logging/README.md b/manual/core/logging/README.md index ff0ee5303b6..e3f8bfa7777 100644 --- a/manual/core/logging/README.md +++ b/manual/core/logging/README.md @@ -1,3 +1,22 @@ + + ## Logging ### Quick overview @@ -215,4 +234,4 @@ console). [SLF4J]: https://www.slf4j.org/ [binding]: https://www.slf4j.org/manual.html#swapping [Logback]: http://logback.qos.ch -[Log4J]: https://logging.apache.org/log4j \ No newline at end of file +[Log4J]: https://logging.apache.org/log4j diff --git a/manual/core/metadata/README.md b/manual/core/metadata/README.md index 79cfc96524f..73609ee0542 100644 --- a/manual/core/metadata/README.md +++ b/manual/core/metadata/README.md @@ -1,3 +1,22 @@ + + ## Metadata ### Quick overview @@ -56,6 +75,6 @@ new keyspace in the schema metadata before the token metadata was updated. Schema and node state events are debounced. This allows you to control how often the metadata gets refreshed. See the [Performance](../performance/#debouncing) page for more details. -[Session#getMetadata]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/session/Session.html#getMetadata-- -[Metadata]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/metadata/Metadata.html -[Node]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/metadata/Node.html \ No newline at end of file +[Session#getMetadata]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/Session.html#getMetadata-- +[Metadata]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/metadata/Metadata.html +[Node]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/metadata/Node.html diff --git a/manual/core/metadata/node/README.md b/manual/core/metadata/node/README.md index 49da884802b..fea04e5f262 100644 --- a/manual/core/metadata/node/README.md +++ b/manual/core/metadata/node/README.md @@ -1,3 +1,22 @@ + + ## Node metadata ### Quick overview @@ -7,7 +26,7 @@ actively connected). * [Node] instances are mutable, the fields will update in real time. * getting notifications: - [CqlSession.builder().withNodeStateListener][SessionBuilder.withNodeStateListener]. + [CqlSession.builder().addNodeStateListener][SessionBuilder.addNodeStateListener]. ----- @@ -51,7 +70,7 @@ but in general it represents the proximity to the client, and `LOCAL` nodes will coordinators. They also influence pooling options. [Node#getExtras()] contains additional free-form properties. This is intended for future evolution -or custom driver extensions. In particular, if the driver is connected to Datastax Enterprise, the +or custom driver extensions. In particular, if the driver is connected to DataStax Enterprise, the map will contain additional information under the keys defined in [DseNodeProperties]: ```java @@ -59,8 +78,10 @@ Object rawDseVersion = node.getExtras().get(DseNodeProperties.DSE_VERSION); Version dseVersion = (rawDseVersion == null) ? null : (Version) rawDseVersion; ``` +### Notifications + If you need to follow node state changes, you don't need to poll the metadata manually; instead, -you can register a listener to get notified when changes occur: +you can register one or more listeners to get notified when changes occur: ```java NodeStateListener listener = @@ -71,13 +92,28 @@ NodeStateListener listener = } }; CqlSession session = CqlSession.builder() - .withNodeStateListener(listener) + .addNodeStateListener(listener) .build(); ``` See [NodeStateListener] for the list of available methods. [NodeStateListenerBase] is a convenience implementation with empty methods, for when you only need to override a few of them. +It is also possible to register one or more listeners via the configuration: + +```hocon +datastax-java-driver { + advanced { + node-state-listener.classes = [com.example.app.MyNodeStateListener1,com.example.app.MyNodeStateListener2] + } +} +``` + +Listeners registered via configuration will be instantiated with reflection; they must have a public +constructor taking a `DriverContext` argument. + +The two registration methods (programmatic and via the configuration) can be used simultaneously. + ### Advanced topics #### Forcing a node down @@ -112,17 +148,17 @@ beyond the scope of this document; if you're interested, study the `TopologyMoni the source code. -[Metadata#getNodes]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/metadata/Metadata.html#getNodes-- -[Node]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/metadata/Node.html -[Node#getState()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/metadata/Node.html#getState-- -[Node#getDatacenter()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/metadata/Node.html#getDatacenter-- -[Node#getRack()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/metadata/Node.html#getRack-- -[Node#getDistance()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/metadata/Node.html#getDistance-- -[Node#getExtras()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/metadata/Node.html#getExtras-- -[Node#getOpenConnections()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/metadata/Node.html#getOpenConnections-- -[Node#isReconnecting()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/metadata/Node.html#isReconnecting-- -[NodeState]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/metadata/NodeState.html -[NodeStateListener]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/metadata/NodeStateListener.html -[NodeStateListenerBase]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/metadata/NodeStateListenerBase.html -[SessionBuilder.withNodeStateListener]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/session/SessionBuilder.html#withNodeStateListener-com.datastax.oss.driver.api.core.metadata.NodeStateListener- -[DseNodeProperties]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/metadata/DseNodeProperties.html \ No newline at end of file +[Metadata#getNodes]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/metadata/Metadata.html#getNodes-- +[Node]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/metadata/Node.html +[Node#getState()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/metadata/Node.html#getState-- +[Node#getDatacenter()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/metadata/Node.html#getDatacenter-- +[Node#getRack()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/metadata/Node.html#getRack-- +[Node#getDistance()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/metadata/Node.html#getDistance-- +[Node#getExtras()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/metadata/Node.html#getExtras-- +[Node#getOpenConnections()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/metadata/Node.html#getOpenConnections-- +[Node#isReconnecting()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/metadata/Node.html#isReconnecting-- +[NodeState]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/metadata/NodeState.html +[NodeStateListener]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/metadata/NodeStateListener.html +[NodeStateListenerBase]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/metadata/NodeStateListenerBase.html +[SessionBuilder.addNodeStateListener]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/SessionBuilder.html#addNodeStateListener-com.datastax.oss.driver.api.core.metadata.NodeStateListener- +[DseNodeProperties]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/metadata/DseNodeProperties.html diff --git a/manual/core/metadata/schema/README.md b/manual/core/metadata/schema/README.md index a140a421ae2..20521d1def4 100644 --- a/manual/core/metadata/schema/README.md +++ b/manual/core/metadata/schema/README.md @@ -1,3 +1,22 @@ + + ## Schema metadata ### Quick overview @@ -6,7 +25,7 @@ * immutable (must invoke again to observe changes). * getting notifications: - [CqlSession.builder().withSchemaChangeListener][SessionBuilder#withSchemaChangeListener]. + [CqlSession.builder().addSchemaChangeListener][SessionBuilder#addSchemaChangeListener]. * enabling/disabling: `advanced.metadata.schema.enabled` in the configuration, or [session.setSchemaMetadataEnabled()][Session#setSchemaMetadataEnabled]. * filtering: `advanced.metadata.schema.refreshed-keyspaces` in the configuration. @@ -70,7 +89,7 @@ All other types (keyspaces, tables, etc.) are identical to their OSS counterpart ### Notifications If you need to follow schema changes, you don't need to poll the metadata manually; instead, -you can register a listener to get notified when changes occur: +you can register one or more listeners to get notified when changes occur: ```java SchemaChangeListener listener = @@ -81,7 +100,7 @@ SchemaChangeListener listener = } }; CqlSession session = CqlSession.builder() - .withSchemaChangeListener(listener) + .addSchemaChangeListener(listener) .build(); session.execute("CREATE TABLE test.foo (k int PRIMARY KEY)"); @@ -90,6 +109,20 @@ session.execute("CREATE TABLE test.foo (k int PRIMARY KEY)"); See [SchemaChangeListener] for the list of available methods. [SchemaChangeListenerBase] is a convenience implementation with empty methods, for when you only need to override a few of them. +It is also possible to register one or more listeners via the configuration: + +```hocon +datastax-java-driver { + advanced { + schema-change-listener.classes = [com.example.app.MySchemaChangeListener1,com.example.app.MySchemaChangeListener2] + } +} +``` + +Listeners registered via configuration will be instantiated with reflection; they must have a public +constructor taking a `DriverContext` argument. + +The two registration methods (programmatic and via the configuration) can be used simultaneously. ### Configuration @@ -132,7 +165,54 @@ You can also limit the metadata to a subset of keyspaces: datastax-java-driver.advanced.metadata.schema.refreshed-keyspaces = [ "users", "products" ] ``` -If the property is absent or the list is empty, it is interpreted as "all keyspaces". +Each element in the list can be one of the following: + +1. An exact name inclusion, for example `"Ks1"`. If the name is case-sensitive, it must appear in + its exact case. +2. An exact name exclusion, for example `"!Ks1"`. +3. A regex inclusion, enclosed in slashes, for example `"/^Ks.*/"`. The part between the slashes + must follow the syntax rules of [java.util.regex.Pattern]. The regex must match the entire + keyspace name (no partial matching). +4. A regex exclusion, for example `"!/^Ks.*/"`. + +If the list is empty, or the option is unset, all keyspaces will match. Otherwise: + +* If a keyspace matches an exact name inclusion, it is always included, regardless of what any other + rule says. +* Otherwise, if it matches an exact name exclusion, it is always excluded, regardless of what any + regex rule says. +* Otherwise, if there are regex rules: + + * if they're only inclusions, the keyspace must match at least one of them. + * if they're only exclusions, the keyspace must match none of them. + * if they're both, the keyspace must match at least one inclusion and none of the + exclusions. + +For example, given the keyspaces `system`, `ks1`, `ks2`, `data1` and `data2`, here's the outcome of +a few filters: + +|Filter|Outcome|Translation| +|---|---|---| +| `[]` | `system`, `ks1`, `ks2`, `data1`, `data2` | Include all. | +| `["ks1", "ks2"]` | `ks1`, `ks2` | Include ks1 and ks2 (recommended, see explanation below). | +| `["!system"]` | `ks1`, `ks2`, `data1`, `data2` | Include all except system. | +| `["/^ks.*/"]` | `ks1`, `ks2` | Include all that start with ks. | +| `["!/^ks.*/"]` | `system`, `data1`, `data2` | Exclude all that start with ks (and include everything else). | +| `["system", "/^ks.*/"]` | `system`, `ks1`, `ks2` | Include system, and all that start with ks. | +| `["/^ks.*/", "!ks2"]` | `ks1` | Include all that start with ks, except ks2. | +| `["!/^ks.*/", "ks1"]` | `system`, `ks1`, `data1`, `data2` | Exclude all that start with ks, except ks1 (and also include everything else). | +| `["/^s.*/", /^ks.*/", "!/.*2$/"]` | `system`, `ks1` | Include all that start with s or ks, except if they end with 2. | + + +If an element is malformed, or if its regex has a syntax error, a warning is logged and that single +element is ignored. + +The default configuration (see [reference.conf](../../configuration/reference/)) excludes all +Cassandra and DSE system keyspaces. + +Try to use only exact name inclusions if possible. This allows the driver to filter on the server +side with a `WHERE IN` clause. If you use any other rule, it has to fetch all system rows and filter +on the client side. Note that, if you change the list at runtime, `onKeyspaceAdded`/`onKeyspaceDropped` will be invoked on your schema listeners for the newly included/excluded keyspaces. @@ -260,15 +340,16 @@ unavailable for the excluded keyspaces. If you issue schema-altering requests from the driver (e.g. `session.execute("CREATE TABLE ..")`), take a look at the [Performance](../../performance/#schema-updates) page for a few tips. -[Metadata#getKeyspaces]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/metadata/Metadata.html#getKeyspaces-- -[SchemaChangeListener]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/metadata/schema/SchemaChangeListener.html -[SchemaChangeListenerBase]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/metadata/schema/SchemaChangeListenerBase.html -[Session#setSchemaMetadataEnabled]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/session/Session.html#setSchemaMetadataEnabled-java.lang.Boolean- -[Session#checkSchemaAgreementAsync]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/session/Session.html#checkSchemaAgreementAsync-- -[SessionBuilder#withSchemaChangeListener]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/session/SessionBuilder.html#withSchemaChangeListener-com.datastax.oss.driver.api.core.metadata.schema.SchemaChangeListener- -[ExecutionInfo#isSchemaInAgreement]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/ExecutionInfo.html#isSchemaInAgreement-- -[com.datastax.dse.driver.api.core.metadata.schema]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/metadata/schema/package-frame.html -[DseFunctionMetadata]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/metadata/schema/DseFunctionMetadata.html -[DseAggregateMetadata]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/metadata/schema/DseAggregateMetadata.html - -[JAVA-750]: https://datastax-oss.atlassian.net/browse/JAVA-750 \ No newline at end of file +[Metadata#getKeyspaces]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/metadata/Metadata.html#getKeyspaces-- +[SchemaChangeListener]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/metadata/schema/SchemaChangeListener.html +[SchemaChangeListenerBase]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/metadata/schema/SchemaChangeListenerBase.html +[Session#setSchemaMetadataEnabled]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/Session.html#setSchemaMetadataEnabled-java.lang.Boolean- +[Session#checkSchemaAgreementAsync]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/Session.html#checkSchemaAgreementAsync-- +[SessionBuilder#addSchemaChangeListener]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/SessionBuilder.html#addSchemaChangeListener-com.datastax.oss.driver.api.core.metadata.schema.SchemaChangeListener- +[ExecutionInfo#isSchemaInAgreement]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/ExecutionInfo.html#isSchemaInAgreement-- +[com.datastax.dse.driver.api.core.metadata.schema]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/metadata/schema/package-frame.html +[DseFunctionMetadata]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/metadata/schema/DseFunctionMetadata.html +[DseAggregateMetadata]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/metadata/schema/DseAggregateMetadata.html + +[JAVA-750]: https://datastax-oss.atlassian.net/browse/JAVA-750 +[java.util.regex.Pattern]: https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html diff --git a/manual/core/metadata/token/README.md b/manual/core/metadata/token/README.md index 38765047f86..4d7cd9252df 100644 --- a/manual/core/metadata/token/README.md +++ b/manual/core/metadata/token/README.md @@ -1,3 +1,22 @@ + + ## Token metadata ### Quick overview @@ -169,5 +188,5 @@ on [schema metadata](../schema/). If schema metadata is disabled or filtered, to also be unavailable for the excluded keyspaces. -[Metadata#getTokenMap]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/metadata/Metadata.html#getTokenMap-- -[TokenMap]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/metadata/TokenMap.html \ No newline at end of file +[Metadata#getTokenMap]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/metadata/Metadata.html#getTokenMap-- +[TokenMap]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/metadata/TokenMap.html diff --git a/manual/core/metrics/README.md b/manual/core/metrics/README.md index 4a15a95f2eb..ef5d9b453f0 100644 --- a/manual/core/metrics/README.md +++ b/manual/core/metrics/README.md @@ -1,70 +1,92 @@ + + ## Metrics ### Quick overview -* `advanced.metrics` in the configuration. All disabled by default, can be selected individually. +* `advanced.metrics` in the configuration. All metrics disabled by default. To enable, select the + metrics library to use, then define which individual metrics to activate. * some metrics are per node, others global to the session, or both. * unlike driver 3, JMX is not provided out of the box. You need to add the dependency manually. ----- -The driver exposes measurements of its internal behavior through a choice of three popular metrics -frameworks: [Dropwizard Metrics], [Micrometer Metrics] or [MicroProfile Metrics]. Application -developers can select a metrics framework, which metrics are enabled, and export them to a -monitoring tool. +The driver is able to report measurements of its internal behavior to a variety of metrics +libraries, and ships with bindings for three popular ones: [Dropwizard Metrics] , [Micrometer +Metrics] and [MicroProfile Metrics]. -### Structure - -There are two categories of metrics: +### Selecting a Metrics Library -* session-level: the measured data is global to a `Session` instance. For example, `connected-nodes` - measures the number of nodes to which we have connections. -* node-level: the data is specific to a node (and therefore there is one metric instance per node). - For example, `pool.open-connections` measures the number of connections open to this particular - node. - -Metric names are path-like, dot-separated strings. The driver prefixes them with the name of the -session (see `session-name` in the configuration), and in the case of node-level metrics, `nodes` -followed by a textual representation of the node's address. For example: +#### Dropwizard Metrics -``` -s0.connected-nodes => 2 -s0.nodes.127_0_0_1:9042.pool.open-connections => 2 -s0.nodes.127_0_0_2:9042.pool.open-connections => 1 -``` +Dropwizard is the driver's default metrics library; there is no additional configuration nor any +extra dependency to add if you wish to use Dropwizard. -### Configuration +#### Micrometer -By default, all metrics are disabled. You can turn them on individually in the configuration, by -adding their name to these lists: +To use Micrometer you must: + +1. Define `MicrometerMetricsFactory` as the metrics factory to use in the driver configuration: ``` datastax-java-driver.advanced.metrics { - session.enabled = [ connected-nodes, cql-requests ] - node.enabled = [ pool.open-connections, pool.in-flight ] + factory.class = MicrometerMetricsFactory } ``` -To find out which metrics are available, see the [reference configuration]. It contains a -commented-out line for each metric, with detailed explanations on its intended usage. +2. Add a dependency to `java-driver-metrics-micrometer` in your application. This separate driver +module contains the actual bindings for Micrometer, and depends itself on the Micrometer library: -If you specify a metric that doesn't exist, it will be ignored and a warning will be logged. +```xml + + org.apache.cassandra + java-driver-metrics-micrometer + ${driver.version} + +``` -The `metrics` section may also contain additional configuration for some specific metrics; again, -see the [reference configuration] for more details. +3. You should also exclude Dropwizard and HdrHistogram, which are two transitive dependencies of the +driver, because they are not relevant when using Micrometer: -#### Changing the Metrics Frameworks +```xml + + org.apache.cassandra + java-driver-core + + + io.dropwizard.metrics + metrics-core + + + org.hdrhistogram + HdrHistogram + + + +``` -The default metrics framework is Dropwizard. You can change this to either Micrometer or -MicroProfile in the configuration: +#### MicroProfile Metrics -``` -datastax-java-driver.advanced.metrics { - factory.class = MicrometerMetricsFactory -} -``` +To use MicroProfile Metrics you must: -or +1. Define `MicroProfileMetricsFactory` as the metrics factory to use in the driver configuration: ``` datastax-java-driver.advanced.metrics { @@ -72,32 +94,156 @@ datastax-java-driver.advanced.metrics { } ``` -In addition to the configuration change above, you will also need to include the appropriate module -in your project. For Micrometer: +2. Add a dependency to `java-driver-metrics-microprofile` in your application. This separate driver +module contains the actual bindings for MicroProfile, and depends itself on the MicroProfile Metrics +library: ```xml - com.datastax.oss - java-driver-metrics-micrometer + org.apache.cassandra + java-driver-metrics-microprofile ${driver.version} ``` -For MicroProfile: +3. You should also exclude Dropwizard and HdrHistogram, which are two transitive dependencies of the +driver, because they are not relevant when using MicroProfile Metrics: ```xml - com.datastax.oss - java-driver-metrics-microprofile - ${driver.version} + org.apache.cassandra + java-driver-core + + + io.dropwizard.metrics + metrics-core + + + org.hdrhistogram + HdrHistogram + + ``` -#### Metric Registry +#### Other Metrics libraries + +Other metrics libraries can also be used. However, you will need to provide a custom +metrics factory. Simply implement the +`com.datastax.oss.driver.internal.core.metrics.MetricsFactory` interface for your library of choice, +then pass the fully-qualified name of that implementation class to the driver using the +`advanced.metrics.factory.class` option. See the [reference configuration]. + +You will certainly need to add the metrics library as a dependency to your application as well. +It is also recommended excluding Dropwizard and HdrHistogram, as shown above. + +### Enabling specific driver metrics + +Now that the metrics library is configured, you need to activate the driver metrics you are +interested in. + +There are two categories of driver metrics: + +* session-level: the measured data is global to a `Session` instance. For example, `connected-nodes` + measures the number of nodes to which we have connections. +* node-level: the data is specific to a node (and therefore there is one metric instance per node). + For example, `pool.open-connections` measures the number of connections open to this particular + node. + +To find out which metrics are available, see the [reference configuration]. It contains a +commented-out line for each metric, with detailed explanations on its intended usage. + +By default, all metrics are disabled. You can turn them on individually in the configuration, by +adding their name to these lists: + +``` +datastax-java-driver.advanced.metrics { + session.enabled = [ connected-nodes, cql-requests ] + node.enabled = [ pool.open-connections, pool.in-flight ] +} +``` + +If you specify a metric that doesn't exist, it will be ignored, and a warning will be logged. + +Finally, if you are using Dropwizard or Micrometer and enabled any metric of timer type, such as +`cql-requests`, it is also possible to provide additional configuration to fine-tune the underlying +histogram's characteristics and precision, such as its highest expected latency, its number of +significant digits to use, and its refresh interval. Again, see the [reference configuration] for +more details. + +### Selecting a metric identifier style + +Most metric libraries uniquely identify a metric by a name and, optionally, by a set of key-value +pairs, usually called tags. + +The `advanced.metrics.id-generator.class` option is used to customize how the driver generates +metric identifiers. The driver ships with two built-in implementations: + +- `DefaultMetricIdGenerator`: generates identifiers composed solely of (unique) metric names; it + does not generate tags. All metric names start with the name of the session (see `session-name` in + the configuration), and in the case of node-level metrics, this is followed by `.nodes.`, followed + by a textual representation of the node's address. All names end with the metric distinctive name. + See below for examples. This generator is mostly suitable for use with metrics libraries that do + not support tags, like Dropwizard. + +- `TaggingMetricIdGenerator`: generates identifiers composed of a name and one or two tags. + Session-level metric names start with the `session.` prefix followed by the metric distinctive + name; node-level metric names start with the `nodes.` prefix followed by the metric distinctive + name. Session-level tags will include a `session` tag whose value is the session name (see + `session-name` in the configuration); node-level tags will include the same `session` tag, and + also a `node` tag whose value is the node's address. See below for examples. This generator is + mostly suitable for use with metrics libraries that support tags, like Micrometer or MicroProfile + Metrics. -For any of the three metrics frameworks, you can provide an external Metric Registry object when -building a Session. This will easily allow your application to export the driver's operational -metrics to whatever reporting system you want to use. +For example, here is how each one of them generates identifiers for the session metric "bytes-sent", +assuming that the session is named "s0": + +- `DefaultMetricIdGenerator`: + - name:`s0.bytes-sent` + - tags: `{}` +- `TaggingMetricIdGenerator`: + - name: `session.bytes-sent` + - tags: `{ "session" : "s0" }` + +Here is how each one of them generates identifiers for the node metric "bytes-sent", assuming that +the session is named "s0", and the node's broadcast address is 10.1.2.3:9042: + +- `DefaultMetricIdGenerator`: + - name : `s0.nodes.10_1_2_3:9042.bytes-sent` + - tags: `{}` +- `TaggingMetricIdGenerator`: + - name `nodes.bytes-sent` + - tags: `{ "session" : "s0", "node" : "\10.1.2.3:9042" }` + +As shown above, both built-in implementations generate names that are path-like structures separated +by dots. This is indeed the most common expected format by reporting tools. + +Finally, it is also possible to define a global prefix for all metric names; this can be done with +the `advanced.metrics.id-generator.prefix` option. + +The prefix should not start nor end with a dot or any other path separator; the following are two +valid examples: `cassandra` or `myapp.prod.cassandra`. + +For example, if this prefix is set to `cassandra`, here is how the session metric "bytes-sent" would +be named, assuming that the session is named "s0": + +- with `DefaultMetricIdGenerator`: `cassandra.s0.bytes-sent` +- with `TaggingMetricIdGenerator`: `cassandra.session.bytes-sent` + +Here is how the node metric "bytes-sent" would be named, assuming that the session is named "s0", +and the node's broadcast address is 10.1.2.3:9042: + +- with `DefaultMetricIdGenerator`: `cassandra.s0.nodes.10_1_2_3:9042.bytes-sent` +- with `TaggingMetricIdGenerator`: `cassandra.nodes.bytes-sent` + +### Using an external metric registry + +Regardless of which metrics library is used, you can provide an external metric registry object when +building a session. This allows the driver to transparently export its operational metrics to +whatever reporting system you want to use. + +To pass a metric registry object to the session, use the `CqlSessionBuilder.withMetricRegistry()` +method: ```java CqlSessionBuilder builder = CqlSession.builder(); @@ -105,43 +251,51 @@ builder.withMetricRegistry(myRegistryObject); CqlSession session = builder.build(); ``` -In the above example, `myRegistryObject` should be an instance of the base registry type for the -metrics framework you are using: +Beware that the driver does not inspect the provided object, it simply passes it to the metrics +factory in use; it is the user's responsibility to provide registry objects compatible with the +metrics library in use. For reference, here are the expected base types for the three built-in +metrics libraries: -``` -Dropwizard: com.codahale.metrics.MetricRegistry -Micrometer: io.micrometer.core.instrument.MeterRegistry -MicroProfile: org.eclipse.microprofile.metrics.MetricRegistry -``` +* Dropwizard: `com.codahale.metrics.MetricRegistry` +* Micrometer: `io.micrometer.core.instrument.MeterRegistry` +* MicroProfile: `org.eclipse.microprofile.metrics.MetricRegistry` + +**NOTE:** MicroProfile **requires** an external instance of its registry to be provided. For +Micrometer, if no registry object is provided, Micrometer's `globalRegistry` will be used. For +Dropwizard, if no registry object is provided, an instance of `MetricRegistry` will be created and +used (in which case, it can be retrieved programmatically if needed, see below). -**NOTE:** Only MicroProfile **requires** an external instance of its Registry to be provided. For -Micrometer, if no Registry object is provided, Micrometer's `globalRegistry` will be used. For -Dropwizard, if no Registry object is provided, an instance of `MetricRegistry` will be created and -used. +### Programmatic access to driver metrics -### Export +Programmatic access to driver metrics is only available when using Dropwizard Metrics. Users of +other libraries are encouraged to provide an external registry when creating the driver session (see +above), then use it to gain programmatic access to the driver metrics. -The Dropwizard `MetricRegistry` is exposed via `session.getMetrics().getRegistry()`. You can -retrieve it and configure a `Reporter` to send the metrics to a monitoring tool. +The Dropwizard `MetricRegistry` object is exposed in the driver API via +`session.getMetrics().getRegistry()`. You can retrieve it and, for example, configure a `Reporter` +to send the metrics to a monitoring tool. -**NOTE:** At this time, `session.getMetrics()` is not available when using Micrometer or -MicroProfile metrics. If you wish to use either of those metrics frameworks, it is recommended to -provide a Registry implementation to the driver as described in the [Metric Registry -section](#metric-registry), and follow best practices for exporting that registry to your desired -reporting framework. +**NOTE:** Beware that `session.getMetrics()` is not available when using other metrics libraries, +and will throw a `NoClassDefFoundError` at runtime if accessed in such circumstances. -#### JMX +### Exposing driver metrics with JMX Unlike previous driver versions, JMX support is not included out of the box. +The way to add JMX support to your application depends largely on the metrics library being used. We +show below instructions for Dropwizard only. Micrometer also has support for JMX: please refer to +its [official documentation][Micrometer JMX]. + +#### Dropwizard Metrics + Add the following dependency to your application (make sure the version matches the `metrics-core` dependency of the driver): -``` +```xml io.dropwizard.metrics metrics-jmx - 4.0.2 + 4.1.2 ``` @@ -201,14 +355,14 @@ JmxReporter reporter = reporter.start(); ``` -#### Other protocols +### Exporting metrics with other protocols Dropwizard Metrics has built-in reporters for other output formats: JSON (via a servlet), stdout, CSV files, SLF4J logs and Graphite. Refer to their [manual][Dropwizard manual] for more details. - -[Dropwizard Metrics]: http://metrics.dropwizard.io/4.0.0/manual/index.html -[Dropwizard Manual]: http://metrics.dropwizard.io/4.0.0/getting-started.html#reporting-via-http +[Dropwizard Metrics]: https://metrics.dropwizard.io/4.1.2 +[Dropwizard Manual]: https://metrics.dropwizard.io/4.1.2/getting-started.html [Micrometer Metrics]: https://micrometer.io/docs +[Micrometer JMX]: https://micrometer.io/docs/registry/jmx [MicroProfile Metrics]: https://github.com/eclipse/microprofile-metrics -[reference configuration]: ../configuration/reference/ \ No newline at end of file +[reference configuration]: ../configuration/reference/ diff --git a/manual/core/native_protocol/README.md b/manual/core/native_protocol/README.md index 6704b8394c4..42146e63f42 100644 --- a/manual/core/native_protocol/README.md +++ b/manual/core/native_protocol/README.md @@ -1,3 +1,22 @@ + + ## Native protocol ### Quick overview @@ -21,21 +40,18 @@ only available with specific protocol versions. ### Compatibility matrix -Java driver 4 supports protocol versions 3 to 5. By default, the version is negotiated with the +Java Driver 4 supports protocol versions 3 to 5. By default, the version is negotiated with the first node the driver connects to: -| Cassandra version | Negotiated protocol version with driver 4 ¹ | -|---------------------|-------------------------------------------------| -| 2.1.x | v3 | -| 2.2.x | v4 | -| 3.x | v4 | -| 4.x ² | v5 | +| Cassandra version | Negotiated protocol version with driver 4 ¹ | +|-------------------|-------------------------------------------------| +| 2.1.x | v3 | +| 2.2.x | v4 | +| 3.x | v4 | +| 4.x | v5 | *(1) for previous driver versions, see the [3.x documentation][driver3]* -*(2) at the time of writing, Cassandra 4 is not released yet. Protocol v5 support is still in beta, -and must be enabled explicitly (negotiation will yield v4).* - Since version 4.5.0, the driver can also use DSE protocols when all nodes are running a version of DSE. The table below shows the protocol matrix for these cases: @@ -43,10 +59,10 @@ DSE. The table below shows the protocol matrix for these cases: |---------------------|-------------------------------------------------| | 4.7/4.8 | v3 | | 5.0 | v4 | -| 5.1 | DSE_V1 ³ | -| 6.0/6.7/6.8 | DSE_V2 ³ | +| 5.1 | DSE_V1 ² | +| 6.0/6.7/6.8 | DSE_V2 ² | -*(3) DSE Protocols are chosen before other Cassandra native protocols.* +*(2) DSE Protocols are chosen before other Cassandra native protocols.* ### Controlling the protocol version @@ -62,11 +78,14 @@ the [configuration](../configuration/): ``` datastax-java-driver { advanced.protocol { - version = v3 + version = V3 } } ``` +Note that the protocol version you specify above is case sensitive so make sure to only use uppercase letters. +"V3" is correct, "v3" is not. + If you force a version that is too high for the server, you'll get an error: ``` @@ -135,6 +154,6 @@ If you want to see the details of mixed cluster negotiation, enable `DEBUG` leve [protocol spec]: https://github.com/datastax/native-protocol/tree/1.x/src/main/resources [driver3]: https://docs.datastax.com/en/developer/java-driver/3.10/manual/native_protocol/ -[ExecutionInfo.getWarnings]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/ExecutionInfo.html#getWarnings-- -[Request.getCustomPayload]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/session/Request.html#getCustomPayload-- -[AttachmentPoint.getProtocolVersion]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/detach/AttachmentPoint.html#getProtocolVersion-- +[ExecutionInfo.getWarnings]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/ExecutionInfo.html#getWarnings-- +[Request.getCustomPayload]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/Request.html#getCustomPayload-- +[AttachmentPoint.getProtocolVersion]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/detach/AttachmentPoint.html#getProtocolVersion-- diff --git a/manual/core/non_blocking/README.md b/manual/core/non_blocking/README.md new file mode 100644 index 00000000000..f320ffd13d2 --- /dev/null +++ b/manual/core/non_blocking/README.md @@ -0,0 +1,306 @@ + + +## Non-blocking programming + +### Quick overview + +With the advent of reactive programming, the demand for fully non-blocking libraries has become +popular among application developers. The recent availability of frameworks enforcing lock-freedom, +such as [Vert.x] or [Reactor], along with tools for automatic detection of blocking calls like +[BlockHound], has exacerbated this trend even more so. + +[Vert.x]: https://vertx.io +[Reactor]: https://projectreactor.io +[BlockHound]: https://github.com/reactor/BlockHound + +**In summary, when used properly, the Java Driver offers non-blocking guarantees for most +of its operations, and during most of the session lifecycle.** + +These guarantees and their exceptions are detailed below. A final chapter explains how to use the +driver with BlockHound. + +The developer guide also has more information on driver internals and its +[concurrency model](../../developer/common/concurrency). + +### Definition of "non-blocking" + +Since the term "non-blocking" is subject to interpretation, in this page the term should be +understood as "[lock-free]": a program is non-blocking if at least one thread is guaranteed to make +progress; such programs are implemented without locks, mutexes nor semaphores, using only low-level +primitives such as atomic variables and CAS (compare-and-swap) instructions. + +A further distinction is generally established between "lock-free" and "wait-free" algorithms: the +former ones allow progress of the overall system, while the latter ones allow each thread to make +progress at any time. This distinction is however rather theoretical and is outside the scope of +this document. + +[lock-free]: https://www.baeldung.com/lock-free-programming + +### Driver lock-free guarantees + +#### Driver lock-free guarantees per execution models + +The driver offers many execution models. For the built-in ones, the lock-free guarantees are as +follows: + +* The synchronous API is blocking and does not offer any lock-free guarantee. +* The [asynchronous](../async) API is implemented in lock-free algorithms. +* The [reactive](../reactive) API is implemented in lock-free algorithms (it's actually wait-free). + +For example, calling any synchronous method declared in [`SyncCqlSession`], such as [`execute`], +will block until the result is available. These methods should never be used in non-blocking +applications. + +[`SyncCqlSession`]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/SyncCqlSession.html` +[`execute`]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/SyncCqlSession.html#execute-com.datastax.oss.driver.api.core.cql.Statement- + +However, the asynchronous methods declared in [`AsyncCqlSession`], such as [`executeAsync`], are all +safe for use in non-blocking applications; the statement execution and asynchronous result delivery +is guaranteed to never block. + +[`AsyncCqlSession`]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/AsyncCqlSession.html +[`executeAsync`]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/AsyncCqlSession.html#executeAsync-com.datastax.oss.driver.api.core.cql.Statement- + +The same applies to the methods declared in [`ReactiveSession`] such as [`executeReactive`]: the +returned publisher will never block when subscribed to, until the final results are delivered to +the subscriber. + +[`ReactiveSession`]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/cql/reactive/ReactiveSession.html +[`executeReactive`]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/cql/reactive/ReactiveSession.html#executeReactive-com.datastax.oss.driver.api.core.cql.Statement- + +There is one exception though: continuous paging queries (a feature specific to DSE) have a special +execution model which uses internal locks for coordination. Although such locks are only held for +extremely brief periods of time, and never under high contention, this execution model doesn't +qualify as lock-free. + +As a consequence, all methods declared in [`ContinuousSession`] and [`ContinuousReactiveSession`] +cannot be considered as implemented 100% lock-free, even those built on top of the asynchronous or +reactive APIs like [`executeContinuouslyAsync`] and [`executeContinuouslyReactive`]. In practice +though, continuous paging is extremely efficient and can safely be used in most non-blocking +contexts, unless they require strict lock-freedom. + +[`ContinuousSession`]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/cql/continuous/ContinuousSession.html +[`ContinuousReactiveSession`]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/cql/continuous/reactive/ContinuousReactiveSession.html +[`executeContinuouslyAsync`]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/cql/continuous/ContinuousSession.html#executeContinuouslyAsync-com.datastax.oss.driver.api.core.cql.Statement- +[`executeContinuouslyReactive`]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/cql/continuous/reactive/ContinuousReactiveSession.html#executeContinuouslyReactive-com.datastax.oss.driver.api.core.cql.Statement- + +#### Driver lock-free guarantees per session lifecycle phases + +The guarantees vary according to three possible session states: initializing, running, and closing. + +Session initialization is a costly operation that performs many I/O operations, hitting both the +local filesystem (configuration files) and the network (connection initialization). This procedure +is triggered by a call to [`SessionBuilder.buildAsync()`] and happens partially on the calling +thread, and partially asynchronously on an internal driver thread. + +* The creation of the [driver context] happens synchronously on the calling thread. The context + creation usually requires file I/O, mainly to read configuration files. A call to + `SessionBuilder.buildAsync()`, in spite of its name, is thus a blocking call and must be + dispatched to a thread that is allowed to block. +* The rest of the initialization process will happen asynchronously, on an internal driver admin + thread. This process is mostly non-blocking, with a few exceptions listed below. Therefore, + the driver admin thread performing the initialization tasks must be allowed to block, at least + temporarily. + +[driver context]: ../../developer/common/context + +For the reasons above, the initialization phase obviously doesn't qualify as lock-free. For +non-blocking applications, it is generally advised to trigger session initialization during +application startup, before strong non-blocking guarantees are enforced on application threads. + +Similarly, a call to [`SessionBuilder.build()`] should be considered blocking as it will block the +calling thread and wait until the method returns. For this reason, calls to `SessionBuilder.build()` +should be avoided in non-blocking applications. + +[`SessionBuilder.buildAsync()`]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/SessionBuilder.html#buildAsync-- +[`SessionBuilder.build()`]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/SessionBuilder.html#build-- + +Once the session is initialized, however, the driver is guaranteed to be non-blocking during the +session's lifecycle, and under normal operation, unless otherwise noted elsewhere in this document. + +Finally, closing the session is generally non-blocking, but the driver offers no strong guarantees +during that phase. Therefore, calls to any method declared in [`AsyncAutoCloseable`], including the +asynchronous ones like [`closeAsync()`], should also be preferably deferred until the application is +shut down and lock-freedom enforcement is disabled. + +[`AsyncAutoCloseable`]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/AsyncAutoCloseable.html +[`closeAsync()`]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/AsyncAutoCloseable.html#closeAsync-- + +#### Driver lock-free guarantees for specific components + +Certain driver components are not implemented in lock-free algorithms. + +For example, [`SafeInitNodeStateListener`] is implemented with internal locks for coordination. It +should not be used if strict lock-freedom is enforced. + +[`SafeInitNodeStateListener`]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/metadata/SafeInitNodeStateListener.html + +The `RateLimitingRequestThrottler` is currently blocking. The `ConcurrencyLimitingRequestThrottler` +is lock-free. + +See the section about [throttling](../throttling) for details about these components. Depending on +how many requests are being executed in parallel, the thread contention on these locks can be high: +in short, if your application enforces strict lock-freedom, then you should not use the +`RateLimitingRequestThrottler`. + +[request throttlers]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/throttling/RequestThrottler.html + +Other components may be lock-free, *except* for their first invocation. This is the case of the +following items: + +* All built-in implementations of [`TimestampGenerator`], upon instantiation; +* The utility method [`Uuids.timeBased()`]. + +[`TimestampGenerator`]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/time/TimestampGenerator.html +[`Uuids.timeBased()`]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/uuid/Uuids.html#timeBased-- + +Both components need to access native libraries when they get initialized and this may involve +hitting the local filesystem, thus causing the initialization to become a blocking call. + +Timestamp generators are automatically created when the session is initialized, and are thus +generally safe to use afterwards. + +`Uuids.timeBased()`, however, is a convenience method that the driver doesn't use internally. For +this reason, it is advised that this method be called once during application startup, so that it is +safe to use it afterwards in a non-blocking context. + +Alternatively, it's possible to disable the usage of client-side timestamp generation, and/or the +usage of native libraries. See the manual sections on [query timestamps](../query_timestamps) and +[integration](../integration) for more information. + +One component, the codec registry, can block when its [`register`] method is called; it is +therefore advised that codecs should be registered during application startup exclusively. See the +[custom codecs](../custom_codecs) section for more details about registering codecs. + +[`register`]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/registry/MutableCodecRegistry.html#register-com.datastax.oss.driver.api.core.type.codec.TypeCodec- + +Finally, a few internal components also use locks, but only during session initialization; once the +session is ready, they are either discarded, or don't use locks anymore for the rest of the +session's lifecycle. + +These components are safe to use once the session is ready, although they could be reported by +lock-freedom monitoring tools. They are listed below in case their exclusion is necessary: + +* `com.datastax.oss.driver.internal.core.context.DefaultNettyOptions` +* `com.datastax.oss.driver.internal.core.util.concurrent.LazyReference` +* `com.datastax.oss.driver.internal.core.util.concurrent.ReplayingEventFilter` + +#### Driver lock-free guarantees on topology and status events + +Topology and status events can cause the driver to use locks temporarily. + +When a node gets added to the cluster, or when a node state changes (DOWN to UP or vice versa), the +driver needs to notify a few components: the load balancing policies need to coordinate in order to +assign a new distance to the node (LOCAL, REMOTE or IGNORED); and the node connection pool will have +to be resized either to accommodate new connections, or to close existing ones. + +These operations use internal locks for coordination. Again, they are only held for extremely brief +periods of time, and never under high contention. Note that this behavior cannot be disabled or +changed; if you need to enforce strict lock-freedom, and topology or status changes are being +reported as infringements, consider adding exceptions for the following method calls: + + * `com.datastax.oss.driver.internal.core.pool.ChannelSet#add(DriverChannel)` + * `com.datastax.oss.driver.internal.core.pool.ChannelSet#remote(DriverChannel)` + * `com.datastax.oss.driver.internal.core.metadata.LoadBalancingPolicyWrapper$SinglePolicyDistanceReporter#setDistance(Node,NodeDistance)` + +#### Driver lock-free guarantees on random uuid generation + +Until driver 4.9, the [`Uuids.random()`] method was a blocking call. Because of that, this method +could not be used in non-blocking contexts, making UUID generation a difficult issue to solve. + +Moreover, this method is used in a few places internally. This situation was unfortunate because +lock-freedom enforcement tools could report calls to that method, but it was impossible to suppress +these calls. Thanks to [JAVA-2449], released with driver 4.10.0, `Uuids.random()` became a +non-blocking call and random UUIDs can now be safely generated in non-blocking applications. + +[`Uuids.random()`]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/uuid/Uuids.html#random-- +[JAVA-2449]: https://datastax-oss.atlassian.net/browse/JAVA-2449 + +#### Driver lock-free guarantees when reloading the configuration + +The driver has a pluggable configuration mechanism built around the [`DriverConfigLoader`] +interface. Implementors may choose to support [hot-reloading] of configuration files, and the +default built-in implementation has this feature enabled by default. + +Beware that a hot-reloading of the default configuration mechanism is performed on a driver internal +admin thread. If hot-reloading is enabled, then this might be reported by lock-freedom infringement +detectors. If that is the case, it is advised to disable hot-reloading by setting the +`datastax-java-driver.basic.config-reload-interval` option to 0. See the manual page on +[configuration](../configuration) for more information. + +[`DriverConfigLoader`]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/config/DriverConfigLoader.html +[hot-reloading]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/config/DriverConfigLoader.html#supportsReloading-- + +#### Driver lock-free guarantees when connecting to DSE + +When connecting to clusters running recent DSE versions, the driver automatically enables periodic +status reporting. When preparing the status report, the driver has to hit the local filesystem, and +because of that, the status reporting process does not qualify as lock-free. + +If lock-freedom is being enforced, then automatic status reporting must be disabled by setting the +`datastax-java-driver.advanced.monitor-reporting.enabled` property to false in the driver +configuration. + +### Driver mechanism for detection of blocking calls + +The driver has its own mechanism for detecting blocking calls happening on an internal driver +thread. This mechanism is capable of detecting and reporting blatant cases of misuse of the +asynchronous and reactive APIs, e.g. when the synchronous API is invoked inside a future or callback +produced by the asynchronous execution of a statement. See the core manual page on the +[asynchronous](../async) API or the developer manual page on +[driver concurrency](../../developer/common/concurrency) for details. + +The driver is not capable, however, of detecting low-level lock-freedom infringements, such as the +usage of locks. You must use an external tool to achieve that. See below how to use BlockHound for +that. + +### Using the driver with Reactor BlockHound + +[Reactor]'s tool for automatic detection of blocking calls, [BlockHound], is capable of detecting +and reporting any sort of blocking calls, including I/O, locks, `Thread.sleep`, etc. + +When used with the driver, BlockHound can report some calls that, for the reasons explained above, +could be safely considered as false positives. + +For this reason, the driver, since version 4.10, ships with a custom `DriverBlockHoundIntegration` +class which is automatically discovered by BlockHound through the Service Loader mechanism. It +contains BlockHound customizations that target most of the cases detailed above, and prevent them +from being reported as blocking calls. + +More specifically, the following items are currently declared to be allowed: + +* Loading of native libraries during startup (`TimestampGenerator`); +* Locks held during startup only (`DefaultNettyOptions`, `LazyReference`, `ReplayingEventFilter`); +* Locks held during startup and topology and status events processing (`ChannelSet`, + `DistanceReporter`); +* Locks held when executing continuous paging queries; +* Locks held during calls to `MutableCodecRegistry.register()` and `Uuids.timeBased()`. + +The following items are NOT declared to be allowed and are likely to be reported by BlockHound if +used: + +* Request throttlers; +* Automatic status reporting; +* `SafeInitNodeStateListener`. + +Note that other blocking startup steps, e.g. loading of configuration files, are also not declared +to be allowed, because these are genuine blocking I/O calls. For this reason, if BlockHound is being +used, the loading of the driver context, performed by the thread calling `SessionBuilder.build()` +or `SessionBuilder.buildAsync()`, must be allowed to perform blocking calls. diff --git a/manual/core/paging/README.md b/manual/core/paging/README.md index 9dec6c80f78..2df92bd69d1 100644 --- a/manual/core/paging/README.md +++ b/manual/core/paging/README.md @@ -1,3 +1,22 @@ + + ## Paging ### Quick overview @@ -253,12 +272,12 @@ protocol page size and the logical page size to the same value. The [driver examples] include two complete web service implementations demonstrating forward-only and offset paging. -[ResultSet]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/ResultSet.html -[AsyncResultSet]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/AsyncResultSet.html -[AsyncPagingIterable.hasMorePages]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/AsyncPagingIterable.html#hasMorePages-- -[AsyncPagingIterable.fetchNextPage]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/AsyncPagingIterable.html#fetchNextPage-- -[OffsetPager]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/paging/OffsetPager.html -[PagingState]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/PagingState.html +[ResultSet]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/ResultSet.html +[AsyncResultSet]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/AsyncResultSet.html +[AsyncPagingIterable.hasMorePages]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/AsyncPagingIterable.html#hasMorePages-- +[AsyncPagingIterable.fetchNextPage]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/AsyncPagingIterable.html#fetchNextPage-- +[OffsetPager]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/paging/OffsetPager.html +[PagingState]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/PagingState.html [CompletionStage]: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletionStage.html diff --git a/manual/core/performance/README.md b/manual/core/performance/README.md index 9e200a3ffb5..3afb321968e 100644 --- a/manual/core/performance/README.md +++ b/manual/core/performance/README.md @@ -1,3 +1,22 @@ + + ## Performance This page is intended as a checklist for everything related to driver performance. Most of the @@ -345,8 +364,8 @@ possible to reuse the same event loop group for I/O, admin tasks, and even your (the driver's internal code is fully asynchronous so it will never block any thread). The timer is the only one that will have to stay on a separate thread. -[AccessibleByName]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/data/AccessibleByName.html -[CqlIdentifier]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/CqlIdentifier.html -[CqlSession.prepare(SimpleStatement)]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/CqlSession.html#prepare-com.datastax.oss.driver.api.core.cql.SimpleStatement- -[GenericType]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/reflect/GenericType.html -[Statement.setNode()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/Statement.html#setNode-com.datastax.oss.driver.api.core.metadata.Node- \ No newline at end of file +[AccessibleByName]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/data/AccessibleByName.html +[CqlIdentifier]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/CqlIdentifier.html +[CqlSession.prepare(SimpleStatement)]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/CqlSession.html#prepare-com.datastax.oss.driver.api.core.cql.SimpleStatement- +[GenericType]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/reflect/GenericType.html +[Statement.setNode()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/Statement.html#setNode-com.datastax.oss.driver.api.core.metadata.Node- diff --git a/manual/core/pooling/README.md b/manual/core/pooling/README.md index ef6f1068f2a..578de6b4abd 100644 --- a/manual/core/pooling/README.md +++ b/manual/core/pooling/README.md @@ -1,3 +1,22 @@ + + ## Connection pooling ### Quick overview @@ -170,5 +189,5 @@ you experience the issue, here's what to look out for: Try adding more connections per node. Thanks to the driver's hot-reload mechanism, you can do that at runtime and see the effects immediately. -[CqlSession]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/CqlSession.html -[CASSANDRA-8086]: https://issues.apache.org/jira/browse/CASSANDRA-8086 \ No newline at end of file +[CqlSession]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/CqlSession.html +[CASSANDRA-8086]: https://issues.apache.org/jira/browse/CASSANDRA-8086 diff --git a/manual/core/query_timestamps/README.md b/manual/core/query_timestamps/README.md index ac50c53da90..4498afe21c4 100644 --- a/manual/core/query_timestamps/README.md +++ b/manual/core/query_timestamps/README.md @@ -1,3 +1,22 @@ + + ## Query timestamps ### Quick overview @@ -187,9 +206,9 @@ Here is the order of precedence of all the methods described so far: 3. otherwise, if the timestamp generator assigned a timestamp, use it; 4. otherwise, let the server assign the timestamp. -[TimestampGenerator]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/time/TimestampGenerator.html +[TimestampGenerator]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/time/TimestampGenerator.html [gettimeofday]: http://man7.org/linux/man-pages/man2/settimeofday.2.html [JNR]: https://github.com/jnr/jnr-posix [Lightweight transactions]: https://docs.datastax.com/en/dse/6.0/cql/cql/cql_using/useInsertLWT.html -[Statement.setQueryTimestamp()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/Statement.html#setQueryTimestamp-long- +[Statement.setQueryTimestamp()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/Statement.html#setQueryTimestamp-long- diff --git a/manual/core/reactive/README.md b/manual/core/reactive/README.md index 25f74a26579..37a2e3411b8 100644 --- a/manual/core/reactive/README.md +++ b/manual/core/reactive/README.md @@ -1,3 +1,22 @@ + + ## Reactive Style Programming The driver provides built-in support for reactive queries. The [CqlSession] interface extends @@ -6,13 +25,15 @@ streams]. Notes: -* reactive capabilities require the [Reactive Streams API] to be present on the classpath. The +* Reactive capabilities require the [Reactive Streams API] to be present on the classpath. The driver has a dependency on that library, but if your application does not use reactive queries at all, it is possible to exclude it to minimize the number of runtime dependencies. If the library cannot be found at runtime, reactive queries won't be available, and a warning will be logged, but the driver will otherwise operate normally (this is also valid for OSGi deployments). -* for historical reasons, reactive-related driver types reside in a package prefixed with `dse`; +* For historical reasons, reactive-related driver types reside in a package prefixed with `dse`; however, reactive queries also work with regular Cassandra. +* The reactive execution model is implemented in a non-blocking fashion: see the manual page on + [non-blocking programming](../non_blocking) for details. ### Overview @@ -365,18 +386,18 @@ Note that the driver already has a [built-in retry mechanism] that can transpare queries; the above example should be seen as a demonstration of application-level retries, when a more fine-grained control of what should be retried, and how, is required. -[CqlSession]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/CqlSession.html -[ReactiveSession]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/cql/reactive/ReactiveSession.html -[ResultSet]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/ResultSet.html -[ReactiveResultSet]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/cql/reactive/ReactiveResultSet.html -[ReactiveRow]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/cql/reactive/ReactiveRow.html -[Row]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/Row.html -[getColumnDefinitions]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/cql/reactive/ReactiveResultSet.html#getColumnDefinitions-- -[getExecutionInfos]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/cql/reactive/ReactiveResultSet.html#getExecutionInfos-- -[wasApplied]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/cql/reactive/ReactiveResultSet.html#wasApplied-- -[ReactiveRow.getColumnDefinitions]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/cql/reactive/ReactiveRow.html#getColumnDefinitions-- -[ReactiveRow.getExecutionInfo]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/cql/reactive/ReactiveRow.html#getExecutionInfo-- -[ReactiveRow.wasApplied]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/cql/reactive/ReactiveRow.html#wasApplied-- +[CqlSession]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/CqlSession.html +[ReactiveSession]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/cql/reactive/ReactiveSession.html +[ResultSet]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/ResultSet.html +[ReactiveResultSet]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/cql/reactive/ReactiveResultSet.html +[ReactiveRow]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/cql/reactive/ReactiveRow.html +[Row]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/Row.html +[getColumnDefinitions]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/cql/reactive/ReactiveResultSet.html#getColumnDefinitions-- +[getExecutionInfos]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/cql/reactive/ReactiveResultSet.html#getExecutionInfos-- +[wasApplied]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/cql/reactive/ReactiveResultSet.html#wasApplied-- +[ReactiveRow.getColumnDefinitions]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/cql/reactive/ReactiveRow.html#getColumnDefinitions-- +[ReactiveRow.getExecutionInfo]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/cql/reactive/ReactiveRow.html#getExecutionInfo-- +[ReactiveRow.wasApplied]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/cql/reactive/ReactiveRow.html#wasApplied-- [built-in retry mechanism]: ../retries/ [request throttling]: ../throttling/ diff --git a/manual/core/reconnection/README.md b/manual/core/reconnection/README.md index 24290baf9ab..3eb6dad9c05 100644 --- a/manual/core/reconnection/README.md +++ b/manual/core/reconnection/README.md @@ -1,3 +1,22 @@ + + ## Reconnection ### Quick overview @@ -84,7 +103,7 @@ Note that the session is not accessible until it is fully ready: the `CqlSession call — or the future returned by `buildAsync()` — will not complete until the connection was established. -[ConstantReconnectionPolicy]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/internal/core/connection/ConstantReconnectionPolicy.html -[DriverContext]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/context/DriverContext.html -[ExponentialReconnectionPolicy]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/internal/core/connection/ExponentialReconnectionPolicy.html -[ReconnectionPolicy]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/connection/ReconnectionPolicy.html \ No newline at end of file +[ConstantReconnectionPolicy]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/internal/core/connection/ConstantReconnectionPolicy.html +[DriverContext]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/context/DriverContext.html +[ExponentialReconnectionPolicy]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/internal/core/connection/ExponentialReconnectionPolicy.html +[ReconnectionPolicy]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/connection/ReconnectionPolicy.html diff --git a/manual/core/request_id/README.md b/manual/core/request_id/README.md new file mode 100644 index 00000000000..a766a4419af --- /dev/null +++ b/manual/core/request_id/README.md @@ -0,0 +1,48 @@ + + +## Request Id + +### Quick overview + +Users can inject an identifier for each individual CQL request, and such ID can be written in to the [custom payload](https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v5.spec) to +correlate a request across the driver and the Apache Cassandra server. + +A request ID generator needs to generate both: +- Session request ID: an identifier for an entire session.execute() call +- Node request ID: an identifier for the execution of a CQL statement against a particular node. There can be one or more node requests for a single session request, due to retries or speculative executions. + +Usage: +* Inject ID generator: set the desired `RequestIdGenerator` in `advanced.request-id.generator.class`. +* Add ID to custom payload: the default behavior of a `RequestIdGenerator` is to add the request ID into the custom payload with the key `request-id`. Override `RequestIdGenerator.getDecoratedStatement` to customize the behavior. + +### Request Id Generator Configuration + +Request ID generator can be declared in the [configuration](../configuration/) as follows: + +``` +datastax-java-driver.advanced.request-id.generator { + class = com.example.app.MyGenerator +} +``` + +To register your own request ID generator, specify the name of the class +that implements `RequestIdGenerator`. + +The generated ID will be added to the log message of `CqlRequestHandler`, and propagated to other classes, e.g. the request trackers. \ No newline at end of file diff --git a/manual/core/request_tracker/README.md b/manual/core/request_tracker/README.md index dfcf23d4b4b..c135abfe53f 100644 --- a/manual/core/request_tracker/README.md +++ b/manual/core/request_tracker/README.md @@ -1,3 +1,22 @@ + + ## Request tracker ### Quick overview @@ -7,7 +26,7 @@ Callback that gets invoked for every request: success or error, globally and for * `advanced.request-tracker` in the configuration; defaults to none, also available: request logger, or write your own. * or programmatically: - [CqlSession.builder().withRequestTracker()][SessionBuilder.withRequestTracker]. + [CqlSession.builder().addRequestTracker()][SessionBuilder.addRequestTracker]. ----- @@ -16,28 +35,34 @@ every application request. The driver comes with an optional implementation that ### Configuration -The tracker is enabled in the [configuration](../configuration/). The default implementation does -nothing: +Request trackers can be declared in the [configuration](../configuration/) as follows: ``` datastax-java-driver.advanced.request-tracker { - class = NoopRequestTracker + classes = [com.example.app.MyTracker1,com.example.app.MyTracker2] } ``` -To use a different tracker, specify the name of a class that implements [RequestTracker]. One such -class is the built-in request logger (see the next section), you can also create your own -implementation. +By default, no tracker is registered. To register your own trackers, specify the name of a class +that implements [RequestTracker]. One such class is the built-in request logger (see the next +section), but you can also create your own implementation. + +Also, trackers registered via configuration will be instantiated with reflection; they must have a +public constructor taking a `DriverContext` argument. Sometimes you have a tracker instance already in your code, and need to pass it programmatically instead of referencing a class. The session builder has a method for that: ```java -RequestTracker myTracker = ...; -CqlSession session = CqlSession.builder().withRequestTracker(myTracker).build(); +RequestTracker myTracker1 = ...; +RequestTracker myTracker2 = ...; +CqlSession session = CqlSession.builder() + .addRequestTracker(myTracker1) + .addRequestTracker(myTracker2) + .build(); ``` -When you provide the tracker in this manner, the configuration will be ignored. +The two registration methods (programmatic and via the configuration) can be used simultaneously. ### Request logger @@ -46,7 +71,7 @@ requests as "slow" above a given threshold, limit the line size for large querie ``` datastax-java-driver.advanced.request-tracker { - class = RequestLogger + classes = [RequestLogger] logs { # Whether to log successful requests. @@ -117,5 +142,5 @@ all FROM users WHERE user_id=? [v0=42] com.datastax.oss.driver.api.core.servererrors.InvalidQueryException: Undefined column name all ``` -[RequestTracker]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/tracker/RequestTracker.html -[SessionBuilder.withRequestTracker]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/session/SessionBuilder.html#withRequestTracker-com.datastax.oss.driver.api.core.tracker.RequestTracker- \ No newline at end of file +[RequestTracker]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/tracker/RequestTracker.html +[SessionBuilder.addRequestTracker]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/SessionBuilder.html#addRequestTracker-com.datastax.oss.driver.api.core.tracker.RequestTracker- diff --git a/manual/core/retries/README.md b/manual/core/retries/README.md index 8c6190f36b1..e92f8e214aa 100644 --- a/manual/core/retries/README.md +++ b/manual/core/retries/README.md @@ -1,3 +1,22 @@ + + ## Retries ### Quick overview @@ -7,25 +26,56 @@ What to do when a request failed on a node: retry (same or other node), rethrow, * `advanced.retry-policy` in the configuration. Default policy retries at most once, in cases that have a high chance of success; you can also write your own. * can have per-profile policies. -* only kicks in if the query is idempotent. +* only kicks in if the query is [idempotent](../idempotence). ----- When a query fails, it sometimes makes sense to retry it: the error might be temporary, or the query might work on a different node. The driver uses a *retry policy* to determine when and how to retry. -It is defined in the [configuration](../configuration/): - + +### Built-in retry policies + +The driver ships with two retry policies: `DefaultRetryPolicy` –– the default –– and +`ConsistencyDowngradingRetryPolicy`. + +The default retry policy should be preferred in most cases as it only retries when *it is perfectly +safe to do so*, and when *the chances of success are high enough* to warrant a retry. + +`ConsistencyDowngradingRetryPolicy` is provided for cases where the application can tolerate a +temporary degradation of its consistency guarantees. Its general behavior is as follows: if, based +on the information the coordinator returns, retrying the operation with the initially requested +consistency has a chance to succeed, do it. Otherwise, if based on this information, we know that +the initially requested consistency level *cannot be achieved currently*, then: + +* For writes, ignore the exception *if we know the write has been persisted on at least one + replica*. +* For reads, try reading again at a weaker consistency level. + +Keep in mind that this may break invariants! For example, if your application relies on immediate +write visibility by writing and reading at QUORUM only, downgrading a write to ONE could cause that +write to go unnoticed by subsequent reads at QUORUM. Furthermore, this policy doesn't always respect +datacenter locality; for example, it may downgrade LOCAL_QUORUM to ONE, and thus could accidentally +send a write that was intended for the local datacenter to another datacenter. In summary: **only +use this retry policy if you understand the consequences.** + +Since `DefaultRetryPolicy` is already the driver's default retry policy, no special configuration +is required to activate it. To use `ConsistencyDowngradingRetryPolicy` instead, the following +option must be declared in the driver [configuration](../configuration/): + ``` -datastax-java-driver.advanced.retry-policy { - class = DefaultRetryPolicy -} +datastax-java-driver.advanced.retry-policy.class = ConsistencyDowngradingRetryPolicy ``` -The behavior of the default policy will be detailed in the sections below. You can also use your -own policy by specifying the fully-qualified name of a class that implements [RetryPolicy]. +You can also use your own policy by specifying for the above option the fully-qualified name of a +class that implements [RetryPolicy]. + +### Behavior -The policy has several methods that cover different error cases. Each method returns a decision to -indicate what to do next: +The behavior of both policies will be detailed in the sections below. + +The policy has several methods that cover different error cases. Each method returns a +[RetryVerdict]. A retry verdict essentially provides the driver with a [RetryDecision] to indicate +what to do next. There are four possible retry decisions: * retry on the same node; * retry on the next node in the [query plan](../load_balancing/) for this statement; @@ -33,7 +83,7 @@ indicate what to do next: using the asynchronous API); * ignore the exception. That is, mark the request as successful, and return an empty result set. -### onUnavailable +#### `onUnavailableVerdict` A request reached the coordinator, but there weren't enough live replicas to achieve the requested consistency level. The coordinator replied with an `UNAVAILABLE` error. @@ -48,7 +98,14 @@ rationale is that the first coordinator might have been network-isolated from al (thinking they're down), but still able to communicate with the client; in that case, retrying on the same node has almost no chance of success, but moving to the next node might solve the issue. -### onReadTimeout +`ConsistencyDowngradingRetryPolicy` also triggers a maximum of one retry, but instead of trying the +next node, it will downgrade the initial consistency level, if possible, and retry *the same node*. +Note that if it is not possible to downgrade, this policy will rethrow the exception. For example, +if the original consistency level was QUORUM, and 2 replicas were required to achieve a quorum, but +only one replica is alive, then the query will be retried with consistency ONE. If no replica was +alive however, there is no point in downgrading, and the policy will rethrow. + +#### `onReadTimeoutVerdict` A read request reached the coordinator, which initially believed that there were enough live replicas to process it. But one or several replicas were too slow to answer within the predefined @@ -73,7 +130,12 @@ retrieval, not having detected that replica as dead yet. The reasoning is that b the timeout, the dead replica will likely have been detected as dead and the retry has a high chance of success. -### onWriteTimeout +`ConsistencyDowngradingRetryPolicy` behaves like the default policy when enough replicas responded. +If not enough replicas responded however, it will attempt to downgrade the initial consistency +level, and retry *the same node*. If it is not possible to downgrade, this policy will rethrow the +exception. + +#### `onWriteTimeoutVerdict` This is similar to `onReadTimeout`, but for write operations. The reason reads and writes are handled separately is because a read is obviously a non mutating operation, whereas a write is @@ -91,7 +153,20 @@ small subset of nodes in the local datacenter; a timeout usually means that none alive but the coordinator hadn't detected them as dead yet. By the time we get the timeout, the dead nodes will likely have been detected as dead, and the retry has a high chance of success. -### onRequestAborted +`ConsistencyDowngradingRetryPolicy` also triggers a maximum of one retry, but behaves differently: + +* For `SIMPLE` and `BATCH` write types: if at least one replica acknowledged the write, the policy + will assume that the write will be eventually replicated, and decide to ignore the error; in other + words, it will consider that the write already succeeded, albeit with weaker consistency + guarantees: retrying is therefore useless. If no replica acknowledged the write, the policy will + rethrow the error. +* For `UNLOGGED_BATCH` write type: since only part of the batch could have been persisted, the + policy will attempt to downgrade the consistency level and retry *on the same node*. If + downgrading is not possible, the policy will rethrow. +* For `BATCH_LOG` write type: the policy will retry the same node, for the reasons explained above. +* For other write types: the policy will always rethrow. + +#### `onRequestAbortedVerdict` The request was aborted before we could get a response from the coordinator. This can happen in two cases: @@ -104,10 +179,10 @@ cases: This method is only invoked for [idempotent](../idempotence/) statements. Otherwise, the driver bypasses the retry policy and always rethrows the error. -The default policy retries on the next node if the connection was closed, and rethrows (assuming a -driver bug) in all other cases. +Both the default policy and `ConsistencyDowngradingRetryPolicy` retry on the next node if the +connection was closed, and rethrow (assuming a driver bug) in all other cases. -### onErrorResponse +#### `onErrorResponseVerdict` The coordinator replied with an error other than `READ_TIMEOUT`, `WRITE_TIMEOUT` or `UNAVAILABLE`. Namely, this covers [OverloadedException], [ServerError], [TruncateException], @@ -116,7 +191,8 @@ Namely, this covers [OverloadedException], [ServerError], [TruncateException], This method is only invoked for [idempotent](../idempotence/) statements. Otherwise, the driver bypasses the retry policy and always rethrows the error. -The default policy rethrows read and write failures, and retries other errors on the next node. +Both the default policy and `ConsistencyDowngradingRetryPolicy` rethrow read and write failures, +and retry other errors on the next node. ### Hard-coded rules @@ -174,20 +250,21 @@ configuration). Each request uses its declared profile's policy. If it doesn't declare any profile, or if the profile doesn't have a dedicated policy, then the default profile's policy is used. -[AllNodesFailedException]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/AllNodesFailedException.html -[ClosedConnectionException]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/connection/ClosedConnectionException.html -[DriverTimeoutException]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/DriverTimeoutException.html -[FunctionFailureException]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/servererrors/FunctionFailureException.html -[HeartbeatException]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/connection/HeartbeatException.html -[ProtocolError]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/servererrors/ProtocolError.html -[OverloadedException]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/servererrors/OverloadedException.html -[QueryValidationException]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/servererrors/QueryValidationException.html -[ReadFailureException]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/servererrors/ReadFailureException.html -[ReadTimeoutException]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/servererrors/ReadTimeoutException.html -[RetryDecision]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/retry/RetryDecision.html -[RetryPolicy]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/retry/RetryPolicy.html -[ServerError]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/servererrors/ServerError.html -[TruncateException]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/servererrors/TruncateException.html -[UnavailableException]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/servererrors/UnavailableException.html -[WriteFailureException]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/servererrors/WriteFailureException.html -[WriteTimeoutException]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/servererrors/WriteTimeoutException.html +[AllNodesFailedException]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/AllNodesFailedException.html +[ClosedConnectionException]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/connection/ClosedConnectionException.html +[DriverTimeoutException]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/DriverTimeoutException.html +[FunctionFailureException]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/servererrors/FunctionFailureException.html +[HeartbeatException]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/connection/HeartbeatException.html +[ProtocolError]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/servererrors/ProtocolError.html +[OverloadedException]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/servererrors/OverloadedException.html +[QueryValidationException]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/servererrors/QueryValidationException.html +[ReadFailureException]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/servererrors/ReadFailureException.html +[ReadTimeoutException]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/servererrors/ReadTimeoutException.html +[RetryDecision]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/retry/RetryDecision.html +[RetryPolicy]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/retry/RetryPolicy.html +[RetryVerdict]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/retry/RetryVerdict.html +[ServerError]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/servererrors/ServerError.html +[TruncateException]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/servererrors/TruncateException.html +[UnavailableException]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/servererrors/UnavailableException.html +[WriteFailureException]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/servererrors/WriteFailureException.html +[WriteTimeoutException]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/servererrors/WriteTimeoutException.html diff --git a/manual/core/shaded_jar/README.md b/manual/core/shaded_jar/README.md index 2f52e44c6a4..8e183c0efb5 100644 --- a/manual/core/shaded_jar/README.md +++ b/manual/core/shaded_jar/README.md @@ -1,3 +1,22 @@ + + ## Using the shaded JAR The default `java-driver-core` JAR depends on a number of [third party @@ -10,7 +29,7 @@ dependency to `java-driver-core` by: ```xml - com.datastax.oss + org.apache.cassandra java-driver-core-shaded ${driver.version} @@ -21,18 +40,18 @@ you need to remove its dependency to the non-shaded JAR: ```xml - com.datastax.oss + org.apache.cassandra java-driver-core-shaded ${driver.version} - com.datastax.oss + org.apache.cassandra java-driver-query-builder ${driver.version} - com.datastax.oss + org.apache.cassandra java-driver-core @@ -51,7 +70,7 @@ Notes: ```xml - com.datastax.oss + org.apache.cassandra java-driver-core ${driver.version} diff --git a/manual/core/speculative_execution/README.md b/manual/core/speculative_execution/README.md index aa324c53c4f..5666d6a1363 100644 --- a/manual/core/speculative_execution/README.md +++ b/manual/core/speculative_execution/README.md @@ -1,3 +1,22 @@ + + ## Speculative query execution ### Quick overview @@ -250,4 +269,4 @@ profiles have the same configuration). Each request uses its declared profile's policy. If it doesn't declare any profile, or if the profile doesn't have a dedicated policy, then the default profile's policy is used. -[SpeculativeExecutionPolicy]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/specex/SpeculativeExecutionPolicy.html \ No newline at end of file +[SpeculativeExecutionPolicy]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/specex/SpeculativeExecutionPolicy.html diff --git a/manual/core/ssl/README.md b/manual/core/ssl/README.md index de3a05f59ad..913c7bc6c9a 100644 --- a/manual/core/ssl/README.md +++ b/manual/core/ssl/README.md @@ -1,3 +1,22 @@ + + ## SSL ### Quick overview @@ -75,11 +94,13 @@ If you're using a CA, sign the client certificate with it (see the blog post lin this page). Then the nodes' truststores only need to contain the CA's certificate (which should already be the case if you've followed the steps for inter-node encryption). +`DefaultSslEngineFactory` supports client keystore reloading; see property +`advanced.ssl-engine-factory.keystore-reload-interval`. ### Driver configuration By default, the driver's SSL support is based on the JDK's built-in implementation: JSSE (Java -Secure Socket Extension),. +Secure Socket Extension). To enable it, you need to define an engine factory in the [configuration](../configuration/). @@ -107,6 +128,12 @@ datastax-java-driver { // truststore-password = password123 // keystore-path = /path/to/client.keystore // keystore-password = password123 + + # The duration between attempts to reload the keystore from the contents of the file specified + # by `keystore-path`. This is mainly relevant in environments where certificates have short + # lifetimes and applications are restarted infrequently, since an expired client certificate + # will prevent new connections from being established until the application is restarted. + // keystore-reload-interval = 30 minutes } } ``` @@ -204,6 +231,6 @@ the box, but with a bit of custom development it is fairly easy to add. See [dsClientToNode]: https://docs.datastax.com/en/cassandra/3.0/cassandra/configuration/secureSSLClientToNode.html [pickle]: http://thelastpickle.com/blog/2015/09/30/hardening-cassandra-step-by-step-part-1-server-to-server.html [JSSE system properties]: http://docs.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html#Customization -[SessionBuilder.withSslEngineFactory]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/session/SessionBuilder.html#withSslEngineFactory-com.datastax.oss.driver.api.core.ssl.SslEngineFactory- -[SessionBuilder.withSslContext]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/session/SessionBuilder.html#withSslContext-javax.net.ssl.SSLContext- -[ProgrammaticSslEngineFactory]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/ssl/ProgrammaticSslEngineFactory.html +[SessionBuilder.withSslEngineFactory]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/SessionBuilder.html#withSslEngineFactory-com.datastax.oss.driver.api.core.ssl.SslEngineFactory- +[SessionBuilder.withSslContext]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/SessionBuilder.html#withSslContext-javax.net.ssl.SSLContext- +[ProgrammaticSslEngineFactory]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/ssl/ProgrammaticSslEngineFactory.html diff --git a/manual/core/statements/README.md b/manual/core/statements/README.md index 8587aa7ffc6..394e81ae00e 100644 --- a/manual/core/statements/README.md +++ b/manual/core/statements/README.md @@ -1,3 +1,22 @@ + + ## Statements ### Quick overview @@ -59,7 +78,7 @@ the [configuration](../configuration/). Namely, these are: idempotent flag, quer consistency levels and page size. We recommended the configuration approach whenever possible (you can create execution profiles to capture common combinations of those options). -[Statement]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/Statement.html -[StatementBuilder]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/StatementBuilder.html -[execute]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/session/Session.html#execute-com.datastax.oss.driver.api.core.cql.Statement- -[executeAsync]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/session/Session.html#executeAsync-com.datastax.oss.driver.api.core.cql.Statement- +[Statement]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/Statement.html +[StatementBuilder]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/StatementBuilder.html +[execute]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/Session.html#execute-com.datastax.oss.driver.api.core.cql.Statement- +[executeAsync]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/Session.html#executeAsync-com.datastax.oss.driver.api.core.cql.Statement- diff --git a/manual/core/statements/batch/README.md b/manual/core/statements/batch/README.md index b691e1ea292..f080fe16ab0 100644 --- a/manual/core/statements/batch/README.md +++ b/manual/core/statements/batch/README.md @@ -1,3 +1,22 @@ + + ## Batch statements ### Quick overview @@ -61,8 +80,8 @@ In addition, simple statements with named parameters are currently not supported due to a [protocol limitation][CASSANDRA-10246] that will be fixed in a future version). If you try to execute such a batch, an `IllegalArgumentException` is thrown. -[BatchStatement]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/BatchStatement.html -[BatchStatement.newInstance()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/BatchStatement.html#newInstance-com.datastax.oss.driver.api.core.cql.BatchType- -[BatchStatement.builder()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/BatchStatement.html#builder-com.datastax.oss.driver.api.core.cql.BatchType- +[BatchStatement]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/BatchStatement.html +[BatchStatement.newInstance()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/BatchStatement.html#newInstance-com.datastax.oss.driver.api.core.cql.BatchType- +[BatchStatement.builder()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/BatchStatement.html#builder-com.datastax.oss.driver.api.core.cql.BatchType- [batch_dse]: http://docs.datastax.com/en/dse/6.7/cql/cql/cql_using/useBatch.html [CASSANDRA-10246]: https://issues.apache.org/jira/browse/CASSANDRA-10246 diff --git a/manual/core/statements/per_query_keyspace/README.md b/manual/core/statements/per_query_keyspace/README.md index cc61e732e2b..9a7ffa338c9 100644 --- a/manual/core/statements/per_query_keyspace/README.md +++ b/manual/core/statements/per_query_keyspace/README.md @@ -1,3 +1,22 @@ + + ## Per-query keyspace ### Quick overview @@ -124,6 +143,6 @@ SimpleStatement statement = At some point in the future, when Cassandra 4 becomes prevalent and using a per-query keyspace is the norm, we'll probably deprecate `setRoutingKeyspace()`. -[token-aware routing]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/session/Request.html#getRoutingKey-- +[token-aware routing]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/Request.html#getRoutingKey-- -[CASSANDRA-10145]: https://issues.apache.org/jira/browse/CASSANDRA-10145 \ No newline at end of file +[CASSANDRA-10145]: https://issues.apache.org/jira/browse/CASSANDRA-10145 diff --git a/manual/core/statements/prepared/README.md b/manual/core/statements/prepared/README.md index 17ffefd39bf..5a87b238cbc 100644 --- a/manual/core/statements/prepared/README.md +++ b/manual/core/statements/prepared/README.md @@ -1,3 +1,22 @@ + + ## Prepared statements ### Quick overview @@ -330,10 +349,10 @@ With Cassandra 4 and [native protocol](../../native_protocol/) v5, this issue is new version with the response; the driver updates its local cache transparently, and the client can observe the new columns in the result set. -[BoundStatement]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/BoundStatement.html -[Session.prepare]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/CqlSession.html#prepare-com.datastax.oss.driver.api.core.cql.SimpleStatement- +[BoundStatement]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/BoundStatement.html +[Session.prepare]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/CqlSession.html#prepare-com.datastax.oss.driver.api.core.cql.SimpleStatement- [CASSANDRA-10786]: https://issues.apache.org/jira/browse/CASSANDRA-10786 [CASSANDRA-10813]: https://issues.apache.org/jira/browse/CASSANDRA-10813 [guava eviction]: https://github.com/google/guava/wiki/CachesExplained#reference-based-eviction -[PreparedStatement.bind]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/PreparedStatement.html#bind-java.lang.Object...- -[PreparedStatement.boundStatementBuilder]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/PreparedStatement.html#boundStatementBuilder-java.lang.Object...- +[PreparedStatement.bind]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/PreparedStatement.html#bind-java.lang.Object...- +[PreparedStatement.boundStatementBuilder]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/PreparedStatement.html#boundStatementBuilder-java.lang.Object...- diff --git a/manual/core/statements/simple/README.md b/manual/core/statements/simple/README.md index a9599d9ed12..13ddbb7a389 100644 --- a/manual/core/statements/simple/README.md +++ b/manual/core/statements/simple/README.md @@ -1,3 +1,22 @@ + + ## Simple statements ### Quick overview @@ -182,6 +201,6 @@ session.execute( Or you could also use [prepared statements](../prepared/), which don't have this limitation since parameter types are known in advance. -[SimpleStatement]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/SimpleStatement.html -[SimpleStatement.newInstance()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/SimpleStatement.html#newInstance-java.lang.String- -[SimpleStatement.builder()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/SimpleStatement.html#builder-java.lang.String- +[SimpleStatement]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/SimpleStatement.html +[SimpleStatement.newInstance()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/SimpleStatement.html#newInstance-java.lang.String- +[SimpleStatement.builder()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/SimpleStatement.html#builder-java.lang.String- diff --git a/manual/core/temporal_types/README.md b/manual/core/temporal_types/README.md index 17467e8d6c5..6542d5b8dac 100644 --- a/manual/core/temporal_types/README.md +++ b/manual/core/temporal_types/README.md @@ -1,3 +1,22 @@ + + ## Temporal types ### Quick overview @@ -146,7 +165,7 @@ System.out.println(dateTime.minus(CqlDuration.from("1h15s15ns"))); // prints "2018-10-03T22:59:44.999999985-07:00[America/Los_Angeles]" ``` -[CqlDuration]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/data/CqlDuration.html -[TypeCodecs.ZONED_TIMESTAMP_SYSTEM]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/TypeCodecs.html#ZONED_TIMESTAMP_SYSTEM -[TypeCodecs.ZONED_TIMESTAMP_UTC]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/TypeCodecs.html#ZONED_TIMESTAMP_UTC -[TypeCodecs.zonedTimestampAt()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/TypeCodecs.html#zonedTimestampAt-java.time.ZoneId- \ No newline at end of file +[CqlDuration]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/data/CqlDuration.html +[TypeCodecs.ZONED_TIMESTAMP_SYSTEM]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/TypeCodecs.html#ZONED_TIMESTAMP_SYSTEM +[TypeCodecs.ZONED_TIMESTAMP_UTC]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/TypeCodecs.html#ZONED_TIMESTAMP_UTC +[TypeCodecs.zonedTimestampAt()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/TypeCodecs.html#zonedTimestampAt-java.time.ZoneId- diff --git a/manual/core/throttling/README.md b/manual/core/throttling/README.md index 7eee629ae5a..275c0cb5b40 100644 --- a/manual/core/throttling/README.md +++ b/manual/core/throttling/README.md @@ -1,3 +1,22 @@ + + ## Request throttling ### Quick overview @@ -145,6 +164,6 @@ datastax-java-driver { If you enable `throttling.delay`, make sure to also check the associated extra options to correctly size the underlying histograms (`metrics.session.throttling.delay.*`). -[RequestThrottlingException]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/RequestThrottlingException.html -[AllNodesFailedException]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/AllNodesFailedException.html -[BusyConnectionException]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/connection/BusyConnectionException.html \ No newline at end of file +[RequestThrottlingException]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/RequestThrottlingException.html +[AllNodesFailedException]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/AllNodesFailedException.html +[BusyConnectionException]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/connection/BusyConnectionException.html diff --git a/manual/core/tracing/README.md b/manual/core/tracing/README.md index adb267bf07a..f9beca8e49b 100644 --- a/manual/core/tracing/README.md +++ b/manual/core/tracing/README.md @@ -1,3 +1,22 @@ + + ## Query tracing ### Quick overview @@ -113,9 +132,9 @@ for (TraceEvent event : trace.getEvents()) { If you call `getQueryTrace()` for a statement that didn't have tracing enabled, an exception is thrown. -[ExecutionInfo]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/ExecutionInfo.html -[QueryTrace]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/QueryTrace.html -[Statement.setTracing()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/Statement.html#setTracing-boolean- -[StatementBuilder.setTracing()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/StatementBuilder.html#setTracing-- -[ExecutionInfo.getTracingId()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/ExecutionInfo.html#getTracingId-- -[ExecutionInfo.getQueryTrace()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/ExecutionInfo.html#getQueryTrace-- +[ExecutionInfo]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/ExecutionInfo.html +[QueryTrace]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/QueryTrace.html +[Statement.setTracing()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/Statement.html#setTracing-boolean- +[StatementBuilder.setTracing()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/StatementBuilder.html#setTracing-- +[ExecutionInfo.getTracingId()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/ExecutionInfo.html#getTracingId-- +[ExecutionInfo.getQueryTrace()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/ExecutionInfo.html#getQueryTrace-- diff --git a/manual/core/tuples/README.md b/manual/core/tuples/README.md index 763f6d3ebba..d0684b77569 100644 --- a/manual/core/tuples/README.md +++ b/manual/core/tuples/README.md @@ -1,3 +1,22 @@ + + ## Tuples ### Quick overview @@ -139,5 +158,5 @@ BoundStatement bs = [cql_doc]: https://docs.datastax.com/en/cql/3.3/cql/cql_reference/tupleType.html -[TupleType]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/TupleType.html -[TupleValue]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/data/TupleValue.html +[TupleType]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/TupleType.html +[TupleValue]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/data/TupleValue.html diff --git a/manual/core/udts/README.md b/manual/core/udts/README.md index 12584c140cb..a22057030ae 100644 --- a/manual/core/udts/README.md +++ b/manual/core/udts/README.md @@ -1,3 +1,22 @@ + + ## User-defined types ### Quick overview @@ -135,5 +154,5 @@ session.execute(bs); [cql_doc]: https://docs.datastax.com/en/cql/3.3/cql/cql_reference/cqlRefUDType.html -[UdtValue]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/data/UdtValue.html -[UserDefinedType]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/UserDefinedType.html \ No newline at end of file +[UdtValue]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/data/UdtValue.html +[UserDefinedType]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/UserDefinedType.html diff --git a/manual/developer/README.md b/manual/developer/README.md index 975ab16c176..b6e0bda16ed 100644 --- a/manual/developer/README.md +++ b/manual/developer/README.md @@ -1,3 +1,22 @@ + + ## Developer docs This section explains how driver internals work. The intended audience is: @@ -16,4 +35,4 @@ from lowest to highest level: * [Request execution](request_execution/): higher-level handling of user requests and responses; * [Administrative tasks](admin/): everything else (cluster state and metadata). -If you're reading this on GitHub, the `.nav` file in each directory contains a suggested order. \ No newline at end of file +If you're reading this on GitHub, the `.nav` file in each directory contains a suggested order. diff --git a/manual/developer/admin/README.md b/manual/developer/admin/README.md index def3b6a2927..0ebd9e2d746 100644 --- a/manual/developer/admin/README.md +++ b/manual/developer/admin/README.md @@ -1,3 +1,22 @@ + + ## Administrative tasks Aside from the main task of [executing user requests](../request_execution), the driver also needs @@ -320,4 +339,4 @@ It's less likely that this will be overridden directly. But the schema querying abstracted behind two factories that handle the differences between Cassandra versions: `SchemaQueriesFactory` and `SchemaParserFactory`. These are pluggable by [extending the context](../common/context/#overriding-a-context-component) and overriding the corresponding -`buildXxx` methods. \ No newline at end of file +`buildXxx` methods. diff --git a/manual/developer/common/README.md b/manual/developer/common/README.md index c227f0826a5..13ad8639e62 100644 --- a/manual/developer/common/README.md +++ b/manual/developer/common/README.md @@ -1,3 +1,22 @@ + + ## Common infrastructure This covers utilities or concept that are shared throughout the codebase: diff --git a/manual/developer/common/concurrency/README.md b/manual/developer/common/concurrency/README.md index 3c6078f2eb4..fb493930d6e 100644 --- a/manual/developer/common/concurrency/README.md +++ b/manual/developer/common/concurrency/README.md @@ -1,3 +1,22 @@ + + ## Concurrency The driver is a highly concurrent environment. We try to use thread confinement to simplify the @@ -77,12 +96,16 @@ fields, and methods are guaranteed to always run in isolation, eliminating subtl ### Non-blocking -Whether on the hot or cold path, internal code **never blocks**. If an internal component needs to -execute a query, it does so asynchronously, and registers callbacks to process the results. -Examples of this can be found in `ReprepareOnUp` and `DefaultTopologyMonitor` (among others). +Whether on the hot or cold path, internal code is almost 100% lock-free. The driver guarantees on +lock-freedom are [detailed](../../../core/non_blocking) in the core manual. + +If an internal component needs to execute a query, it does so asynchronously, and registers +callbacks to process the results. Examples of this can be found in `ReprepareOnUp` and +`DefaultTopologyMonitor` (among others). -The only place where the driver blocks are synchronous wrapper methods in the public API, for -example: +The only place where the driver blocks is when using the synchronous API (methods declared in +[`SyncCqlSession`]), and when calling other synchronous wrapper methods in the public API, for +example, [`ExecutionInfo.getQueryTrace()`]: ```java public interface ExecutionInfo { @@ -95,6 +118,11 @@ public interface ExecutionInfo { } ``` +When a public API method is blocking, this is generally clearly stated in its javadocs. + +[`ExecutionInfo.getQueryTrace()`]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/ExecutionInfo.html#getQueryTrace-- +[`SyncCqlSession`]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/SyncCqlSession.html` + `BlockingOperation` is a utility to check that those methods aren't called on I/O threads, which could introduce deadlocks. diff --git a/manual/developer/common/context/README.md b/manual/developer/common/context/README.md index 3c6143e970d..e20d5ad0ddb 100644 --- a/manual/developer/common/context/README.md +++ b/manual/developer/common/context/README.md @@ -1,3 +1,22 @@ + + ## Driver context The context holds the driver's internal components. It is exposed in the public API as diff --git a/manual/developer/common/event_bus/README.md b/manual/developer/common/event_bus/README.md index 837f8c69082..74729ac6656 100644 --- a/manual/developer/common/event_bus/README.md +++ b/manual/developer/common/event_bus/README.md @@ -1,3 +1,22 @@ + + ## Event bus `EventBus` is a bare-bones messaging mechanism, to decouple components from each other, and diff --git a/manual/developer/native_protocol/README.md b/manual/developer/native_protocol/README.md index 11c936d272b..b96553fc51b 100644 --- a/manual/developer/native_protocol/README.md +++ b/manual/developer/native_protocol/README.md @@ -1,3 +1,22 @@ + + ## Native protocol layer The native protocol layer encodes protocol messages into binary, before they are sent over the @@ -9,10 +28,8 @@ This part of the code lives in its own project: The protocol specifications are available in [native-protocol/src/main/resources](https://github.com/datastax/native-protocol/tree/1.x/src/main/resources). -These files originally come from Cassandra, we copy them over for easy access. Note that, if the -latest version is a beta (this is the case for v5 at the time of writing -- September 2019), the -specification might not be up to date. Always compare with the latest revision in -[cassandra/doc](https://github.com/apache/cassandra/tree/trunk/doc). +These files originally come from Cassandra, we copy them over for easy access. Authoritative specifications can +always be found in [cassandra/doc](https://github.com/apache/cassandra/tree/trunk/doc). For a broad overview of how protocol types are used in the driver, let's step through an example: diff --git a/manual/developer/netty_pipeline/README.md b/manual/developer/netty_pipeline/README.md index 58a32a67a59..b596832e202 100644 --- a/manual/developer/netty_pipeline/README.md +++ b/manual/developer/netty_pipeline/README.md @@ -1,3 +1,22 @@ + + ## Netty pipeline With the [protocol layer](../native_protocol) in place, the next step is to build the logic for a @@ -158,4 +177,4 @@ boringssl. This requires a bit of custom development against the internal API: [SslContext]: https://netty.io/4.1/api/io/netty/handler/ssl/SslContext.html [SslContext.newHandler]: https://netty.io/4.1/api/io/netty/handler/ssl/SslContext.html#newHandler-io.netty.buffer.ByteBufAllocator- -[SslContextBuilder.forClient]: https://netty.io/4.1/api/io/netty/handler/ssl/SslContextBuilder.html#forClient-- \ No newline at end of file +[SslContextBuilder.forClient]: https://netty.io/4.1/api/io/netty/handler/ssl/SslContextBuilder.html#forClient-- diff --git a/manual/developer/request_execution/README.md b/manual/developer/request_execution/README.md index c6ec04e3b1a..38a0a55fbd7 100644 --- a/manual/developer/request_execution/README.md +++ b/manual/developer/request_execution/README.md @@ -1,3 +1,22 @@ + + ## Request execution The [Netty pipeline](../netty_pipeline/) gives us the ability to send low-level protocol messages on diff --git a/manual/mapper/README.md b/manual/mapper/README.md index 8e745bf44f9..27005b671ad 100644 --- a/manual/mapper/README.md +++ b/manual/mapper/README.md @@ -1,10 +1,29 @@ + + ## Mapper The mapper generates the boilerplate to execute queries and convert the results into application-level objects. -It is published as two artifacts: `com.datastax.oss:java-driver-mapper-processor` and -`com.datastax.oss:java-driver-mapper-runtime`. See [Integration](config/) for detailed instructions +It is published as two artifacts: `org.apache.cassandra:java-driver-mapper-processor` and +`org.apache.cassandra:java-driver-mapper-runtime`. See [Integration](config/) for detailed instructions for different build tools. ### Quick start diff --git a/manual/mapper/config/README.md b/manual/mapper/config/README.md index 5a6df9d2ba7..1e4f9981306 100644 --- a/manual/mapper/config/README.md +++ b/manual/mapper/config/README.md @@ -1,3 +1,22 @@ + + ## Integration ### Builds tools @@ -21,7 +40,7 @@ configuration (make sure you use version 3.5 or higher): - com.datastax.oss + org.apache.cassandra java-driver-mapper-runtime ${java-driver.version} @@ -37,7 +56,7 @@ configuration (make sure you use version 3.5 or higher): 1.8 - com.datastax.oss + org.apache.cassandra java-driver-mapper-processor ${java-driver.version} @@ -61,13 +80,13 @@ as a regular dependency in the "provided" scope: ```xml - com.datastax.oss + org.apache.cassandra java-driver-mapper-processor ${java-driver.version} provided - com.datastax.oss + org.apache.cassandra java-driver-mapper-runtime ${java-driver.version} diff --git a/manual/mapper/config/kotlin/README.md b/manual/mapper/config/kotlin/README.md index 533ccb62e57..a78bf04fb79 100644 --- a/manual/mapper/config/kotlin/README.md +++ b/manual/mapper/config/kotlin/README.md @@ -1,3 +1,22 @@ + + ## Kotlin [Kotlin](https://kotlinlang.org/) is an alternative language for the JVM. Its compact syntax and @@ -79,7 +98,7 @@ before compilation: - com.datastax.oss + org.apache.cassandra java-driver-mapper-processor ${java-driver.version} @@ -106,4 +125,4 @@ before compilation: [build.gradle]: https://github.com/DataStax-Examples/object-mapper-jvm/blob/master/kotlin/build.gradle [UserDao.kt]: https://github.com/DataStax-Examples/object-mapper-jvm/blob/master/kotlin/src/main/kotlin/com/datastax/examples/mapper/killrvideo/user/UserDao.kt -[@PropertyStrategy]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/PropertyStrategy.html +[@PropertyStrategy]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/PropertyStrategy.html diff --git a/manual/mapper/config/lombok/README.md b/manual/mapper/config/lombok/README.md index e2a4f0263c8..b87f8f79ea4 100644 --- a/manual/mapper/config/lombok/README.md +++ b/manual/mapper/config/lombok/README.md @@ -1,3 +1,22 @@ + + ## Lombok [Lombok](https://projectlombok.org/) is a popular library that automates repetitive code, such as diff --git a/manual/mapper/config/record/README.md b/manual/mapper/config/record/README.md index 3a3b1d6e39e..95530d52742 100644 --- a/manual/mapper/config/record/README.md +++ b/manual/mapper/config/record/README.md @@ -1,3 +1,22 @@ + + ## Java 14 Records Java 14 introduced [Record] as a lightweight, immutable alternative to POJOs. You can map annotated @@ -27,7 +46,7 @@ You need to build with Java 14, and pass the `--enable-preview` flag to both the runtime JVM. See [pom.xml] in the example. -[@PropertyStrategy]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/PropertyStrategy.html +[@PropertyStrategy]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/PropertyStrategy.html [DataStax-Examples/object-mapper-jvm/record]: https://github.com/DataStax-Examples/object-mapper-jvm/tree/master/record [pom.xml]: https://github.com/DataStax-Examples/object-mapper-jvm/blob/master/record/pom.xml diff --git a/manual/mapper/config/scala/README.md b/manual/mapper/config/scala/README.md index 46749d10286..2cb75273d0b 100644 --- a/manual/mapper/config/scala/README.md +++ b/manual/mapper/config/scala/README.md @@ -1,3 +1,22 @@ + + ## Scala [Scala](https://www.scala-lang.org/) is an alternative language for the JVM. It doesn't support @@ -54,4 +73,4 @@ mapper builder. [DataStax-Examples/object-mapper-jvm/scala]: https://github.com/DataStax-Examples/object-mapper-jvm/tree/master/scala [build.sbt]: https://github.com/DataStax-Examples/object-mapper-jvm/blob/master/scala/build.sbt -[@PropertyStrategy]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/PropertyStrategy.html +[@PropertyStrategy]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/PropertyStrategy.html diff --git a/manual/mapper/daos/README.md b/manual/mapper/daos/README.md index a29af184550..d12172bf056 100644 --- a/manual/mapper/daos/README.md +++ b/manual/mapper/daos/README.md @@ -1,3 +1,22 @@ + + ## DAOs ### Quick overview @@ -148,8 +167,8 @@ In this case, any annotations declared in `Dao1` would be chosen over `Dao2`. To control how the hierarchy is scanned, annotate interfaces with [@HierarchyScanStrategy]. -[@Dao]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/Dao.html -[@DaoFactory]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/DaoFactory.html -[@DefaultNullSavingStrategy]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/DefaultNullSavingStrategy.html -[@HierarchyScanStrategy]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/HierarchyScanStrategy.html +[@Dao]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/Dao.html +[@DaoFactory]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/DaoFactory.html +[@DefaultNullSavingStrategy]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/DefaultNullSavingStrategy.html +[@HierarchyScanStrategy]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/HierarchyScanStrategy.html [Entity Inheritance]: ../entities/#inheritance diff --git a/manual/mapper/daos/custom_types/README.md b/manual/mapper/daos/custom_types/README.md index 18b3900eafc..19f689655a7 100644 --- a/manual/mapper/daos/custom_types/README.md +++ b/manual/mapper/daos/custom_types/README.md @@ -1,3 +1,22 @@ + + ## Custom result types The mapper supports a pre-defined set of built-in types for DAO method results. For example, a @@ -236,8 +255,8 @@ flag: With this configuration, if a DAO method declares a non built-in return type, it will be surfaced as a compiler error. -[EntityHelper]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/entity/EntityHelper.html -[GenericType]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/reflect/GenericType.html -[MapperContext]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/MapperContext.html -[MapperResultProducer]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/result/MapperResultProducer.html -[MapperResultProducerService]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/result/MapperResultProducerService.html +[EntityHelper]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/entity/EntityHelper.html +[GenericType]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/reflect/GenericType.html +[MapperContext]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/MapperContext.html +[MapperResultProducer]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/result/MapperResultProducer.html +[MapperResultProducerService]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/result/MapperResultProducerService.html diff --git a/manual/mapper/daos/delete/README.md b/manual/mapper/daos/delete/README.md index 5fc0550fb02..e67ecdc8a6e 100644 --- a/manual/mapper/daos/delete/README.md +++ b/manual/mapper/daos/delete/README.md @@ -1,3 +1,22 @@ + + ## Delete methods Annotate a DAO method with [@Delete] to generate a query that deletes an [Entity](../../entities): @@ -151,16 +170,16 @@ If a table was specified when creating the DAO, then the generated query targets Otherwise, it uses the default table name for the entity (which is determined by the name of the entity class and the [naming strategy](../../entities/#naming-strategy)). -[default keyspace]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/session/SessionBuilder.html#withKeyspace-com.datastax.oss.driver.api.core.CqlIdentifier- -[AsyncResultSet]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/AsyncResultSet.html -[@ClusteringColumn]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/ClusteringColumn.html -[@Delete]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/Delete.html -[@PartitionKey]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/PartitionKey.html -[ResultSet]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/ResultSet.html -[ResultSet#wasApplied()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/ResultSet.html#wasApplied-- -[BoundStatement]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/BoundStatement.html -[ReactiveResultSet]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/cql/reactive/ReactiveResultSet.html +[default keyspace]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/SessionBuilder.html#withKeyspace-com.datastax.oss.driver.api.core.CqlIdentifier- +[AsyncResultSet]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/AsyncResultSet.html +[@ClusteringColumn]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/ClusteringColumn.html +[@Delete]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/Delete.html +[@PartitionKey]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/PartitionKey.html +[ResultSet]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/ResultSet.html +[ResultSet#wasApplied()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/ResultSet.html#wasApplied-- +[BoundStatement]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/BoundStatement.html +[ReactiveResultSet]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/cql/reactive/ReactiveResultSet.html [CompletionStage]: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletionStage.html -[CompletableFuture]: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html \ No newline at end of file +[CompletableFuture]: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html diff --git a/manual/mapper/daos/getentity/README.md b/manual/mapper/daos/getentity/README.md index b4228a0fce1..de9a530b558 100644 --- a/manual/mapper/daos/getentity/README.md +++ b/manual/mapper/daos/getentity/README.md @@ -1,3 +1,22 @@ + + ## GetEntity methods Annotate a DAO method with [@GetEntity] to convert a core driver data structure into one or more @@ -23,6 +42,54 @@ product.setDescription(row.get("description", String.class)); It does not perform a query. Instead, those methods are intended for cases where you already have a query result, and just need the conversion logic. +### Lenient mode + +By default, the mapper operates in "strict" mode: the source row must contain a matching column for +every property in the entity definition, *including computed ones*. If such a column is not found, +an error will be thrown. + +Starting with driver 4.12.0, the `@GetEntity` annotation has a new `lenient` attribute. If this +attribute is explicitly set to `true`, the mapper will operate in "lenient" mode: all entity +properties that have a matching column in the source row will be set. However, *unmatched properties +will be left untouched*. + +As an example to illustrate how lenient mode works, assume that we have the following entity and +DAO: + +```java +@Entity class Product { + + @PartitionKey int id; + String description; + float price; + // other members omitted +} + +interface ProductDao { + + @GetEntity(lenient = true) + Product getLenient(Row row); + +} +``` + +Then the following code would be possible: + +```java +// row does not contain the price column +Row row = session.execute("SELECT id, description FROM product").one(); +Product product = productDao.getLenient(row); +assert product.price == 0.0; +``` + +Since no `price` column was found in the source row, `product.price` wasn't set and was left to its +default value (0.0). Without lenient mode, the code above would throw an error instead. + +Lenient mode allows to achieve the equivalent of driver 3.x [manual mapping +feature](https://docs.datastax.com/en/developer/java-driver/3.10/manual/object_mapper/using/#manual-mapping). + +**Beware that lenient mode may result in incomplete entities being produced.** + ### Parameters The method must have a single parameter. The following types are allowed: @@ -41,7 +108,7 @@ The method can return: * a single entity instance. If the argument is a result set type, the generated code will extract the first row and convert it, or return `null` if the result set is empty. - ````java + ```java @GetEntity Product asProduct(Row row); @@ -56,7 +123,20 @@ The method can return: @GetEntity PagingIterable asProducts(ResultSet resultSet); ``` - + +* a [Stream] of an entity class. In that case, the type of the parameter **must** be [ResultSet]. + Each row in the result set will be converted into an entity instance. + + Note: even if streams are lazily evaluated, results are fetched synchronously; therefore, as the + returned stream is traversed, blocking calls may occur, as more results are fetched from the + server in the background. For details about the stream's characteristics, see + [PagingIterable.spliterator]. + + ```java + @GetEntity + Stream asProducts(ResultSet resultSet); + ``` + * a [MappedAsyncPagingIterable] of an entity class. In that case, the type of the parameter **must** be [AsyncResultSet]. Each row in the result set will be converted into an entity instance. @@ -69,15 +149,17 @@ If the return type doesn't match the parameter type (for example [PagingIterable [AsyncResultSet]), the mapper processor will issue a compile-time error. -[@GetEntity]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/GetEntity.html -[AsyncResultSet]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/AsyncResultSet.html -[GettableByName]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/data/GettableByName.html -[MappedAsyncPagingIterable]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/MappedAsyncPagingIterable.html -[PagingIterable]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/PagingIterable.html -[ResultSet]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/ResultSet.html -[Row]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/Row.html -[UdtValue]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/data/UdtValue.html +[@GetEntity]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/GetEntity.html +[AsyncResultSet]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/AsyncResultSet.html +[GettableByName]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/data/GettableByName.html +[MappedAsyncPagingIterable]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/MappedAsyncPagingIterable.html +[PagingIterable]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/PagingIterable.html +[PagingIterable.spliterator]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/PagingIterable.html#spliterator-- +[ResultSet]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/ResultSet.html +[Row]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/Row.html +[UdtValue]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/data/UdtValue.html +[Stream]: https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html diff --git a/manual/mapper/daos/increment/README.md b/manual/mapper/daos/increment/README.md index 5c1f2713e2d..44b017be2e1 100644 --- a/manual/mapper/daos/increment/README.md +++ b/manual/mapper/daos/increment/README.md @@ -1,3 +1,22 @@ + + ## Increment methods Annotate a DAO method with [@Increment] to generate a query that updates a counter table that is @@ -75,12 +94,12 @@ If a table was specified when creating the DAO, then the generated query targets Otherwise, it uses the default table name for the entity (which is determined by the name of the entity class and the naming convention). -[@Increment]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/Increment.html -[ReactiveResultSet]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/cql/reactive/ReactiveResultSet.html -[default keyspace]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/session/SessionBuilder.html#withKeyspace-com.datastax.oss.driver.api.core.CqlIdentifier- -[@ClusteringColumn]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/ClusteringColumn.html -[@PartitionKey]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/PartitionKey.html -[@CqlName]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/CqlName.html +[@Increment]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/Increment.html +[ReactiveResultSet]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/cql/reactive/ReactiveResultSet.html +[default keyspace]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/SessionBuilder.html#withKeyspace-com.datastax.oss.driver.api.core.CqlIdentifier- +[@ClusteringColumn]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/ClusteringColumn.html +[@PartitionKey]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/PartitionKey.html +[@CqlName]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/CqlName.html [CompletionStage]: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletionStage.html [CompletableFuture]: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html diff --git a/manual/mapper/daos/insert/README.md b/manual/mapper/daos/insert/README.md index 1cf6800ade6..b90ffa33a32 100644 --- a/manual/mapper/daos/insert/README.md +++ b/manual/mapper/daos/insert/README.md @@ -1,3 +1,22 @@ + + ## Insert methods Annotate a DAO method with [@Insert] to generate a query that inserts an [Entity](../../entities): @@ -108,13 +127,13 @@ If a table was specified when creating the DAO, then the generated query targets Otherwise, it uses the default table name for the entity (which is determined by the name of the entity class and the [naming strategy](../../entities/#naming-strategy)). -[default keyspace]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/session/SessionBuilder.html#withKeyspace-com.datastax.oss.driver.api.core.CqlIdentifier- -[@Insert]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/Insert.html -[ResultSet]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/ResultSet.html -[ResultSet#wasApplied()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/ResultSet.html#wasApplied-- -[ResultSet#getExecutionInfo()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/ResultSet.html#getExecutionInfo-- -[BoundStatement]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/BoundStatement.html -[ReactiveResultSet]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/cql/reactive/ReactiveResultSet.html +[default keyspace]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/SessionBuilder.html#withKeyspace-com.datastax.oss.driver.api.core.CqlIdentifier- +[@Insert]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/Insert.html +[ResultSet]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/ResultSet.html +[ResultSet#wasApplied()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/ResultSet.html#wasApplied-- +[ResultSet#getExecutionInfo()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/ResultSet.html#getExecutionInfo-- +[BoundStatement]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/BoundStatement.html +[ReactiveResultSet]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/cql/reactive/ReactiveResultSet.html [CompletionStage]: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletionStage.html [CompletableFuture]: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html diff --git a/manual/mapper/daos/null_saving/README.md b/manual/mapper/daos/null_saving/README.md index b88b61d4e9e..eed98934356 100644 --- a/manual/mapper/daos/null_saving/README.md +++ b/manual/mapper/daos/null_saving/README.md @@ -1,3 +1,22 @@ + + ## Null saving strategy The null saving strategy controls how null entity properties are handled when writing to the @@ -93,10 +112,10 @@ public interface UserDao extends InventoryDao { } ``` -[@DefaultNullSavingStrategy]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/DefaultNullSavingStrategy.html -[BoundStatement]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/BoundStatement.html -[MapperException]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/MapperException.html -[DO_NOT_SET]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/entity/saving/NullSavingStrategy.html#DO_NOT_SET -[SET_TO_NULL]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/entity/saving/NullSavingStrategy.html#SET_TO_NULL +[@DefaultNullSavingStrategy]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/DefaultNullSavingStrategy.html +[BoundStatement]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/BoundStatement.html +[MapperException]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/MapperException.html +[DO_NOT_SET]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/entity/saving/NullSavingStrategy.html#DO_NOT_SET +[SET_TO_NULL]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/entity/saving/NullSavingStrategy.html#SET_TO_NULL [CASSANDRA-7304]: https://issues.apache.org/jira/browse/CASSANDRA-7304 diff --git a/manual/mapper/daos/query/README.md b/manual/mapper/daos/query/README.md index d053928b379..a11753da880 100644 --- a/manual/mapper/daos/query/README.md +++ b/manual/mapper/daos/query/README.md @@ -1,3 +1,22 @@ + + ## Query methods Annotate a DAO method with [@Query] to provide your own query string: @@ -59,6 +78,9 @@ The method can return: * a [PagingIterable]. The method will convert each row into an entity instance. +* a [Stream]. The method will convert each row into an entity instance. For details about the + stream's characteristics, see [PagingIterable.spliterator]. + * a [CompletionStage] or [CompletableFuture] of any of the above. The method will execute the query asynchronously. Note that for result sets and iterables, you need to switch to the asynchronous equivalent [AsyncResultSet] and [MappedAsyncPagingIterable] respectively. @@ -110,18 +132,20 @@ Then: query succeeds or not depends on whether the session that the mapper was built with has a [default keyspace]. -[default keyspace]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/session/SessionBuilder.html#withKeyspace-com.datastax.oss.driver.api.core.CqlIdentifier- -[@Query]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/Query.html -[AsyncResultSet]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/AsyncResultSet.html -[ResultSet]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/ResultSet.html -[ResultSet#wasApplied()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/ResultSet.html#wasApplied-- -[MappedAsyncPagingIterable]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/MappedAsyncPagingIterable.html -[PagingIterable]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/PagingIterable.html -[Row]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/Row.html -[BoundStatement]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/BoundStatement.html -[ReactiveResultSet]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/cql/reactive/ReactiveResultSet.html -[MappedReactiveResultSet]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/mapper/reactive/MappedReactiveResultSet.html +[default keyspace]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/SessionBuilder.html#withKeyspace-com.datastax.oss.driver.api.core.CqlIdentifier- +[@Query]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/Query.html +[AsyncResultSet]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/AsyncResultSet.html +[ResultSet]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/ResultSet.html +[ResultSet#wasApplied()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/ResultSet.html#wasApplied-- +[MappedAsyncPagingIterable]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/MappedAsyncPagingIterable.html +[PagingIterable]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/PagingIterable.html +[PagingIterable.spliterator]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/PagingIterable.html#spliterator-- +[Row]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/Row.html +[BoundStatement]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/BoundStatement.html +[ReactiveResultSet]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/cql/reactive/ReactiveResultSet.html +[MappedReactiveResultSet]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/mapper/reactive/MappedReactiveResultSet.html [CompletionStage]: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletionStage.html [CompletableFuture]: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html [Optional]: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html +[Stream]: https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html diff --git a/manual/mapper/daos/queryprovider/README.md b/manual/mapper/daos/queryprovider/README.md index 8a64b94a10f..593a3a6b1a4 100644 --- a/manual/mapper/daos/queryprovider/README.md +++ b/manual/mapper/daos/queryprovider/README.md @@ -1,3 +1,22 @@ + + ## Query provider methods Annotate a DAO method with [@QueryProvider] to delegate the execution of the query to one of your @@ -137,11 +156,11 @@ Here is the full implementation: the desired [PagingIterable][PagingIterable]. -[@QueryProvider]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/QueryProvider.html -[providerClass]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/QueryProvider.html#providerClass-- -[entityHelpers]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/QueryProvider.html#entityHelpers-- -[providerMethod]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/QueryProvider.html#providerMethod-- -[MapperContext]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/MapperContext.html -[EntityHelper]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/EntityHelper.html -[ResultSet]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/ResultSet.html -[PagingIterable]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/PagingIterable.html +[@QueryProvider]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/QueryProvider.html +[providerClass]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/QueryProvider.html#providerClass-- +[entityHelpers]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/QueryProvider.html#entityHelpers-- +[providerMethod]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/QueryProvider.html#providerMethod-- +[MapperContext]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/MapperContext.html +[EntityHelper]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/EntityHelper.html +[ResultSet]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/ResultSet.html +[PagingIterable]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/PagingIterable.html diff --git a/manual/mapper/daos/select/README.md b/manual/mapper/daos/select/README.md index 5e1cdcdc79d..fb6c4ca2077 100644 --- a/manual/mapper/daos/select/README.md +++ b/manual/mapper/daos/select/README.md @@ -1,3 +1,22 @@ + + ## Select methods Annotate a DAO method with [@Select] to generate a query that selects one or more rows, and maps @@ -108,6 +127,19 @@ In all cases, the method can return: PagingIterable findByDescription(String searchString); ``` +* a [Stream] of the entity class. It behaves like a result set, except that each element is a mapped + entity instead of a row. + + Note: even if streams are lazily evaluated, the query will be executed synchronously; also, as + the returned stream is traversed, more blocking calls may occur, as more results are fetched + from the server in the background. For details about the stream's characteristics, see + [PagingIterable.spliterator]. + + ```java + @Select(customWhereClause = "description LIKE :searchString") + Stream findByDescription(String searchString); + ``` + * a [CompletionStage] or [CompletableFuture] of any of the above. The method will execute the query asynchronously. Note that for iterables, you need to switch to the asynchronous equivalent [MappedAsyncPagingIterable]. @@ -122,6 +154,11 @@ In all cases, the method can return: @Select(customWhereClause = "description LIKE :searchString") CompletionStage> findByDescriptionAsync(String searchString); ``` + + For streams, even if the initial query is executed asynchronously, traversing the returned + stream may block the traversing thread. Blocking calls can indeed be required as more results + are fetched from the server in the background. For this reason, _the usage of + `CompletionStage>` cannot be considered as a fully asynchronous execution method_. * a [MappedReactiveResultSet] of the entity class. @@ -142,20 +179,22 @@ If a table was specified when creating the DAO, then the generated query targets Otherwise, it uses the default table name for the entity (which is determined by the name of the entity class and the [naming strategy](../../entities/#naming-strategy)). -[default keyspace]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/session/SessionBuilder.html#withKeyspace-com.datastax.oss.driver.api.core.CqlIdentifier- -[@ClusteringColumn]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/ClusteringColumn.html -[@PartitionKey]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/PartitionKey.html -[@Select]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/Select.html -[allowFiltering()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/Select.html#allowFiltering-- -[customWhereClause()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/Select.html#customWhereClause-- -[groupBy()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/Select.html#groupBy-- -[limit()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/Select.html#limit-- -[orderBy()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/Select.html#orderBy-- -[perPartitionLimit()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/Select.html#perPartitionLimit-- -[MappedAsyncPagingIterable]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/MappedAsyncPagingIterable.html -[PagingIterable]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/PagingIterable.html -[MappedReactiveResultSet]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/mapper/reactive/MappedReactiveResultSet.html +[default keyspace]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/SessionBuilder.html#withKeyspace-com.datastax.oss.driver.api.core.CqlIdentifier- +[@ClusteringColumn]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/ClusteringColumn.html +[@PartitionKey]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/PartitionKey.html +[@Select]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/Select.html +[allowFiltering()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/Select.html#allowFiltering-- +[customWhereClause()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/Select.html#customWhereClause-- +[groupBy()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/Select.html#groupBy-- +[limit()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/Select.html#limit-- +[orderBy()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/Select.html#orderBy-- +[perPartitionLimit()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/Select.html#perPartitionLimit-- +[MappedAsyncPagingIterable]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/MappedAsyncPagingIterable.html +[PagingIterable]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/PagingIterable.html +[PagingIterable.spliterator]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/PagingIterable.html#spliterator-- +[MappedReactiveResultSet]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/mapper/reactive/MappedReactiveResultSet.html [CompletionStage]: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletionStage.html [CompletableFuture]: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html [Optional]: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html +[Stream]: https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html diff --git a/manual/mapper/daos/setentity/README.md b/manual/mapper/daos/setentity/README.md index 5232afcb277..eeb7957f62e 100644 --- a/manual/mapper/daos/setentity/README.md +++ b/manual/mapper/daos/setentity/README.md @@ -1,3 +1,22 @@ + + ## SetEntity methods Annotate a DAO method with [@SetEntity] to fill a core driver data structure from an @@ -21,6 +40,55 @@ boundStatement = boundStatement.set("description", product.getDescription(), Str It does not perform a query. Instead, those methods are intended for cases where you will execute the query yourself, and just need the conversion logic. +### Lenient mode + +By default, the mapper operates in "strict" mode: the target statement must contain a matching +column for every property in the entity definition, *except computed ones*. If such a column is not +found, an error will be thrown. + +Starting with driver 4.12.0, the `@SetEntity` annotation has a new `lenient` attribute. If this +attribute is explicitly set to `true`, the mapper will operate in "lenient" mode: all entity +properties that have a matching column in the target statement will be set. However, *unmatched +properties will be left untouched*. + +As an example to illustrate how lenient mode works, assume that we have the following entity and +DAO: + +```java +@Entity class Product { + + @PartitionKey int id; + String description; + float price; + // other members omitted +} + +interface ProductDao { + + @SetEntity(lenient = true) + BoundStatement setLenient(Product product, BoundStatement stmt); + +} +``` + +Then the following code would be possible: + +```java +Product product = new Product(1, "scented candle", 12.99); +// stmt does not contain the price column +BoundStatement stmt = session.prepare("INSERT INTO product (id, description) VALUES (?, ?)").bind(); +stmt = productDao.setLenient(product, stmt); +``` + +Since no `price` column was found in the target statement, `product.price` wasn't read (if the +statement is executed, the resulting row in the database will have a price of zero). Without lenient +mode, the code above would throw an error instead. + +Lenient mode allows to achieve the equivalent of driver 3.x [manual mapping +feature](https://docs.datastax.com/en/developer/java-driver/3.10/manual/object_mapper/using/#manual-mapping). + +**Beware that lenient mode may result in incomplete rows being inserted in the database.** + ### Parameters The method must have two parameters: one is the entity instance, the other must be a subtype of @@ -63,8 +131,8 @@ BoundStatement bind(Product product, BoundStatement statement); If you use a void method with [BoundStatement], the mapper processor will issue a compile-time warning. -[@SetEntity]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/SetEntity.html -[BoundStatement]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/BoundStatement.html -[BoundStatementBuilder]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/BoundStatementBuilder.html -[SettableByName]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/data/SettableByName.html -[UdtValue]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/data/UdtValue.html +[@SetEntity]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/SetEntity.html +[BoundStatement]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/BoundStatement.html +[BoundStatementBuilder]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/BoundStatementBuilder.html +[SettableByName]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/data/SettableByName.html +[UdtValue]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/data/UdtValue.html diff --git a/manual/mapper/daos/statement_attributes/README.md b/manual/mapper/daos/statement_attributes/README.md index 4f26a84004f..f772df36775 100644 --- a/manual/mapper/daos/statement_attributes/README.md +++ b/manual/mapper/daos/statement_attributes/README.md @@ -1,3 +1,22 @@ + + ## Statement attributes The [@Delete](../delete/), [@Insert](../insert/), [@Query](../query/), [@Select](../select/) and @@ -60,4 +79,4 @@ Product product = dao.findById(1, builder -> builder.setConsistencyLevel(DefaultConsistencyLevel.QUORUM)); ``` -[@StatementAttributes]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/StatementAttributes.html \ No newline at end of file +[@StatementAttributes]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/StatementAttributes.html diff --git a/manual/mapper/daos/update/README.md b/manual/mapper/daos/update/README.md index 2b39db5c4a0..87e9286c800 100644 --- a/manual/mapper/daos/update/README.md +++ b/manual/mapper/daos/update/README.md @@ -1,3 +1,22 @@ + + ## Update methods Annotate a DAO method with [@Update] to generate a query that updates one or more @@ -143,13 +162,13 @@ If a table was specified when creating the DAO, then the generated query targets Otherwise, it uses the default table name for the entity (which is determined by the name of the entity class and the naming convention). -[default keyspace]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/session/SessionBuilder.html#withKeyspace-com.datastax.oss.driver.api.core.CqlIdentifier- -[@Update]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/Update.html +[default keyspace]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/SessionBuilder.html#withKeyspace-com.datastax.oss.driver.api.core.CqlIdentifier- +[@Update]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/Update.html -[AsyncResultSet]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/AsyncResultSet.html +[AsyncResultSet]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/AsyncResultSet.html [Boolean]: https://docs.oracle.com/javase/8/docs/api/index.html?java/lang/Boolean.html [CompletionStage]: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletionStage.html [CompletableFuture]: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html -[ResultSet]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/ResultSet.html -[BoundStatement]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/cql/BoundStatement.html -[ReactiveResultSet]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/core/cql/reactive/ReactiveResultSet.html +[ResultSet]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/ResultSet.html +[BoundStatement]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/cql/BoundStatement.html +[ReactiveResultSet]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/core/cql/reactive/ReactiveResultSet.html diff --git a/manual/mapper/entities/README.md b/manual/mapper/entities/README.md index 29a83725750..978c781245f 100644 --- a/manual/mapper/entities/README.md +++ b/manual/mapper/entities/README.md @@ -1,3 +1,22 @@ + + ## Entities ### Quick overview @@ -555,22 +574,22 @@ the same level. To control how the class hierarchy is scanned, annotate classes with [@HierarchyScanStrategy]. -[@ClusteringColumn]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/ClusteringColumn.html -[@CqlName]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/CqlName.html -[@Dao]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/Dao.html -[@Entity]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/Entity.html -[NameConverter]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/entity/naming/NameConverter.html -[NamingConvention]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/entity/naming/NamingConvention.html -[@NamingStrategy]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/NamingStrategy.html -[@PartitionKey]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/PartitionKey.html -[@Computed]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/Computed.html -[@Select]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/Select.html -[@Insert]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/Insert.html -[@Update]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/Update.html -[@GetEntity]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/GetEntity.html -[@Query]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/Query.html +[@ClusteringColumn]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/ClusteringColumn.html +[@CqlName]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/CqlName.html +[@Dao]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/Dao.html +[@Entity]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/Entity.html +[NameConverter]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/entity/naming/NameConverter.html +[NamingConvention]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/entity/naming/NamingConvention.html +[@NamingStrategy]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/NamingStrategy.html +[@PartitionKey]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/PartitionKey.html +[@Computed]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/Computed.html +[@Select]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/Select.html +[@Insert]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/Insert.html +[@Update]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/Update.html +[@GetEntity]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/GetEntity.html +[@Query]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/Query.html [aliases]: http://cassandra.apache.org/doc/latest/cql/dml.html?#aliases -[@Transient]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/Transient.html -[@TransientProperties]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/TransientProperties.html -[@HierarchyScanStrategy]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/HierarchyScanStrategy.html -[@PropertyStrategy]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/PropertyStrategy.html +[@Transient]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/Transient.html +[@TransientProperties]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/TransientProperties.html +[@HierarchyScanStrategy]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/HierarchyScanStrategy.html +[@PropertyStrategy]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/PropertyStrategy.html diff --git a/manual/mapper/mapper/README.md b/manual/mapper/mapper/README.md index 2dd0e500f4e..752424c9a3b 100644 --- a/manual/mapper/mapper/README.md +++ b/manual/mapper/mapper/README.md @@ -1,3 +1,22 @@ + + ## Mapper interface ### Quick overview @@ -39,7 +58,7 @@ public interface InventoryMapper { ``` The builder allows you to create a mapper instance, by wrapping a core `CqlSession` (if you need -more details on how to create a session, refer to the [core driver documentation](../core/)). +more details on how to create a session, refer to the [core driver documentation](../../core/)). ```java CqlSession session = CqlSession.builder().build(); @@ -227,8 +246,11 @@ InventoryMapper inventoryMapper = new InventoryMapperBuilder(session) .build(); ``` -[CqlIdentifier]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/CqlIdentifier.html -[@DaoFactory]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/DaoFactory.html -[@DaoKeyspace]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/DaoKeyspace.html -[@DaoTable]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/DaoTable.html -[@Mapper]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/mapper/annotations/Mapper.html +You can also permanently disable validation of an individual entity by annotating it with +`@SchemaHint(targetElement = NONE)`. + +[CqlIdentifier]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/CqlIdentifier.html +[@DaoFactory]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/DaoFactory.html +[@DaoKeyspace]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/DaoKeyspace.html +[@DaoTable]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/DaoTable.html +[@Mapper]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/mapper/annotations/Mapper.html diff --git a/manual/osgi/README.md b/manual/osgi/README.md index 0983292d859..92cd4625b68 100644 --- a/manual/osgi/README.md +++ b/manual/osgi/README.md @@ -1,3 +1,22 @@ + + # OSGi The driver is available as an [OSGi] bundle. More specifically, the following maven artifacts are @@ -138,7 +157,7 @@ starting the driver: [driver configuration]: ../core/configuration [OSGi]:https://www.osgi.org [JNR]: https://github.com/jnr/jnr-posix -[withClassLoader()]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/session/SessionBuilder.html#withClassLoader-java.lang.ClassLoader- +[withClassLoader()]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/session/SessionBuilder.html#withClassLoader-java.lang.ClassLoader- [JAVA-1127]:https://datastax-oss.atlassian.net/browse/JAVA-1127 -[DriverConfigLoader.fromDefaults(ClassLoader)]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/config/DriverConfigLoader.html#fromDefaults-java.lang.ClassLoader- -[DriverConfigLoader.programmaticBuilder(ClassLoader)]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/config/DriverConfigLoader.html#programmaticBuilder-java.lang.ClassLoader- +[DriverConfigLoader.fromDefaults(ClassLoader)]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/config/DriverConfigLoader.html#fromDefaults-java.lang.ClassLoader- +[DriverConfigLoader.programmaticBuilder(ClassLoader)]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/config/DriverConfigLoader.html#programmaticBuilder-java.lang.ClassLoader- diff --git a/manual/query_builder/README.md b/manual/query_builder/README.md index c3f7d5f5e11..d1932b329e7 100644 --- a/manual/query_builder/README.md +++ b/manual/query_builder/README.md @@ -1,3 +1,22 @@ + + ## Query builder The query builder is a utility to **generate CQL queries programmatically**. For example, it could @@ -12,7 +31,7 @@ To use it in your application, add the following dependency: ```xml - com.datastax.oss + org.apache.cassandra java-driver-query-builder ${driver.version} @@ -70,13 +89,13 @@ SimpleStatement statement = select.build(); SimpleStatementBuilder builder = select.builder(); ``` -#### Datastax Enterprise +#### DataStax Enterprise The driver provides two additional entry points for DSE-specific queries: [DseQueryBuilder] and [DseSchemaBuilder]. They extend their respective non-DSE counterparts, so anything that is available on the default query builder can also be done with the DSE query builder. -We recommend that you use those classes if you are targeting Datastax Enterprise; they will be +We recommend that you use those classes if you are targeting DataStax Enterprise; they will be enriched in the future if DSE adds custom CQL syntax. Currently, the only difference is the support for the `DETERMINISTIC` and `MONOTONIC` keywords when @@ -212,8 +231,8 @@ For a complete tour of the API, browse the child pages in this manual: * [Terms](term/) * [Idempotence](idempotence/) -[QueryBuilder]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/querybuilder/QueryBuilder.html -[SchemaBuilder]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/querybuilder/SchemaBuilder.html -[CqlIdentifier]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/CqlIdentifier.html -[DseQueryBuilder]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/querybuilder/DseQueryBuilder.html -[DseSchemaBuilder]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/dse/driver/api/querybuilder/DseSchemaBuilder.html +[QueryBuilder]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/querybuilder/QueryBuilder.html +[SchemaBuilder]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/querybuilder/SchemaBuilder.html +[CqlIdentifier]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/CqlIdentifier.html +[DseQueryBuilder]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/querybuilder/DseQueryBuilder.html +[DseSchemaBuilder]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/dse/driver/api/querybuilder/DseSchemaBuilder.html diff --git a/manual/query_builder/condition/README.md b/manual/query_builder/condition/README.md index 9b25e53235b..1a6a37eb2ef 100644 --- a/manual/query_builder/condition/README.md +++ b/manual/query_builder/condition/README.md @@ -1,3 +1,22 @@ + + ## Conditions A condition is a clause that appears after the IF keyword in a conditional [UPDATE](../update/) or @@ -132,4 +151,4 @@ It is mutually exclusive with column conditions: if you previously specified col the statement, they will be ignored; conversely, adding a column condition cancels a previous IF EXISTS clause. -[Condition]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/querybuilder/condition/Condition.html +[Condition]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/querybuilder/condition/Condition.html diff --git a/manual/query_builder/delete/README.md b/manual/query_builder/delete/README.md index 413366779b0..8e97920ae9f 100644 --- a/manual/query_builder/delete/README.md +++ b/manual/query_builder/delete/README.md @@ -1,3 +1,22 @@ + + ## DELETE To start a DELETE query, use one of the `deleteFrom` methods in [QueryBuilder]. There are several @@ -141,5 +160,5 @@ deleteFrom("user") Conditions are a common feature used by UPDATE and DELETE, so they have a [dedicated page](../condition) in this manual. -[QueryBuilder]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/querybuilder/QueryBuilder.html -[Selector]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/querybuilder/select/Selector.html +[QueryBuilder]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/querybuilder/QueryBuilder.html +[Selector]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/querybuilder/select/Selector.html diff --git a/manual/query_builder/idempotence/README.md b/manual/query_builder/idempotence/README.md index 9fd6d39114d..2f97151d277 100644 --- a/manual/query_builder/idempotence/README.md +++ b/manual/query_builder/idempotence/README.md @@ -1,3 +1,22 @@ + + ## Idempotence in the query builder When you generate a statement (or a statement builder) from the query builder, it automatically @@ -225,4 +244,4 @@ sequential history that is correct. From our clients' point of view, there were But overall the column changed from 1 to 2. There is no ordering of the two operations that can explain that change. We broke linearizability by doing a transparent retry at step 6. -[linearizability]: https://en.wikipedia.org/wiki/Linearizability#Definition_of_linearizability \ No newline at end of file +[linearizability]: https://en.wikipedia.org/wiki/Linearizability#Definition_of_linearizability diff --git a/manual/query_builder/insert/README.md b/manual/query_builder/insert/README.md index d038fd9d44a..6bac896d9b8 100644 --- a/manual/query_builder/insert/README.md +++ b/manual/query_builder/insert/README.md @@ -1,3 +1,22 @@ + + ## INSERT To start an INSERT query, use one of the `insertInto` methods in [QueryBuilder]. There are @@ -114,4 +133,4 @@ is executed. This is distinctly different than setting the value to null. Passin this method will only remove the USING TTL clause from the query, which will not alter the TTL (if one is set) in Cassandra. -[QueryBuilder]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/querybuilder/QueryBuilder.html \ No newline at end of file +[QueryBuilder]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/querybuilder/QueryBuilder.html diff --git a/manual/query_builder/relation/README.md b/manual/query_builder/relation/README.md index 20d0b184cf5..eb1c728888e 100644 --- a/manual/query_builder/relation/README.md +++ b/manual/query_builder/relation/README.md @@ -1,3 +1,22 @@ + + ## Relations A relation is a clause that appears after the WHERE keyword, and restricts the rows that the @@ -201,5 +220,5 @@ This should be used with caution, as it's possible to generate invalid CQL that execution time; on the other hand, it can be used as a workaround to handle new CQL features that are not yet covered by the query builder. -[QueryBuilder]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/querybuilder/QueryBuilder.html -[Relation]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/querybuilder/relation/Relation.html +[QueryBuilder]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/querybuilder/QueryBuilder.html +[Relation]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/querybuilder/relation/Relation.html diff --git a/manual/query_builder/schema/README.md b/manual/query_builder/schema/README.md index 1210491a1c6..0472c8e8c6f 100644 --- a/manual/query_builder/schema/README.md +++ b/manual/query_builder/schema/README.md @@ -1,3 +1,22 @@ + + # Schema builder The schema builder is an additional API provided by [java-driver-query-builder](../) that enables @@ -44,4 +63,4 @@ element type: * [function](function/) * [aggregate](aggregate/) -[SchemaBuilder]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/querybuilder/SchemaBuilder.html +[SchemaBuilder]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/querybuilder/SchemaBuilder.html diff --git a/manual/query_builder/schema/aggregate/README.md b/manual/query_builder/schema/aggregate/README.md index 9a6fba24819..a54f8703d69 100644 --- a/manual/query_builder/schema/aggregate/README.md +++ b/manual/query_builder/schema/aggregate/README.md @@ -1,3 +1,22 @@ + + ## Aggregate Aggregates enable users to apply User-defined functions (UDF) to rows in a data set and combine @@ -76,4 +95,4 @@ dropAggregate("average").ifExists(); // DROP AGGREGATE IF EXISTS average ``` -[SchemaBuilder]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/querybuilder/SchemaBuilder.html +[SchemaBuilder]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/querybuilder/SchemaBuilder.html diff --git a/manual/query_builder/schema/function/README.md b/manual/query_builder/schema/function/README.md index e1a17cf7d92..001327626b1 100644 --- a/manual/query_builder/schema/function/README.md +++ b/manual/query_builder/schema/function/README.md @@ -1,3 +1,22 @@ + + ## Function User-defined functions (UDF) enable users to create user code written in JSR-232 compliant scripting @@ -92,4 +111,4 @@ dropFunction("log").ifExists(); // DROP FUNCTION IF EXISTS log ``` -[SchemaBuilder]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/querybuilder/SchemaBuilder.html +[SchemaBuilder]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/querybuilder/SchemaBuilder.html diff --git a/manual/query_builder/schema/index/README.md b/manual/query_builder/schema/index/README.md index 2aa435e5b7c..c0c9448dfab 100644 --- a/manual/query_builder/schema/index/README.md +++ b/manual/query_builder/schema/index/README.md @@ -1,3 +1,22 @@ + + # Index An index provides a means of expanding the query capabilities of a table. [SchemaBuilder] offers @@ -99,4 +118,4 @@ dropIndex("my_idx").ifExists(); // DROP INDEX IF EXISTS my_idx ``` -[SchemaBuilder]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/querybuilder/SchemaBuilder.html +[SchemaBuilder]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/querybuilder/SchemaBuilder.html diff --git a/manual/query_builder/schema/keyspace/README.md b/manual/query_builder/schema/keyspace/README.md index f283ba5b5ee..572e8af1658 100644 --- a/manual/query_builder/schema/keyspace/README.md +++ b/manual/query_builder/schema/keyspace/README.md @@ -1,3 +1,22 @@ + + ## Keyspace A keyspace is a top-level namespace that defines a name, replication strategy and configurable @@ -83,6 +102,6 @@ dropKeyspace("cycling").ifExists(); // DROP KEYSPACE IF EXISTS cycling ``` -[SchemaBuilder]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/querybuilder/SchemaBuilder.html +[SchemaBuilder]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/querybuilder/SchemaBuilder.html diff --git a/manual/query_builder/schema/materialized_view/README.md b/manual/query_builder/schema/materialized_view/README.md index d240c6bd282..c4f495f95aa 100644 --- a/manual/query_builder/schema/materialized_view/README.md +++ b/manual/query_builder/schema/materialized_view/README.md @@ -1,3 +1,22 @@ + + ## Materialized View Materialized Views are an experimental feature introduced in Apache Cassandra 3.0 that provide a @@ -85,5 +104,5 @@ dropTable("cyclist_by_age").ifExists(); // DROP MATERIALIZED VIEW IF EXISTS cyclist_by_age ``` -[SchemaBuilder]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/querybuilder/SchemaBuilder.html -[RelationStructure]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/querybuilder/schema/RelationStructure.html +[SchemaBuilder]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/querybuilder/SchemaBuilder.html +[RelationStructure]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/querybuilder/schema/RelationStructure.html diff --git a/manual/query_builder/schema/table/README.md b/manual/query_builder/schema/table/README.md index ab0664d0280..090f8a1f67b 100644 --- a/manual/query_builder/schema/table/README.md +++ b/manual/query_builder/schema/table/README.md @@ -1,3 +1,22 @@ + + ## Table Data in Apache Cassandra is stored in tables. [SchemaBuilder] offers API methods for creating, @@ -31,12 +50,12 @@ CreateTable create = createTable("cycling", "cyclist_name").withPartitionKey("id A table with only one column is not so typical however. At this point you may provide partition, clustering, regular and static columns using any of the following API methods: -* `withPrimaryKey(name, dataType)` +* `withPartitionKey(name, dataType)` * `withClusteringColumn(name, dataType)` * `withColumn(name, dataType)` * `withStaticColumn(name, dataType)` -Primary key precedence is driven by the order of `withPrimaryKey` and `withClusteringKey` +Primary key precedence is driven by the order of `withPartitionKey` and `withClusteringKey` invocations, for example: @@ -107,6 +126,6 @@ dropTable("cyclist_name").ifExists(); // DROP TABLE IF EXISTS cyclist_name ``` -[SchemaBuilder]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/querybuilder/SchemaBuilder.html -[CreateTableWithOptions]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/querybuilder/schema/CreateTableWithOptions.html -[AlterTableWithOptions]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/querybuilder/schema/AlterTableWithOptions.html +[SchemaBuilder]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/querybuilder/SchemaBuilder.html +[CreateTableWithOptions]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/querybuilder/schema/CreateTableWithOptions.html +[AlterTableWithOptions]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/querybuilder/schema/AlterTableWithOptions.html diff --git a/manual/query_builder/schema/type/README.md b/manual/query_builder/schema/type/README.md index b5d6646fcc7..c289ad776a8 100644 --- a/manual/query_builder/schema/type/README.md +++ b/manual/query_builder/schema/type/README.md @@ -1,3 +1,22 @@ + + ## Type User-defined types are special types that can associate multiple named fields to a single column. @@ -88,4 +107,4 @@ dropTable("address").ifExists(); // DROP TYPE IF EXISTS address ``` -[SchemaBuilder]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/querybuilder/SchemaBuilder.html +[SchemaBuilder]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/querybuilder/SchemaBuilder.html diff --git a/manual/query_builder/select/README.md b/manual/query_builder/select/README.md index e1819f0c128..0425423a402 100644 --- a/manual/query_builder/select/README.md +++ b/manual/query_builder/select/README.md @@ -1,3 +1,22 @@ + + ## SELECT Start your SELECT with the `selectFrom` method in [QueryBuilder]. There are several variants @@ -368,6 +387,29 @@ selectFrom("sensor_data") // SELECT reading FROM sensor_data WHERE id=? ORDER BY date DESC ``` +Vector Search: + +```java + +import com.datastax.oss.driver.api.core.data.CqlVector; + +selectFrom("foo") + .all() + .where(Relation.column("k").isEqualTo(literal(1))) + .orderByAnnOf("c1", CqlVector.newInstance(0.1, 0.2, 0.3)); +// SELECT * FROM foo WHERE k=1 ORDER BY c1 ANN OF [0.1, 0.2, 0.3] + +selectFrom("cycling", "comments_vs") + .column("comment") + .function( + "similarity_cosine", + Selector.column("comment_vector"), + literal(CqlVector.newInstance(0.2, 0.15, 0.3, 0.2, 0.05))) + .orderByAnnOf("comment_vector", CqlVector.newInstance(0.1, 0.15, 0.3, 0.12, 0.05)) + .limit(1); +// SELECT comment,similarity_cosine(comment_vector,[0.2, 0.15, 0.3, 0.2, 0.05]) FROM cycling.comments_vs ORDER BY comment_vector ANN OF [0.1, 0.15, 0.3, 0.12, 0.05] LIMIT 1 +``` + Limits: ```java @@ -391,5 +433,5 @@ selectFrom("user").all().allowFiltering(); // SELECT * FROM user ALLOW FILTERING ``` -[QueryBuilder]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/querybuilder/QueryBuilder.html -[Selector]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/querybuilder/select/Selector.html +[QueryBuilder]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/querybuilder/QueryBuilder.html +[Selector]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/querybuilder/select/Selector.html diff --git a/manual/query_builder/term/README.md b/manual/query_builder/term/README.md index 66f8e4dfaac..460ed8dcb10 100644 --- a/manual/query_builder/term/README.md +++ b/manual/query_builder/term/README.md @@ -1,3 +1,22 @@ + + ## Terms A term is an expression that does not involve the value of a column. It is used: @@ -105,5 +124,5 @@ This should be used with caution, as it's possible to generate invalid CQL that execution time; on the other hand, it can be used as a workaround to handle new CQL features that are not yet covered by the query builder. -[QueryBuilder]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/querybuilder/QueryBuilder.html -[CodecRegistry]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/type/codec/registry/CodecRegistry.html \ No newline at end of file +[QueryBuilder]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/querybuilder/QueryBuilder.html +[CodecRegistry]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/core/type/codec/registry/CodecRegistry.html diff --git a/manual/query_builder/truncate/README.md b/manual/query_builder/truncate/README.md index 3b8e1518e80..c8cd6945123 100644 --- a/manual/query_builder/truncate/README.md +++ b/manual/query_builder/truncate/README.md @@ -1,3 +1,22 @@ + + ## TRUNCATE To create a TRUNCATE query, use one of the `truncate` methods in [QueryBuilder]. There are several @@ -17,4 +36,4 @@ Truncate truncate2 = truncate(CqlIdentifier.fromCql("mytable")); Note that, at this stage, the query is ready to build. After creating a TRUNCATE query it does not take any values. -[QueryBuilder]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/querybuilder/QueryBuilder.html +[QueryBuilder]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/querybuilder/QueryBuilder.html diff --git a/manual/query_builder/update/README.md b/manual/query_builder/update/README.md index 19f9c2f8bb1..15502f52bb7 100644 --- a/manual/query_builder/update/README.md +++ b/manual/query_builder/update/README.md @@ -1,3 +1,22 @@ + + ## UPDATE To start an UPDATE query, use one of the `update` methods in [QueryBuilder]. There are several @@ -251,5 +270,5 @@ update("foo") Conditions are a common feature used by UPDATE and DELETE, so they have a [dedicated page](../condition) in this manual. -[QueryBuilder]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/querybuilder/QueryBuilder.html -[Assignment]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/querybuilder/update/Assignment.html +[QueryBuilder]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/querybuilder/QueryBuilder.html +[Assignment]: https://docs.datastax.com/en/drivers/java/4.17/com/datastax/oss/driver/api/querybuilder/update/Assignment.html diff --git a/mapper-processor/CONTRIBUTING.md b/mapper-processor/CONTRIBUTING.md index 11659a9f936..c6d324106c4 100644 --- a/mapper-processor/CONTRIBUTING.md +++ b/mapper-processor/CONTRIBUTING.md @@ -1,3 +1,22 @@ + + # Mapper contributing guidelines Everything in the [main contribution guidelines](../CONTRIBUTING.md) also applies to the mapper. diff --git a/mapper-processor/pom.xml b/mapper-processor/pom.xml index 9cbd8fe224c..04d8c98c4f0 100644 --- a/mapper-processor/pom.xml +++ b/mapper-processor/pom.xml @@ -1,13 +1,15 @@ diff --git a/mapper-runtime/revapi.json b/mapper-runtime/revapi.json index 18d26a7f7e9..3dc2ea21671 100644 --- a/mapper-runtime/revapi.json +++ b/mapper-runtime/revapi.json @@ -1,5 +1,3 @@ -// Configures Revapi (https://revapi.org/getting-started.html) to check API compatibility between -// successive driver versions. { "revapi": { "java": { @@ -11,7 +9,7 @@ "com\\.datastax\\.(oss|dse)\\.driver\\.internal(\\..+)?", "com\\.datastax\\.oss\\.driver\\.shaded(\\..+)?", "com\\.datastax\\.oss\\.simulacron(\\..+)?", - // Don't re-check sibling modules that this module depends on + "// Don't re-check sibling modules that this module depends on", "com\\.datastax\\.(oss|dse)\\.driver\\.api\\.core(\\..+)?", "com\\.datastax\\.(oss|dse)\\.driver\\.api\\.querybuilder(\\..+)?" ] @@ -22,7 +20,7 @@ { "regex": true, "code": "java.annotation.attributeValueChanged", - "old": "@interface com\.datastax\.oss\.driver\.api\.mapper\.annotations\..*", + "old": "@interface com\\.datastax\\.oss\\.driver\\.api\\.mapper\\.annotations\\..*", "annotationType": "java.lang.annotation.Retention", "attribute": "value", "oldValue": "java.lang.annotation.RetentionPolicy.CLASS", diff --git a/mapper-runtime/src/main/java/com/datastax/dse/driver/api/mapper/reactive/MappedReactiveResultSet.java b/mapper-runtime/src/main/java/com/datastax/dse/driver/api/mapper/reactive/MappedReactiveResultSet.java index 5f16f262032..b4e6960ed66 100644 --- a/mapper-runtime/src/main/java/com/datastax/dse/driver/api/mapper/reactive/MappedReactiveResultSet.java +++ b/mapper-runtime/src/main/java/com/datastax/dse/driver/api/mapper/reactive/MappedReactiveResultSet.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/dse/driver/internal/mapper/reactive/DefaultMappedReactiveResultSet.java b/mapper-runtime/src/main/java/com/datastax/dse/driver/internal/mapper/reactive/DefaultMappedReactiveResultSet.java index 71452d7a746..e1e701faddd 100644 --- a/mapper-runtime/src/main/java/com/datastax/dse/driver/internal/mapper/reactive/DefaultMappedReactiveResultSet.java +++ b/mapper-runtime/src/main/java/com/datastax/dse/driver/internal/mapper/reactive/DefaultMappedReactiveResultSet.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/dse/driver/internal/mapper/reactive/FailedMappedReactiveResultSet.java b/mapper-runtime/src/main/java/com/datastax/dse/driver/internal/mapper/reactive/FailedMappedReactiveResultSet.java index 9590d597678..3ed27edbf9d 100644 --- a/mapper-runtime/src/main/java/com/datastax/dse/driver/internal/mapper/reactive/FailedMappedReactiveResultSet.java +++ b/mapper-runtime/src/main/java/com/datastax/dse/driver/internal/mapper/reactive/FailedMappedReactiveResultSet.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/dse/driver/internal/mapper/reactive/ReactiveDaoBase.java b/mapper-runtime/src/main/java/com/datastax/dse/driver/internal/mapper/reactive/ReactiveDaoBase.java index 23c21c6f5f7..56576829a40 100644 --- a/mapper-runtime/src/main/java/com/datastax/dse/driver/internal/mapper/reactive/ReactiveDaoBase.java +++ b/mapper-runtime/src/main/java/com/datastax/dse/driver/internal/mapper/reactive/ReactiveDaoBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -35,6 +37,6 @@ protected ReactiveResultSet executeReactive(Statement statement) { protected MappedReactiveResultSet executeReactiveAndMap( Statement statement, EntityHelper entityHelper) { ReactiveResultSet source = executeReactive(statement); - return new DefaultMappedReactiveResultSet<>(source, entityHelper::get); + return new DefaultMappedReactiveResultSet<>(source, row -> entityHelper.get(row, false)); } } diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/MapperBuilder.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/MapperBuilder.java index 7e93807afbd..3838892172a 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/MapperBuilder.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/MapperBuilder.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/MapperContext.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/MapperContext.java index 249eecc0215..9f9df5f93f7 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/MapperContext.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/MapperContext.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/MapperException.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/MapperException.java index 06b0f1646cf..f659ac00ad5 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/MapperException.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/MapperException.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/ClusteringColumn.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/ClusteringColumn.java index 7fd80dfc8e7..cfbf97e73aa 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/ClusteringColumn.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/ClusteringColumn.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Computed.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Computed.java index ef9b79f1863..817bbf2c294 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Computed.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Computed.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/CqlName.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/CqlName.java index 374d0dfe5c1..9b9ef15afb6 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/CqlName.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/CqlName.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Dao.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Dao.java index 89a9edd2076..bcab01d98fc 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Dao.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Dao.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/DaoFactory.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/DaoFactory.java index 8c886c8c53d..c792c132fb0 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/DaoFactory.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/DaoFactory.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/DaoKeyspace.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/DaoKeyspace.java index d0935c45fb5..6f24ffa9d56 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/DaoKeyspace.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/DaoKeyspace.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/DaoProfile.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/DaoProfile.java index 02009897909..66fc3ed433a 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/DaoProfile.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/DaoProfile.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/DaoTable.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/DaoTable.java index c0e1c882937..7ac0d66dd6c 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/DaoTable.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/DaoTable.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/DefaultNullSavingStrategy.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/DefaultNullSavingStrategy.java index e1f92a761c5..a5c33b3f17f 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/DefaultNullSavingStrategy.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/DefaultNullSavingStrategy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Delete.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Delete.java index 85b5db6a39e..a9d2c03912f 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Delete.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Delete.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Entity.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Entity.java index a8046f33adc..506c7f13d22 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Entity.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Entity.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -47,8 +49,9 @@ * getDescription}) and has no parameters. The name of the property is obtained by removing * the "get" prefix and decapitalizing ({@code description}), and the type of the property is * the return type of the getter. - *

  • there must be a matching setter method ({@code setDescription}), with a single - * parameter that has the same type as the property (the return type does not matter). + *
  • unless the entity is {@linkplain PropertyStrategy#mutable() immutable}, there must + * be a matching setter method ({@code setDescription}), with a single parameter that has the + * same type as the property (the return type does not matter). * * * There may also be a matching field ({@code description}) that has the same type as the diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/GetEntity.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/GetEntity.java index ff4d5a8805c..d86174bdc49 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/GetEntity.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/GetEntity.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -102,4 +104,18 @@ */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) -public @interface GetEntity {} +public @interface GetEntity { + + /** + * Whether to tolerate missing columns in the source data structure. + * + *

    If {@code false} (the default), then the source must contain a matching column for every + * property in the entity definition, including computed ones. If such a column is not + * found, an {@link IllegalArgumentException} will be thrown. + * + *

    If {@code true}, the mapper will operate on a best-effort basis and attempt to read all + * entity properties that have a matching column in the source, leaving unmatched properties + * untouched. Beware that this may result in a partially-populated entity instance. + */ + boolean lenient() default false; +} diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/HierarchyScanStrategy.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/HierarchyScanStrategy.java index 74aa433287e..0b064b8597d 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/HierarchyScanStrategy.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/HierarchyScanStrategy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Increment.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Increment.java index c87ccb330b3..bb86fa5b8ab 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Increment.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Increment.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Insert.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Insert.java index 43675626568..602a673d8a7 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Insert.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Insert.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Mapper.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Mapper.java index 5463639b8f8..8cdaf28fc51 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Mapper.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Mapper.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/NamingStrategy.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/NamingStrategy.java index 2970e0e3207..b5121b144b2 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/NamingStrategy.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/NamingStrategy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/PartitionKey.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/PartitionKey.java index 1cfb4c31812..1dff4280f5b 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/PartitionKey.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/PartitionKey.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/PropertyStrategy.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/PropertyStrategy.java index ecd699ba93f..4d66fd84e33 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/PropertyStrategy.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/PropertyStrategy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Query.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Query.java index 85be754852b..c362453bb3a 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Query.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Query.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/QueryProvider.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/QueryProvider.java index 64bbeef210a..d8194d12e8b 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/QueryProvider.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/QueryProvider.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/SchemaHint.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/SchemaHint.java index b33ec132f08..d680798ba5a 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/SchemaHint.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/SchemaHint.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -39,6 +41,9 @@ *

    By default, the mapper first tries to match the entity with a table, and if that doesn't work, * with a UDT. This annotation allows you to provide a hint as to which check should be done, so * that the mapper can skip the other one. + * + *

    In addition, you can ask to completely skip the validation for this entity by using {@link + * TargetElement#NONE}. */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @@ -47,6 +52,8 @@ enum TargetElement { TABLE, - UDT + UDT, + NONE, + ; } } diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Select.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Select.java index 0e5635cc9e8..46c7994809d 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Select.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Select.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/SetEntity.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/SetEntity.java index 834c549c3b7..cc1cb9b7e88 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/SetEntity.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/SetEntity.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -98,4 +100,17 @@ * or {@link NullSavingStrategy#DO_NOT_SET}. */ NullSavingStrategy nullSavingStrategy() default NullSavingStrategy.DO_NOT_SET; + + /** + * Whether to tolerate missing columns in the target data structure. + * + *

    If {@code false} (the default), then the target must contain a matching column for every + * property in the entity definition, except computed ones. If such a column is not + * found, an {@link IllegalArgumentException} will be thrown. + * + *

    If {@code true}, the mapper will operate on a best-effort basis and attempt to write all + * entity properties that have a matching column in the target, leaving unmatched properties + * untouched. Beware that this may result in a partially-populated target. + */ + boolean lenient() default false; } diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/StatementAttributes.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/StatementAttributes.java index 8190ebfb18e..56f32432ea8 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/StatementAttributes.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/StatementAttributes.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Transient.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Transient.java index e88a2f140ab..1db111ccfd2 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Transient.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Transient.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/TransientProperties.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/TransientProperties.java index f1960613c75..97b8c5c99a2 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/TransientProperties.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/TransientProperties.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Update.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Update.java index c0d2a697b2d..02930d73aa4 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Update.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/annotations/Update.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/entity/EntityHelper.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/entity/EntityHelper.java index 81f3144d529..653b02c5d0c 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/entity/EntityHelper.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/entity/EntityHelper.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -49,7 +51,20 @@ public interface EntityHelper { /** * Sets the properties of an entity instance into a target data structure. * - *

    For example: + * @deprecated Use {@link #set(Object, SettableByName, NullSavingStrategy, boolean)} instead. + */ + @NonNull + @Deprecated + > SettableT set( + @NonNull EntityT entity, + @NonNull SettableT target, + @NonNull NullSavingStrategy nullSavingStrategy); + + /** + * Sets the properties of an entity instance into a target data structure. + * + *

    The generated code will attempt to write all entity properties in the target data structure. + * For example: * *

    {@code
        * target = target.set("id", entity.getId(), UUID.class);
    @@ -59,25 +74,50 @@ public interface EntityHelper {
        *
        * The column names are inferred from the naming strategy for this entity.
        *
    +   * 

    The target will typically be one of the built-in driver subtypes: {@link BoundStatement}, + * {@link BoundStatementBuilder} or {@link UdtValue}. Note that the default {@link BoundStatement} + * implementation is immutable, therefore this argument won't be modified in-place: you need to + * use the return value to get the resulting structure. + * + *

    If {@code lenient} is {@code true}, the mapper will operate on a best-effort basis and + * attempt to write all entity properties that have a matching column in the target, leaving + * unmatched properties untouched. Beware that this may result in a partially-populated target. + * + *

    If {@code lenient} is {@code false}, then the target must contain a matching column for + * every property in the entity definition, except computed ones. If such a column is not + * found, an {@link IllegalArgumentException} will be thrown. + * * @param entity the entity that the values will be read from. - * @param target the data structure to fill. This will typically be one of the built-in driver - * subtypes: {@link BoundStatement}, {@link BoundStatementBuilder} or {@link UdtValue}. Note - * that the default {@link BoundStatement} implementation is immutable, therefore this - * argument won't be modified in-place: you need to use the return value to get the resulting - * structure. + * @param target the data structure to fill. + * @param lenient whether to tolerate incomplete targets. * @return the data structure resulting from the assignments. This is useful for immutable target * implementations (see above), otherwise it will be the same as {@code target}. + * @throws IllegalArgumentException if lenient is false and the target does not contain matching + * columns for every entity property. */ @NonNull - > SettableT set( + default > SettableT set( @NonNull EntityT entity, @NonNull SettableT target, - @NonNull NullSavingStrategy nullSavingStrategy); + @NonNull NullSavingStrategy nullSavingStrategy, + boolean lenient) { + return set(entity, target, nullSavingStrategy); + } /** * Gets values from a data structure to fill an entity instance. * - *

    For example: + * @deprecated Use {@link #get(GettableByName, boolean)} instead. + */ + @NonNull + @Deprecated + EntityT get(@NonNull GettableByName source); + + /** + * Gets values from a data structure to fill an entity instance. + * + *

    The generated code will attempt to read all entity properties from the source data + * structure. For example: * *

    {@code
        * User returnValue = new User();
    @@ -88,14 +128,29 @@ > SettableT set(
        *
        * The column names are inferred from the naming strategy for this entity.
        *
    -   * @param source the data structure to read from. This will typically be one of the built-in
    -   *     driver subtypes: {@link Row} or {@link UdtValue} ({@link BoundStatement} and {@link
    -   *     BoundStatementBuilder} are also possible, although it's less likely that data would be read
    -   *     back from them in this manner).
    +   * 

    The source will typically be one of the built-in driver subtypes: {@link Row} or {@link + * UdtValue} ({@link BoundStatement} and {@link BoundStatementBuilder} are also possible, although + * it's less likely that data would be read back from them in this manner). + * + *

    If {@code lenient} is {@code true}, the mapper will operate on a best-effort basis and + * attempt to read all entity properties that have a matching column in the source, leaving + * unmatched properties untouched. Beware that this may result in a partially-populated entity + * instance. + * + *

    If {@code lenient} is {@code false}, then the source must contain a matching column for + * every property in the entity definition, including computed ones. If such a column is + * not found, an {@link IllegalArgumentException} will be thrown. + * + * @param source the data structure to read from. + * @param lenient whether to tolerate incomplete sources. * @return the resulting entity. + * @throws IllegalArgumentException if lenient is false and the source does not contain matching + * columns for every entity property. */ @NonNull - EntityT get(@NonNull GettableByName source); + default EntityT get(@NonNull GettableByName source, boolean lenient) { + return get(source); + } /** * Builds an insert query for this entity. diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/entity/naming/GetterStyle.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/entity/naming/GetterStyle.java index 849265f62b4..21e4755f4dd 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/entity/naming/GetterStyle.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/entity/naming/GetterStyle.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/entity/naming/NameConverter.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/entity/naming/NameConverter.java index efc3b2d006f..ac9d05895b9 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/entity/naming/NameConverter.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/entity/naming/NameConverter.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/entity/naming/NamingConvention.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/entity/naming/NamingConvention.java index 0a3913aa93e..8846e4f6fcb 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/entity/naming/NamingConvention.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/entity/naming/NamingConvention.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/entity/naming/SetterStyle.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/entity/naming/SetterStyle.java index 4bd9b96b297..26e301c5f76 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/entity/naming/SetterStyle.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/entity/naming/SetterStyle.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/entity/saving/NullSavingStrategy.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/entity/saving/NullSavingStrategy.java index 9b0b668b69e..f2233e5721c 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/entity/saving/NullSavingStrategy.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/entity/saving/NullSavingStrategy.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/result/MapperResultProducer.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/result/MapperResultProducer.java index 279363ac969..d262986b75f 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/result/MapperResultProducer.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/result/MapperResultProducer.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/result/MapperResultProducerService.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/result/MapperResultProducerService.java index 6ff193fcf49..b8afdba53b1 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/result/MapperResultProducerService.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/api/mapper/result/MapperResultProducerService.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/internal/mapper/DaoBase.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/internal/mapper/DaoBase.java index 27539ce0482..5f617de52e1 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/internal/mapper/DaoBase.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/internal/mapper/DaoBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -35,11 +37,14 @@ import com.datastax.oss.driver.api.mapper.entity.saving.NullSavingStrategy; import com.datastax.oss.driver.internal.core.ConsistencyLevelRegistry; import com.datastax.oss.driver.internal.core.context.InternalDriverContext; +import com.datastax.oss.driver.internal.core.cql.ResultSets; import com.datastax.oss.protocol.internal.ProtocolConstants; import java.time.Duration; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; /** Base class for generated implementations of {@link Dao}-annotated interfaces. */ public class DaoBase { @@ -222,12 +227,12 @@ protected EntityT executeAndMapToSingleEntity( private EntityT asEntity(Row row, EntityHelper entityHelper) { return (row == null - // Special case for INSERT IF NOT EXISTS. If the row did not exists, the query returns + // Special case for INSERT IF NOT EXISTS. If the row did not exist, the query returns // only [applied], we want to return null to indicate there was no previous entity || (row.getColumnDefinitions().size() == 1 && row.getColumnDefinitions().get(0).getName().equals(APPLIED))) ? null - : entityHelper.get(row); + : entityHelper.get(row, false); } protected Optional executeAndMapToOptionalEntity( @@ -237,7 +242,13 @@ protected Optional executeAndMapToOptionalEntity( protected PagingIterable executeAndMapToEntityIterable( Statement statement, EntityHelper entityHelper) { - return execute(statement).map(entityHelper::get); + return execute(statement).map(row -> entityHelper.get(row, false)); + } + + protected Stream executeAndMapToEntityStream( + Statement statement, EntityHelper entityHelper) { + return StreamSupport.stream( + execute(statement).map(row -> entityHelper.get(row, false)).spliterator(), false); } protected CompletableFuture executeAsync(Statement statement) { @@ -280,7 +291,14 @@ protected CompletableFuture> executeAsyncAndMapToOpt protected CompletableFuture> executeAsyncAndMapToEntityIterable( Statement statement, EntityHelper entityHelper) { - return executeAsync(statement).thenApply(rs -> rs.map(entityHelper::get)); + return executeAsync(statement).thenApply(rs -> rs.map(row -> entityHelper.get(row, false))); + } + + protected CompletableFuture> executeAsyncAndMapToEntityStream( + Statement statement, EntityHelper entityHelper) { + return executeAsync(statement) + .thenApply(ResultSets::newInstance) + .thenApply(rs -> StreamSupport.stream(rs.map(entityHelper::get).spliterator(), false)); } protected static void throwIfProtocolVersionV3(MapperContext context) { diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/internal/mapper/DaoCacheKey.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/internal/mapper/DaoCacheKey.java index ee6b8f52ac9..32fae259769 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/internal/mapper/DaoCacheKey.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/internal/mapper/DaoCacheKey.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/internal/mapper/DefaultMapperContext.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/internal/mapper/DefaultMapperContext.java index 9ba08d8c65d..2d09c2e853f 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/internal/mapper/DefaultMapperContext.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/internal/mapper/DefaultMapperContext.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -24,23 +26,26 @@ import com.datastax.oss.driver.api.mapper.entity.naming.NameConverter; import com.datastax.oss.driver.api.mapper.result.MapperResultProducer; import com.datastax.oss.driver.api.mapper.result.MapperResultProducerService; +import com.datastax.oss.driver.internal.core.context.InternalDriverContext; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableList; import com.datastax.oss.protocol.internal.util.collection.NullAllowingImmutableMap; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; import java.lang.reflect.InvocationTargetException; -import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.ServiceConfigurationError; import java.util.ServiceLoader; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class DefaultMapperContext implements MapperContext { - private static final List RESULT_PRODUCERS = getResultProducers(); + private static final Logger LOGGER = LoggerFactory.getLogger(DefaultMapperContext.class); - private static final ConcurrentMap, MapperResultProducer> RESULT_PRODUCER_CACHE = + private final ConcurrentMap, MapperResultProducer> resultProducerCache = new ConcurrentHashMap<>(); private final CqlSession session; @@ -50,6 +55,7 @@ public class DefaultMapperContext implements MapperContext { private final DriverExecutionProfile executionProfile; private final ConcurrentMap, NameConverter> nameConverterCache; private final Map customState; + private final ImmutableList resultProducers; public DefaultMapperContext( @NonNull CqlSession session, @@ -86,6 +92,8 @@ private DefaultMapperContext( this.customState = customState; this.executionProfileName = executionProfileName; this.executionProfile = executionProfile; + this.resultProducers = + locateResultProducers(((InternalDriverContext) session.getContext()).getClassLoader()); } public DefaultMapperContext withDaoParameters( @@ -154,10 +162,10 @@ public Map getCustomState() { @NonNull @Override public MapperResultProducer getResultProducer(@NonNull GenericType resultToProduce) { - return RESULT_PRODUCER_CACHE.computeIfAbsent( + return resultProducerCache.computeIfAbsent( resultToProduce, k -> { - for (MapperResultProducer resultProducer : RESULT_PRODUCERS) { + for (MapperResultProducer resultProducer : resultProducers) { if (resultProducer.canProduce(k)) { return resultProducer; } @@ -185,11 +193,22 @@ private static NameConverter buildNameConverter(Class c } } - private static List getResultProducers() { - ImmutableList.Builder result = ImmutableList.builder(); - ServiceLoader loader = - ServiceLoader.load(MapperResultProducerService.class); - loader.iterator().forEachRemaining(provider -> result.addAll(provider.getProducers())); - return result.build(); + private static ImmutableList locateResultProducers( + ClassLoader classLoader) { + LOGGER.debug( + "Locating result producers with CL = {}, MapperResultProducerService CL = {}", + classLoader, + MapperResultProducerService.class.getClassLoader()); + ImmutableList.Builder builder = ImmutableList.builder(); + try { + ServiceLoader loader = + ServiceLoader.load(MapperResultProducerService.class, classLoader); + loader.iterator().forEachRemaining(provider -> builder.addAll(provider.getProducers())); + } catch (Exception | ServiceConfigurationError e) { + LOGGER.error("Failed to locate result producers", e); + } + ImmutableList producers = builder.build(); + LOGGER.debug("Located {} result producers: {}", producers.size(), producers); + return producers; } } diff --git a/mapper-runtime/src/main/java/com/datastax/oss/driver/internal/mapper/entity/EntityHelperBase.java b/mapper-runtime/src/main/java/com/datastax/oss/driver/internal/mapper/entity/EntityHelperBase.java index d1198cff5d4..3977ea0c451 100644 --- a/mapper-runtime/src/main/java/com/datastax/oss/driver/internal/mapper/entity/EntityHelperBase.java +++ b/mapper-runtime/src/main/java/com/datastax/oss/driver/internal/mapper/entity/EntityHelperBase.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,6 +18,13 @@ package com.datastax.oss.driver.internal.mapper.entity; import com.datastax.oss.driver.api.core.CqlIdentifier; +import com.datastax.oss.driver.api.core.cql.BoundStatement; +import com.datastax.oss.driver.api.core.cql.BoundStatementBuilder; +import com.datastax.oss.driver.api.core.cql.Row; +import com.datastax.oss.driver.api.core.data.AccessibleByName; +import com.datastax.oss.driver.api.core.data.GettableByName; +import com.datastax.oss.driver.api.core.data.SettableByName; +import com.datastax.oss.driver.api.core.data.UdtValue; import com.datastax.oss.driver.api.core.metadata.schema.ColumnMetadata; import com.datastax.oss.driver.api.core.metadata.schema.KeyspaceMetadata; import com.datastax.oss.driver.api.core.type.DataType; @@ -30,6 +39,7 @@ import com.datastax.oss.driver.api.mapper.annotations.DaoKeyspace; import com.datastax.oss.driver.api.mapper.annotations.Entity; import com.datastax.oss.driver.api.mapper.entity.EntityHelper; +import com.datastax.oss.driver.api.mapper.entity.saving.NullSavingStrategy; import com.datastax.oss.driver.internal.core.util.CollectionsUtils; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; @@ -76,6 +86,23 @@ public CqlIdentifier getTableId() { return tableId; } + @NonNull + @Override + @Deprecated + public > SettableT set( + @NonNull EntityT entity, + @NonNull SettableT target, + @NonNull NullSavingStrategy nullSavingStrategy) { + return set(entity, target, nullSavingStrategy, false); + } + + @NonNull + @Override + @Deprecated + public EntityT get(@NonNull GettableByName source) { + return get(source, false); + } + public void throwIfKeyspaceMissing() { if (this.getKeyspaceId() == null && !context.getSession().getKeyspace().isPresent()) { throw new MapperException( @@ -201,6 +228,26 @@ public void throwMissingTypesIfNotEmpty( public boolean keyspaceNamePresent( Map keyspaces, CqlIdentifier keyspaceId) { - return keyspaces.keySet().contains(keyspaceId); + return keyspaces.containsKey(keyspaceId); + } + + public boolean hasProperty(AccessibleByName source, String name) { + if (source instanceof Row) { + return ((Row) source).getColumnDefinitions().contains(name); + } else if (source instanceof UdtValue) { + return ((UdtValue) source).getType().contains(name); + } else if (source instanceof BoundStatement) { + return ((BoundStatement) source) + .getPreparedStatement() + .getVariableDefinitions() + .contains(name); + } else if (source instanceof BoundStatementBuilder) { + return ((BoundStatementBuilder) source) + .getPreparedStatement() + .getVariableDefinitions() + .contains(name); + } + // other implementations: assume the property is present + return true; } } diff --git a/mapper-runtime/src/test/java/com/datastax/dse/driver/api/mapper/DependencyCheckTest.java b/mapper-runtime/src/test/java/com/datastax/dse/driver/api/mapper/DependencyCheckTest.java index 787d88fea4d..03c1e5bb24f 100644 --- a/mapper-runtime/src/test/java/com/datastax/dse/driver/api/mapper/DependencyCheckTest.java +++ b/mapper-runtime/src/test/java/com/datastax/dse/driver/api/mapper/DependencyCheckTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/test/java/com/datastax/dse/driver/api/mapper/reactive/MappedReactiveResultSetTckTest.java b/mapper-runtime/src/test/java/com/datastax/dse/driver/api/mapper/reactive/MappedReactiveResultSetTckTest.java index cc62393ade3..efd223b1314 100644 --- a/mapper-runtime/src/test/java/com/datastax/dse/driver/api/mapper/reactive/MappedReactiveResultSetTckTest.java +++ b/mapper-runtime/src/test/java/com/datastax/dse/driver/api/mapper/reactive/MappedReactiveResultSetTckTest.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/test/java/com/datastax/dse/driver/api/mapper/reactive/MockAsyncResultSet.java b/mapper-runtime/src/test/java/com/datastax/dse/driver/api/mapper/reactive/MockAsyncResultSet.java index 058b706ca59..849839b7904 100644 --- a/mapper-runtime/src/test/java/com/datastax/dse/driver/api/mapper/reactive/MockAsyncResultSet.java +++ b/mapper-runtime/src/test/java/com/datastax/dse/driver/api/mapper/reactive/MockAsyncResultSet.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/test/java/com/datastax/dse/driver/api/mapper/reactive/MockRow.java b/mapper-runtime/src/test/java/com/datastax/dse/driver/api/mapper/reactive/MockRow.java index b3aeddfada6..0c3ead94349 100644 --- a/mapper-runtime/src/test/java/com/datastax/dse/driver/api/mapper/reactive/MockRow.java +++ b/mapper-runtime/src/test/java/com/datastax/dse/driver/api/mapper/reactive/MockRow.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/mapper-runtime/src/test/java/com/datastax/dse/driver/api/mapper/reactive/TestSubscriber.java b/mapper-runtime/src/test/java/com/datastax/dse/driver/api/mapper/reactive/TestSubscriber.java index 0eaaf508fe9..6886b9a7622 100644 --- a/mapper-runtime/src/test/java/com/datastax/dse/driver/api/mapper/reactive/TestSubscriber.java +++ b/mapper-runtime/src/test/java/com/datastax/dse/driver/api/mapper/reactive/TestSubscriber.java @@ -1,11 +1,13 @@ /* - * Copyright DataStax, Inc. + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -15,6 +17,8 @@ */ package com.datastax.dse.driver.api.mapper.reactive; +import static org.assertj.core.api.Fail.fail; + import com.datastax.oss.driver.shaded.guava.common.util.concurrent.Uninterruptibles; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; @@ -68,6 +72,8 @@ public List getElements() { } public void awaitTermination() { - Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.MINUTES); + if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.MINUTES)) { + fail("subscriber not terminated"); + } } } diff --git a/mapper-runtime/src/test/resources/project.properties b/mapper-runtime/src/test/resources/project.properties index a977778735e..66eab90b6e4 100644 --- a/mapper-runtime/src/test/resources/project.properties +++ b/mapper-runtime/src/test/resources/project.properties @@ -1,11 +1,13 @@ # -# Copyright DataStax, Inc. +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, diff --git a/metrics/micrometer/pom.xml b/metrics/micrometer/pom.xml index 5dde458d947..37ba8556a53 100644 --- a/metrics/micrometer/pom.xml +++ b/metrics/micrometer/pom.xml @@ -1,13 +1,15 @@ + +# Java Driver OSGi Tests This module contains OSGi tests for the driver. @@ -34,8 +53,8 @@ OSGi ones, you can do so as follows: You can pass the following system properties to your tests: 1. `ccm.version`: the CCM version to use -2. `ccm.dse`: whether to use DSE -3. `osgi.debug`: whether to enable remote debugging of the OSGi container (see +2. `ccm.distribution`: choose target backend type (e.g. DSE, HCD) +3. `osgi.debug`: whether to enable remote debugging of the OSGi container (see below). ## Debugging OSGi tests @@ -45,4 +64,4 @@ First, you can enable DEBUG logs for the Pax Exam framework by editing the Alternatively, you can debug the remote OSGi container by passing the system property `-Dosgi.debug=true`. In this case the framework will prompt for a -remote debugger on port 5005. \ No newline at end of file +remote debugger on port 5005. diff --git a/osgi-tests/pom.xml b/osgi-tests/pom.xml index 9a3c62ae770..c2cc4d830f1 100644 --- a/osgi-tests/pom.xml +++ b/osgi-tests/pom.xml @@ -1,13 +1,15 @@ + +# How to run the Driver duration tests + +Note: the procedure described in this page is currently only accessible to DataStax employees. + +## Overview + +A duration test applies a constant, pre-defined load to the cluster for an extended period of time, +typically 2 or 3 days, while also generating some chaos by randomly restarting nodes. The load is +a mix of reads, writes, and deletes. + +Duration tests are useful to detect performance regressions between 2 different driver versions. + +The Java Driver duration tests are stored in a [private +repository](https://github.com/riptano/driver-examples/tree/java-driver-4.x/java/durationTest/) +accessible only to DataStax employees. + +A duration test executes in an infinite loop the following actions: + +1. Confirm row does not exist +2. Write row +3. Confirm read of row +4. Delete row +5. Confirm row does not exist + +The actions are performed randomly via SimpleStatements, BatchStatements (except on reads), and +PreparedStatements. + +## Running the duration tests on DataStax Fallout + +DataStax internal Fallout server has modules that allow to automate running and monitoring duration +tests. + +### Step 0: Set up a Graphite server + +1. If you haven't done this yet, create a new Fallout test based on the [graphite-setup.yaml] + template. +2. Run the test and wait for its successful completion. + * Choose a `keep_alive` parameter that is large enough to run all the planned duration tests. + E.g. if you intend to run duration tests for 10 days, set this parameter to a value greater + than or equal to `10d`. The default is 15 days. +3. Obtain the IP of the Graphite server: + * Navigate to the test artifacts. The IP can be found in the `ctool-cluster-info.txt` file of + the server group: + ![ctool-cluster-info](ctool-cluster-info.png) + * Log in to the Graphite server to check that the server was correctly set up: + `http://:3000` (VPN required). + The username/password is Graphite's default: `admin/admin`. + +Two Grafana dashboards should be loaded automatically: + +* `Java Driver 4 Duration Test Metrics (aggregate)`: provides high-level information such as + the number of completed tests per minute. Useful to compare different test runs. +* `Java Driver 4 Duration Test Metrics (focus)`: provides detailed information for one specific + test run. Can be useful to drill down on issues encountered during the test, or to inspect + latencies, throughput, etc. + +If the above Grafana dashboards are not loaded for some reason, they can be found in this [private +repository](https://github.com/riptano/testeng-devtools/tree/master/duration-tests/java/grafana). + +### Steps 1 to N: Run duration tests and compare results + +1. If you haven't done this yet, create a new Fallout test based on the [duration-test.yaml] + template. +2. For each combination of server and driver that you wish to test, launch a distinct test run and + modify its parameters to match the desired scenario: + * Change `server_type` and`server_version` to match the exact server you plan on testing + against; + * Change `driver_rev` and `driver_label` to be whatever driver revision you are using ( + `driver_label` is merely for reporting purposes); + * Don't forget to change the `graphite_host` parameter to match the Graphite server IP obtained + in the previous step; + * Finally, choose the desired duration (default is 2 days). +3. Run the test and monitor the performance on the Graphite server. + +Once a test run is finished, the cluster and the client VMs are destroyed, but their logs are +conserved as test artifacts in Fallout. diff --git a/performance/ctool-cluster-info.png b/performance/ctool-cluster-info.png index 041203cbf42..550b077b7eb 100644 Binary files a/performance/ctool-cluster-info.png and b/performance/ctool-cluster-info.png differ diff --git a/performance/duration-test.yaml b/performance/duration-test.yaml new file mode 100644 index 00000000000..6e718f2add8 --- /dev/null +++ b/performance/duration-test.yaml @@ -0,0 +1,99 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# Possible values: cassandra or dse +server_type: cassandra +# Server version (e.g. 3.11.7 or 6.8.8) +server_version: 3.11.7 +# The driver Git revision to checkout and build (can be a branch name, a tag name or a commit SHA) +driver_rev: 4.x +# A distinctive driver label to use, for reporting purposes (will appear in Graphite metric names) +driver_label: 4.10.0 +# The IP of a running Graphite server, see graphite-setup.yaml +graphite_host: 1.2.3.4 +# How long to run the duration test, default: 2 days +duration: 2d +# Cloud-specific settings +cloud_provider: nebula +cloud_tenant: drivers-automation +instance_type: m4.4xlarge + +--- + +ensemble: + server: + node.count: 3 + provisioner: + name: ctool + properties: + mark_for_reuse: false + cloud.provider: {{cloud_provider}} + cloud.tenant: {{cloud_tenant}} + cloud.instance.type: {{instance_type}} + configuration_manager: + - name: ctool + properties: + java.version: openjdk8 + product.install.type: tarball + product.type: {{server_type}} + product.version: {{server_version}} + cassandra.yaml: + hinted_handoff_enabled: false + datacenters: + datacenter1: + size: 3 + workload: cassandra + client: + node.count: 1 + provisioner: + name: ctool + properties: + mark_for_reuse: false + cloud.provider: {{cloud_provider}} + cloud.tenant: {{cloud_tenant}} + cloud.instance.type: {{instance_type}} + configuration_manager: + - name: ctool + properties: + java.version: openjdk8 + install.maven: true + - name: java_driver + properties: + oss.git.repository: git@github.com:datastax/java-driver.git + oss.git.branch: {{driver_rev}} + type: FOUR_X_OSS + - name: java_driver_duration_test + properties: + git.branch: java-driver-4.x +workload: + phases: + - run-duration-test: + module: java_driver_duration_test + properties: + is.four: true + duration: {{duration}} + graphite.host: {{graphite_host}} + graphite.prefix: duration-test-java-driver-{{driver_label}}-{{server_type}}-{{server_version}} + kill-nodes: + module: killnode_rhino + properties: + target.strategy: whitelist + target.number_of_nodes: 1 + target.selector: "*:*" + repeat.delay: 120 + repeat.iterations: 0 + graceful: true diff --git a/performance/graphite-setup.yaml b/performance/graphite-setup.yaml index be6a55b7919..99bb8ecc8cc 100644 --- a/performance/graphite-setup.yaml +++ b/performance/graphite-setup.yaml @@ -1,102 +1,61 @@ -dse_version: 6.0.11 -# Driver branch to use -driver_oss_branch: 4.x -# Driver dse branch to use -driver_dse_branch: 4.x -# Driver version identifier (used as part of graphite prefix) -driver_version: 4.8.0 -# Driver examples branch to use -driver_examples_branch: java-driver-4.x -# How long to run test for -duration: 2d +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# How long should the Graphite server be kept alive, default: 15 days +keep_alive: 15d +# Cloud-specific settings +cloud_provider: nebula +cloud_tenant: drivers-automation +instance_type: m4.2xlarge --- ensemble: - observer: + server: node.count: 1 provisioner: name: ctool properties: mark_for_reuse: true - cloud.provider: openstack - cloud.tenant: performance - cloud.instance.type: ms1.small + cluster_ttl: {{keep_alive}} + cloud.provider: {{cloud_provider}} + cloud.tenant: {{cloud_tenant}} + cloud.instance.type: {{instance_type}} configuration_manager: - name: ctool_monitoring properties: graphite.create_server: true - server: - node.count: 3 - provisioner: - name: ctool - properties: - mark_for_reuse: true - cloud.provider: openstack - cloud.tenant: performance - cloud.instance.type: ms1.small - configuration_manager: - - name: ctool - properties: - product.type: dse - product.install.type: tarball - product.version: {{dse_version}} - cassandra.yaml: - hinted_handoff_enabled: false - datacenters: - datacenter1: - size: 3 - workload: cassandra client: node.count: 1 provisioner: name: ctool properties: - mark_for_reuse: true - cloud.provider: openstack - cloud.tenant: performance - cloud.instance.type: ms1.small - configuration_manager: - - name: ctool - properties: - java.version: openjdk8 - install.maven: true - - name: java_driver - properties: - oss.git.repository: git@github.com:datastax/java-driver.git - oss.git.branch: {{driver_oss_branch}} - dse.git.branch: {{driver_dse_branch}} - type: FOUR_X_OSS - - name: java_driver_duration_test - properties: - git.branch: {{driver_examples_branch}} + mark_for_reuse: false + cloud.provider: {{cloud_provider}} + cloud.tenant: {{cloud_tenant}} + cloud.instance.type: {{instance_type}} workload: phases: - upload-dashboards-to-grafana: module: bash properties: script: | - echo "BASH SCRIPT FALLOUT HOST IS..." - echo "${FALLOUT_OBSERVER_NODE0_GRAPHITE_HOST}" - + echo "Graphite server IP: ${FALLOUT_SERVER_NODE0_MONITORING_GRAPHITE_HOST}" git clone git@github.com:riptano/testeng-devtools.git ${FALLOUT_SCRATCH_DIR}/dashboard - curl --user admin:admin -d "@${FALLOUT_SCRATCH_DIR}/dashboard/duration-tests/java/grafana/aggregate.json" -X POST -H "Content-Type: application/json" http://${FALLOUT_OBSERVER_NODE0_MONITORING_GRAPHITE_HOST}:3000/api/dashboards/db/ - curl --user admin:admin -d "@${FALLOUT_SCRATCH_DIR}/dashboard/duration-tests/java/grafana/aggregate4.json" -X POST -H "Content-Type: application/json" http://${FALLOUT_OBSERVER_NODE0_MONITORING_GRAPHITE_HOST}:3000/api/dashboards/db/ - curl --user admin:admin -d "@${FALLOUT_SCRATCH_DIR}/dashboard/duration-tests/java/grafana/focus.json" -X POST -H "Content-Type: application/json" http://${FALLOUT_OBSERVER_NODE0_MONITORING_GRAPHITE_HOST}:3000/api/dashboards/db/ - curl --user admin:admin -d "@${FALLOUT_SCRATCH_DIR}/dashboard/duration-tests/java/grafana/focus4.json" -X POST -H "Content-Type: application/json" http://${FALLOUT_OBSERVER_NODE0_MONITORING_GRAPHITE_HOST}:3000/api/dashboards/db/ + curl --user admin:admin -d "@${FALLOUT_SCRATCH_DIR}/dashboard/duration-tests/java/grafana/aggregate4.json" -X POST -H "Content-Type: application/json" http://${FALLOUT_SERVER_NODE0_MONITORING_GRAPHITE_HOST}:3000/api/dashboards/db/ + curl --user admin:admin -d "@${FALLOUT_SCRATCH_DIR}/dashboard/duration-tests/java/grafana/focus4.json" -X POST -H "Content-Type: application/json" http://${FALLOUT_SERVER_NODE0_MONITORING_GRAPHITE_HOST}:3000/api/dashboards/db/ target.group: client - - run-endurance: - module: java_driver_duration_test - properties: - duration: {{duration}} - is.four: true - graphite.prefix: endurance-test-java-{{driver_version}}-DSE-{{dse_version}} - - kill_nodes: - module: killnode_rhino - properties: - target.strategy: whitelist - target.number_of_nodes: 1 - target.selector: "*:*" - repeat.delay: 120 - repeat.iterations: 0 - graceful: true diff --git a/performance/metrics-dashboards.png b/performance/metrics-dashboards.png deleted file mode 100644 index 6ffb85b9f18..00000000000 Binary files a/performance/metrics-dashboards.png and /dev/null differ diff --git a/performance/oss-performance-setup.yaml b/performance/oss-performance-setup.yaml deleted file mode 100644 index 46eafb238b6..00000000000 --- a/performance/oss-performance-setup.yaml +++ /dev/null @@ -1,79 +0,0 @@ -cassandra_version: cassandra-3.11.4 -cassandra_install_type: git -# Driver branch to use -driver_oss_branch: 4.x -# Driver dse branch to use -driver_dse_branch: 4.x -# Driver version identifier (used as part of graphite prefix) -driver_version: 4.8.0 -# Driver examples branch to use -driver_examples_branch: java-driver-4.x -# How long to run test for -duration: 2d -# The ip of the observer node from graphite-setup.yaml step -graphite_host: {provide-graphite-host-ip} - ---- - -ensemble: - server: - node.count: 3 - provisioner: - name: ctool - properties: - mark_for_reuse: true - cloud.provider: openstack - cloud.tenant: performance - cloud.instance.type: ms1.small - cluster_ttl: 2d - configuration_manager: - - name: ctool - properties: - java.version: openjdk8 - product.type: cassandra - product.install.type: {{cassandra_install_type}} - product.version: {{cassandra_version}} - cassandra.yaml: - hinted_handoff_enabled: false - client: - node.count: 1 - provisioner: - name: ctool - properties: - mark_for_reuse: true - cluster_ttl: 2d - cloud.provider: openstack - cloud.tenant: performance - cloud.instance.type: ms1.small - configuration_manager: - - name: ctool - properties: - java.version: openjdk8 - install.maven: true - - name: java_driver - properties: - oss.git.repository: git@github.com:datastax/java-driver.git - oss.git.branch: {{driver_oss_branch}} - dse.git.branch: {{driver_dse_branch}} - type: FOUR_X_OSS - - name: java_driver_duration_test - properties: - git.branch: {{driver_examples_branch}} -workload: - phases: - - run-endurance: - module: java_driver_duration_test - properties: - duration: {{duration}} - is.four: true - graphite.host: {{graphite_host}} - graphite.prefix: endurance-test-java-{{driver_version}}-OSS-{{cassandra_version}} - kill_nodes: - module: killnode_rhino - properties: - target.strategy: whitelist - target.number_of_nodes: 1 - target.selector: "*:*" - repeat.delay: 120 - repeat.iterations: 0 - graceful: true diff --git a/pom.xml b/pom.xml index 823d979fbab..eb83459cfb4 100644 --- a/pom.xml +++ b/pom.xml @@ -1,13 +1,15 @@ 4.0.0 - com.datastax.oss + + org.apache + apache + 23 + + org.apache.cassandra java-driver-parent - 4.10.0-SNAPSHOT + 4.19.3-SNAPSHOT pom - DataStax Java driver for Apache Cassandra(R) - A driver for Apache Cassandra(R) 2.1+ that works exclusively with the Cassandra Query Language version 3 (CQL3) and Cassandra's native protocol versions 3 and above. + Apache Cassandra Java Driver https://github.com/datastax/java-driver 2017 @@ -32,60 +38,69 @@ query-builder mapper-runtime mapper-processor - test-infra metrics/micrometer metrics/microprofile + guava-shaded + test-infra integration-tests osgi-tests + distribution-source distribution + distribution-tests examples bom - true UTF-8 UTF-8 - 1.3.4 - 2.1.11 - 4.0.5 - 4.1.51.Final + 1.4.1 + + 2.1.12 + 4.1.18 + 4.1.130.Final 1.2.1 - 3.4.8 + + 3.5.6 + 1.7.26 - 1.0.2 - 20190722 - 2.11.0 - 2.11.0 - 1.9.12 + + 1.0.3 + 20230227 + 2.13.5 + ${jackson.version} - 1.1.7.3 - 1.6.0 + 1.1.10.1 + 1.10.1 - 3.13.1 + 3.19.0 1.3 - 4.12 + 4.13.2 1.2.3 6.0.0 - 6.0.3 - 4.13.3 - 0.8.9 - 1.0 - 2.28 + 7.0.1 + 4.13.4 + 2.6.4 + 0.11.0 + 1.1.4 + 2.31 2.5.0 - 2.0.1 + 2.1.1 1.1.4 2.2.2 - 4.0.2 + 4.0.3 2.0.0-M19 - 2.22.2 - 20.0.0 + 3.0.0 + 22.0.0.2 false ${skipTests} - com.datastax.oss + org.apache.cassandra java-driver-core ${project.version} test-jar @@ -96,10 +111,10 @@ ${netty.version} - + com.google.guava guava - 25.1-jre + 33.3.1-jre com.typesafe @@ -122,14 +137,15 @@ ${snappy.version} - org.lz4 + at.yawk.lz4 lz4-java ${lz4.version} com.github.jnr jnr-posix - 3.0.50 + + 3.1.15 io.dropwizard.metrics @@ -202,7 +218,7 @@ com.squareup javapoet - 1.11.1 + 1.13.0 junit @@ -267,12 +283,17 @@ org.ops4j.pax.url pax-url-wrap - 2.5.4 + ${pax-url.version} org.ops4j.pax.url pax-url-reference - 2.6.2 + ${pax-url.version} + + + org.ops4j.pax.tinybundles + tinybundles + 3.0.0 org.glassfish @@ -322,7 +343,7 @@ javax.annotation javax.annotation-api - 1.2 + 1.3.2 com.fasterxml.jackson.core @@ -337,7 +358,7 @@ com.google.testing.compile compile-testing - 0.18 + 0.19 org.awaitility @@ -347,7 +368,7 @@ org.testng testng - 6.14.3 + 7.3.0 org.apache.directory.server @@ -408,17 +429,34 @@ io.micrometer micrometer-core - 1.5.0 + 1.6.5 org.eclipse.microprofile.metrics microprofile-metrics-api - 2.3 + 3.0 io.smallrye smallrye-metrics - 2.4.2 + 3.0.3 + + + io.projectreactor + reactor-bom + 2020.0.5 + pom + import + + + io.projectreactor.tools + blockhound + 1.0.8.RELEASE + + + io.projectreactor.tools + blockhound-junit-platform + 1.0.8.RELEASE @@ -427,7 +465,7 @@ maven-compiler-plugin - 3.6.1 + 3.8.1 com.coveo @@ -454,11 +492,11 @@ maven-shade-plugin - 3.1.1 + 3.2.3 maven-assembly-plugin - 3.1.0 + 3.3.0 @@ -475,15 +513,15 @@ maven-source-plugin - 3.0.1 + 3.1.0 maven-javadoc-plugin - 3.1.1 + 3.2.0 maven-jar-plugin - 3.0.2 + 3.2.0 org.sonatype.plugins @@ -492,7 +530,7 @@ maven-gpg-plugin - 1.5 + 1.6 maven-release-plugin @@ -500,47 +538,46 @@ maven-install-plugin - 2.4 + 2.5.2 maven-deploy-plugin - 2.7 + 2.8.2 maven-dependency-plugin - 3.1.1 + 3.1.2 org.jacoco jacoco-maven-plugin - 0.8.3 + 0.8.10 org.apache.felix maven-bundle-plugin - 3.5.1 + 5.1.1 org.revapi revapi-maven-plugin - 0.10.5 + 0.15.1 false \d+\.\d+\.\d+ - - - - - java.class.externalClassExposedInAPI - - - + + + ${project.groupId}:${project.artifactId}:RELEASE + + + revapi.json + org.revapi revapi-java - 0.19.1 + 0.28.4 @@ -554,9 +591,33 @@ flatten-maven-plugin 1.2.1 + + org.apache.maven.plugins + maven-enforcer-plugin + 3.5.0 + + + maven-enforcer-plugin + + + enforce-maven + + enforce + + + + + + [3.8.1,) + + + + + + maven-compiler-plugin @@ -568,6 +629,7 @@ -Xep:FutureReturnValueIgnored:OFF -Xep:PreferJavaTimeOverload:OFF -Xep:AnnotateFormatMethod:OFF + -Xep:WildcardImport:WARN -XepExcludedPaths:.*/target/(?:generated-sources|generated-test-sources)/.* true @@ -624,13 +686,15 @@ license-maven-plugin **/pom.xml + src/**/native-image.properties **/src/main/config/ide/** @@ -683,6 +748,7 @@ limitations under the License.]]> maven-surefire-plugin + ${testing.jvm}/bin/java ${project.basedir}/src/test/resources/logback-test.xml @@ -709,7 +775,7 @@ limitations under the License.]]> true ossrh - https://oss.sonatype.org/ + https://repository.apache.org/ false true @@ -722,6 +788,12 @@ limitations under the License.]]> jar-no-fork + + + LICENSE_binary + NOTICE_binary.txt + + @@ -749,28 +821,6 @@ limitations under the License.]]> - - attach-javadocs - - jar - - -

    - - - - -]]>
    - - --allow-script-in-comments - - - check-api-leaks @@ -870,15 +920,17 @@ height="0" width="0" style="display:none;visibility:hidden"> check - - - - revapi.json - - + + org.apache.maven.plugins + maven-remote-resources-plugin + 1.7.0 + + true + + @@ -915,13 +967,82 @@ height="0" width="0" style="display:none;visibility:hidden"> true + + + test-jdk-environment + + + !testJavaHome + + + + ${env.JAVA_HOME} + + + + + test-jdk-specified + + + testJavaHome + + + + ${testJavaHome} + + + + + test-jdk-8 + + [8,) + + + + + test-jdk-11 + + [11,) + + + + + test-jdk-14 + + [14,) + + + + -XX:+AllowRedefinitionToAddDeleteMethods + + + + + test-jdk-17 + + [17,) + + + + -XX:+AllowRedefinitionToAddDeleteMethods + + --add-opens java.base/jdk.internal.util.random=ALL-UNNAMED + + + + + test-jdk-21 + + [21,) + + + + -XX:+AllowRedefinitionToAddDeleteMethods + + --add-opens=java.base/jdk.internal.util.random=ALL-UNNAMED + + - - - ossrh - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - Apache 2 diff --git a/pre-commit.sh b/pre-commit.sh index c87ea5bf9ca..912564ae81e 100755 --- a/pre-commit.sh +++ b/pre-commit.sh @@ -1,4 +1,20 @@ #!/usr/bin/env bash +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. # STASH_NAME="pre-commit-$(date +%s)" # git stash save --keep-index $STASH_NAME diff --git a/query-builder/pom.xml b/query-builder/pom.xml index ddf668c530a..2bfe1bee8f5 100644 --- a/query-builder/pom.xml +++ b/query-builder/pom.xml @@ -1,13 +1,15 @@ + ## Upgrade guide +### 4.18.1 + +#### Keystore reloading in DefaultSslEngineFactory + +`DefaultSslEngineFactory` now includes an optional keystore reloading interval, for detecting changes in the local +client keystore file. This is relevant in environments with mTLS enabled and short-lived client certificates, especially +when an application restart might not always happen between a new keystore becoming available and the previous +keystore certificate expiring. + +This feature is disabled by default for compatibility. To enable, see `keystore-reload-interval` in `reference.conf`. + +### 4.17.0 + +#### Support for Java17 + +With the completion of [JAVA-3042](https://datastax-oss.atlassian.net/browse/JAVA-3042) the driver now passes our automated test matrix for Java Driver releases. +If you discover an issue with the Java Driver running on Java 17, please let us know. We will triage and address Java 17 issues. + +#### Updated API for vector search + +The 4.16.0 release introduced support for the CQL `vector` datatype. This release modifies the `CqlVector` +value type used to represent a CQL vector to make it easier to use. `CqlVector` now implements the Iterable interface +as well as several methods modelled on the JDK's List interface. For more, see +[JAVA-3060](https://datastax-oss.atlassian.net/browse/JAVA-3060). + +The builder interface was replaced with factory methods that resemble similar methods on `CqlDuration`. +For example, the following code will create a keyspace and table, populate that table with some data, and then execute +a query that will return a `vector` type. This data is retrieved directly via `Row.getVector()` and the resulting +`CqlVector` value object can be interrogated directly. + +```java +try (CqlSession session = new CqlSessionBuilder().withLocalDatacenter("datacenter1").build()) { + + session.execute("DROP KEYSPACE IF EXISTS test"); + session.execute("CREATE KEYSPACE test WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}"); + session.execute("CREATE TABLE test.foo(i int primary key, j vector)"); + session.execute("CREATE CUSTOM INDEX ann_index ON test.foo(j) USING 'StorageAttachedIndex'"); + session.execute("INSERT INTO test.foo (i, j) VALUES (1, [8, 2.3, 58])"); + session.execute("INSERT INTO test.foo (i, j) VALUES (2, [1.2, 3.4, 5.6])"); + session.execute("INSERT INTO test.foo (i, j) VALUES (5, [23, 18, 3.9])"); + ResultSet rs=session.execute("SELECT j FROM test.foo WHERE j ann of [3.4, 7.8, 9.1] limit 1"); + for (Row row : rs){ + CqlVector v = row.getVector(0, Float.class); + System.out.println(v); + if (Iterables.size(v) != 3) { + throw new RuntimeException("Expected vector with three dimensions"); + } + } +} +``` + +You can also use the `CqlVector` type with prepared statements: + +```java +PreparedStatement preparedInsert = session.prepare("INSERT INTO test.foo (i, j) VALUES (?,?)"); +CqlVector vector = CqlVector.newInstance(1.4f, 2.5f, 3.6f); +session.execute(preparedInsert.bind(3, vector)); +``` + +In some cases, it makes sense to access the vector directly as an array of some numerical type. This version +supports such use cases by providing a codec which translates a CQL vector to and from a primitive array. Only float arrays are supported. +You can find more information about this codec in the manual documentation on [custom codecs](../manual/core/custom_codecs/) + +### 4.15.0 + +#### CodecNotFoundException now extends DriverException + +Before [JAVA-2995](https://datastax-oss.atlassian.net/browse/JAVA-2995), `CodecNotFoundException` +was extending `RuntimeException`. This is a discrepancy as all other exceptions extend +`DriverException`, which in turn extends `RuntimeException`. + +This was causing integrators to do workarounds in order to react on all exceptions correctly. + +The change introduced by JAVA-2995 shouldn't be a problem for most users. But if your code was using +a logic such as below, it won't compile anymore: + +```java +try { + doSomethingWithDriver(); +} catch(DriverException e) { +} catch(CodecNotFoundException e) { +} +``` + +You need to either reverse the catch order and catch `CodecNotFoundException` first: + +```java +try { + doSomethingWithDriver(); +} catch(CodecNotFoundException e) { +} catch(DriverException e) { +} +``` + +Or catch only `DriverException`: + +```java +try { + doSomethingWithDriver(); +} catch(DriverException e) { +} +``` + +### 4.14.0 + +#### AllNodesFailedException instead of NoNodeAvailableException in certain cases + +[JAVA-2959](https://datastax-oss.atlassian.net/browse/JAVA-2959) changed the behavior for when a +request cannot be executed because all nodes tried were busy. Previously you would get back a +`NoNodeAvailableException` but you will now get back an `AllNodesFailedException` where the +`getAllErrors` map contains a `NodeUnavailableException` for that node. + +#### Esri Geometry dependency now optional + +Previous versions of the Java Driver defined a mandatory dependency on the Esri geometry library. +This library offered support for primitive geometric types supported by DSE. As of driver 4.14.0 +this dependency is now optional. + +If you do not use DSE (or if you do but do not use the support for geometric types within DSE) you +should experience no disruption. If you are using geometric types with DSE you'll now need to +explicitly declare a dependency on the Esri library: + +```xml + + com.esri.geometry + esri-geometry-api + ${esri.version} + +``` + +See the [integration](../manual/core/integration/#esri) section in the manual for more details. + +### 4.13.0 + +#### Enhanced support for GraalVM native images + +[JAVA-2940](https://datastax-oss.atlassian.net/browse/JAVA-2940) introduced an enhanced support for +building GraalVM native images. + +If you were building a native image for your application, please verify your native image builder +configuration. Most of the extra configuration required until now is likely to not be necessary +anymore. + +Refer to this [manual page](../manual/core/graalvm) for details. + +#### Registration of multiple listeners and trackers + +[JAVA-2951](https://datastax-oss.atlassian.net/browse/JAVA-2951) introduced the ability to register +more than one instance of the following interfaces: + +* [RequestTracker](https://docs.datastax.com/en/drivers/java/4.12/com/datastax/oss/driver/api/core/tracker/RequestTracker.html) +* [NodeStateListener](https://docs.datastax.com/en/drivers/java/4.12/com/datastax/oss/driver/api/core/metadata/NodeStateListener.html) +* [SchemaChangeListener](https://docs.datastax.com/en/drivers/java/4.12/com/datastax/oss/driver/api/core/metadata/schema/SchemaChangeListener.html) + +Multiple components can now be registered both programmatically and through the configuration. _If +both approaches are used, components will add up and will all be registered_ (whereas previously, +the programmatic approach would take precedence over the configuration one). + +When using the programmatic approach to register multiple components, you should use the new +`SessionBuilder` methods `addRequestTracker`, `addNodeStateListener` and `addSchemaChangeListener`: + +```java +CqlSessionBuilder builder = CqlSession.builder(); +builder + .addRequestTracker(tracker1) + .addRequestTracker(tracker2); +builder + .addNodeStateListener(nodeStateListener1) + .addNodeStateListener(nodeStateListener2); +builder + .addSchemaChangeListener(schemaChangeListener1) + .addSchemaChangeListener(schemaChangeListener2); +``` + +To support registration of multiple components through the configuration, the following +configuration options were deprecated because they only allow one component to be declared: + +* `advanced.request-tracker.class` +* `advanced.node-state-listener.class` +* `advanced.schema-change-listener.class` + +They are still honored, but the driver will log a warning if they are used. They should now be +replaced with the following ones, that accept a list of classes to instantiate, instead of just +one: + +* `advanced.request-tracker.classes` +* `advanced.node-state-listener.classes` +* `advanced.schema-change-listener.classes` + +Example: + +```hocon +datastax-java-driver { + advanced { + # RequestLogger is a driver built-in tracker + request-tracker.classes = [RequestLogger,com.example.app.MyRequestTracker] + node-state-listener.classes = [com.example.app.MyNodeStateListener1,com.example.app.MyNodeStateListener2] + schema-change-listener.classes = [com.example.app.MySchemaChangeListener] + } +} +``` + +When more than one component of the same type is registered, the driver will distribute received +signals to all components in sequence, by order of their registration, starting with the +programmatically-provided ones. If a component throws an error, the error is intercepted and logged. + +### 4.12.0 + +#### MicroProfile Metrics upgraded to 3.0 + +The MicroProfile Metrics library has been upgraded from version 2.4 to 3.0. Since this upgrade +involves backwards-incompatible binary changes, users of this library and of the +`java-driver-metrics-microprofile` module are required to take the appropriate action: + +* If your application is still using MicroProfile Metrics < 3.0, you can still upgrade the core + driver to 4.12, but you now must keep `java-driver-metrics-microprofile` in version 4.11 or lower, + as newer versions will not work. + +* If your application is using MicroProfile Metrics >= 3.0, then you must upgrade to driver 4.12 or + higher, as previous versions of `java-driver-metrics-microprofile` will not work. + +#### Mapper `@GetEntity` and `@SetEntity` methods can now be lenient + +Thanks to [JAVA-2935](https://datastax-oss.atlassian.net/browse/JAVA-2935), `@GetEntity` and +`@SetEntity` methods now have a new `lenient` attribute. + +If the attribute is `false` (the default value), then the source row or the target statement must +contain a matching column for every property in the entity definition. If such a column is not +found, an error will be thrown. This corresponds to the mapper's current behavior prior to the +introduction of the new attribute. + +If the new attribute is explicitly set to `true` however, the mapper will operate on a best-effort +basis and attempt to read or write all entity properties that have a matching column in the source +row or in the target statement, *leaving unmatched properties untouched*. + +This new, lenient behavior allows to achieve the equivalent of driver 3.x +[lenient mapping](https://docs.datastax.com/en/developer/java-driver/3.10/manual/object_mapper/using/#manual-mapping). + +Read the manual pages on [@GetEntity](../manual/mapper/daos/getentity) methods and +[@SetEntity](../manual/mapper/daos/setentity) methods for more details and examples of lenient mode. + +### 4.11.0 + +#### Native protocol V5 is now production-ready + +Thanks to [JAVA-2704](https://datastax-oss.atlassian.net/browse/JAVA-2704), 4.11.0 is the first +version in the driver 4.x series to fully support Cassandra's native protocol version 5, which has +been promoted from beta to production-ready in the upcoming Cassandra 4.0 release. + +Users should not experience any disruption. When connecting to Cassandra 4.0, V5 will be +transparently selected as the protocol version to use. + +#### Customizable metric names, support for metric tags + +[JAVA-2872](https://datastax-oss.atlassian.net/browse/JAVA-2872) introduced the ability to configure +how metric identifiers are generated. Metric names can now be configured, but most importantly, +metric tags are now supported. See the [metrics](../manual/core/metrics/) section of the online +manual, or the `advanced.metrics.id-generator` section in the +[reference.conf](../manual/core/configuration/reference/) file for details. + +Users should not experience any disruption. However, those using metrics libraries that support tags +are encouraged to try out the new `TaggingMetricIdGenerator`, as it generates metric names and tags +that will look more familiar to users of libraries such as Micrometer or MicroProfile Metrics (and +look nicer when exported to Prometheus or Graphite). + +#### New `NodeDistanceEvaluator` API + +All driver built-in load-balancing policies now accept a new optional component called +[NodeDistanceEvaluator]. This component gets invoked each time a node is added to the cluster or +comes back up. If the evaluator returns a non-null distance for the node, that distance will be +used, otherwise the driver will use its built-in logic to assign a default distance to it. + +[NodeDistanceEvaluator]: https://docs.datastax.com/en/drivers/java/4.11/com/datastax/oss/driver/api/core/loadbalancing/NodeDistanceEvaluator.html + +This component replaces the old "node filter" component. As a consequence, all `withNodeFilter` +methods in `SessionBuilder` are now deprecated and should be replaced by the equivalent +`withNodeDistanceEvaluator` methods. + +If you have an existing node filter implementation, it can be converted to a `NodeDistanceEvaluator` +very easily: + +```java +Predicate nodeFilter = ... +NodeDistanceEvaluator nodeEvaluator = + (node, dc) -> nodeFilter.test(node) ? null : NodeDistance.IGNORED; +``` + +The above can also be achieved by an adapter class as shown below: + +```java +public class NodeFilterToDistanceEvaluatorAdapter implements NodeDistanceEvaluator { + + private final Predicate nodeFilter; + + public NodeFilterToDistanceEvaluatorAdapter(@NonNull Predicate nodeFilter) { + this.nodeFilter = nodeFilter; + } + + @Nullable @Override + public NodeDistance evaluateDistance(@NonNull Node node, @Nullable String localDc) { + return nodeFilter.test(node) ? null : NodeDistance.IGNORED; + } +} +``` + +Finally, the `datastax-java-driver.basic.load-balancing-policy.filter.class` configuration option +has been deprecated; it should be replaced with a node distance evaluator class defined by the +`datastax-java-driver.basic.load-balancing-policy.evaluator.class` option instead. + +### 4.10.0 + +#### Cross-datacenter failover + +[JAVA-2899](https://datastax-oss.atlassian.net/browse/JAVA-2899) re-introduced the ability to +perform cross-datacenter failover using the driver's built-in load balancing policies. See [Load +balancing](../manual/core/loadbalancing/) in the manual for details. + +Cross-datacenter failover is disabled by default, therefore existing applications should not +experience any disruption. + +#### New `RetryVerdict` API + +[JAVA-2900](https://datastax-oss.atlassian.net/browse/JAVA-2900) introduced [`RetryVerdict`], a new +interface that allows custom retry policies to customize the request before it is retried. + +For this reason, the following methods in the `RetryPolicy` interface were added; they all return +a `RetryVerdict` instance: + +1. [`onReadTimeoutVerdict`](https://docs.datastax.com/en/drivers/java/4.11/com/datastax/oss/driver/api/core/retry/RetryPolicy.html#onReadTimeoutVerdict-com.datastax.oss.driver.api.core.session.Request-com.datastax.oss.driver.api.core.ConsistencyLevel-int-int-boolean-int-) +2. [`onWriteTimeoutVerdict`](https://docs.datastax.com/en/drivers/java/4.11/com/datastax/oss/driver/api/core/retry/RetryPolicy.html#onWriteTimeoutVerdict-com.datastax.oss.driver.api.core.session.Request-com.datastax.oss.driver.api.core.ConsistencyLevel-com.datastax.oss.driver.api.core.servererrors.WriteType-int-int-int-) +3. [`onUnavailableVerdict`](https://docs.datastax.com/en/drivers/java/4.11/com/datastax/oss/driver/api/core/retry/RetryPolicy.html#onUnavailableVerdict-com.datastax.oss.driver.api.core.session.Request-com.datastax.oss.driver.api.core.ConsistencyLevel-int-int-int-) +4. [`onRequestAbortedVerdict`](https://docs.datastax.com/en/drivers/java/4.11/com/datastax/oss/driver/api/core/retry/RetryPolicy.html#onRequestAbortedVerdict-com.datastax.oss.driver.api.core.session.Request-java.lang.Throwable-int-) +5. [`onErrorResponseVerdict`](https://docs.datastax.com/en/drivers/java/4.11/com/datastax/oss/driver/api/core/retry/RetryPolicy.html#onErrorResponseVerdict-com.datastax.oss.driver.api.core.session.Request-com.datastax.oss.driver.api.core.servererrors.CoordinatorException-int-) + +The following methods were deprecated and will be removed in the next major version: + +1. [`onReadTimeout`](https://docs.datastax.com/en/drivers/java/4.11/com/datastax/oss/driver/api/core/retry/RetryPolicy.html#onReadTimeout-com.datastax.oss.driver.api.core.session.Request-com.datastax.oss.driver.api.core.ConsistencyLevel-int-int-boolean-int-) +2. [`onWriteTimeout`](https://docs.datastax.com/en/drivers/java/4.11/com/datastax/oss/driver/api/core/retry/RetryPolicy.html#onWriteTimeout-com.datastax.oss.driver.api.core.session.Request-com.datastax.oss.driver.api.core.ConsistencyLevel-com.datastax.oss.driver.api.core.servererrors.WriteType-int-int-int-) +3. [`onUnavailable`](https://docs.datastax.com/en/drivers/java/4.11/com/datastax/oss/driver/api/core/retry/RetryPolicy.html#onUnavailable-com.datastax.oss.driver.api.core.session.Request-com.datastax.oss.driver.api.core.ConsistencyLevel-int-int-int-) +4. [`onRequestAborted`](https://docs.datastax.com/en/drivers/java/4.11/com/datastax/oss/driver/api/core/retry/RetryPolicy.html#onRequestAborted-com.datastax.oss.driver.api.core.session.Request-java.lang.Throwable-int-) +5. [`onErrorResponse`](https://docs.datastax.com/en/drivers/java/4.11/com/datastax/oss/driver/api/core/retry/RetryPolicy.html#onErrorResponse-com.datastax.oss.driver.api.core.session.Request-com.datastax.oss.driver.api.core.servererrors.CoordinatorException-int-) + +Driver 4.10.0 also re-introduced a retry policy whose behavior is equivalent to the +`DowngradingConsistencyRetryPolicy` from driver 3.x. See this +[FAQ entry](https://docs.datastax.com/en/developer/java-driver/4.11/faq/#where-is-downgrading-consistency-retry-policy) +for more information. + +[`RetryVerdict`]: https://docs.datastax.com/en/drivers/java/4.11/com/datastax/oss/driver/api/core/retry/RetryVerdict.html + +#### Enhancements to the `Uuids` utility class + +[JAVA-2449](https://datastax-oss.atlassian.net/browse/JAVA-2449) modified the implementation of +[Uuids.random()]: this method does not delegate anymore to the JDK's `java.util.UUID.randomUUID()` +implementation, but instead re-implements random UUID generation using the non-cryptographic +random number generator `java.util.Random`. + +For most users, non-cryptographic strength is enough and this change should translate into better +performance when generating UUIDs for database insertion. However, in the unlikely case where your +application requires cryptographic strength for UUID generation, you should update your code to +use `java.util.UUID.randomUUID()` instead of `com.datastax.oss.driver.api.core.uuid.Uuids.random()` +from now on. + +This release also introduces two new methods for random UUID generation: + +1. [Uuids.random(Random)]: similar to `Uuids.random()` but allows to pass a custom instance of + `java.util.Random` and/or re-use the same instance across calls. +2. [Uuids.random(SplittableRandom)]: similar to `Uuids.random()` but uses a + `java.util.SplittableRandom` instead. + +[Uuids.random()]: https://docs.datastax.com/en/drivers/java/4.11/com/datastax/oss/driver/api/core/uuid/Uuids.html#random-- +[Uuids.random(Random)]: https://docs.datastax.com/en/drivers/java/4.11/com/datastax/oss/driver/api/core/uuid/Uuids.html#random-java.util.Random- +[Uuids.random(SplittableRandom)]: https://docs.datastax.com/en/drivers/java/4.11/com/datastax/oss/driver/api/core/uuid/Uuids.html#random-java.util.SplittableRandom- + +#### System and DSE keyspaces automatically excluded from metadata and token map computation + +[JAVA-2871](https://datastax-oss.atlassian.net/browse/JAVA-2871) now allows for a more fine-grained +control over which keyspaces should qualify for metadata and token map computation, including the +ability to *exclude* keyspaces based on their names. + +From now on, the following keyspaces are automatically excluded: + +1. The `system` keyspace; +2. All keyspaces starting with `system_`; +3. DSE-specific keyspaces: + 1. All keyspaces starting with `dse_`; + 2. The `solr_admin` keyspace; + 3. The `OpsCenter` keyspace. + +This means that they won't show up anymore in [Metadata.getKeyspaces()], and [TokenMap] will return +empty replicas and token ranges for them. If you need the driver to keep computing metadata and +token map for these keyspaces, you now must modify the following configuration option: +`datastax-java-driver.advanced.metadata.schema.refreshed-keyspaces`. + +[Metadata.getKeyspaces()]: https://docs.datastax.com/en/drivers/java/4.11/com/datastax/oss/driver/api/core/metadata/Metadata.html#getKeyspaces-- +[TokenMap]: https://docs.datastax.com/en/drivers/java/4.11/com/datastax/oss/driver/api/core/metadata/TokenMap.html + +#### DSE Graph dependencies are now optional + +Until driver 4.9.0, the driver declared a mandatory dependency to Apache TinkerPop, a library +required only when connecting to DSE Graph. The vast majority of Apache Cassandra users did not need +that library, but were paying the price of having that heavy-weight library in their application's +classpath. + +_Starting with driver 4.10.0, TinkerPop is now considered an optional dependency_. + +Regular users of Apache Cassandra that do not use DSE Graph will not notice any disruption. + +DSE Graph users, however, will now have to explicitly declare a dependency to Apache TinkerPop. This +can be achieved with Maven by adding the following dependencies to the `` section of +your POM file: + +```xml + + org.apache.tinkerpop + gremlin-core + ${tinkerpop.version} + + + org.apache.tinkerpop + tinkergraph-gremlin + ${tinkerpop.version} + +``` + +See the [integration](../manual/core/integration/#tinker-pop) section in the manual for more details +as well as a driver vs. TinkerPop version compatibility matrix. + ### 4.5.x - 4.6.0 These versions are subject to [JAVA-2676](https://datastax-oss.atlassian.net/browse/JAVA-2676), a @@ -8,7 +454,7 @@ least 4.6.1. ### 4.4.0 -Datastax Enterprise support is now available directly in the main driver. There is no longer a +DataStax Enterprise support is now available directly in the main driver. There is no longer a separate DSE driver. #### For Apache Cassandra® users @@ -20,11 +466,11 @@ Apart from that, the only visible change is that DSE-specific features are now e * new execution methods: `CqlSession.executeGraph`, `CqlSession.executeContinuously*`. They all have default implementations so this doesn't break binary compatibility. You can just ignore them. -* new driver dependencies: Tinkerpop, ESRI, Reactive Streams. If you want to keep your classpath +* new driver dependencies: TinkerPop, ESRI, Reactive Streams. If you want to keep your classpath lean, you can exclude some dependencies when you don't use the corresponding DSE features; see the [Integration>Driver dependencies](../manual/core/integration/#driver-dependencies) section. -#### For Datastax Enterprise users +#### For DataStax Enterprise users Adjust your Maven coordinates to use the unified artifact: @@ -98,7 +544,7 @@ you can obtain in most web environments by calling `Thread.getContextClassLoader See the javadocs of [SessionBuilder.withClassLoader] for more information. -[SessionBuilder.withClassLoader]: https://docs.datastax.com/en/drivers/java/4.9/com/datastax/oss/driver/api/core/session/SessionBuilder.html#withClassLoader-java.lang.ClassLoader- +[SessionBuilder.withClassLoader]: https://docs.datastax.com/en/drivers/java/4.11/com/datastax/oss/driver/api/core/session/SessionBuilder.html#withClassLoader-java.lang.ClassLoader- ### 4.1.0 @@ -150,7 +596,7 @@ We have dropped support for legacy protocol versions v1 and v2. As a result, the compatible with: * **Apache Cassandra®: 2.1 and above**; -* **Datastax Enterprise: 4.7 and above**. +* **DataStax Enterprise: 4.7 and above**. #### Packages @@ -167,7 +613,7 @@ import com.datastax.driver.core.Row; import com.datastax.driver.core.SimpleStatement; SimpleStatement statement = - new SimpleStatement("SELECT release_version FROM system.local"); + new SimpleStatement("SELECT release_version FROM system.local"); ResultSet resultSet = session.execute(statement); Row row = resultSet.one(); System.out.println(row.getString("release_version")); @@ -179,7 +625,7 @@ import com.datastax.oss.driver.api.core.cql.Row; import com.datastax.oss.driver.api.core.cql.SimpleStatement; SimpleStatement statement = - SimpleStatement.newInstance("SELECT release_version FROM system.local"); + SimpleStatement.newInstance("SELECT release_version FROM system.local"); ResultSet resultSet = session.execute(statement); Row row = resultSet.one(); System.out.println(row.getString("release_version")); @@ -242,9 +688,9 @@ datastax-java-driver { // Application code: SimpleStatement statement1 = - SimpleStatement.newInstance("...").setExecutionProfileName("profile1"); + SimpleStatement.newInstance("...").setExecutionProfileName("profile1"); SimpleStatement statement2 = - SimpleStatement.newInstance("...").setExecutionProfileName("profile2"); + SimpleStatement.newInstance("...").setExecutionProfileName("profile2"); ``` The configuration can be reloaded periodically at runtime: @@ -363,13 +809,13 @@ propagating its own consistency level to its bound statements: ```java PreparedStatement ps1 = - session.prepare( - SimpleStatement.newInstance("SELECT * FROM product WHERE sku = ?") - .setConsistencyLevel(DefaultConsistencyLevel.ONE)); + session.prepare( + SimpleStatement.newInstance("SELECT * FROM product WHERE sku = ?") + .setConsistencyLevel(DefaultConsistencyLevel.ONE)); PreparedStatement ps2 = - session.prepare( - SimpleStatement.newInstance("SELECT * FROM product WHERE sku = ?") - .setConsistencyLevel(DefaultConsistencyLevel.TWO)); + session.prepare( + SimpleStatement.newInstance("SELECT * FROM product WHERE sku = ?") + .setConsistencyLevel(DefaultConsistencyLevel.TWO)); assert ps1 != ps2; @@ -470,8 +916,8 @@ Optional ks = metadata.getKeyspace("test"); assert !ks.isPresent(); session.execute( - "CREATE KEYSPACE IF NOT EXISTS test " - + "WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}"); + "CREATE KEYSPACE IF NOT EXISTS test " + + "WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}"); // This is still the same metadata from before the CREATE ks = metadata.getKeyspace("test");